text
stringlengths
14
6.51M
unit kawalpemilu_integration; { ref: https://www.kawalpilkada.id/#/tabulasi.html/Provinsi/2017 Kode Province: dki jakarta: 25823 [x] USAGE // textual information with TKawalPemiluIntegration.Create do begin Result := ProvinceRealCountInfo(provinceCode); Free; end; // full json data with TKawalPemiluIntegration.Create do begin Result := ProvinceRealCount(provinceCode); Free; end; } {$mode objfpc}{$H+} interface uses common, http_lib, logutil_lib, fpjson, jsonparser, Classes, SysUtils; type { TKawalPemiluIntegration } TKawalPemiluIntegration = class(TInterfacedObject) private FResultCode: integer; FResultText: string; jsonData: TJSONData; function getData(APath: string): string; function getDataAsInteger(APath: string): integer; public constructor Create; destructor Destroy; property ResultCode: integer read FResultCode; property ResultText: string read FResultText; function ProvinceRealCount(AProvinceCode: string): string; function ProvinceRealCountInfo(AProvinceCode: string): string; end; implementation const KAWALPEMILU_PROVINCE_REALCOUNT_URL = 'https://www.kawalpilkada.id/kandidat/refreshagregasi/2017/Provinsi/%s'; KAWALPEMILU_PROVINCE_REALCOUNT_PUTARAN2_URL = 'https://www.kawalpilkada.id/suara/get/2017-Putaran-2/Provinsi/%s'; var Response: IHTTPResponse; { TKawalPemiluIntegration } function TKawalPemiluIntegration.getData(APath: string): string; begin Result := ''; try Result := jsonData.GetPath(APath).AsString; except end; end; function TKawalPemiluIntegration.getDataAsInteger(APath: string): integer; begin Result := 0; try Result := jsonData.GetPath(APath).AsInteger; except end; end; constructor TKawalPemiluIntegration.Create; begin end; destructor TKawalPemiluIntegration.Destroy; begin if Assigned(jsonData) then jsonData.Free; end; function TKawalPemiluIntegration.ProvinceRealCount(AProvinceCode: string): string; begin Result := ''; if AProvinceCode = '' then Exit; with THTTPLib.Create(format(KAWALPEMILU_PROVINCE_REALCOUNT_PUTARAN2_URL, [AProvinceCode])) do begin try Response := Post; FResultCode := Response.ResultCode; FResultText := Response.ResultText; if FResultCode = 200 then begin Result := FResultText; jsonData := GetJSON(Result); end; except end; Free; end; end; function TKawalPemiluIntegration.ProvinceRealCountInfo(AProvinceCode: string): string; var i, suara1, suara2, suara3, total: integer; totalSuara2, totalSuara3: integer; percent1, percent2, percent3: double; s: string; paslon1, paslon2, paslon3: string; begin Result := ProvinceRealCount(AProvinceCode); if Result = '' then Exit; Result := 'Update QuickCount:'; totalSuara2 := 0; totalSuara3 := 0; for i:=0 to 5 do begin s := #10 + getData('[0]['+i2s(i)+'].nama'); s := s + ' (' + i2s(getDataAsInteger('[0]['+i2s(i)+'].totalpemilih')) + ')'; s := s + #10 + i2s(getDataAsInteger('[0]['+i2s(i)+'].jumlahTPS')) + ' TPS'; suara2 := getDataAsInteger('[0]['+i2s(i)+'].suaraKandidat.2.suaraTPS'); suara3 := getDataAsInteger('[0]['+i2s(i)+'].suaraKandidat.3.suaraTPS'); totalSuara2 := totalSuara2 + suara2; totalSuara3 := totalSuara3 + suara3; Result := Result + #10 + s; Result := Result + #10 + 'Suara TPS'; Result := Result + #10 + '2. ' + FormatFloat('##,##0', suara2); Result := Result + #10 + '3. ' + FormatFloat('##,##0', suara3); suara2 := getDataAsInteger('[0]['+i2s(i)+'].suaraKandidat.2.suaraKPU'); suara3 := getDataAsInteger('[0]['+i2s(i)+'].suaraKandidat.3.suaraKPU'); //Result := Result + #10 + 'Suara KPU'; //Result := Result + #10 + '2. ' + FormatFloat('##,##0', suara2); //Result := Result + #10 + '3. ' + FormatFloat('##,##0', suara3); end; total := totalSuara2 + totalSuara3; percent2 := (totalSuara2 * 100) / total; percent3 := (totalSuara3 * 100) / total; Result := Result + #10#10'Total:'; s := ' (' + FormatFloat('##,##0.00', percent2) + ')'; Result := Result + #10 + '2. ' + FormatFloat('##,##0', totalSuara2) + s; s := ' (' + FormatFloat('##,##0.00', percent3) + ')'; Result := Result + #10 + '3. ' + FormatFloat('##,##0', totalSuara3) + s; Exit; die( Result); { if getData('[1].tahun') = '' then begin Result := 'Maaf, data belum tersedia.'; Exit; end; } Result := 'Update Real Count: ' + getData('[1].nama'); Result := Result + #10#10 + 'Calon:```'; Result := Result + #10 + '1. ' + getData('[1].suaraKandidat.1.nama'); Result := Result + #10 + '2. ' + getData('[1].suaraKandidat.2.nama'); Result := Result + #10 + '3. ' + getData('[1].suaraKandidat.3.nama'); Result := Result + '```'; Result := Result + #10#10 + getData('[1].jumlahTPSdilockHC') + ' dari ' + getData('[1].jumlahTPS') + ' TPS'; Result := Result + #10 + 'Suara Sah: ' + getData('[1].suarasahHC'); Result := Result + #10 + 'Suara Tidak Sah: ' + getData('[1].suaratidaksahHC'); // TPS Result := Result + #10 + '\n*Suara TPS:*'; suara1 := getDataAsInteger('[1].suaraKandidat.1.suaraTPS'); suara2 := getDataAsInteger('[1].suaraKandidat.2.suaraTPS'); suara3 := getDataAsInteger('[1].suaraKandidat.3.suaraTPS'); Result := Result + #10 + '1. ' + FormatFloat('###,##0', suara1); Result := Result + #10 + '2. ' + FormatFloat('###,##0', suara2); Result := Result + #10 + '3. ' + FormatFloat('###,##0', suara3); // C1 Result := Result + #10 + '\n*Verifikasi C1:*'; suara1 := getDataAsInteger('[1].suaraKandidat.1.suaraVerifikasiC1'); suara2 := getDataAsInteger('[1].suaraKandidat.2.suaraVerifikasiC1'); suara3 := getDataAsInteger('[1].suaraKandidat.3.suaraVerifikasiC1'); total := suara1 + suara2 + suara3; if total > 0 then begin percent1 := suara1 * 100 / total; percent2 := suara2 * 100 / total; percent3 := suara3 * 100 / total; end; s := ' (' + FormatFloat('##,##0.00', percent1) + ')'; Result := Result + #10 + '1. ' + FormatFloat('##,##0', suara1) + s; s := ' (' + FormatFloat('##,##0.00', percent2) + ')'; Result := Result + #10 + '2. ' + FormatFloat('##,##0', suara2) + s; s := ' (' + FormatFloat('##,##0.00', percent3) + ')'; Result := Result + #10 + '3. ' + FormatFloat('##,##0', suara3) + s; Result := StringReplace(Result, #10, '\n', [rfReplaceAll]); end; end.
{*******************************************************} { } { NTS Aero UI Library } { Created by GooD-NTS ( good.nts@gmail.com ) } { http://ntscorp.ru/ Copyright(c) 2011 } { License: Mozilla Public License 1.1 } { } {*******************************************************} unit UI.Aero.BackForward; interface {$I '../../Common/CompilerVersion.Inc'} uses {$IFDEF HAS_UNITSCOPE} System.SysUtils, System.Classes, System.Types, Winapi.Windows, Winapi.Messages, Winapi.GDIPUTIL, Winapi.GDIPOBJ, Winapi.GDIPAPI, Vcl.Controls, Vcl.Graphics, Vcl.Imaging.pngimage, Vcl.Menus, Vcl.ExtCtrls, {$ELSE} Windows, SysUtils, Messages, Classes, Types, Controls, Graphics, Menus, Winapi.GDIPUTIL, Winapi.GDIPOBJ, Winapi.GDIPAPI, ExtCtrls, PNGImage, {$ENDIF} UI.Aero.Globals, UI.Aero.Core, UI.Aero.Button.Theme, UI.Aero.Button.Custom, UI.Aero.Button.Image, UI.Aero.Core.CustomControl, UI.Aero.Core.Images; type TButtonClickEvent = procedure(Sender: TObject; Index: Integer) of object; TAeroBackForward = class(TWinControl) public class var Resources_Images_xp_w3k: String; private class constructor Create; Private buttons: Array [0..2] of TAeroThemeButton; AeroXP: Array [1..3] of TPNGImage; FGoToMenu: TPopupMenu; FOnBtnClick: TButtonClickEvent; function GetBtnEnabled(const Index: Integer): BooLean; procedure SetBtnEnabled(const Index: Integer; const Value: BooLean); procedure SetGoToMenu(const Value: TPopupMenu); Protected procedure CreateButtons; Virtual; procedure DestroyButtons; Virtual; procedure SetButtonsProperty; Virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure btnBackMenuClick(Sender: TObject); procedure buttonClick(Sender: TObject); procedure xp_w3k_theme(const Sender: TAeroCustomButton; PartID, StateID: Integer; Surface: TCanvas); procedure LoadMsStyle; procedure FreeMsStyle; Public CurrentIndex: Integer; NeedUpDate: Boolean; Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; Published Property EnabledBack: BooLean Index 0 Read GetBtnEnabled Write SetBtnEnabled; Property EnabledForward: BooLean Index 1 Read GetBtnEnabled Write SetBtnEnabled; Property EnabledMenu: BooLean Index 2 Read GetBtnEnabled Write SetBtnEnabled; property GoToMenu: TPopupMenu read FGoToMenu write SetGoToMenu; property OnButtonClick: TButtonClickEvent Read FOnBtnClick Write FOnBtnClick; end; TAeroIEBackForward = class(TCustomAeroControl) public class var ResourcesImagesPath: String; private class constructor Create; private bmBackground: TBitmap; bmMask: TBitmap; bmButton: Array [bsNormal..bsDisabled] of TBitmap; FStateBack: TAeroButtonState; FStateForward: TAeroButtonState; FBackDown: boolean; FForwardDown: boolean; FTravelMenu: TPopupMenu; FMenuTimer: TTimer; FOnBtnClick: TButtonClickEvent; FOnlyBackButton: Boolean; function GetButtonEnabled(const Index: Integer): boolean; procedure SetButtonEnabled(const Index: Integer; const Value: boolean); procedure SetTravelMenu(const Value: TPopupMenu); procedure ShowTravelMenu(Sender: TObject); procedure SetOnlyBackButton(const Value: Boolean); protected function GetRenderState: TRenderConfig; override; procedure RenderControl(const PaintDC: hDC); procedure ClassicRender(const ACanvas: TCanvas); override; procedure ThemedRender(const PaintDC: hDC; const Surface: TGPGraphics; var RConfig: TRenderConfig); override; procedure PostRender(const Surface: TCanvas;const RConfig: TRenderConfig); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); OverRide; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure WndProc(var Message: TMessage); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Click; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnlyBackButton: Boolean read FOnlyBackButton write SetOnlyBackButton default false; property EnabledBack: boolean index 0 read GetButtonEnabled write SetButtonEnabled default false; property EnabledForward: boolean index 1 read GetButtonEnabled write SetButtonEnabled default false; property TravelMenu: TPopupMenu read FTravelMenu write SetTravelMenu; property OnButtonClick: TButtonClickEvent Read FOnBtnClick Write FOnBtnClick; end; implementation uses NTS.Code.Helpers; class constructor TAeroBackForward.Create; begin if Assigned(RegisterComponentsProc) then begin TAeroBackForward.Resources_Images_xp_w3k := GetEnvironmentVariable('NTS_LIB_ROOT')+'\NTS UI Aero\Resources\Images\'; end else begin TAeroBackForward.Resources_Images_xp_w3k := '???ERROR_PATH***'; end; end; class constructor TAeroIEBackForward.Create; begin if Assigned(RegisterComponentsProc) then begin TAeroIEBackForward.ResourcesImagesPath := GetEnvironmentVariable('NTS_LIB_ROOT') + '\NTS UI Aero\Resources\Images\' end else begin TAeroIEBackForward.ResourcesImagesPath := '???ERROR_PATH***'; end; end; { TAeroBackForward } Constructor TAeroBackForward.Create(AOwner: TComponent); begin Inherited Create(AOwner); NeedUpDate:= True; CurrentIndex:= 0; ControlStyle:= ControlStyle+[csParentBackground]-[csOpaque]; Height:= 31; Width:= 81; CreateButtons; SetButtonsProperty; end; Destructor TAeroBackForward.Destroy; begin DestroyButtons; Inherited Destroy; end; procedure TAeroBackForward.Notification(AComponent: TComponent; Operation: TOperation); begin Inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FGoToMenu) then FGoToMenu:= nil; end; procedure TAeroBackForward.CreateButtons; const bntName: Array [0..2] of String = ('btnBack','btnForward','btnBackMenu'); var I: Integer; begin if not AeroCore.RunWindowsVista then LoadMsStyle; for I:=0 to 2 do begin buttons[I]:= TAeroThemeButton.Create(Self); buttons[I].Name:= bntName[I]; buttons[I].Parent:= Self; buttons[I].Tag:= I; if not AeroCore.RunWindowsVista then buttons[I].OnThemePaint:= xp_w3k_theme; end; end; procedure TAeroBackForward.DestroyButtons; var I: Integer; begin for I:=0 to 2 do buttons[I].Free; if not AeroCore.RunWindowsVista then FreeMsStyle; end; procedure TAeroBackForward.SetButtonsProperty; var I: Integer; begin for I:=1 to 3 do with buttons[I-1] do begin Top:= -2; if AeroCore.RunWindowsVista then Height:= 33 else Height:= 29; ThemeClassName:= 'Navigation'; DrawCaption:= False; State.StateNormal:= 1; State.StateHightLight:= 2; State.StateFocused:= 2; State.StateDown:= 3; State.StateDisabled:= 4; State.PartNormal:= I; State.PartHightLight:= I; State.PartFocused:= I; State.PartDown:= I; State.PartDisabled:= I; end; with buttons[0] do begin Left:= 0; Width:= 33; OnClick:= buttonClick; end; with buttons[1] do begin Left:= 32; Width:= 33; OnClick:= buttonClick; end; with buttons[2] do begin Left:= 64; Width:= 17; OnClick:= btnBackMenuClick; end; end; procedure TAeroBackForward.SetGoToMenu(const Value: TPopupMenu); begin FGoToMenu:= Value; end; function TAeroBackForward.GetBtnEnabled(const Index: Integer): BooLean; begin Result:= buttons[Index].Enabled; end; procedure TAeroBackForward.SetBtnEnabled(const Index: Integer; const Value: BooLean); begin buttons[Index].Enabled:= Value; end; procedure TAeroBackForward.btnBackMenuClick(Sender: TObject); var Point: TPoint; begin if Assigned(FGoToMenu) then begin Point:= buttons[2].ClientOrigin; Point.Y:= Point.Y+buttons[2].Height; with Point do FGoToMenu.Popup(X, Y); end; end; procedure TAeroBackForward.buttonClick(Sender: TObject); begin if Assigned(FOnBtnClick) then FOnBtnClick(Self,TAeroThemeButton(Sender).Tag); end; procedure TAeroBackForward.LoadMsStyle; const bntName: Array [1..3] of String = ('933.png','935.png','937.png'); var I: Integer; Dir: String; begin Dir:= TAeroBackForward.Resources_Images_xp_w3k; for I:=1 to 3 do begin AeroXP[I]:= TPNGImage.Create; if FileExists(Dir+bntName[I]) then AeroXP[I].LoadFromFile(Dir+bntName[I]) else MessageBox(0, pChar('Cant load image: '+sLineBreak+Dir+bntName[I]), 'Aero UI - Error', MB_ICONHAND OR MB_OK); end; end; procedure TAeroBackForward.FreeMsStyle; var I: Integer; begin for I:=1 to 3 do AeroXP[I].Free; end; procedure TAeroBackForward.xp_w3k_theme(const Sender: TAeroCustomButton; PartID, StateID: Integer; Surface: TCanvas); begin Surface.Draw(0,-(27*(StateID-1))+2,AeroXP[PartID]); end; { TAeroIEBackForward } Constructor TAeroIEBackForward.Create(AOwner: TComponent); begin Inherited Create(AOwner); FMenuTimer:= TTimer.Create(Self); FMenuTimer.Enabled:= False; FMenuTimer.Interval:= 300; FMenuTimer.OnTimer:= ShowTravelMenu; FOnlyBackButton:= False; FStateBack:= bsDisabled; FStateForward:= bsDisabled; FBackDown:= false; FForwardDown:= false; bmBackground:= AeroPicture.LoadImage( ResourcesImagesPath+'TRAVEL_BACKGROUND_MINIE.png' ); bmMask:= AeroPicture.LoadImage( ResourcesImagesPath+'TRAVEL_MINIE_MASK.png' ); bmButton[bsNormal]:= AeroPicture.LoadImage( ResourcesImagesPath+'TRAVEL_ENABLED_MINIE.png' ); bmButton[bsHightLight]:= AeroPicture.LoadImage( ResourcesImagesPath+'TRAVEL_HOT_MINIE.png' ); bmButton[bsDown]:= AeroPicture.LoadImage( ResourcesImagesPath+'TRAVEL_PRESSED_MINIE.png' ); bmButton[bsDisabled]:= AeroPicture.LoadImage( ResourcesImagesPath+'TRAVEL_DISABLED_MINIE.png' ); Height:= 36; Width:= 76; end; Destructor TAeroIEBackForward.Destroy; begin if Assigned(bmButton[bsNormal]) then bmButton[bsNormal].Free(); if Assigned(bmButton[bsHightLight]) then bmButton[bsHightLight].Free(); if Assigned(bmButton[bsDown]) then bmButton[bsDown].Free(); if Assigned(bmButton[bsDisabled]) then bmButton[bsDisabled].Free(); if Assigned(bmMask) then bmMask.Free(); if Assigned(bmBackground) then bmBackground.Free(); FMenuTimer.Free; inherited Destroy; end; function TAeroIEBackForward.GetRenderState: TRenderConfig; begin Result:= [rsBuffer]; end; procedure TAeroIEBackForward.Click; begin inherited Click; if Assigned(FOnBtnClick) then begin if FStateBack in [bsHightLight, bsDown] then FOnBtnClick(Self, 0); if FStateForward in [bsHightLight, bsDown] then FOnBtnClick(Self, 1); end; end; procedure TAeroIEBackForward.ThemedRender(const PaintDC: hDC; const Surface: TGPGraphics; var RConfig: TRenderConfig); begin RenderControl(PaintDC); end; procedure TAeroIEBackForward.ClassicRender(const ACanvas: TCanvas); begin RenderControl(ACanvas.Handle); end; procedure TAeroIEBackForward.PostRender(const Surface: TCanvas; const RConfig: TRenderConfig); begin end; procedure TAeroIEBackForward.RenderControl(const PaintDC: hDC); function Size(cx, cy: Integer): TSize; begin Result.cx:= cx; Result.cy:= cy; end; begin if Assigned(bmMask) and Assigned(bmBackground) then begin if not FOnlyBackButton then AeroPicture.Draw(PaintDC, bmBackground, Point(0, 1)); if Self.Enabled then begin if csDesigning in ComponentState then begin AeroPicture.DrawPart(PaintDC, bmMask.Canvas.Handle, Point(0,0), Size(38, 35), 0, ioHorizontal); AeroPicture.DrawPart(PaintDC, bmButton[bsNormal].Canvas.Handle, Point(0,0), Size(38, 35), 0, ioHorizontal); if not FOnlyBackButton then AeroPicture.DrawPart(PaintDC, bmButton[bsDisabled].Canvas.Handle, Point(38,0), Size(38, 35), 1, ioHorizontal); end else begin if FStateBack <> bsDisabled then AeroPicture.DrawPart(PaintDC, bmMask.Canvas.Handle, Point(0,0), Size(38, 35), 0, ioHorizontal); if not FOnlyBackButton and (FStateForward <> bsDisabled) then AeroPicture.DrawPart(PaintDC, bmMask.Canvas.Handle, Point(38,0), Size(38, 35), 1, ioHorizontal); AeroPicture.DrawPart(PaintDC, bmButton[FStateBack].Canvas.Handle, Point(0,0), Size(38, 35), 0, ioHorizontal); if not FOnlyBackButton then AeroPicture.DrawPart(PaintDC, bmButton[FStateForward].Canvas.Handle, Point(38,0), Size(38, 35), 1, ioHorizontal); end; end else AeroPicture.Draw(PaintDC, bmButton[bsDisabled], Point(0, 0)); end; end; procedure TAeroIEBackForward.SetButtonEnabled(const Index: Integer; const Value: boolean); begin case Index of 0: if Value then FStateBack:= bsNormal else FStateBack:= bsDisabled; 1: if Value then FStateForward:= bsNormal else FStateForward:= bsDisabled; end; Invalidate; end; procedure TAeroIEBackForward.SetOnlyBackButton(const Value: Boolean); begin if FOnlyBackButton <> Value then begin FOnlyBackButton := Value; Invalidate; end; end; procedure TAeroIEBackForward.SetTravelMenu(const Value: TPopupMenu); begin FTravelMenu := Value; if Value <> nil then begin Value.ParentBiDiModeChanged(Self); Value.FreeNotification(Self); end; end; procedure TAeroIEBackForward.ShowTravelMenu(Sender: TObject); begin FMenuTimer.Enabled:= False; if FBackDown and Assigned(FTravelMenu) then begin FBackDown:= False; FStateBack:= bsNormal; with Self.ClientToScreen( Point(0, Height-3) ) do FTravelMenu.Popup(x, y); end; if FForwardDown and Assigned(FTravelMenu) then begin FForwardDown:= False; FStateForward:= bsNormal; with Self.ClientToScreen( Point(38, Height-3) ) do FTravelMenu.Popup(x, y); end; end; function TAeroIEBackForward.GetButtonEnabled(const Index: Integer): boolean; begin case Index of 0: Result:= FStateBack <> bsDisabled; 1: Result:= FStateForward <> bsDisabled; else Result:= False; end; end; procedure TAeroIEBackForward.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var OStateBack: TAeroButtonState; OStateForward: TAeroButtonState; begin Inherited MouseDown(Button, Shift, X, Y); if Button = mbLeft then begin OStateBack:= FStateBack; OStateForward:= FStateForward; if (FStateBack <> bsDisabled) then begin if Point(X,Y).InRect( Rect(0, 0, 38, 35) ) then begin FStateBack:= bsDown; FBackDown:= True; FMenuTimer.Enabled:= True; end else FBackDown:= False; end; if (FStateForward <> bsDisabled) then begin if Point(X,Y).InRect( Rect(38, 0, 76, 35) ) then begin FStateForward:= bsDown; FForwardDown:= True; FMenuTimer.Enabled:= True; end else FForwardDown:= False; end; if (OStateBack <> FStateBack) or (OStateForward <> FStateForward) then Invalidate; end; end; procedure TAeroIEBackForward.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Inherited MouseUp(Button, Shift, X, Y); FMenuTimer.Enabled:= True; FBackDown:= False; FForwardDown:= False; MouseMove(Shift, X, Y); end; procedure TAeroIEBackForward.Notification(AComponent: TComponent; Operation: TOperation); begin Inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FTravelMenu) then FTravelMenu:= nil; end; procedure TAeroIEBackForward.MouseMove(Shift: TShiftState; X, Y: Integer); var OStateBack: TAeroButtonState; OStateForward: TAeroButtonState; begin Inherited MouseMove(Shift, X, Y); OStateBack:= FStateBack; OStateForward:= FStateForward; if (FStateBack <> bsDisabled) then begin if Point(X,Y).InRect( Rect(0, 0, 38, 35) ) then begin if FBackDown then FStateBack:= bsDown else FStateBack:= bsHightLight end else FStateBack:= bsNormal; end; if (FStateForward <> bsDisabled) then begin if Point(X,Y).InRect( Rect(38, 0, 76, 35) ) then begin if FForwardDown then FStateForward:= bsDown else FStateForward:= bsHightLight end else FStateForward:= bsNormal; end; if (OStateBack <> FStateBack) or (OStateForward <> FStateForward) then begin Invalidate; end; end; procedure TAeroIEBackForward.WndProc(var Message: TMessage); begin Inherited WndProc(Message); case Message.Msg of CM_MOUSEENTER: Invalidate; CM_MOUSELEAVE: begin if (FStateBack <> bsDisabled) then FStateBack:= bsNormal; if (FStateForward <> bsDisabled) then FStateForward:= bsNormal; Invalidate; end; end; end; end.
{ Cross platform Database implementation } { To implement a Database interface, subclass TBaseKDBConnection overriding all the virtual methods, and subclass the TKDBConnectionManager and implement functionality as required to set up and manage connections, and a connection factories. When creating databases, you have the choice of creating the appropriate class directly, or using the factory provided in this unit. Known implementations: Unit ManagerClass Description odbcconn TODBCConnectionManager Standard ODBC Connection class ibconn TIBConnectionManager Direct Interbase interface dbisam TDBISAMConnManager DBIsam with auto-recovery } unit KDBManager; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } // This section used by scripting system {!Wrapper uses KClasses,Classes,KProcs,AdvFilers,AdvObjects,AdvIterators, MSSEWrap, MSSEWrap_Wrapper} // script access at this level is strictly controlled. // until further notice, connection managers cannot be created directly in scripts. // instead, you must expose the ability to create and manage connections elsewhere // portions of this functionality will not be available in the scripting layer {!ignore TKDBConnection.ExecSQLBatch} // not really supportable in script engine, and not important {!ignore TConnectionState} {!ignore TKDBManagerList} {!ignore TKDBManager} {!ignore @.KDBManagers} {!ignore KDB_ALL_PROVIDERS} interface uses SysUtils, SyncObjs, Classes, Contnrs, IniFiles, Generics.Collections, kCritSct, KSettings, StringSupport, GuidSupport, AdvExceptions, AdvObjects, AdvGenerics, KDBLogging, KDBDialects, DateSupport; {!Script Hide} const DEFAULT_CONNECTION_WAIT_LENGTH = 1000; DEFAULT_CONNECTION_REFRESH_PERIOD = 200; CONNECTION_UNKNOWN = 0; CONNECTION_OK = 1; CONNECTION_FAIL = 2; {!Script Show} type EKDBException = class (Exception); {!Script Hide} // these are all the known providers. Just because the enumerations are defined doesn't // mean that the provider is supported by all 3 of compiler, application, and system // access is odbc but settings are done differently TKDBProvider = (kdbpUnknown, kdbpDSN, kdbpODBC, kdbpFirebird, kdbpDBIsam, kdbpDBXpress, kdbpSoapClient, kdbpMySQL, kdbpAccess, kdbpSQLite); TKDBProviderSet = set of TKDBProvider; const KDB_ALL_PROVIDERS = [Low(TKDBProvider) .. High(TKDBProvider)]; type {!Script Show} {@enum TKDBColumnType Lists possible database Column types } TKDBColumnType = (ctUnknown, ctBoolean, ctInteger, ctNumeric, ctFloat, ctChar, ctDateTime, ctBlob, ctInt64, ctUnicode); {!Script Hide} // Meta data TKDBTableType = (kdbUser, kdbView, kdbSystem); TKDBColumn = class (TAdvObject) private FName: String; FLength: Integer; FDataType: TKDBColumnType; FNullable: Boolean; public constructor Create(name : String); overload; function Link : TKDBColumn; overload; property Name : String read FName write FName; property DataType : TKDBColumnType read FDataType write FDataType; property Length : Integer read FLength write FLength; property Nullable : Boolean read FNullable write FNullable; function Describe : String; end; TKDBIndex = class (TAdvObject) private FUnique: Boolean; FName: String; FColumns: TAdvList<TKDBColumn>; public constructor Create; override; destructor Destroy; override; property Name : String read FName write FName; property Unique : Boolean read FUnique write FUnique; property Columns : TAdvList<TKDBColumn> read FColumns; function Describe : String; end; TKDBRelationship = class (TAdvObject) private FColumn: String; FDestTable : String; FDestColumn : String; public Property Column : String read FColumn write FColumn; Property DestTable : String read FDestTable write FDestTable; Property DestColumn : String read FDestColumn write FDestColumn; function Describe : String; end; TKDBTable = class (TAdvObject) private FName: String; FColumns: TAdvList<TKDBColumn>; FIndexes: TAdvList<TKDBIndex>; FRelationships : TAdvList<TKDBRelationship>; FTableType: TKDBTableType; FOwner: String; FDescription: String; FOrderMatters : Boolean; public constructor Create; override; destructor Destroy; override; function Link : TKDBTable; overload; property Columns : TAdvList<TKDBColumn> read FColumns; property Indexes : TAdvList<TKDBIndex> read FIndexes; Property Relationships : TAdvList<TKDBRelationship> read FRelationships; property Name : String read FName write FName; property TableType : TKDBTableType read FTableType write FTableType; property Owner : String read FOwner write FOwner; property Description : String read FDescription write FDescription; Property OrderMatters : Boolean read FOrderMatters write FOrderMatters; function hasColumn(name : String) : boolean; end; TKDBMetaData = class (TAdvObject) private FTables: TAdvList<TKDBTable>; FProcedures : TStringList; FSupportsProcedures : Boolean; public constructor Create; override; destructor Destroy; override; property Tables : TAdvList<TKDBTable> read FTables; property Procedures : TStringList read FProcedures; property SupportsProcedures : Boolean read FSupportsProcedures write FSupportsProcedures; function HasTable(name : String) : boolean; function GetTable(name : String) : TKDBTable; end; TKDBManager = class; TOnChangeConnectionCount = procedure (oSender : TKDBManager) of Object; TKDBBoundParam = class (TAdvObject); {!Script Show} {@Class TKDBConnection Database connection that exposes a SQL based interface to the appropriate database. These cannot be created directly - you must use a TDBConnPool.GetConnection call to get a connection. The connection must always be returned using TDBConnPool.YieldConnection otherwise the connection will leak. } TKDBConnection = class (TAdvObject) Private FOwner: TKDBManager; FNoFree : Boolean; FBoundItems : TAdvMap<TKDBBoundParam>; FUsage : String; FUsed : TDateTime; FTables : TStrings; FRowCount : integer; FPrepareCount : integer; FInTransaction : Boolean; // local storage for applications using the connection FHolder: TObject; FTag: Integer; // execution FSQL : string; FTerminated: Boolean; FTransactionId: String; function GetTables : TStrings; function LookupInternal(ATableName, AKeyField, AKeyValue, AValueField, ADefault: String; bAsString: Boolean): String; function GetColBlobAsString(ACol: Integer): String; function GetColBlobAsStringByName(AName: String): String; Protected // caching for blobs, for use by concrete implementations procedure KeepBoundObj(sName : String; AObj : TKDBBoundParam); // worker routines for descendants to override procedure StartTransactV; virtual; abstract; procedure CommitV; virtual; abstract; procedure RollbackV; virtual; abstract; procedure RenameTableV(AOldTableName, ANewTableName: String); virtual; abstract; procedure RenameColumnV(ATableName, AOldColumnName, ANewColumnName: String; AColumnDetails: String); virtual; abstract; procedure DropTableV(ATableName : String); virtual; abstract; procedure DropColumnV(ATableName, AColumnName : String); virtual; abstract; procedure ClearDatabaseV; virtual; abstract; procedure PrepareV; virtual; abstract; procedure ExecuteV; virtual; abstract; procedure TerminateV; virtual; abstract; function FetchNextV: Boolean; virtual; abstract; function ColByNameV(AColName: String): Integer; virtual; abstract; function ColNameV(ACol: Integer): String; virtual; abstract; procedure BindInt64V(AParamName: String; AParamValue: Int64); virtual; abstract; procedure BindIntegerV(AParamName: String; AParamValue: Integer); virtual; abstract; procedure BindKeyV(AParamName: String; AParamValue: Integer); virtual; abstract; procedure BindDoubleV(AParamName: String; AParamValue: Double); virtual; abstract; procedure BindStringV(AParamName: String; AParamValue: String); virtual; abstract; procedure BindTimeStampV(AParamName: String; AParamValue: DateSupport.TTimeStamp); virtual; abstract; procedure BindDateTimeExV(AParamName: String; AParamValue: TDateTimeEx); virtual; abstract; procedure BindBlobV(AParamName: String; AParamValue: TBytes); virtual; abstract; procedure BindNullV(AParamName: String); virtual; abstract; function GetColCountV: Integer; Virtual; Abstract; function GetColStringV(ACol: Word): String; Virtual; Abstract; function GetColIntegerV(ACol: Word): Integer; Virtual; Abstract; function GetColInt64V(ACol: Word): Int64; Virtual; Abstract; function GetColDoubleV(ACol: Word): Double; Virtual; Abstract; function GetColBlobV(ACol: Word): TBytes; Virtual; Abstract; function GetColNullV(ACol: Word): Boolean; Virtual; Abstract; function GetColTimestampV(ACol: Word): DateSupport.TTimestamp; Virtual; Abstract; function GetColDateTimeExV(ACol: Word): TDateTimeEx; Virtual; Abstract; function GetColTypeV(ACol: Word): TKDBColumnType; Virtual; Abstract; function GetColKeyV(ACol: Word): Integer; Virtual; Abstract; function GetRowsAffectedV: Integer; Virtual; Abstract; function FetchMetaDataV : TKDBMetaData; Virtual; Abstract; procedure ListTablesV(AList : TStrings); virtual; abstract; function DatabaseSizeV : int64; virtual; abstract; Function TableSizeV(sName : String):int64; virtual; abstract; function SupportsSizingV : Boolean; virtual; abstract; Public constructor Create(AOwner: TKDBManager); destructor Destroy; Override; function link : TKDBConnection; overload; {@member Prepare After setting the SQL content, prepare the statement so Parameter Binding and execution can be done. You must call prepare before binding and execution. If you are using Interbase, you must call terminate after calling prepare - use a try finally construct } procedure Prepare; {@member Execute Execute the SQL Statement. Will raise an exception if there is a problem } procedure Execute; {@member Terminate Clean up. You should call terminate before returning the connection to the pool or using it again } procedure Terminate; {!Script Hide} property Usage: String Read FUsage Write FUsage; property UseStarted : TDateTime read FUsed; property Holder: TObject Read FHolder Write FHolder; property Tag: Integer Read FTag Write FTag; property Owner: TKDBManager Read FOwner; // when the application finishes with the connection, it should use one of these to free the connection procedure Release; procedure Error(AException: Exception; AErrMsg : string = ''); // run a group of sql statements as a group // note: if you avoid binding timestamps and binaries in order to use this // routine, the NDM will remove it and make you clean up // not supported in scripting procedure ExecSQLBatch(ASql: array of String); function FetchMetaData : TKDBMetaData; {!Script Show} // public for scripting engine - usually would be private function GetColCount: Integer; function GetColString(ACol: Integer): String; function GetColInteger(ACol: Integer): Integer; function GetColInt64(ACol: Integer): Int64; function GetColDouble(ACol: Integer): Double; function GetColBlob(ACol: Integer): TBytes; function GetColNull(ACol: Integer): Boolean; function GetColTimestamp(ACol: Integer): DateSupport.TTimestamp; function GetColDateTimeEx(ACol: Integer): TDateTimeEx; function GetColType(ACol: Integer): TKDBColumnType; function GetRowsAffected: Integer; function GetColStringByName(AName: String): String; function GetColBlobByName(AName: String): TBytes; function GetColIntegerByName(AName: String): Integer; function GetColInt64ByName(AName: String): Int64; function GetColDoubleByName(AName: String): Double; function GetColTimeStampByName(AName: String): DateSupport.TTimestamp; function GetColDateTimeExByName(AName: String): TDateTimeEx; function GetColTypeByName(AName: String): TKDBColumnType; function GetColNullByName(AName: String): Boolean; {!Script Hide} function GetColKey(ACol: Integer): Integer; function GetColKeyByName(AName: String): Integer; {!Script Show} {@member ExecSQL Execute a single SQL statement (update, insert, etc. Returns the number of rows affected). You can't use this meaningfully with select statements } function ExecSQL(ASql: String) : integer; overload; function ExecSQL(ASql: String; rows : integer) : integer; overload; {@member DatabaseSize Get the size of the database } function DatabaseSize : int64; {@member TableSize Get the size of the specified table } Function TableSize(sName : String):int64; {@member SupportsSizing True if the underlying connection supports determining database and table size } function SupportsSizing : Boolean; {@member CountSQL Execute a Count SQL Statement and return the value returned. Use an SQL Statement of the following form: select count(KeyField) from Table where conditions The first column of the first set of data is returned as an integer. It's also possible to use sql such as Select max(KeyField) from Table } function CountSQL(ASql: String): Cardinal; {@member ExistsByKey Quickly check whether table sTableName has a record where sKeyField has value iKey. assumes that keyField has an appropriate index. } Function ExistsByKey(Const sTableName, sKeyField : String; ikey : Integer) : Boolean; {@member Lookup Given a tablename, return the value of ValueField where KeyField is the same as keyvalue. the keyfield can be a number or a string. if there is no match, Default will be returned as the value } function Lookup(ATableName, AKeyField, AKeyValue, AValueField, ADefault: String): String; {@member LookupString Given a tablename, return the value of ValueField where KeyField is the same as keyvalue. the keyfield can be a number or a string. if there is no match, Default will be returned as the value The SQL will always be generated as a string - avoid cast errors from SQL } function LookupString(ATableName, AKeyField, AKeyValue, AValueField, ADefault: String): String; {@member RenameTable Rename a table in the database. Each platform generally provides a specific mechanism to do this, but the implementation varies widely. this works on all supported platforms. Renaming may fail to due to relational or other constraints. In this case an exception will usually be raised (provider platform dependent) } procedure RenameTable(AOldTableName, ANewTableName: String); {@member DropTable Drop a table from the database. on most platforms this equates to executing the SQL statement Drop Table "tablename" } procedure DropTable(ATableName : String); {@member DropColumn Drop a column from a table in the database. } procedure DropColumn(ATableName, AColumnName: String); {@member RenameColumn Rename a Column in a table. Each platform generally provides a specific mechanism to do this, but the implementation varies widely. this works on all supported platforms. Renaming may fail to due to relational or other constraints. In this case an exception will usually be raised (provider platform dependent) } procedure RenameColumn(ATableName, AOldColumnName, ANewColumnName: String; AColumnDetails: String = ''); {!Script hide} procedure ListTables(AList : TStrings); {!Script Show} {@member Tables A List of all the tables in the database } property Tables : TStrings Read GetTables; {@member ClearDatabase Completely drop non system content in database. For obvious reasons, this needs to be used with considerable care. Also it should be used before anything else has been done with the database. } procedure ClearDatabase; {@member StartTransact Start a transaction. Close with Commit or RollBack. } procedure StartTransact; {@member Commit Close a transaction and commit changes to the database. (note: Multi-stage commits & Rollbacks are not supported) } procedure Commit; {@member Rollback Abandon transaction (no changes to the database). (note: Multi-stage commits & Rollbacks are not supported) } procedure Rollback; property InTransaction : Boolean read FInTransaction; {@member Fetchnext Iterate through the recordset after execute has been called. You must call Fetchnext before the the first record. Fetchnext will return false once there is no more records to retrieve. Forward cursors only } function FetchNext: Boolean; {@member ColByName Determine the index of a column by it's name } function ColByName(AColName: String): Integer; {@member ColName Determine the Name of a column by it's index } function ColName(ACol: Integer): String; {@member BindInt64 Bind an Int64 value to a named parameter. You can call this after using an SQL statement like this: insert into table (field) values (:i) this will bind the value i to the parameter. } procedure BindInt64(AParamName: String; AParamValue: Int64); {@member BindInteger Bind an Integer value to a named parameter. You can call this after using an SQL statement like this: insert into table (field) values (:i) this will bind the value i to the parameter. } procedure BindInteger(AParamName: String; AParamValue: Integer); {!Script Hide} procedure BindKey(AParamName: String; AParamValue: Integer); {!Script Show} {@member BindDouble Bind a Double (Float) value to a named parameter. You can call this after using an SQL statement like this: insert into table (field) values (:d) } procedure BindDouble(AParamName: String; AParamValue: Double); {@member BindString Bind a String value to a named parameter. You can call this after using an SQL statement like this: insert into table (field) values (:s) } procedure BindString(AParamName: String; AParamValue: String); {@member BindStringOrNull Bind a String value to a named parameter, or null } procedure BindStringOrNull(AParamName: String; AParamValue: String); {@member BindTimeStamp Bind a TTimeStamp value to a named parameter. You can call this after using an SQL statement like this: insert into table (field) values (:t) } procedure BindTimeStamp(AParamName: String; AParamValue: DateSupport.TTimeStamp); {@member BindDateAndTime Bind a DateTime value to a named parameter. You can call this after using an SQL statement like this: insert into table (field) values (:t) } procedure BindDateTimeEx(AParamName: String; AParamValue: TDateTimeEx); {!Script Hide} {@member BindBlob Bind a Binary value to a named parameter. You can call this after using an SQL statement like this: insert into table (field) values (:t) use this for Blob fields Note that BindBinary works differently to the other bind calls. It is the caller's responsibility to make sure that the memory pointed to in the binary does not change until after execute is called. } procedure BindBlob(AParamName: String; AParamValue: TBytes); {!Script Show} {@member BindBlobFromString Bind a Binary value to a named parameter. But present a string for binding You can call this after using an SQL statement like this: insert into table (field) values (:t) use this for Blob fields } procedure BindBlobFromString(AParamName: String; AParamValue: String); {@member BindIntegerFromBoolean Bind an integer from a boolean value. Database value will be 1 if true } procedure BindIntegerFromBoolean(AParamName: String; AParamValue: Boolean); {@member BindNull Bind the Null value to a named parameter. You can call this after using an SQL statement like this: insert into table (field) values (:t) } procedure BindNull(AParamName: String); {!Script Hide} property ColKey [ACol: Integer]: Integer Read GetColKey; {!Script Show} {@member ColType Get Column Col Field Type } property ColType [ACol: Integer]: TKDBColumnType Read GetColType; {@member ColNull True if Column ACol(index) Value is Null } property ColNull [ACol: Integer]: Boolean Read GetColNull; {@member ColString Get true if Column ACol(index) is null } property ColString [ACol: Integer]: String Read GetColString; {@member ColInteger Get Column ACol(index) as an Integer } property ColInteger [ACol: Integer]: Integer Read GetColInteger; {@member ColInt64 Get Column ACol(index) as a Int64 } property ColInt64 [ACol: Integer]: Int64 Read GetColInt64; {@member ColDouble Get Column ACol(index) as a Double (Float) } property ColDouble [ACol: Integer]: Double Read GetColDouble; {@member ColMemory Get Column ACol(index) as a blob } property ColBlob [ACol: Integer]: TBytes Read GetColBlob; property ColBlobAsString [ACol: Integer]: String Read GetColBlobAsString; {@member ColTimestamp Get Column ACol(index) as a TTimestamp } property ColTimestamp [ACol: Integer]: DateSupport.TTimestamp Read GetColTimestamp; {@member ColDateTimeEx Get Column ACol(index) as a DateAndTime } property ColDateTimeEx [ACol: Integer]: TDateTimeEx Read GetColDateTimeEx; {!Script Hide} property ColKeyByName [AName: String]: Integer Read GetColKeyByName; {!Script Show} {@member ColTypeByName Get Column "AName" Field Type} property ColTypeByName [AName: String]: TKDBColumnType Read GetColTypeByName; {@member ColNullByName true if Column "AName" value is Null} property ColNullByName [AName: String]: Boolean Read GetColNullByName; {@member ColStringByName Get Column "AName" as a String} property ColStringByName [AName: String]: String Read GetColStringByName; {@member ColIntegerByName Get Column "AName" as an integer} property ColIntegerByName [AName: String]: Integer Read GetColIntegerByName; {@member ColInt64ByName Get Column "AName" as a Int64} property ColInt64ByName [AName: String]: Int64 Read GetColInt64ByName; {@member ColDoubleByName Get Column "AName" as a Double (Float)} property ColDoubleByName [AName: String]: Double Read GetColDoubleByName; {@member ColMemoryByName Get Column "AName" as a Blob} property ColBlobByName [AName: String]: TBytes Read GetColBlobByName; property ColBlobAsStringByName[AName: String]: String Read GetColBlobAsStringByName; {@member ColTimeStampByName Get Column "AName" as a TTimeStamp} property ColTimeStampByName [AName: String]: DateSupport.TTimeStamp Read GetColTimeStampByName; {@member ColDateTimeExByName Get Column "AName" as a TDateTimeEx} property ColDateTimeExByName [AName: String]: TDateTimeEx Read GetColDateTimeExByName; {@member ColCount Number of columns in current result set } property ColCount: Integer Read GetColCount; {@member RowsAffected The number of rows affected by an insert, update or delete. not valid after a select } property RowsAffected: Integer Read GetRowsAffected; property transactionId : String read FTransactionId write FTransactionId; published {@member SQL The SQL string to execute } property SQL: String Read FSql Write FSql; end; TKDBConnectionProc = reference to Procedure (conn : TKDBConnection); TKDBManager = class(TAdvObject) Private FSemaphore : TSemaphore; FWaitCreate : boolean; FConnections : TAdvList<TKDBConnection>; FAvail: TAdvList<TKDBConnection>; FInUse : TAdvList<TKDBConnection>; FDBLogger : TKDBLogger; FClosing : boolean; FOnChangeConnectionCount : TOnChangeConnectionCount; FServerIsAvailable : Boolean; FLastServerGood : TDateTime; FLastServerError : String; FThreadWaitCount : integer; FMaxConnCount : Integer; FName : string; FTag : integer; function PopAvail : TKDBConnection; function GetCurrentCount: Integer; procedure Release(AConn : TKDBConnection); procedure Error(AConn : TKDBConnection; AException: Exception; AErrMsg : string); function GetCurrentUse: Integer; procedure SetMaxConnCount(const Value: Integer); procedure CheckWait; Protected FLock : TCriticalSection; function ConnectionFactory: TKDBConnection; Virtual; Abstract; function GetDBPlatform: TKDBPlatform; Virtual; Abstract; function GetDBProvider: TKDBProvider; Virtual; Abstract; function GetDBDetails: String; Virtual; Abstract; function GetDriver: String; Virtual; Abstract; procedure init; virtual; Public constructor Create(AName : String; AMaxConnCount: Integer); overload; constructor create(AName : String; ASettings : TSettingsAdapter; AIdent : String = ''); overload; virtual; abstract; destructor Destroy; Override; function Link : TKDBManager; overload; procedure ExecSQL(ASql, AName : String); function GetConnection(const AUsage: String): TKDBConnection; procedure connection(usage : String; proc : TKDBConnectionProc); procedure SaveSettings(ASettings : TSettingsAdapter); virtual; abstract; property MaxConnCount : Integer Read FMaxConnCount write SetMaxConnCount; property CurrConnCount: Integer Read GetCurrentCount; property CurrUseCount : Integer read GetCurrentUse; property Logger : TKDBLogger read FDBLogger; property Platform: TKDBPlatform read GetDBPlatform; property Provider : TKDBProvider read GetDBProvider; property DBDetails: String read GetDBDetails; Property Driver : String read GetDriver; function GetConnSummary : String; property Tag : integer read FTag write FTag; Property ServerIsAvailable : Boolean read FServerIsAvailable; Function ServerErrorStatus : String; property Name : string read FName; property OnChangeConnectionCount : TOnChangeConnectionCount Read FOnChangeConnectionCount Write FOnChangeConnectionCount; class function IsSupportAvailable(APlatform : TKDBPlatform; Var VMsg : String):Boolean; virtual; abstract; end; TKDBManagerClass = class of TKDBManager; TKDBManagerEvent = procedure (AConnMan : TKDBManager; ABeingCreated : Boolean) of object; TKDBHook = class (TAdvObject) private FHook : TKDBManagerEvent; FName : String; public constructor create(Name : String; Hook : TKDBManagerEvent); end; TKDBManagerList = class (TAdvObject) private FLock : TCriticalSection; FHooks : TAdvList<TKDBHook>; FList : TList<TKDBManager>; procedure AddConnMan(AConnMan : TKDBManager); procedure RemoveConnMan(AConnMan : TKDBManager); function GetConnMan(i : Integer):TKDBManager; function GetConnManByName(s : String):TKDBManager; public constructor Create; override; destructor Destroy; override; procedure Lock; procedure UnLock; property ConnMan[i : Integer]:TKDBManager read GetConnMan; property ConnManByName[s : String]:TKDBManager read GetConnManByName; default; function HasConnManByName(s : String) : Boolean; procedure RegisterHook(AName : String; AHook : TKDBManagerEvent); procedure UnRegisterHook(AName : String); function dump : String; end; {@routine DescribeType Get a string Description of a given column type } function DescribeType(AColType: TKDBColumnType): String; function KDBManagers : TKDBManagerList; implementation uses // Windows, ThreadSupport, ErrorSupport; const ASSERT_UNIT = 'KDBManager'; KDB_COLUMN_TYPE_NAMES : Array [TKDBColumnType] of String = ('ctUnknown', 'ctBoolean', 'ctInteger', 'ctNumeric', 'ctFloat', 'ctChar', 'ctDateTime', 'ctBlob', 'ctInt64', 'ctUnicode'); KDB_TABLE_TYPE_NAMES : Array [TKDBTableType] of String = ('kdbUser', 'kdbView', 'kdbSystem'); var GManagers : TKDBManagerList = nil; { TKDBConnection } constructor TKDBConnection.Create(AOwner: TKDBManager); var i : integer; begin inherited create; FNoFree := false; FOwner := AOwner; FUsage := ''; FHolder := nil; FTag := 0; FSQL := ''; FTerminated := true; FInTransaction := false; FBoundItems := TAdvMap<TKDBBoundParam>.create; FTables := TStringList.create; end; destructor TKDBConnection.Destroy; begin FBoundItems.free; FTables.free; inherited; end; procedure TKDBConnection.BindBlob(AParamName: String; AParamValue: TBytes); begin BindBlobV(AParamName, AParamValue); end; procedure TKDBConnection.BindBlobFromString(AParamName, AParamValue: String); var b : TBytes; begin b := TEncoding.UTF8.GetBytes(AParamValue); BindBlob(AParamName, b); end; procedure TKDBConnection.BindIntegerFromBoolean(AParamName: String; AParamValue: Boolean); begin if AParamValue then begin BindInteger(AParamName, 1); end else begin BindInteger(AParamName, 0); end; end; function TKDBConnection.CountSQL(ASql: String): Cardinal; begin FSQL := ASql; Prepare; try Execute; if not FetchNext then result := 0 else Result := ColInteger[1]; finally Terminate; end; end; procedure TKDBConnection.Error(AException: Exception; AErrMsg : string =''); begin FOwner.Error(self, AException, AErrMsg); end; function TKDBConnection.ExecSQL(ASql: String; rows : integer) : integer; begin FSQL := ASql; Prepare; try Execute; result := GetRowsAffected; if (result <> rows) then raise Exception.Create('Error running sql - wrong row count (expected '+inttostr(rows)+', affected '+inttostr(result)+' for sql '+asql+')'); finally Terminate; end; end; Function TKDBConnection.ExecSQL(ASql: String) : integer; begin if asql = '' then exit; FSQL := ASql; Prepare; try Execute; result := GetRowsAffected; finally Terminate; end; end; procedure TKDBConnection.ExecSQLBatch(ASql: array of String); var i: Integer; begin if InTransaction then begin for i := low(ASql) to high(ASql) do ExecSQL(ASql[i]); end else begin StartTransact; try for i := low(ASql) to high(ASql) do ExecSQL(ASql[i]); Commit; except on e : exception do begin Rollback; recordStack(e); raise; end; end; end; end; function TKDBConnection.GetColDoubleByName(AName: String): Double; begin result := GetColDouble(ColByName(AName)); end; function TKDBConnection.GetColInt64ByName(AName: String): Int64; begin result := GetColInt64(ColByName(AName)); end; function TKDBConnection.GetColIntegerByName(AName: String): Integer; begin result := GetColInteger(ColByName(AName)); end; function TKDBConnection.GetColKeyByName(AName: String): Integer; begin result := GetColKey(ColByName(AName)); end; function TKDBConnection.GetColNullByName(AName: String): Boolean; begin result := GetColNull(ColByName(AName)); end; function TKDBConnection.GetColStringByName(AName: String): String; begin result := GetColString(ColByName(AName)); end; function TKDBConnection.GetColTimeStampByName(AName: String): DateSupport.TTimestamp; begin result := GetColTimestamp(ColByName(AName)); end; function TKDBConnection.GetColDateTimeExByName(AName: String): TDateTimeEx; begin result := TDateTimeEx.fromTS(GetColTimestamp(ColByName(AName))); end; function TKDBConnection.GetColTypeByName(AName: String): TKDBColumnType; begin result := GetColType(ColByName(AName)); end; procedure TKDBConnection.Release; begin FOwner.Release(self); end; function TKDBConnection.Lookup(ATableName, AKeyField, AKeyValue, AValueField, ADefault: String): String; begin result := LookupInternal(ATableName, AKeyField, AKeyValue, AValueField, ADefault, False); end; function TKDBConnection.LookupString(ATableName, AKeyField, AKeyValue, AValueField, ADefault: String): String; begin result := LookupInternal(ATableName, AKeyField, AKeyValue, AValueField, ADefault, True); end; function TKDBConnection.LookupInternal(ATableName, AKeyField, AKeyValue, AValueField, ADefault: String; bAsString : Boolean): String; var FVal : Double; begin if StringIsInteger32(AKeyValue) and not bAsString then FSQL := 'Select ' + AValueField + ' from ' + ATableName + ' where ' + AKeyField + ' = ' + AKeyValue else FSQL := 'Select ' + AValueField + ' from ' + ATableName + ' where ' + AKeyField + ' = ''' + AKeyValue + ''''; Prepare; try Execute; if FetchNext then begin case ColTypeByName[AValueField] of ctUnknown: raise EKDBException.Create('Field type UNKNOWN not supported in a macro lookup'); ctBoolean: raise EKDBException.Create('Field type Boolean not supported in a macro lookup'); ctBlob: raise EKDBException.Create('Field type Blob not supported in a macro lookup'); ctInteger, ctInt64, ctNumeric: begin Result := IntToStr(ColIntegerByName[AValueField]); end; ctFloat: begin // ok, well, we will try to get it as an integer if we can. FVal := ColDoubleByName[AValueField]; if abs(FVal - trunc(FVal)) < 0.00001 then // allow for float uncertainty result := inttostr(round(FVal)) else result := FloatToStrF(FVal, ffGeneral, 4, 4); end; ctChar: begin Result := ColStringByName[AValueField]; end; ctDateTime: begin Result := FormatDateTime('c', TsToDateTime(ColTimeStampByName[AValuefield])); end; else begin raise EKDBException.Create('Field type unknown in a macro lookup'); end; end; end else begin Result := ADefault; end; finally Terminate; end; end; procedure TKDBConnection.Prepare; begin FTerminated := false; FBoundItems.Clear; inc(FPrepareCount); PrepareV; end; function TKDBConnection.FetchNext: Boolean; begin inc(FRowCount); result := FetchNextV; end; procedure TKDBConnection.Terminate; begin FTerminated := true; TerminateV; end; procedure TKDBConnection.StartTransact; begin StartTransactV; FInTransaction := true; FTransactionId := NewGuidId; end; procedure TKDBConnection.Commit; begin // order here is important. // if the commit fails, then a rollback is required, so we are still in the transaction CommitV; FInTransaction := False; end; procedure TKDBConnection.Rollback; begin FInTransaction := False; RollbackV; end; procedure TKDBConnection.KeepBoundObj(sName : String; AObj : TKDBBoundParam); begin FBoundItems.AddOrSetValue(sName, aObj); end; function TKDBConnection.link: TKDBConnection; begin result := TKDBConnection(inherited link); end; function TKDBConnection.GetTables : TStrings; begin FTables.Clear; ListTables(FTables); result := FTables; end; procedure TKDBConnection.BindDouble(AParamName: String; AParamValue: Double); begin BindDoubleV(AParamName, AParamValue); end; procedure TKDBConnection.BindInt64(AParamName: String; AParamValue: Int64); begin BindInt64V(AParamName, AParamValue); end; procedure TKDBConnection.BindInteger(AParamName: String; AParamValue: Integer); begin BindIntegerV(AParamName, AParamValue); end; procedure TKDBConnection.BindKey(AParamName: String; AParamValue: Integer); begin BindKeyV(AParamName, AParamValue); end; procedure TKDBConnection.BindNull(AParamName: String); begin BindNullV(AParamName); end; procedure TKDBConnection.BindString(AParamName, AParamValue: String); begin BindStringV(AParamName, AParamValue); end; procedure TKDBConnection.BindStringOrNull(AParamName, AParamValue: String); begin if AParamValue = '' then BindNull(aParamName) else BindString(aParamName, AParamValue); end; procedure TKDBConnection.BindTimeStamp(AParamName: String; AParamValue: TTimeStamp); begin BindTimeStampV(AParamName, AParamValue); end; procedure TKDBConnection.ClearDatabase; begin ClearDatabaseV; end; function TKDBConnection.ColByName(AColName: String): Integer; begin result := ColByNameV(AColName); end; function TKDBConnection.ColName(ACol: Integer): String; begin result := ColNameV(ACol); end; procedure TKDBConnection.Execute; begin ExecuteV; end; procedure TKDBConnection.RenameColumn(ATableName, AOldColumnName, ANewColumnName, AColumnDetails: String); begin RenameColumnV(ATableName, AOldColumnName, ANewColumnName, AColumnDetails); end; procedure TKDBConnection.RenameTable(AOldTableName, ANewTableName: String); begin RenameTableV(AoldTableName, ANewTableName); end; function TKDBConnection.FetchMetaData: TKDBMetaData; begin result := FetchMetaDataV; end; function TKDBConnection.GetColBlob(ACol: Integer): TBytes; begin result := GetColBlobV(ACol); end; function TKDBConnection.GetColBlobAsString(ACol: Integer): String; begin result := TEncoding.UTF8.GetString(ColBlob[aCol]); end; function TKDBConnection.GetColBlobAsStringByName(AName: String): String; begin result := TEncoding.UTF8.GetString(ColBlobByName[AName]); end; function TKDBConnection.GetColBlobByName(AName: String): TBytes; begin result := GetColBlob(ColByName(AName)); end; function TKDBConnection.GetColCount: Integer; begin result := GetColCountV; end; function TKDBConnection.GetColDouble(ACol: Integer): Double; begin result := GetColDoubleV(ACol); end; function TKDBConnection.GetColInt64(ACol: Integer): Int64; begin result := GetColInt64V(ACol); end; function TKDBConnection.GetColInteger(ACol: Integer): Integer; begin result := GetColIntegerV(ACol); end; function TKDBConnection.GetColKey(ACol: Integer): Integer; begin result := GetColKeyV(ACol); end; function TKDBConnection.GetColNull(ACol: Integer): Boolean; begin result := GetColNullV(ACol); end; function TKDBConnection.GetColString(ACol: Integer): String; begin result := GetColStringV(ACol); end; function TKDBConnection.GetColTimestamp(ACol: Integer): TTimestamp; begin result := GetColTimestampV(ACol); end; function TKDBConnection.GetColDateTimeEx(ACol: Integer): TDateTimeEx; begin result := GetColDateTimeExV(ACol); end; function TKDBConnection.GetColType(ACol: Integer): TKDBColumnType; begin result := GetColTypeV(ACol); end; function TKDBConnection.GetRowsAffected: Integer; begin result := GetRowsAffectedV; end; procedure TKDBConnection.ListTables(AList: TStrings); begin ListTablesV(AList); end; procedure TKDBConnection.DropTable(ATableName: String); begin DropTableV(ATableName); end; procedure TKDBConnection.DropColumn(ATableName, AColumnName: String); begin DropColumnV(ATableName, AColumnName); end; function TKDBConnection.ExistsByKey(const sTableName, sKeyField: String; ikey: Integer): Boolean; begin result := CountSQL('Select '+sKeyField+' from '+sTableName+' where '+sKeyField+' = '+inttostr(iKey)) > 0; end; procedure TKDBConnection.BindDateTimeEx(AParamName: String; AParamValue: TDateTimeEx); begin BindDateTimeExV(aParamName, AParamValue); end; function TKDBConnection.DatabaseSize : int64; Begin result := DatabaseSizeV; End; Function TKDBConnection.TableSize(sName : String):int64; Begin result := TableSizeV(sName); End; function TKDBConnection.SupportsSizing : Boolean; Begin result := SupportsSizingV; End; { TKDBManager } constructor TKDBManager.Create(AName : String; AMaxConnCount: Integer); begin inherited create; FName := AName; FMaxConnCount := AMaxConnCount; FLock := TCriticalSection.create; FDBLogger := TKDBLogger.create; FSemaphore := TSemaphore.Create(nil, 0, 4{ $FFFF}, ''); FWaitCreate := false; FConnections := TAdvList<TKDBConnection>.create; FAvail := TAdvList<TKDBConnection>.create; FInUse := TAdvList<TKDBConnection>.create; FClosing := false; GManagers.AddConnMan(self); init; end; procedure TKDBManager.init; begin end; destructor TKDBManager.Destroy; begin FClosing := true; if GManagers <> nil then GManagers.RemoveConnMan(self); FAvail.free; FInUse.free; FConnections.Free; FSemaphore.free; FDBLogger.free; FLock.Free; inherited; end; function TKDBManager.GetCurrentCount: Integer; begin FLock.Enter; try result := FConnections.Count; finally FLock.Leave; end; end; procedure TKDBManager.CheckWait; begin if FWaitCreate then begin FLock.Lock; try inc(FThreadWaitCount); finally FLock.Unlock; end; try if FSemaphore.WaitFor(DEFAULT_CONNECTION_WAIT_LENGTH) = wrError then raise EKDBException.Create('['+Name+'] KDBManager Wait Failed - ' + ErrorAsString(GetLastError)); finally FLock.Lock; try dec(FThreadWaitCount); finally FLock.Unlock; end; end; end; end; function TKDBManager.GetConnection(const AUsage: String): TKDBConnection; var LCreateNew: Boolean; begin CheckWait; result := PopAvail; if not assigned(result) then begin // there's a small chance that we will get more than the max number of exceptions // with this locking strategy. This is a better outcome that other performance options LCreateNew := (CurrConnCount < MaxConnCount) or (MaxConnCount = 0); if LCreateNew then begin try result := ConnectionFactory; except on e:exception do begin FLock.Enter; Try FServerIsAvailable := False; FLastServerError := e.message; Finally FLock.Leave; End; recordStack(e); raise; end; end; FLock.Enter; Try FConnections.Add(result); FServerIsAvailable := true; FLastServerError := ''; Finally FLock.Leave; End; result.FNoFree := true; FLock.Enter; try FWaitCreate := (FMaxConnCount > 0) and (FConnections.Count = FMaxConnCount); finally FLock.Leave; end; if Assigned(FOnChangeConnectionCount) Then FOnChangeConnectionCount(self); end else begin raise EKDBException.create('No Database Connections Available for "'+AUsage+'" (used: '+GetConnSummary+')'); end; end; FLock.Enter; // lock this because of debugger try result.FUsage := AUsage; result.FUsed := now; result.FRowCount := 0; result.FPrepareCount := 0; result.Sql := ''; FInUse.Add(result.Link); finally FLock.Leave; end; end; procedure TKDBManager.Release(AConn : TKDBConnection); var LDispose : boolean; LIndex : integer; s : String; begin FDBLogger.RecordUsage(AConn.Usage, AConn.FUsed, AConn.FRowCount, AConn.FPrepareCount, nil, ''); FLock.Enter; // must lock because of the debugger try LDispose := (FConnections.count > FMaxConnCount) and (FMaxConnCount > 0); LIndex := FInUse.IndexOf(AConn); FInUse.Delete(LIndex); FLastServerGood := now; FServerIsAvailable := true; s := AConn.FUsage; AConn.FUsage := ''; AConn.FUsed := 0; if LDispose then begin FConnections.Remove(AConn); FWaitCreate := (FMaxConnCount > 0) and (FConnections.count = FMaxConnCount); end else begin FAvail.Add(AConn.Link); try if FThreadWaitCount > 0 then FSemaphore.Release; except on e : exception do Writeln('Error releasing semaphore for '+s+': '+e.message+' for '+s); end; end; finally FLock.Leave; end; if LDispose then begin AConn.FNoFree := false; try AConn.free; except end; if Assigned(FOnChangeConnectionCount) Then FOnChangeConnectionCount(self); end; end; procedure TKDBManager.Error(AConn : TKDBConnection; AException: Exception; AErrMsg : string); var LIndex : integer; s : String; begin FDBLogger.RecordUsage(AConn.Usage, AConn.FUsed, AConn.FRowCount, AConn.FPrepareCount, AException, AErrMsg); FLock.Enter; // must lock because of the debugger try LIndex := FInUse.IndexOf(AConn); if LIndex > -1 then begin FInUse.Delete(LIndex); end; FConnections.Remove(AConn); FWaitCreate := (FMaxConnCount > 0) and (FConnections.count > FMaxConnCount div 2); if FAvail.Count = 0 then begin FServerIsAvailable := false; FLastServerError := AException.message; End; try if FThreadWaitCount > 0 then FSemaphore.Release; except on e : exception do raise Exception.Create('Error (2) releasing semaphore for '+AConn.Usage+': '+e.message+'. please report this error to grahameg@gmail.com (original error = "'+AException.Message+'"'); end; finally FLock.Leave; end; if Assigned(FOnChangeConnectionCount) Then FOnChangeConnectionCount(self); end; function TKDBManager.GetConnSummary: String; var i : integer; begin result := ''; FLock.Enter; try for i := 0 to FInUse.Count - 1 do begin StringAppend(result, (FInUse[i] as TKDBConnection).FUsage+' '+DescribePeriod(now - (FInUse[i] as TKDBConnection).FUsed)+' ('+(FInUse[i] as TKDBConnection).SQL+')', ','); end; if result <> '' then begin result := 'InUse '+inttostr(FInUse.Count)+' of '+inttostr(FConnections.count)+': '+result; end else begin result := inttostr(FConnections.count)+' Connections Resting'; end; finally FLock.Leave; end; end; function TKDBManager.GetCurrentUse: Integer; begin FLock.Enter; try result := FInUse.Count; finally FLock.Leave; end; end; function TKDBManager.Link: TKDBManager; begin result := TKDBManager(inherited link); end; function TKDBManager.PopAvail: TKDBConnection; begin FLock.Enter; try if FAvail.Count > 0 then begin result := FAvail[FAvail.count - 1]; FAvail.Delete(FAvail.count - 1); end else begin result := nil; end; finally FLock.Leave; end; end; procedure TKDBManager.ExecSQL(ASql, AName : String); var LConn : TKDBConnection; begin LConn := GetConnection(AName); try LConn.ExecSQL(ASql); LConn.Release; except on e:exception do begin LConn.Error(e); recordStack(e); raise; end; end; end; function KDBManagers : TKDBManagerList; begin result := GManagers; end; function DescribeType(AColType: TKDBColumnType): String; begin case AColType of ctUnknown: begin Result := 'Unknown'; end; ctBoolean: begin Result := 'Boolean'; end; ctInteger: begin Result := 'Integer'; end; ctNumeric: begin Result := 'Numeric'; end; ctFloat: begin Result := 'Float'; end; ctChar: begin Result := 'Char'; end; ctDateTime: begin Result := 'DateTime'; end; ctBlob: begin Result := 'Blob'; end; ctInt64: begin Result := 'Int64'; end; else begin Result := ('Unknown columntype?'); end; end; end; procedure TKDBManager.SetMaxConnCount(const Value: Integer); begin FLock.Enter; try FMaxConnCount := Value; finally FLock.Leave; end; end; procedure TKDBManager.connection(usage: String; proc: TKDBConnectionProc); var conn : TKDBConnection; begin conn := GetConnection(usage); try proc(conn); conn.Release; except on e : exception do begin conn.Error(e); raise; end; end; end; { TKDBManagerList } constructor TKDBManagerList.create; begin inherited create; FLock := TCriticalSection.create; FHooks := TAdvList<TKDBHook>.create; FList := TList<TKDBManager>.create; end; destructor TKDBManagerList.destroy; begin FLock.free; FHooks.free; FList.Free; inherited; end; function TKDBManagerList.dump: String; var i : integer; begin result := ''; for i := 0 to FList.Count - 1 do result := result + FList[i].FName+' : '+ FList[i].GetConnSummary+#13#10; end; procedure TKDBManagerList.AddConnMan(AConnMan : TKDBManager); var i : integer; begin Lock; try FList.Add(AConnMan); for i := 0 to FHooks.count -1 do FHooks[i].FHook(AConnMan, true); finally Unlock; end; end; procedure TKDBManagerList.RemoveConnMan(AConnMan : TKDBManager); var i : integer; begin Lock; try for i := 0 to FHooks.count -1 do FHooks[i].FHook(AConnMan, false); FList.Remove(AConnMan); finally Unlock; end; end; function TKDBManagerList.GetConnMan(i : Integer):TKDBManager; begin result := FList[i]; end; function TKDBManagerList.HasConnManByName(s : String) : Boolean; begin result := GetConnManByName(s) <> nil; End; function TKDBManagerList.GetConnManByName(s : String):TKDBManager; var k : TKDBManager; begin result := nil; for k in FList do if k.Name = s then begin result := k; exit; end; end; procedure TKDBManagerList.Lock; begin FLock.Enter; end; procedure TKDBManagerList.UnLock; begin FLock.Leave; end; procedure TKDBManagerList.RegisterHook(AName : String; AHook : TKDBManagerEvent); begin FHooks.Add(TKDBHook.create(AName, AHook)); end; procedure TKDBManagerList.UnRegisterHook(AName : String); var i : integer; begin for i := FHooks.Count - 1 downto 0 do if FHooks[i].FName = AName then FHooks.Delete(i); end; { TKDBHook } constructor TKDBHook.create(Name : String; Hook : TKDBManagerEvent); begin inherited create; FName := name; FHook := Hook; end; { TKDBColumn } constructor TKDBColumn.Create(name: String); begin inherited create; self.Name := name; end; function TKDBColumn.Describe : String; begin case FDataType of ctBoolean : result := FName + ' : bool'; ctInteger : result := FName + ' : int'; ctNumeric : result := FName + ' : numeric'; ctFloat : result := FName + ' : float'; ctChar : result := FName + ' : char('+inttostr(FLength)+')'; ctDateTime : result := FName + ' : dateTime'; ctBlob : result := FName + ' : Binary'; ctInt64 : result := FName + ' : int64'; ctUnicode : result := FName + ' : nChar('+inttostr(FLength)+')'; else {ctUnknown:} result := FName + ' : unknown'; end; if not FNullable then begin result := result +' [not Null]'; end; end; function TKDBColumn.Link: TKDBColumn; begin result := TKDBColumn(Inherited Link); end; function CommaText(list : TAdvList<TKDBColumn>) : String; var s : TStringBuilder; b : boolean; c : TKDBColumn; begin b := false; s := TStringBuilder.Create; try for C in list do begin if (b) then s.Append(',') else b := true; s.Append(C.Name); end; finally s.Free; end; end; { TKDBIndex } constructor TKDBIndex.create; begin inherited; FColumns := TAdvList<TKDBColumn>.create; end; destructor TKDBIndex.destroy; begin FColumns.Free; inherited; end; function TKDBIndex.Describe : String; begin if FUnique then begin Result := 'UNIQUE '; end else begin Result := ''; end; Result := Result + 'INDEX ' + FName + ' ON (' + CommaText(FColumns) + ')'; end; function TKDBRelationship.Describe : String; Begin result := FColumn + ' -> '+FDestTable+'.'+FDestColumn; End; { TKDBTable } constructor TKDBTable.create; begin inherited; FColumns := TAdvList<TKDBColumn>.CREATE; FIndexes := TAdvList<TKDBIndex>.create; FRelationships := TAdvList<TKDBRelationship>.create; end; destructor TKDBTable.destroy; begin FRelationships.Free; FColumns.Free; FIndexes.Free; inherited; end; function TKDBTable.hasColumn(name: String): boolean; var c : TKDBColumn; begin result := false; for c in FColumns do result := result or (c.Name = name); end; function TKDBTable.Link: TKDBTable; begin result := TKDBTable(inherited link); end; { TKDBMetaData } constructor TKDBMetaData.create; begin inherited; FTables := TAdvList<TKDBTable>.create; FProcedures := TStringList.create; end; destructor TKDBMetaData.destroy; begin FTables.Free; FProcedures.Free; inherited; end; function TKDBMetaData.GetTable(name: String): TKDBTable; var i : integer; begin result := nil; for i := 0 to Tables.Count - 1 do if Tables[i].Name = name then result := Tables[i]; end; function TKDBMetaData.HasTable(name: String): boolean; var i : integer; begin result := false; for i := 0 to Tables.Count - 1 do if Tables[i].Name = name then result := true; end; Function TKDBManager.ServerErrorStatus : String; Begin FLock.Enter; try if ServerIsAvailable then result := '' else result := 'Database '+DBDetails+' has been unavailable for '+DescribePeriod(now - FLastServerGood)+'. Last Error = '+FLastServerError; Finally FLock.Leave; End; End; procedure CloseUPGManagers; var m : TKDBManagerList; begin m := GManagers; GManagers := nil; m.free; end; initialization GManagers := TKDBManagerList.create; finalization CloseUPGManagers; end.
unit uRendererVCL; interface uses VCL.Graphics, uSimpleRayTracer; type TRendererVCL = class private FSimpleRayTracer: TSimpleRayTracer; public constructor Create(aWidth, aHeight: integer; aAntiAlias: integer = 1); destructor Destroy; override; function DoRender: TBitmap; end; implementation uses System.Types; { TRendererVCL } constructor TRendererVCL.Create(aWidth, aHeight, aAntiAlias: integer); begin FSimpleRayTracer := TSimpleRayTracer.Create(aWidth, aHeight, aAntiAlias); end; destructor TRendererVCL.Destroy; begin FSimpleRayTracer.Free; inherited; end; function TRendererVCL.DoRender: TBitmap; var bmp: TBitmap; CurrRow, OffSet: integer; x,y: integer; pRed, pGreen, pBlue, pAlpha: PByte; c: RGBType; h: integer; begin FSimpleRayTracer.CalculatePixelColors; bmp := TBitmap.Create; bmp.PixelFormat := pf24bit; bmp.Width := FSimpleRayTracer.getWidth; bmp.Height := FSimpleRayTracer.getHeight; h := FSimpleRayTracer.getHeight; CurrRow := Integer(bmp.ScanLine[0]); OffSet := Integer(bmp.ScanLine[1]) - CurrRow; for y := 0 to bmp.Height - 1 do begin for x := 0 to bmp.Width - 1 do begin pBlue := pByte(CurrRow + x*3); pGreen := pByte(CurrRow + x*3 + 1); pRed := pByte(CurrRow + x*3 + 2); pAlpha := pByte(CurrRow + x*3 + 3); c := FSimpleRayTracer.getPixelData(x, h-y); pBlue^ := round(c.b * 255); pGreen^ := round(c.g * 255); pRed^ := round(c.r * 255); pAlpha^ := 255; end; inc(CurrRow, OffSet); end; Result := bmp; end; end.
unit BusinessObjects; interface uses MVCFramework.Serializer.Commons; type TBaseBO = class private FID: Integer; procedure SetID(const Value: Integer); public procedure CheckInsert; virtual; procedure CheckUpdate; virtual; procedure CheckDelete; virtual; property ID: Integer read FID write SetID; end; [MVCNameCase(ncLowerCase)] TArticle = class(TBaseBO) private FPrice: Currency; FCode: string; FDescription: string; procedure SetCode(const Value: string); procedure SetDescription(const Value: string); procedure SetPrice(const Value: Currency); public procedure CheckInsert; override; procedure CheckUpdate; override; procedure CheckDelete; override; [MVCColumn('CODICE')] property Code: string read FCode write SetCode; [MVCColumn('DESCRIZIONE')] property Description: string read FDescription write SetDescription; [MVCColumn('PREZZO')] property Price: Currency read FPrice write SetPrice; end; implementation uses System.SysUtils, System.RegularExpressions; { TBaseBO } procedure TBaseBO.CheckDelete; begin end; procedure TBaseBO.CheckInsert; begin end; procedure TBaseBO.CheckUpdate; begin end; procedure TBaseBO.SetID(const Value: Integer); begin FID := Value; end; { TArticolo } procedure TArticle.CheckDelete; begin inherited; if Price <= 5 then raise Exception.Create('Cannot delete an article with a price below 5 euros (yes, it is a silly check)'); end; procedure TArticle.CheckInsert; begin inherited; if not TRegEx.IsMatch(Code, '^C[0-9]{2,4}') then raise Exception.Create('Article code must be in the format "CXX or CXXX or CXXXX"'); end; procedure TArticle.CheckUpdate; begin inherited; CheckInsert; if Price <= 2 then raise Exception.Create('We cannot sell so low cost pizzas!'); end; procedure TArticle.SetCode(const Value: string); begin FCode := Value; end; procedure TArticle.SetDescription(const Value: string); begin FDescription := Value; end; procedure TArticle.SetPrice(const Value: Currency); begin FPrice := Value; end; end.
unit UFrameFilter; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFmFilter, StdCtrls, ExtCtrls, UFileBaseInfo, siComp, UMainForm; type TFrameFilterPage = class(TFrame) plInclude: TPanel; gbIncludeFilter: TGroupBox; FrameInclude: TFrameFilter; plExclude: TPanel; gbExcludeFilter: TGroupBox; FrameExclude: TFrameFilter; siLang_FrameFilterPage: TsiLang; private { Private declarations } public procedure IniFrame; procedure SetDefaultStatus; public procedure SetRootPathList( RootPathList : TStringList ); procedure SetIncludeFilterList( FilterList : TFileFilterList ); procedure SetExcludeFilterList( FilterList : TFileFilterList ); public function getIncludeFilterList : TFileFilterList; function getExcludeFilterList : TFileFilterList; public procedure RefreshLanguage; end; implementation {$R *.dfm} { TFrame1 } function TFrameFilterPage.getExcludeFilterList: TFileFilterList; begin Result := FrameExclude.getFilterList; end; function TFrameFilterPage.getIncludeFilterList: TFileFilterList; begin Result := FrameInclude.getFilterList; end; procedure TFrameFilterPage.IniFrame; begin FrameInclude.SetIsInclude( True ); FrameExclude.SetIsInclude( False ); end; procedure TFrameFilterPage.RefreshLanguage; begin FrameInclude.RefreshLanguage; FrameExclude.RefreshLanguage; end; procedure TFrameFilterPage.SetDefaultStatus; begin FrameInclude.SetDefaultStatus; FrameExclude.SetDefaultStatus; end; procedure TFrameFilterPage.SetExcludeFilterList(FilterList: TFileFilterList); begin FrameExclude.SetFilterList( FilterList ); end; procedure TFrameFilterPage.SetIncludeFilterList(FilterList: TFileFilterList); begin FrameInclude.SetFilterList( FilterList ); end; procedure TFrameFilterPage.SetRootPathList(RootPathList: TStringList); begin FrameInclude.SetRootPathList( RootPathList ); FrameExclude.SetRootPathList( RootPathList ); end; end.
unit fEscolheAnimal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AdvEdit, DB, ADODB, Grids, BaseGrid, AdvGrid, DBAdvGrid, ExtCtrls, AdvObj, fFormPesquisa, Entidades.Cadastro, Aurelius.Bind.Dataset, ActnList, System.Actions; type TfmEscolheAnimal = class(TfmFormPesquisa) AureliusDataset1: TAureliusDataset; AureliusDataset1Self: TAureliusEntityField; AureliusDataset1Id: TIntegerField; AureliusDataset1Nome: TStringField; AureliusDataset1DataNascimento: TDateTimeField; AureliusDataset1Proprietario: TAureliusEntityField; AureliusDataset1Especie: TStringField; AureliusDataset1Raca: TStringField; AureliusDataset1Sexo: TStringField; AureliusDataset1Observacoes: TMemoField; AureliusDataset1ProprietarioNome: TStringField; Button1: TButton; Button3: TButton; ActionList1: TActionList; acEditar: TAction; acNovo: TAction; procedure acEditarExecute(Sender: TObject); procedure acNovoExecute(Sender: TObject); procedure acEditarUpdate(Sender: TObject); protected function Dataset: TAureliusDataset; override; procedure FilterRecord(DataSet: TDataSet; AText: string; var Accept: Boolean); override; end; implementation uses fAnimal, Math; {$R *.dfm} procedure TfmEscolheAnimal.acEditarExecute(Sender: TObject); begin if TfmAnimal.Editar(AureliusDataset1.Current<TAnimal>.Id) then AtualizaListagem; end; procedure TfmEscolheAnimal.acEditarUpdate(Sender: TObject); begin acEditar.Enabled := AureliusDataset1.Current<TAnimal> <> nil; end; procedure TfmEscolheAnimal.acNovoExecute(Sender: TObject); begin if TfmAnimal.Editar(Null) then AtualizaListagem; end; function TfmEscolheAnimal.Dataset: TAureliusDataset; begin Result := AureliusDataset1; end; procedure TfmEscolheAnimal.FilterRecord(DataSet: TDataSet; AText: string; var Accept: Boolean); begin Accept := (AText = '') or (Pos(Uppercase(AText), Uppercase(Dataset.FieldByName('Nome').AsString)) > 0) or (Pos(Uppercase(AText), Uppercase(Dataset.FieldByName('Proprietario.Nome').AsString)) > 0) end; end.
UNIT CRT1; { расширение модуля CRT для задания практикума "Интерфейс программы сортировки" } INTERFACE procedure getcolors(var fc,bc:byte); {запрос текущих переднего (fc) и фонового (bc) цветов} procedure windcoord(var x1,y1,x2,y2:byte); {запрос координат текущего окна (нумерация абсолютная, с 1): (x1,y1) - левый верхний угол (x1-столбец, y1-строка) (x2,y2) - правый нижний угол} function getch(x,y:byte):char; {запрос символа, высвечиваемого в x-й колонке y-й строки окна} function getattr(x,y:byte):byte; {запрос атрибута символа, что в x-й колонке y-й строки окна} procedure putch(x,y:byte; c:char); {запись символа в точку (x,y) окна без изменения атрибута} procedure putattr(x,y:byte; a:byte); {заменить на a атрибут точки (x,y) окна без изменения символа} procedure inkey(var c:char; var spec:boolean); {ввод без эха символа с клавиатуры и присваивание его параметру C; если это управляющий символ, то spec:=true, для обычного spec:=false (Enter, Ecs и Backspace считаются управляющими)} procedure wait; {ждать нажатия любой клавиши (она "глотается")} procedure crsoff; {убрать курсор (сделать невидимым)} procedure crson; {сделать курсор видимым} procedure bell; {звонок} {================================================================} IMPLEMENTATION uses crt; const maxX=80; maxY=25; type pixel=record ch:char; attr:byte end; {элемент образа экрана} var screen80: {видеопамять цветного экрана 25x80} array[1..maxY,1..maxX] of pixel absolute $B800:$0000; procedure testcoord(prname:string; x,y:byte); {проверка координаты точки в окне} var x1,y1,x2,y2:byte; begin windcoord(x1,y1,x2,y2); if (x<1) or (x>x2-x1+1) or (y<1) or (y>y2-y1+1) then begin window(1,1,80,25); gotoXY(1,1); writeln('Error in ',prname,': ','coord. out of window'); write('Press Enter ...'); readln; halt; end; end; procedure getcolors(var fc,bc:byte); {запрос текущих переднего (fc) и фонового (bc) цветов} begin fc:=TextAttr and $F; bc:=(TextAttr shr 4) and $7 end; procedure windcoord(var x1,y1,x2,y2:byte); {запрос координат текущего окна (нумерация абсолютная, с 1): (x1,y1) - левый верхний угол (x1-столбец, y1-строка) (x2,y2) - правый нижний угол} begin x1:=Lo(WindMin)+1; y1:=Hi(WindMin)+1; x2:=Lo(WindMax)+1; y2:=Hi(WindMax)+1; end; function getch(x,y:byte):char; {запрос символа, высвечиваемого в x-й колонке y-й строки окна} begin testcoord('getch',x,y); getch:=screen80[Hi(WindMin)+y,Lo(WindMin)+x].ch; end; function getattr(x,y:byte):byte; {запрос атрибута символа, что в x-й колонке y-й строки окна} begin testcoord('getattr',x,y); getattr:=screen80[Hi(WindMin)+y,Lo(WindMin)+x].attr end; procedure putch(x,y:byte; c:char); {запись символа в точку (x,y) окна без изменения атрибута} begin testcoord('putch',x,y); screen80[Hi(WindMin)+y,Lo(WindMin)+x].ch:=c end; procedure putattr(x,y:byte; a:byte); {заменить на a атрибут точки (x,y) окна без изменения символа} begin testcoord('putattr',x,y); screen80[Hi(WindMin)+y,Lo(WindMin)+x].attr:=a end; procedure inkey(var c:char; var spec:boolean); {ввод без эха символа с клавиатуры и присваивание его параметру C, если это управляющий символ, то spec:=true, обычный - spec:=false (Enter, Ecs и Backspace считаются управляющими) } begin c:=readkey; if c>=#32 then spec:=false else begin spec:=true; if c=#0 then c:=readkey end; end; procedure wait; {ждать нажатия любой клавиши (она "глотается")} var c:char; spec:boolean; begin inkey(c,spec) end; procedure crsoff; {убрать курсор (сделать невидимым)} begin inline( $B4/$03/ {MOV AH,3} $B7/$00/ {MOV BH,0} $CD/$10/ {INT 10h} $80/$CD/$20/ {OR CH,20h} $B4/$01/ {MOV AH,1} $CD/$10 {INT 10h} ); end; procedure crson; {сделать курсор видимым} begin inline( $B4/$03/ {MOV AH,3} $B7/$00/ {MOV BH,0} $CD/$10/ {INT 10h} $80/$E5/$DF/ {AND CH,0BFh} $B4/$01/ {MOV AH,1} $CD/$10 {INT 10h} ); end; procedure bell; {звонок} begin write(#7) end; {=== конец модуля CRT1 ===} end. 
UNIT MxTest; //------------------------------------------------------------------------------ // WinshoeMXResolver Test Demo // //------------------------------------------------------------------------------ // MXResolverTest Written July 21, 1999 // Given a valid DomainName it will return a TStringList of Domain Names for // that domain's mail servers in priority order. That is priority 1 first // 2 second..etc // Many domains such as aol.com or microsoft.com often use several different // Severs to accept mail. Thus sending mail to tbrowkaw@nbc.com does not go // to nbc.com. It goes to ns.ge.com. The MX resolver resolves a domain name // in an email addres to the fully qualified domain name of the mail server(s) // for a domain. // USAGE: // VAR // aDomain : string; // aStrList : TStringList; // // Begin // astrList := tStringList.Create; // aDomain := 'microsoft.com'; // WinshoeMxResolver1.GetMailServers(adomain,aStrList); // With aStrlist do // DoStuff; // aStrList.Free // // Mail servers have a priority. That is if a domain has several mail servers // each server has a priority. When an MX request retuns several mail servers // they are returned in priority order. The first server in the string list // should be tried first. Many large mail services, such as aol.com have // several mail servers. Their priorities are all set to the same value. This // is done to divide the work load evenly between the several servers. Thus // subsequent MX calls to aol.com will produce a returned string list with the // servers in diffenent orders. // // Since ABC radio and TV networks are now owned by Disney, it is interesting // to note that one of the abc.com mail servers is huey.disney.com. Does // anyone know to what tasks, Dewey and Louie are put? The other queston is // does Disney have a computer named goofy? // // // Started Date : 07/20/1999 Version 0.10 Complete : Beta 1.0 07/24/1999 // // Author : Ray Malone // MBS Software // 251 E. 4th St. // Chillicothe, OH 45601 // // MailTo: ray@mbssoftware.com // // //------------------------------------------------------------------------------ INTERFACE USES Windows, Messages, StdCtrls, Classes, Controls, SysUtils, Graphics, Forms, Dialogs, WinShoeDNSResolver, ExtCtrls, ComCtrls, Winshoes, UDPWinshoe; TYPE TMxTestForm = CLASS(TForm) Edit1: TEdit; Memo1: TMemo; ResolveBtn: TButton; Label1: TLabel; Panel1: TPanel; StatusBar: TStatusBar; MXResolver: TWinshoeMXResolver; PROCEDURE FormCreate(Sender: TObject); PROCEDURE ResolveBtnClick(Sender: TObject); PRIVATE { Private declarations } PUBLIC { Public declarations } END; VAR MxTestForm: TMxTestForm; IMPLEMENTATION {$R *.DFM} PROCEDURE TMxTestForm.FormCreate(Sender: TObject); BEGIN StatusBar.SimpleText := 'Name Server: '+MxResolver.Host; Edit1.Text := 'mbssoftware.com'; END; PROCEDURE TMxTestForm.ResolveBtnClick(Sender: TObject); VAR aStrList : TStringList; BEGIN Memo1.Clear; IF Edit1.Text = '' THEN Edit1.Text := 'mbssoftware.com' ELSE BEGIN AstrList := TstringList.Create; TRY MxResolver.GetMailServers(Edit1.Text,aStrList); Memo1.Lines.Add(AstrList.Text); FINALLY AStrList.Free; END; IF Memo1.Lines.Count = 0 THEN Memo1.Lines.Add('No MX Servers Found'); END; END; END.
unit oca.modifiers; interface uses sysutils; const NULLIDX = -1; type idxRange = NULLIDX..MAXINT; tModifiers = (None, Goose, Dice, Bridge, Prison, Inn, Pit, Labyrinth, Death); tOcaModifier = record modifier : tModifiers; cell : integer; next : idxRange; end; tControlRecord = record first : idxRange; erased : idxRange; end; tControl = file of tControlRecord; tData = file of tOcaModifier; tStackOca = record data : tData; control : tControl; end; procedure loadStack (var this : tStackOca; path, filename : string); procedure newEmptyStack (var this : tStackOca; path, filename : string); procedure push (var this : tStackOca; item : tOcaModifier); function peek (var this : tStackOca) : tOcaModifier; function pop (var this : tStackOca) : tOcaModifier; function isEmpty (var this : tStackOca) : boolean; function search (var this : tStackOca; cell : integer; var modifier : tModifiers) : boolean; function nextAfter (var this : tStackOca; modifier : tOcaModifier; var cellnumber : integer) : boolean; function existsCell (var this : tStackOca; cell: integer) : boolean; function generateModifier (var this : tStackOca; modifier : tModifiers; cell: integer) : tOcaModifier; implementation function getControlRecord(var this : tStackOca) : tControlRecord; var Rc : tControlRecord; begin reset(this.control); seek (this.control, 0); read (this.control, Rc); close(this.control); getControlRecord := Rc; end; function quickGetControlRecord(var this : tStackOca) : tControlRecord; var Rc : tControlRecord; begin seek (this.control, 0); read (this.control, Rc); quickGetControlRecord := Rc; end; procedure setControlRecord(var this : tStackOca; Rc : tControlRecord); begin reset(this.control); seek (this.control, 0); write(this.control, Rc); close(this.control); end; procedure quickSetControlRecord(var this : tStackOca; Rc : tControlRecord); begin seek (this.control, 0); write(this.control, Rc); end; procedure loadStack (var this : tStackOca; path, filename : string); var fullFileName : string; Rc : tControlRecord; begin fullFileName := path + filename; //check if data file exists assign(this.data, fullFileName + '.dat'); if not fileexists(fullFileName + '.dat') then rewrite(this.data) else reset(this.data); close(this.data); //check if data file exists assign(this.control, fullFileName + '.ctrl'); if not fileexists(fullFileName + '.ctrl') then begin rewrite(this.control); Rc.first := NULLIDX; Rc.erased := NULLIDX; seek(this.control, 0); write(this.control, Rc); end else reset(this.control); close(this.control); end; procedure newEmptyStack (var this : tStackOca; path, filename : string); var fullFileName : string; Rc : tControlRecord; begin fullFileName := path + filename; //check if data file exists assign(this.data, fullFileName + '.dat'); rewrite(this.data); close(this.data); //check if data file exists assign(this.control, fullFileName + '.ctrl'); rewrite(this.control); Rc.first := NULLIDX; Rc.erased := NULLIDX; seek(this.control, 0); write(this.control, Rc); close(this.control); end; function isEmpty (var this : tStackOca) : Boolean; var Rc : tControlRecord; begin Rc := getControlRecord(this); isEmpty := Rc.first = NULLIDX; end; function quickIsEmpty (var this : tStackOca) : Boolean; var Rc : tControlRecord; begin Rc := quickGetControlRecord(this); quickIsEmpty := Rc.first = NULLIDX; end; // inner function function get (var this : tStackOca; pos : idxRange) : tOcaModifier; var item: tOcaModifier; begin reset (this.data); seek (this.data, pos); read (this.data, item); close (this.data); get := item; end; function quickGet (var this : tStackOca; pos : idxRange) : tOcaModifier; var item: tOcaModifier; begin seek (this.data, pos); read (this.data, item); quickGet := item; end; procedure update (var this : tStackOca; pos : idxRange; var item : tOcaModifier); begin reset (this.data); seek (this.data, pos); write (this.data, item); close (this.data); end; procedure quickUpdate (var this : tStackOca; pos : idxRange; var item : tOcaModifier); begin seek (this.data, pos); write (this.data, item); end; function append (var this : tStackOca; var item : tOcaModifier) : idxRange; var Rc : tControlRecord; pos : idxRange; auxItem : tOcaModifier; begin Rc := getControlRecord(this); pos := NULLIDX; if Rc.erased = NULLIDX then begin reset(this.data); pos := filesize(this.data); seek(this.data, pos); item.next := NULLIDX; write(this.data, item); close(this.data); end else begin pos := Rc.erased; auxItem := get(this, pos); Rc.erased := auxItem.next; item.next := NULLIDX; update(this, pos, item); setControlRecord(this, Rc); end; append := pos; end; function quickAppend (var this : tStackOca; var item : tOcaModifier) : idxRange; var Rc : tControlRecord; pos : idxRange; auxItem : tOcaModifier; begin Rc := quickGetControlRecord(this); pos := NULLIDX; if Rc.erased = NULLIDX then begin pos := filesize(this.data); seek(this.data, pos); item.next := NULLIDX; write(this.data, item); end else begin pos := Rc.erased; auxItem := quickGet(this, pos); Rc.erased := auxItem.next; item.next := NULLIDX; quickUpdate(this, pos, item); quickSetControlRecord(this, Rc); end; quickAppend := pos; end; procedure push (var this : tStackOca; item : tOcaModifier); var auxPos : idxRange; Rc : tControlRecord; begin Rc := getControlRecord(this); if Rc.first = NULLIDX then begin auxPos := append(this, item); Rc := getControlRecord(this); Rc.first := auxPos; end else begin auxPos := append(this, item); Rc := getControlRecord(this); item.next := Rc.first; Rc.first := auxPos; update(this, auxPos, item); end; setControlRecord(this, Rc); end; procedure quickPush (var this : tStackOca; item : tOcaModifier); var auxPos : idxRange; Rc : tControlRecord; begin Rc := quickGetControlRecord(this); if Rc.first = NULLIDX then begin auxPos := quickAppend(this, item); Rc := quickGetControlRecord(this); Rc.first := auxPos; end else begin auxPos := quickAppend(this, item); Rc := quickGetControlRecord(this); item.next := Rc.first; Rc.first := auxPos; quickUpdate(this, auxPos, item); end; quickSetControlRecord(this, Rc); end; function peek (var this : tStackOca) : tOcaModifier; var pos, auxPos : idxRange; auxItem : tOcaModifier; Rc : tControlRecord; begin Rc := getControlRecord(this); if not (Rc.first = NULLIDX) then begin auxItem := get(this, Rc.first); end; peek := auxItem; end; function pop (var this : tStackOca) : tOcaModifier; var pos, auxPos : idxRange; auxItem : tOcaModifier; Rc : tControlRecord; begin Rc := getControlRecord(this); if not (Rc.first = NULLIDX) then begin auxItem := get(this, Rc.first); auxPos := auxItem.next; auxItem.next := Rc.erased; update(this, Rc.first, auxItem); Rc.erased := Rc.first; Rc.first := auxPos; setControlRecord(this, Rc); auxItem.next := NULLIDX; pop := auxItem; end; end; function quickPop (var this : tStackOca) : tOcaModifier; var pos, auxPos : idxRange; auxItem : tOcaModifier; Rc : tControlRecord; begin Rc := quickGetControlRecord(this); if not (Rc.first = NULLIDX) then begin auxItem := quickGet(this, Rc.first); auxPos := auxItem.next; auxItem.next := Rc.erased; quickUpdate(this, Rc.first, auxItem); Rc.erased := Rc.first; Rc.first := auxPos; quickSetControlRecord(this, Rc); auxItem.next := NULLIDX; quickPop := auxItem; end; end; function quickSearch (var this : tStackOca; cell : integer; var modifier : tModifiers) : boolean; var item : tOcaModifier; begin modifier := None; item := quickPop(this); if item.cell = cell then begin modifier := item.modifier; quickSearch := true; end else if quickIsEmpty(this) then quickSearch := false else quickSearch := quickSearch(this, cell, modifier); quickPush(this, item); end; function search (var this : tStackOca; cell : integer; var modifier : tModifiers) : boolean; var found : boolean; begin reset(this.control); reset(this.data); found := quickSearch(this, cell, modifier); close(this.data); close(this.control); search := found; end; function innerNextAfter (var this : tStackOca; modifier : tOcaModifier; var cellnumber : integer; alreadyFound : boolean) : boolean; var item : tOcaModifier; begin if isEmpty(this) then innerNextAfter := false else begin item := pop(this); if alreadyFound then if item.modifier = modifier.modifier then begin cellnumber := item.cell; innerNextAfter := true; end else innerNextAfter := innerNextAfter(this, modifier, cellnumber, alreadyFound) else begin if item.cell = modifier.cell then alreadyFound := true; innerNextAfter := innerNextAfter(this, modifier, cellnumber, alreadyFound); end; push(this, item); end; end; function nextAfter (var this : tStackOca; modifier : tOcaModifier; var cellnumber : integer) : boolean; begin nextAfter := innerNextAfter(this, modifier, cellnumber, false); end; function existsCell (var this : tStackOca; cell: integer) : boolean; var item: tOcaModifier; begin if isEmpty(this) then existsCell := false else begin item := pop(this); if (item.cell = cell) then existsCell := true else existsCell := existsCell(this, cell); push(this, item); end; end; function generateModifier (var this : tStackOca; modifier : tModifiers; cell: integer) : tOcaModifier; var item: tOcaModifier; begin item.modifier := modifier; item.cell := cell; item.next := NULLIDX; generateModifier := item; end; end.
{ *************************************************************************** Copyright (c) 2015-2018 Kike Pérez Unit : Quick.Config.Provider.Json Description : Save config to JSON file Author : Kike Pérez Version : 1.4 Created : 21/10/2017 Modified : 10/12/2018 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Config.Json; {$i QuickLib.inc} interface uses Classes, SysUtils, {$IFDEF DELPHIXE_UP} IOUtils, {$ELSE} Quick.Files, {$ENDIF} Rtti, Quick.Json.Serializer, {$IFDEF FPC} fpjson, fpjsonrtti, {$ELSE} Rest.Json.Types, System.JSON, {$ENDIF} Quick.Config.Base; type TAppConfigJsonProvider = class(TAppConfigProviderBase) private fFilename : string; procedure Load(cConfig : TAppConfig); override; procedure Save(cConfig : TAppConfig); override; public constructor Create; override; property Filename : string read fFilename write fFilename; end; TAppConfigJson = class(TAppConfig) private fProvider : TAppConfigJsonProvider; function GetProvider : IAppConfigProvider; override; public constructor Create; override; destructor Destroy; override; property Provider : TAppConfigJsonProvider read fProvider write fProvider; end; implementation constructor TAppConfigJsonProvider.Create; begin inherited Create; fFilename := TPath.ChangeExtension(ParamStr(0),'json'); end; procedure TAppConfigJsonProvider.Load(cConfig : TAppConfig); var json : TStrings; Serializer : TJsonSerializer; begin //create object with rtti if nil //if not Assigned(Config) then Config := InitObject; if (not FileExists(fFilename)) and (CreateIfNotExists) then begin TAppConfig(cConfig).DefaultValues; Self.Save(cConfig); end; try json := TStringList.Create; try json.LoadFromFile(fFilename); serializer := TJsonSerializer.Create(slPublishedProperty); try //Streamer.Options := Streamer.Options + [jsoDateTimeAsString ,jsoUseFormatString]; //Streamer.DateTimeFormat := 'yyyy-mm-dd"T"hh:mm:ss.zz'; serializer.JsonToObject(cConfig,json.Text); finally serializer.Free; end; finally json.Free; end; except on e : Exception do raise e; end; end; procedure TAppConfigJsonProvider.Save(cConfig : TAppConfig); var json : TStrings; Serializer : TJsonSerializer; ctx : TRttiContext; rprop : TRttiProperty; begin //create object with rtti if nil if not Assigned(cConfig) then cConfig := TAppConfigJson.Create; try json := TStringList.Create; try serializer := TJsonSerializer.Create(TSerializeLevel.slPublishedProperty); try //Streamer.Options := Streamer.Options + [jsoDateTimeAsString ,jsoUseFormatString]; //Streamer.DateTimeFormat := 'yyyy-mm-dd"T"hh:mm:ss.zz'; json.Text := serializer.ObjectToJson(cConfig,True); finally serializer.Free; end; json.SaveToFile(fFilename); cConfig.LastSaved := Now; finally json.Free; end; except on e : Exception do raise e; end; end; { TAppConfigJson } constructor TAppConfigJson.Create; begin inherited; fProvider := TAppConfigJsonProvider.Create; end; destructor TAppConfigJson.Destroy; begin if Assigned(fProvider) then fProvider.Free; inherited; end; function TAppConfigJson.GetProvider: IAppConfigProvider; begin Result := fProvider; end; end.
program ejercicio4; {tipos de datos definidos por el usuario} type cadena = string[50]; rango_act = 1..4; rango_edad = 14..90; {procesos y funciones} procedure cargar_precios(var p1, p2, p3, p4: real); begin write('- Precio 1: '); readln(p1); write('- Precio 2: '); readln(p2); write('- Precio 3: '); readln(p3); write('- Precio 4: '); readln(p4); end; procedure leer_cliente(var ape_nom: cadena; var edad: rango_edad; var act: rango_act); begin write('- Apellido y Nombre: '); readln(ape_nom); IF (ape_nom <> 'ZZZ') THEN BEGIN write('- Edad: '); readln(edad); write('- Actividad elegida: '); readln(act); END; end; {variables del programa principal} var {datos de actividades} precio1, precio2, precio3, precio4: real; {datos del cliente} ape_nom: cadena; edad: rango_edad; act: rango_act; begin writeln('-- DATOS DE LAS ACTIVIDADES --'); writeln; cargar_precios(precio1, precio2, precio3, precio4); writeln; writeln('-- DATOS DE CLIENTES --'); writeln; leer_cliente(ape_nom, edad, act); WHILE (ape_nom <> 'ZZZ') DO BEGIN writeln; CASE act OF 1: writeln('Cliente: ',ape_nom, ' cuota mensual: ', precio1:3:0); 2: writeln('Cliente: ',ape_nom, ' cuota mensual: ', precio2:3:0); 3: writeln('Cliente: ',ape_nom, ' cuota mensual: ', precio3:3:0); 4: writeln('Cliente: ',ape_nom, ' cuota mensual: ', precio4:3:0); ELSE writeln('La actividad elegida no existe.'); END; writeln; leer_cliente(ape_nom, edad, act); END; writeln; writeln('-- Presione una tecla para finalizar --'); readln; end.
unit dao.Usuario; interface uses UConstantes, app.Funcoes, classes.ScriptDDL, model.Usuario, System.StrUtils, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FireDAC.Comp.Client, FireDAC.Comp.DataSet; type TUsuarioDao = class(TObject) strict private class var aInstance : TUsuarioDao; private aDDL : TScriptDDL; aModel : TUsuario; aOperacao : TTipoOperacaoDao; constructor Create(); procedure SetValues(const aDataSet : TFDQuery; const aObject : TUsuario); procedure ClearValues; public property Model : TUsuario read aModel write aModel; property Operacao : TTipoOperacaoDao read aOperacao; procedure Load(const aBusca : String); procedure Insert(); procedure Update(); procedure Limpar(); procedure Ativar(); procedure Desativar(); function Find(const aID : TGUID; const aEmail : String; const IsLoadModel : Boolean) : Boolean; class function GetInstance : TUsuarioDao; end; implementation uses UDM; { TUsuarioDao } function TUsuarioDao.Find(const aID: TGUID; const aEmail: String; const IsLoadModel: Boolean): Boolean; var aSQL : TStringList; aRetorno : Boolean; begin aRetorno := False; aSQL := TStringList.Create; try aSQL.BeginUpdate; aSQL.Add('Select'); aSQL.Add(' u.* '); aSQL.Add('from ' + aDDL.getTableNameUsuario + ' u'); if (aID <> GUID_NULL) then aSQL.Add('where u.id_usuario = :id_usuario') else if (Trim(aEmail) <> EmptyStr) then aSQL.Add('where u.ds_email = :ds_email'); aSQL.EndUpdate; with DM, qrySQL do begin qrySQL.Close; qrySQL.SQL.Text := aSQL.Text; if (aID <> GUID_NULL) then ParamByName('id_usuario').AsString := GUIDToString(aID) else if (Trim(aEmail) <> EmptyStr) then ParamByName('ds_email').AsString := AnsiLowerCase(Trim(aEmail)); if qrySQL.OpenOrExecute then begin aRetorno := (qrySQL.RecordCount > 0); if aRetorno and IsLoadModel then SetValues(qrySQL, aModel) else ClearValues; end; qrySQL.Close; end; finally aSQL.DisposeOf; Result := aRetorno; end; end; class function TUsuarioDao.GetInstance: TUsuarioDao; begin if not Assigned(aInstance) then aInstance := TUsuarioDao.Create(); Result := aInstance; end; procedure TUsuarioDao.Insert; var aQry : TFDQuery; begin aQry := TFDQuery.Create(DM); try aQry.Connection := DM.conn; aQry.Transaction := DM.trans; aQry.UpdateTransaction := DM.trans; with DM, aQry do begin SQL.BeginUpdate; SQL.Add('Insert Into ' + aDDL.getTableNameUsuario + '('); SQL.Add(' id_usuario '); SQL.Add(' , nm_usuario '); SQL.Add(' , ds_email '); SQL.Add(' , ds_senha '); SQL.Add(' , nr_celular '); if (aModel.Cpf <> EmptyStr) then SQL.Add(' , nr_cpf '); SQL.Add(' , tk_dispositivo '); SQL.Add(' , sn_ativo '); SQL.Add(') values ('); SQL.Add(' :id_usuario '); SQL.Add(' , :nm_usuario '); SQL.Add(' , :ds_email '); SQL.Add(' , :ds_senha '); SQL.Add(' , :nr_celular '); if (aModel.Cpf <> EmptyStr) then SQL.Add(' , :nr_cpf '); SQL.Add(' , :tk_dispositivo'); SQL.Add(' , :sn_ativo '); SQL.Add(')'); SQL.EndUpdate; if (aModel.ID = GUID_NULL) then aModel.NewID; ParamByName('id_usuario').AsString := GUIDToString(aModel.ID); ParamByName('nm_usuario').AsString := aModel.Nome; ParamByName('ds_email').AsString := aModel.Email; ParamByName('ds_senha').AsString := MD5(aModel.Senha + aModel.Email); ParamByName('nr_celular').AsString := aModel.Celular; if (aModel.Cpf <> EmptyStr) then ParamByName('nr_cpf').AsString := aModel.Cpf; ParamByName('tk_dispositivo').AsString := aModel.TokenID; ParamByName('sn_ativo').AsString := IfThen(aModel.Ativo, FLAG_SIM, FLAG_NAO); ExecSQL; aOperacao := TTipoOperacaoDao.toIncluido; end; finally aQry.DisposeOf; end; end; procedure TUsuarioDao.Limpar; var aQry : TFDQuery; begin aQry := TFDQuery.Create(DM); try aQry.Connection := DM.conn; aQry.Transaction := DM.trans; aQry.UpdateTransaction := DM.trans; with DM, aQry do begin SQL.BeginUpdate; SQL.Add('Delete from ' + aDDL.getTableNameUsuario); SQL.EndUpdate; ExecSQL; aModel.Ativo := False; aOperacao := TTipoOperacaoDao.toExcluir; end; finally aQry.DisposeOf; end; end; procedure TUsuarioDao.Load(const aBusca: String); var aQry : TFDQuery; aUsuario : TUsuario; aFiltro : String; begin aQry := TFDQuery.Create(DM); try aQry.Connection := DM.conn; aQry.Transaction := DM.trans; aQry.UpdateTransaction := DM.trans; aFiltro := AnsiUpperCase(Trim(aBusca)); with DM, aQry do begin SQL.BeginUpdate; SQL.Add('Select'); SQL.Add(' u.* '); SQL.Add('from ' + aDDL.getTableNameUsuario + ' u'); SQL.Add('where (u.sn_ativo = ' + QuotedStr('S') + ')'); if (Trim(aBusca) <> EmptyStr) then begin aFiltro := '%' + StringReplace(aFiltro, ' ', '%', [rfReplaceAll]) + '%'; SQL.Add(' and (u.nm_usuario like ' + QuotedStr(aFiltro) + ')'); end; SQL.Add('order by'); SQL.Add(' u.nm_usuario '); SQL.EndUpdate; if OpenOrExecute then begin if (RecordCount > 0) then while not Eof do begin aUsuario := TUsuario.GetInstance; SetValues(aQry, aUsuario); aQry.Next; end else ClearValues; end; aQry.Close; end; finally aQry.DisposeOf; end; end; procedure TUsuarioDao.SetValues(const aDataSet: TFDQuery; const aObject: TUsuario); begin with aDataSet, aObject do begin ID := StringToGUID(FieldByName('id_usuario').AsString); Nome := FieldByName('nm_usuario').AsString; Email := FieldByName('ds_email').AsString; Senha := FieldByName('ds_senha').AsString; Cpf := FieldByName('nr_cpf').AsString; Celular := FieldByName('nr_celular').AsString; TokenID := FieldByName('tk_dispositivo').AsString; Ativo := (AnsiUpperCase(FieldByName('sn_ativo').AsString) = 'S'); end; end; procedure TUsuarioDao.Update; var aQry : TFDQuery; begin aQry := TFDQuery.Create(DM); try aQry.Connection := DM.conn; aQry.Transaction := DM.trans; aQry.UpdateTransaction := DM.trans; with DM, aQry do begin SQL.BeginUpdate; SQL.Add('Update ' + aDDL.getTableNameUsuario + ' Set'); SQL.Add(' nm_usuario = :nm_usuario '); SQL.Add(' , ds_email = :ds_email '); if (Trim(aModel.Senha) <> EmptyStr) then SQL.Add(' , ds_senha = :ds_senha '); SQL.Add(' , nr_celular = :nr_celular '); if (aModel.Cpf <> EmptyStr) then SQL.Add(' , nr_cpf = :nr_cpf '); SQL.Add(' , sn_ativo = :sn_ativo '); if (Trim(aModel.TokenID) <> EmptyStr) then SQL.Add(' , tk_dispositivo = :tk_dispositivo '); SQL.Add('where id_usuario = :id_usuario'); SQL.EndUpdate; ParamByName('id_usuario').AsString := GUIDToString(aModel.ID); ParamByName('nm_usuario').AsString := aModel.Nome; ParamByName('ds_email').AsString := aModel.Email; if (Trim(aModel.Senha) <> EmptyStr) then ParamByName('ds_senha').AsString := MD5(aModel.Senha + aModel.Email); ParamByName('nr_celular').AsString := aModel.Celular; if (aModel.Cpf <> EmptyStr) then ParamByName('nr_cpf').AsString := aModel.Cpf; ParamByName('sn_ativo').AsString := IfThen(aModel.Ativo, FLAG_SIM, FLAG_NAO); if (Trim(aModel.TokenID) <> EmptyStr) then ParamByName('tk_dispositivo').AsString := aModel.TokenID; ExecSQL; aOperacao := TTipoOperacaoDao.toEditado; end; finally aQry.DisposeOf; end; end; procedure TUsuarioDao.Ativar; var aQry : TFDQuery; begin aQry := TFDQuery.Create(DM); try aQry.Connection := DM.conn; aQry.Transaction := DM.trans; aQry.UpdateTransaction := DM.trans; with DM, aQry do begin SQL.BeginUpdate; SQL.Add('Update ' + aDDL.getTableNameUsuario + ' Set'); SQL.Add(' nm_usuario = :nm_usuario '); SQL.Add(' , sn_ativo = :sn_ativo '); SQL.Add('where id_usuario = :id_usuario'); SQL.EndUpdate; ParamByName('id_usuario').AsString := GUIDToString(aModel.ID); ParamByName('nm_usuario').AsString := aModel.Nome; ParamByName('sn_ativo').AsString := FLAG_SIM; ExecSQL; aModel.Ativo := True; aOperacao := TTipoOperacaoDao.toEditado; end; finally aQry.DisposeOf; end; end; procedure TUsuarioDao.Desativar; var aQry : TFDQuery; begin aQry := TFDQuery.Create(DM); try aQry.Connection := DM.conn; aQry.Transaction := DM.trans; aQry.UpdateTransaction := DM.trans; with DM, aQry do begin SQL.BeginUpdate; SQL.Add('Update ' + aDDL.getTableNameUsuario + ' Set'); SQL.Add(' sn_ativo = :sn_ativo '); SQL.Add('where id_usuario = :id_usuario'); SQL.EndUpdate; ParamByName('id_usuario').AsString := GUIDToString(aModel.ID); ParamByName('sn_ativo').AsString := FLAG_NAO; ExecSQL; aModel.Ativo := False; aOperacao := TTipoOperacaoDao.toEditado; end; finally aQry.DisposeOf; end; end; procedure TUsuarioDao.ClearValues; begin with aModel do begin ID := GUID_NULL; Nome := EmptyStr; Email := EmptyStr; Senha := EmptyStr; Cpf := EmptyStr; Celular := EmptyStr; TokenID := EmptyStr; Ativo := False; end; end; constructor TUsuarioDao.Create; begin inherited Create; aDDL := TScriptDDL.GetInstance; aModel := TUsuario.GetInstance; aOperacao := TTipoOperacaoDao.toBrowser; end; end.
unit uMunicipioControler; interface uses Vcl.StdCtrls, System.Generics.Collections, uListaEstados, uEstadoDTO, System.SysUtils, uEstadoModel, uMunicipioDTO, uMunicipioModel; type TMunicipioControler = class private oMunicipioModel: TMunicipioModel; public procedure Limpar(out AMunicipioDTO: TMunicipioDTO); procedure ListaEstados(ACmbEstados: TComboBox); function Ler(var AMunicipioDTO: TMunicipioDTO): Boolean; function Salvar(const AMunicipioDTO: TMunicipioDTO): Boolean; function Deletar(const AIDMunicipio: Integer): Boolean; constructor Create; destructor Destroy; override; end; implementation { TMunicipioControler } function TMunicipioControler.Ler(var AMunicipioDTO: TMunicipioDTO): Boolean; begin Result := False; if AMunicipioDTO.IdMunicipio > 0 then Result := oMunicipioModel.Ler(AMunicipioDTO); end; constructor TMunicipioControler.Create; begin oMunicipioModel := TMunicipioModel.Create; end; destructor TMunicipioControler.Destroy; begin if Assigned(oMunicipioModel) then FreeAndNil(oMunicipioModel); inherited; end; function TMunicipioControler.Deletar(const AIDMunicipio: Integer): Boolean; begin Result := False; if (AIDMunicipio > 0) then Result := oMunicipioModel.Deletar(AIDMunicipio); end; procedure TMunicipioControler.Limpar(out AMunicipioDTO: TMunicipioDTO); begin AMunicipioDTO.IdMunicipio := 0; AMunicipioDTO.CodigoIbge := 0; AMunicipioDTO.Nome := EmptyStr; AMunicipioDTO.CEP := 0; AMunicipioDTO.DDD := 0; AMunicipioDTO.Estado := 0; end; procedure TMunicipioControler.ListaEstados(ACmbEstados: TComboBox); var oListaEstados: TListaEstados; oEstadoModel: TEstadoModel; oEstadoDTO: TEstadoDTO; begin ACmbEstados.Items.Clear; oEstadoModel := TEstadoModel.Create; try oListaEstados := TListaEstados.Create([doOwnsValues]); if oEstadoModel.BuscarListaEstados(oListaEstados) then begin for oEstadoDTO in oListaEstados.Values do ACmbEstados.Items.AddObject(oEstadoDTO.Nome, TObject(oEstadoDTO.ID)); end; finally // if Assigned(oEstadoDTO) then // oEstadoDTO.Free; if Assigned(oEstadoModel) then oEstadoModel.Free; if Assigned(oListaEstados) then oListaEstados.Free; end; end; function TMunicipioControler.Salvar(const AMunicipioDTO: TMunicipioDTO) : Boolean; begin // Validar os campos if AMunicipioDTO.IdMunicipio > 0 then Result := oMunicipioModel.Alterar(AMunicipioDTO) else begin AMunicipioDTO.IdMunicipio := oMunicipioModel.BuscarID; Result := oMunicipioModel.Inserir(AMunicipioDTO); end; end; end.
{single instance priority queue main parts contributed by Rassim Eminli} {$INCLUDE switches.pas} unit Pile; interface procedure Create(Size: integer); procedure Free; procedure Empty; function Put(Item, Value: integer): boolean; function TestPut(Item, Value: integer): boolean; function Get(var Item, Value: integer): boolean; implementation const MaxSize=9600; type TheapItem = record Item: integer; Value: integer; end; var bh: array[0..MaxSize-1] of TheapItem; Ix: array[0..MaxSize-1] of integer; n, CurrentSize: integer; {$IFDEF DEBUG}InUse: boolean;{$ENDIF} procedure Create(Size: integer); begin {$IFDEF DEBUG}assert(not InUse, 'Pile is a single instance class, ' +'no multiple usage possible. Always call Pile.Free after use.');{$ENDIF} assert(Size<=MaxSize); if (n <> 0) or (Size > CurrentSize) then begin FillChar(Ix, Size*sizeOf(integer), 255); n := 0; end; CurrentSize := Size; {$IFDEF DEBUG}InUse:=true;{$ENDIF} end; procedure Free; begin {$IFDEF DEBUG}assert(InUse);InUse:=false;{$ENDIF} end; procedure Empty; begin if n <> 0 then begin FillChar(Ix, CurrentSize*sizeOf(integer), 255); n := 0; end; end; //Parent(i) = (i-1)/2. function Put(Item, Value: integer): boolean; //O(lg(n)) var i, j: integer; begin assert(Item<CurrentSize); i := Ix[Item]; if i >= 0 then begin if bh[i].Value <= Value then begin result := False; exit; end; end else begin i := n; Inc(n); end; while i > 0 do begin j := (i-1) shr 1; //Parent(i) = (i-1)/2 if Value >= bh[j].Value then break; bh[i] := bh[j]; Ix[bh[i].Item] := i; i := j; end; // Insert the new Item at the insertion point found. bh[i].Value := Value; bh[i].Item := Item; Ix[bh[i].Item] := i; result := True; end; function TestPut(Item, Value: integer): boolean; var i: integer; begin assert(Item<CurrentSize); i := Ix[Item]; result := (i < 0) or (bh[i].Value > Value); end; //Left(i) = 2*i+1. //Right(i) = 2*i+2 => Left(i)+1 function Get(var Item, Value: integer): boolean; //O(lg(n)) var i, j: integer; last: TheapItem; begin if n = 0 then begin result := False; exit; end; Item := bh[0].Item; Value := bh[0].Value; Ix[Item] := -1; dec(n); if n > 0 then begin last := bh[n]; i := 0; j := 1; while j < n do begin // Right(i) = Left(i)+1 if(j < n-1) and (bh[j].Value > bh[j + 1].Value)then inc(j); if last.Value <= bh[j].Value then break; bh[i] := bh[j]; Ix[bh[i].Item] := i; i := j; j := j shl 1+1; //Left(j) = 2*j+1 end; // Insert the root in the correct place in the heap. bh[i] := last; Ix[last.Item] := i; end; result := True end; initialization n:=0; CurrentSize:=0; {$IFDEF DEBUG}InUse:=false;{$ENDIF} end.
unit OError; {Обработка ошибок} interface procedure Error(Msg : string); procedure Expected(Msg : string); procedure Warning(Msg : string); {=======================================================} implementation uses AsmText, AsmScan; procedure Error(Msg : string); var ELine : integer; begin ELine := Line; while (Ch <> chEOL) and (Ch <> chEOT) do NextCh; if Ch = chEOT then WriteLn; WriteLn('^': LexPos); Writeln('(Строка ', ELine, ') Ошибка: ', Msg); WriteLn; WriteLn('Нажмите ВВОД'); Readln; Halt(1); end; procedure Expected(Msg: string); begin Error('Ожидается ' + Msg); end; procedure Warning(Msg : string); begin WriteLn; Writeln('Предупреждение: ', Msg); WriteLn; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) } unit ormbr.dml.commands; interface uses dbcbr.mapping.classes; type TDMLCommandAutoInc = class private FSequence: TSequenceMapping; FPrimaryKey: TPrimaryKeyMapping; FExistSequence: Boolean; public property Sequence: TSequenceMapping read FSequence write FSequence; property PrimaryKey: TPrimaryKeyMapping read FPrimaryKey write FPrimaryKey; property ExistSequence: Boolean read FExistSequence write FExistSequence; end; implementation end.
(*======================================================================* | unitCodeSnippets | | | | TCodeSnipets loads code snippets from embedded resources - for OTA | | wizards etc. | | | | 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. | | | | Copyright © Colin Wilson 2005 All Rights Reserved | | | Version Date By Description | | ------- ---------- ---- ------------------------------------------| | 1.0 03/08/2005 CPWW Original | *======================================================================*) unit unitCodeSnippets; interface uses Windows, Classes, SysUtils, ConTnrs; type TCodeSnippet = class private fSnippetName: string; fCode: string; public constructor Create (const ASnippetName, ACode : string); property SnippetName : string read fSnippetName; property Code : string read fCode; end; TCodeSnipets = class (TObjectList) private procedure LoadSnipets (instance : THandle); public constructor Create (AModuleInstance : THandle); function GetSnippet (const snippetName : string) : string; function FormatSnippet (const s : string; const ss : array of string; const rs : array of string) : string; end; implementation uses ActiveX; { TCodeSnippet } {*----------------------------------------------------------------------* | TCodeSnippet.Create | | | | Constructor | *----------------------------------------------------------------------*} constructor TCodeSnippet.Create(const ASnippetName, ACode: string); begin fSnippetName := ASnippetName; fCode := ACode; end; { TCodeSnipets } {*----------------------------------------------------------------------* | TCodeSnipets.Create | | | | Constructor | *----------------------------------------------------------------------*} constructor TCodeSnipets.Create(AModuleInstance: THandle); begin inherited Create; LoadSnipets (AModuleInstance); end; {*----------------------------------------------------------------------* | function TCodeSnipets.FormatSnippet | | | | Replaces all occurences of the strings in 'ss' with the | | corresponding string in 'rs'. Finally it replaces all occurences of | | %CreateGUID% with a freshly created GUID. | | | | All this is case insensitive. | *----------------------------------------------------------------------*} function TCodeSnipets.FormatSnippet(const s: string; const ss, rs: array of string): string; var tempStr : string; idx : Integer; max : Integer; function CreateGUID : string; var r : TGUID; begin CoCreateGUID (r); result := GUIDToString (r); end; begin max := High (ss); if High (rs) < max then max := High (rs); result := s; // Replace 'ss' strings with 'rs' strings for idx := 0 to max do result := StringReplace (result, ss [idx], rs [idx], [rfReplaceAll, rfIgnoreCase]); repeat // Create GUIDs tempStr := StringReplace (result, '%CreateGUID%', CreateGuid, [rfIgnoreCase]); if tempStr = result then break; result := tempStr until False; end; {*----------------------------------------------------------------------* | function TCodeSnipets.GetSnippet | | | | Gets the code snippet that for the snippet name. | *----------------------------------------------------------------------*} function TCodeSnipets.GetSnippet(const snippetName: string): string; var i : Integer; begin result := ''; for i := 0 to Count - 1 do if CompareText (snippetName, TCodeSnippet (Items [i]).SnippetName) = 0 then begin result := TCodeSnippet (Items [i]).Code; break end; if result = '' then raise Exception.Create ('Code Snippet ' + snippetName + ' not found') end; {*----------------------------------------------------------------------* | procedure TCodeSnipets.LoadSnipets | | | | Load snippets from the resource. | | | | Each snippet is surrounded by a 'start of snippet' and 'end of | | snippet' marker. 'Start of Snippet' is a line starting with '-', | | and containing a colon followed by the snippet name. | | 'End of Snippet' is simply a line starting with '-'. | | | | Any text between two snippets is ignored. | *----------------------------------------------------------------------*} procedure TCodeSnipets.LoadSnipets(instance: THandle); var resInstance : THandle; res : THandle; codeResource : THandle; i, ps : Integer; l : TStringList; p: PAnsiChar; snippet : TStringList; snippetName : string; s : string; begin ResInstance := FindResourceHInstance(instance); res := FindResource(ResInstance, 'SNIPETS', RT_RCDATA); if res > 0 then begin // We've got a 'SNIPETS' resource! codeResource := LoadResource (ResInstance, res); p := LockResource (codeResource); l := TStringList.Create; try l.Text := UTF8ToString (p); // buffer; // Move snippets into stringlist 'l' snippet := Nil; for i := 0 to l.Count - 1 do begin s := l.Strings [i]; if Copy (s, 1, 1) = '-' then // It's either a snippet end marker or a snippet start marker if Assigned (snippet) then // If there's a snippet going, it must be a snippet end begin Add (TCodeSnippet.Create (snippetName, snippet.Text)); FreeAndNil (snippet) end else begin ps := Pos (':', s); if ps > 0 then begin snippet := TStringList.Create; snippetName := Trim (Copy (s, ps + 1, MaxInt)); end end else if Assigned (snippet) then snippet.Add (s) end; if Assigned (snippet) then begin Add (TCodeSnippet.Create (snippetName, snippet.Text)); FreeAndNil (snippet) end finally l.Free end end end; end.
unit VersionFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, BaseComponent, BaseObjects, Version, ToolWin, ComCtrls; type TfrmVersion = class(TFrame, IBaseComponent) lwVersions: TListView; tlbrBtns: TToolBar; private { Private declarations } FImplementor: TBaseComponentImplementor; function GetBaseComponentImplementor: TBaseComponentImplementor; function GetVersions: TVersions; public { Public declarations } property Versions: TVersions read GetVersions; property Implementor: TBaseComponentImplementor read GetBaseComponentImplementor implements IBaseComponent; function AddVersion(AVerstionName, AVersionReason: string; AVersionDate: TDateTime): TVersion; procedure Prepare; end; TVersionImplementor = class(TBaseComponentImplementor) protected function GetInputObjects: TIDObjects; override; procedure SetInputObjects(const Value: TIDObjects); override; end; implementation uses Facade, SDFacade, ExceptionExt; {$R *.dfm} { TfrmVersion } function TfrmVersion.AddVersion(AVerstionName, AVersionReason: string; AVersionDate: TDateTime): TVersion; var li: TListItem; begin // добавляем Result := Versions.Add; // инициализируем значениями with Result do begin VersionName := AVerstionName; VersionReason := AVersionReason; VersionDate := AVersionDate; end; // пишем в БД Result.Update(); // обновляем представление Versions.MakeList(lwVersions.Items, true, true); end; function TfrmVersion.GetBaseComponentImplementor: TBaseComponentImplementor; begin if not Assigned(FImplementor) then FImplementor := TVersionImplementor.Create; Result := FImplementor; end; function TfrmVersion.GetVersions: TVersions; begin Result := IBaseComponent(Self).InputObjects as TVersions; end; procedure TfrmVersion.Prepare; begin Versions.MakeList(lwVersions.Items, true, false); end; { TVersionImplementor } function TVersionImplementor.GetInputObjects: TIDObjects; begin Result := TMainFacade.GetInstance.AllVersions; end; procedure TVersionImplementor.SetInputObjects(const Value: TIDObjects); begin raise EReadonlyResetProhibited.Create; end; end.
unit uCadastroMovimentacao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, uConn, uClasseMovimentacao, uClasseConta; type TfrmCadMovimetacao = class(TForm) edtValor: TEdit; mmDescri: TMemo; btnConfirmar: TBitBtn; btnCancelar: TBitBtn; edtData: TMaskEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; cmbConta: TComboBox; rgTipoConta: TRadioGroup; Label4: TLabel; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnCancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure rgTipoContaClick(Sender: TObject); procedure btnConfirmarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmCadMovimetacao: TfrmCadMovimetacao; Conn : TConn; Mov : TMovimento; Conta : TConta; implementation {$R *.dfm} uses uLibrary, uTrataException; procedure TfrmCadMovimetacao.btnCancelarClick(Sender: TObject); begin Close; end; procedure TfrmCadMovimetacao.btnConfirmarClick(Sender: TObject); begin with Mov do begin Valor := VerificaTipo( rgTipoConta.ItemIndex,edtValor.Text); IdCon := Conta.IdCon(cmbConta.Items[cmbConta.ItemIndex]); Descri := mmDescri.Text; DtOpe := edtData.Text; // Chamar a function Inserir Movimento if Inserir then begin Application.MessageBox('Concluido!','Confirmação',MB_OK); // Verifica se deseja cadastra outro grupo If (Application.MessageBox(' Deseja fazer outro cadastro? ', 'Salva',36) = 6) then begin // Limpar campos LimpaCampos; // Lista as contas ativas no componete ao clica no RadioGroup cmbConta.Items := Conta.ListaConta( TipoConta( rgTipoConta.ItemIndex ) ); // Pega data Atual edtData.Text := DateToStr(Date); Exit end; end else begin Application.MessageBox('O registro não foi alterado!','Atenção',MB_OK); end; end; Close; end; procedure TfrmCadMovimetacao.FormCreate(Sender: TObject); begin // Instancia as Class no form Conn := TConn.Create; Mov := TMovimento.Create(Conn); Conta := TConta.Create(Conn); end; procedure TfrmCadMovimetacao.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfrmCadMovimetacao.FormShow(Sender: TObject); begin edtData.Text := DateToStr( Date ); // Lista as contas ativas no componete ao abrir form cmbConta.Items := Conta.ListaConta( TipoConta( rgTipoConta.ItemIndex ) ); end; procedure TfrmCadMovimetacao.rgTipoContaClick(Sender: TObject); begin // Lista as contas ativas no componete ao clica no RadioGroup cmbConta.Items := Conta.ListaConta( TipoConta( rgTipoConta.ItemIndex ) ); end; end.
unit uTrataException; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,IniFiles, AppEvnts; type TException = class private LogFile : String; public constructor Create; procedure TrataExc(Sender : TObject; E:Exception); procedure GravaLog(Value : String); end; implementation { TException } constructor TException.Create; begin LogFile:=ChangeFileExt('LogErro','.log'); Application.OnException:= TrataExc; end; procedure TException.GravaLog(Value: String); var txtLog : TextFile; begin AssignFile(txtLog,LogFile); if FileExists(LogFile) then // escreve no arequivo se ele existi Append(txtLog) else // rescreve erro Rewrite(txtLog); try // Escreve o Erro e a data e a hora do Erro Writeln(txtLog, FormatDateTime('dd/mm/YY hh:mm:ss - ',Now) + Value); finally // Fecha arquivo CloseFile(txtLog); end; end; procedure TException.TrataExc(Sender: TObject; E: Exception); begin if TComponent(Sender) is TForm then begin GravaLog('============================================'); GravaLog('Form: '+TForm(Sender).Name); GravaLog('Caption: '+TForm(Sender).Caption); GravaLog('Erro: '+E.ClassName); GravaLog('Erro: '+E.Message); end else begin GravaLog('Form: ' + TForm(TComponent(Sender).Owner).Name); GravaLog('Caption: ' + TForm(TComponent(Sender).Owner).Caption); GravaLog('Erro: ' + E.ClassName); GravaLog('Erro: ' + E.Message); end; ShowMessage(E.Message); end; var TesteExcept : TException; initialization TesteExcept := TException.Create; Finalization TesteExcept.Free; end.
unit Iocp.VariantSocket; interface uses Windows, Classes, SysUtils, Math, Iocp.TcpSocket, Iocp.PacketSocket, Iocp.VariantPacket, Iocp.Utils; type TIocpVariantServerConnection = class(TIocpPacketConnection); TIocpVariantRequestEvent = procedure(Sender: TObject; Client: TIocpVariantServerConnection; Request, Response: TIocpVariantPacket) of object; TIocpVariantServer = class(TIocpPacketServer) private FOnRequest: TIocpVariantRequestEvent; protected procedure TriggerPacketRecv(Client: TIocpPacketConnection; const Packet: TIocpPacket); override; protected procedure DoOnRequest(Client: TIocpVariantServerConnection; Request, Response: TIocpVariantPacket); virtual; public constructor Create(AOwner: TComponent); overload; override; published property OnRequest: TIocpVariantRequestEvent read FOnRequest write FOnRequest; end; TIocpVariantClientConnection = class(TIocpPacketConnection) private FBusyEvent: THandle; FSendStream: TMemoryStream; FRequest, FSyncResponse: TIocpVariantPacket; protected procedure Initialize; override; function GetIsIdle: Boolean; override; public constructor Create(AOwner: TObject); override; destructor Destroy; override; procedure SetBusy(Busy: Boolean); end; TIocpVariantResponseEvent = procedure(Sender: TObject; Client: TIocpVariantClientConnection; Request, Response: TIocpVariantPacket) of object; TIocpVariantClient = class(TIocpPacketSocket) private FOnResponse: TIocpVariantResponseEvent; FServerPort: Word; FServerAddr: string; FRetryDelay: Integer; FTCPRetry: Integer; function GetIdleConnectionAndLock: TIocpVariantClientConnection; function SendRequest(Client: TIocpVariantClientConnection; Request, Response: TIocpVariantPacket): Boolean; function ProcessRetry(var ErrCount: Integer): Boolean; procedure SetRetryDelay(const Value: Integer); protected procedure TriggerPacketRecv(Client: TIocpPacketConnection; const Packet: TIocpPacket); override; protected procedure DoOnResponse(Client: TIocpVariantClientConnection; Request, Response: TIocpVariantPacket); virtual; public constructor Create(AOwner: TComponent); overload; override; function SyncRequest(Request, Response: TIocpVariantPacket): Boolean; overload; // Response由调用者事先创建 function SyncRequest(Request: TIocpVariantPacket): TIocpVariantPacket; overload; // 调用者负责释放返回的数据结构 function AsyncRequest(Request: TIocpVariantPacket): Boolean; published property ServerAddr: string read FServerAddr write FServerAddr; property ServerPort: Word read FServerPort write FServerPort; // <0 无限重试、=0 不重试、>0 重试次数 property TCPRetry: Integer read FTCPRetry write FTCPRetry default 10; property RetryDelay: Integer read FRetryDelay write SetRetryDelay default 2000; property OnResponse: TIocpVariantResponseEvent read FOnResponse write FOnResponse; end; procedure Register; implementation procedure Register; begin RegisterComponents('Iocp', [TIocpVariantClient, TIocpVariantServer]); end; { TIocpVariantServer } constructor TIocpVariantServer.Create(AOwner: TComponent); begin inherited Create(AOwner); ConnectionClass := TIocpVariantServerConnection; end; procedure TIocpVariantServer.DoOnRequest(Client: TIocpVariantServerConnection; Request, Response: TIocpVariantPacket); begin if Assigned(FOnRequest) then FOnRequest(Self, Client, Request, Response); end; procedure TIocpVariantServer.TriggerPacketRecv(Client: TIocpPacketConnection; const Packet: TIocpPacket); var Request, Response: TIocpVariantPacket; Stream: TMemoryStream; begin Request := TIocpVariantPacket.Create; Response := TIocpVariantPacket.Create; Stream := TMemoryStream.Create; try Request.LoadFromBuf(Packet.Data, Packet.Header.DataSize); Response.Cmd := Request.Cmd; Response.Params['success'] := True; DoOnRequest(TIocpVariantServerConnection(Client), Request, Response); Response.SaveToStream(Stream); Client.Send(Stream.Memory, Stream.Size); finally Request.Free; Response.Free; Stream.Free; end; end; { TIocpVariantClientConnection } constructor TIocpVariantClientConnection.Create(AOwner: TObject); begin inherited Create(AOwner); FBusyEvent := CreateEvent(nil, True, True, nil); FSendStream := TMemoryStream.Create; FRequest := TIocpVariantPacket.Create; end; destructor TIocpVariantClientConnection.Destroy; begin CloseHandle(FBusyEvent); FSendStream.Free; FRequest.Free; inherited Destroy; end; function TIocpVariantClientConnection.GetIsIdle: Boolean; begin Result := inherited GetIsIdle and (WaitForSingleObject(FBusyEvent, 0) = WAIT_OBJECT_0); end; procedure TIocpVariantClientConnection.Initialize; begin inherited Initialize; SetBusy(False); end; procedure TIocpVariantClientConnection.SetBusy(Busy: Boolean); begin if Busy then ResetEvent(FBusyEvent) else SetEvent(FBusyEvent); end; { TIocpVariantClient } constructor TIocpVariantClient.Create(AOwner: TComponent); begin inherited Create(AOwner); ConnectionClass := TIocpVariantClientConnection; FTCPRetry := 10; FRetryDelay := 2000; end; procedure TIocpVariantClient.DoOnResponse(Client: TIocpVariantClientConnection; Request, Response: TIocpVariantPacket); begin if Assigned(FOnResponse) then FOnResponse(Self, Client, Request, Response); end; function TIocpVariantClient.GetIdleConnectionAndLock: TIocpVariantClientConnection; var Connection: TIocpSocketConnection; begin try for Connection in LockConnectionList.Values do begin if Connection.IsIdle then begin Result := TIocpVariantClientConnection(Connection); Result.SetBusy(True); Exit; end; end; finally UnlockConnectionList; end; Result := TIocpVariantClientConnection(Connect(FServerAddr, FServerPort)); if (Result <> nil) then Result.SetBusy(True); end; function TIocpVariantClient.ProcessRetry(var ErrCount: Integer): Boolean; begin Inc(ErrCount); if (FTCPRetry > 0) then Result := (ErrCount > FTCPRetry) else if (FTCPRetry < 0) then Result := False else Result := True; end; function TIocpVariantClient.SendRequest(Client: TIocpVariantClientConnection; Request, Response: TIocpVariantPacket): Boolean; begin with Client do begin SetBusy(True); FRequest.Assign(Request); Request.SaveToStream(FSendStream); InterlockedExchangePointer(Pointer(FSyncResponse), Response); Result := (Send(FSendStream.Memory, FSendStream.Size) > 0); end; end; procedure TIocpVariantClient.SetRetryDelay(const Value: Integer); begin FRetryDelay := Min(Value, 500); end; function TIocpVariantClient.AsyncRequest(Request: TIocpVariantPacket): Boolean; var ErrCount: Integer; Client: TIocpVariantClientConnection; begin ErrCount := 0; while True do begin Client := GetIdleConnectionAndLock; if (Client = nil) then Break; Result := SendRequest(Client, Request, nil); // 请求发送成功 if Result then Exit; // 出错,重试 if ProcessRetry(ErrCount) then Exit else begin Client.SetBusy(False); Client.Disconnect; Sleep(FRetryDelay); end; end; // 请求发送失败 Result := False; end; function TIocpVariantClient.SyncRequest(Request, Response: TIocpVariantPacket): Boolean; var ErrCount: Integer; Client: TIocpVariantClientConnection; begin ErrCount := 0; while True do begin Client := GetIdleConnectionAndLock; if (Client = nil) then Break; Result := SendRequest(Client, Request, Response); // 请求发送成功,并且接收返回数据成功 if Result and (WaitForObject(Client.FBusyEvent, Timeout) = WAIT_OBJECT_0) then Exit; // 出错,重试 if ProcessRetry(ErrCount) then Exit else begin Client.SetBusy(False); Client.Disconnect; Sleep(FRetryDelay); end; end; // 请求超时 Result := False; end; function TIocpVariantClient.SyncRequest( Request: TIocpVariantPacket): TIocpVariantPacket; begin Result := TIocpVariantPacket.Create; if not SyncRequest(Request, Result) then FreeAndNil(Result); end; procedure TIocpVariantClient.TriggerPacketRecv(Client: TIocpPacketConnection; const Packet: TIocpPacket); var NeedNewResponse: Boolean; Response: TIocpVariantPacket; begin with TIocpVariantClientConnection(Client) do begin NeedNewResponse := (InterlockedExchangePointer(Pointer(FSyncResponse), FSyncResponse) = nil); if NeedNewResponse then Response := TIocpVariantPacket.Create else Response := FSyncResponse; try Response.LoadFromBuf(Packet.Data, Packet.Header.DataSize); DoOnResponse(TIocpVariantClientConnection(Client), TIocpVariantClientConnection(Client).FRequest, Response); finally SetBusy(False); if NeedNewResponse then Response.Free; end; end; end; end.
unit XLSExport; { ******************************************************************************** ******* XLSReadWriteII V1.14 ******* ******* ******* ******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} interface uses Classes, SysUtils, XLSReadWriteII, XLSRWIIResourceStrings; type TXLSExport = class(TComponent) private procedure SetFilename(const Value: string); protected FFilename: string; FXLS: TXLSReadWriteII; FCurrSheetIndex: integer; FCol1,FCol2: integer; FRow1,FRow2: integer; procedure OpenFile; virtual; procedure WriteFilePrefix; virtual; procedure WritePagePrefix; virtual; procedure WriteRowPrefix; virtual; procedure WriteCell(SheetIndex,Col,Row: integer); virtual; procedure WriteRowSuffix; virtual; procedure WritePageSuffix; virtual; procedure WriteFileSuffix; virtual; procedure CloseFile; virtual; procedure WriteData; virtual; public constructor Create(AOwner: TComponent); override; procedure Write; procedure SaveToStream(Stream: TStream); virtual; published property Col1: integer read FCol1 write FCol1; property Col2: integer read FCol2 write FCol2; property Filename: string read FFilename write SetFilename; property Row1: integer read FRow1 write FRow1; property Row2: integer read FRow2 write FRow2; property XLS: TXLSReadWriteII read FXLS write FXLS; end; implementation { TXLSExport } procedure TXLSExport.CloseFile; begin end; constructor TXLSExport.Create(AOwner: TComponent); begin inherited; FCol1 := -1; FCol2 := -1; FRow1 := -1; FRow2 := -1; end; procedure TXLSExport.OpenFile; begin end; procedure TXLSExport.SaveToStream(Stream: TStream); begin if FXLS = Nil then raise Exception.Create(ersNoTXLSReadWriteIIDefined); WriteData; end; procedure TXLSExport.SetFilename(const Value: string); begin FFilename := Value; end; procedure TXLSExport.Write; begin if FFilename = '' then raise Exception.Create(ersFilenameIsMissing); if FXLS = Nil then raise Exception.Create(ersNoTXLSReadWriteIIDefined); OpenFile; try WriteData; finally CloseFile; end; end; procedure TXLSExport.WriteCell(SheetIndex, Col, Row: integer); begin end; procedure TXLSExport.WriteData; var i,Col,Row: integer; C1,C2,R1,R2: integer; begin WriteFilePrefix; for i := 0 to FXLS.Sheets.Count - 1 do begin FXLS.Sheets[i].CalcDimensions; if FCol1 >= 0 then C1 := FCol1 else C1 := FXLS.Sheets[i].FirstCol; if FCol2 >= 0 then C2 := FCol2 else C2 := FXLS.Sheets[i].LastCol; if FRow1 >= 0 then R1 := FRow1 else R1 := FXLS.Sheets[i].FirstRow; if FRow2 >= 0 then R2 := FRow2 else R2 := FXLS.Sheets[i].LastRow; FCurrSheetIndex := i; WritePagePrefix; for Row := R1 to R2 do begin WriteRowPrefix; for Col := C1 to C2 do WriteCell(i,Col,Row); WriteRowSuffix; end; WritePageSuffix; end; WriteFileSuffix; end; procedure TXLSExport.WriteFilePrefix; begin end; procedure TXLSExport.WriteFileSuffix; begin end; procedure TXLSExport.WritePagePrefix; begin end; procedure TXLSExport.WritePageSuffix; begin end; procedure TXLSExport.WriteRowPrefix; begin end; procedure TXLSExport.WriteRowSuffix; begin end; end.
unit EP_errdlg; {----------------Expression Error Dialogs--------------------- Boite de dialoque de rapport des erreurs de l'évaluateur d'expresssion ->Date:29.07.2008 --------------------------------------------------------------} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls,Eval,gutils; type TErrForm = class(TForm) Button1: TButton; RText: TRichEdit; Descript_text: TMemo; Bevel1: TBevel; private { Private declarations } public { Public declarations } end; //function ShowEpError(EpInfo:Pepinfo;Eparr:Strarr;Errmsg:string):integer; function loadErrInfo(name:string):string; function ShowEpErrorDlg(epstr:pchar;epstrCount:integer;errpos:integer;errmsg:pchar):integer; var ErrForm: TErrForm; ErrList:TStringList; implementation {$R *.dfm} {Fonction qui permet de charger une erreur contenu dans le fichier d'erreur ->Date:29.07.2008} function loadErrInfo(name:string):string; var i:integer; begin try if ErrList=nil then begin ErrList:=TStringList.Create; ErrList.LoadFromFile(Application.ExeName); end; for i:=0 to (ErrList.Count-1) do begin if pos(name,ErrList[i])<>0 then result:=ErrList[i]; end; except result:='Error when loading error file description' ; end; end; {--------------------------------------- affiche une boite de dialogue pour montrer l'erreur dans l'expression à l'utilisateur ->Date:?,revisé:29.07.2008 -----------------------------------------} function ShowEpErrorDlg(epstr:pchar;epstrCount:integer;errpos:integer;errmsg:pchar):integer; var slength:integer; begin ErrForm.RText.SelStart:=0; ErrForm.Descript_text.Clear; ErrForm.RText.Lines.Clear; ErrForm.Descript_text.Lines.Add(Format('Erreur d''évaluation à partir de la Colonne %d',[ErrPos+1])); ErrForm.Descript_text.Lines.Add('Cause:'); ErrForm.Descript_text.Lines.Add(Errmsg); ErrForm.RText.text:=epstr; ErrForm.RText.SelStart:=errpos; slength:=pos(copy(epstr,errpos+1,length(epstr)),' '); if slength=0 then slength:=length(epstr)-errpos; ErrForm.RText.SelLength:=slength; ErrForm.RText.SelAttributes.Color:=12000; ErrForm.ShowModal; end; (* function ShowEpError(EpInfo:PEpInfo;Eparr:Strarr;Errmsg:string):integer; var i,gpos:integer; begin try ErrForm.RText.SelStart:=0;gpos:=0; ErrForm.Descript_text.Clear; ErrForm.RText.Lines.Clear; ErrForm.Descript_text.Lines.Add(Format('Erreur d''évaluation à partir de la Colonne %d',[EpInfo.ErrPos+1])); ErrForm.Descript_text.Lines.Add('Cause:'); ErrForm.Descript_text.Lines.Add(Errmsg); For i:=0 to high(Eparr) do begin if i=EpInfo.ErrPos then begin ErrForm.RText.SelAttributes.Color:=12000; ErrForm.RText.SelText:=Eparr[i]; end else begin ErrForm.RText.SelAttributes.Color:=0; ErrForm.RText.SelText:=Eparr[i] end; gpos:=gpos+Length(Eparr[i]); end; ErrForm.ShowModal; except MessageBox(null,'Important pour Jacob','Erreur interne dans EPEVAL',MB_OK+MB_ICONWARNING); end; end; *) end.
(* Б) Перечислимые типы и диапазоны строятся на базе других типов данных (Byte, ShortInt и так далее). Какие типы данных, по вашему мнению, будут положены в основу следующих диапазонов: *) begin { N : -10..10; //shortint M : -200..200; //smallint R : 0..40000; //word L : 0..400000; //longword S : '0'..'9'; //char } end.
unit ValueSetEditorVCLForm; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, VirtualTrees, Vcl.ComCtrls, Math, Clipbrd, FHIRTypes, FHIRResources, FHIRUtilities, ValueSetEditorCore, ValueSetEditorRegisterServerForm, Vcl.Menus, Vcl.Buttons, Vcl.ImgList, VirtualStringTreeComboBox, StringSupport, Vcl.Imaging.pngimage, Vcl.OleCtrls, SHDocVw, ServerChooser, Vcl.ToolWin, LookAheadUnit, ValueSetEditorAbout, ServerOperationForm, System.ImageList; Const NAME_INFORMATION = 'Value Set Information'; NAME_DEFINE = 'Code Defined By Value Set'; NAME_IMPORT = 'Import Value Set'; NAME_INCLUDE = 'Include Codes'; NAME_EXCLUDE = 'Exclude Codes'; NAME_EXPAND = 'Expansion'; COLOUR_OK = clWhite; COLOUR_MANDATORY = $FFEEEE; COLOUR_ERROR = $EEEEFF; COLOUR_WARNING = $EEFFFF; COLOUR_HINT = $EEFFEE; type TValueSetEditorForm = class(TForm) pnlToolbar: TPanel; opnValueSet: TFileOpenDialog; PageControl1: TPageControl; tabInformation: TTabSheet; tabDefined: TTabSheet; tabComposition: TTabSheet; tabExpansion: TTabSheet; Panel6: TPanel; Label8: TLabel; edtPhone: TEdit; Panel8: TPanel; Label9: TLabel; Panel9: TPanel; Label10: TLabel; edtIdentifier: TEdit; Panel10: TPanel; Label11: TLabel; edtVersion: TEdit; Panel11: TPanel; Label12: TLabel; edtPublisher: TEdit; Panel12: TPanel; Label13: TLabel; edtCopyright: TEdit; Label14: TLabel; edtEmail: TEdit; Label15: TLabel; edtWeb: TEdit; Panel13: TPanel; Label16: TLabel; cbExperimental: TCheckBox; cbxStatus: TComboBox; Panel14: TPanel; Label17: TLabel; edtName: TEdit; tvCodeSystem: TVirtualStringTree; Panel17: TPanel; Panel18: TPanel; Label18: TLabel; edtDefineVersion: TEdit; Panel19: TPanel; Label19: TLabel; edtDefineURI: TEdit; cbDefineCase: TCheckBox; Notebook2: TNotebook; Panel22: TPanel; Panel25: TPanel; Label20: TLabel; Panel23: TPanel; Panel26: TPanel; Panel24: TPanel; Label21: TLabel; Panel27: TPanel; Label22: TLabel; tvFilters: TVirtualStringTree; Panel28: TPanel; Label23: TLabel; tvCodes: TVirtualStringTree; Splitter2: TSplitter; Panel29: TPanel; Label24: TLabel; edtSystemRefVersion: TEdit; CheckBox1: TCheckBox; mnuSaveAs: TPopupMenu; File1: TMenuItem; OSer1: TMenuItem; svValueSet: TFileSaveDialog; oServerasExisting1: TMenuItem; pnlExpansion: TPanel; Button2: TButton; tvExpansion: TVirtualStringTree; lblExpansion: TLabel; Label26: TLabel; edtFilter: TEdit; tvPreview: TVirtualStringTree; MainMenu1: TMainMenu; File2: TMenuItem; New1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; SaveAs1: TMenuItem; Print1: TMenuItem; PrintSetup1: TMenuItem; Exit1: TMenuItem; N1: TMenuItem; N2: TMenuItem; Edit1: TMenuItem; miUndo: TMenuItem; miRedo: TMenuItem; miCut: TMenuItem; miCopy: TMenuItem; miPaste: TMenuItem; PasteSpecial1: TMenuItem; Find1: TMenuItem; N4: TMenuItem; N5: TMenuItem; Help1: TMenuItem; miDoco: TMenuItem; miWebPage: TMenuItem; miAbout: TMenuItem; ools1: TMenuItem; Import2: TMenuItem; Export1: TMenuItem; OpenFromServer1: TMenuItem; pnlDocumentation: TPanel; txtDescription: TMemo; imgEnabled: TImageList; ToolBar1: TToolBar; tbNew: TToolButton; tbOpenFile: TToolButton; tbOpenServer: TToolButton; tbSave: TToolButton; tbSaveAs: TToolButton; ToolButton6: TToolButton; tbUndo: TToolButton; tbRedo: TToolButton; ToolButton9: TToolButton; tbCut: TToolButton; tbCopy: TToolButton; tbPaste: TToolButton; ToolButton13: TToolButton; tbFind: TToolButton; ToolButton15: TToolButton; tbInsert: TToolButton; tbDelete: TToolButton; tbUp: TToolButton; tbDown: TToolButton; tbIn: TToolButton; tbOut: TToolButton; ToolButton22: TToolButton; tbImport: TToolButton; tbExport: TToolButton; ToolButton25: TToolButton; tbHelp: TToolButton; pmTreeView: TPopupMenu; miTvInsert: TMenuItem; miTvDelete: TMenuItem; miTvUp: TMenuItem; miTvDown: TMenuItem; miTvIn: TMenuItem; miTvOut: TMenuItem; edtSystemReference: TLookAheadEdit; edtImportUri: TLookAheadEdit; imgDisabled: TImageList; webDoco: TWebBrowser; WelcomeScreen1: TMenuItem; N3: TMenuItem; OpenfromUrl1: TMenuItem; Panel20: TPanel; Panel21: TPanel; tvStructure: TVirtualStringTree; Splitter1: TSplitter; Label1: TLabel; btnEditCodes: TButton; Label2: TLabel; btnNewImport: TButton; Label3: TLabel; btnNewInclude: TButton; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; btnNewExclude: TButton; Label25: TLabel; pmtvStructure: TPopupMenu; mnuStructureUp: TMenuItem; mnuStructureDown: TMenuItem; mnuStructureInsert: TMenuItem; mnuStructureDelete: TMenuItem; Servers1: TMenuItem; tabStart: TTabSheet; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Label27: TLabel; Label29: TLabel; Label30: TLabel; Label31: TLabel; Label32: TLabel; OpenfromURL2: TMenuItem; Panel5: TPanel; webMRU: TWebBrowser; Label33: TLabel; cbxServer: TComboBox; btnManageServers: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnOpenServerClick(Sender: TObject); procedure btnOpenFileClick(Sender: TObject); procedure tvStructureInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure tvStructureGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure tvStructureInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); procedure tvStructurePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); procedure tvStructureClick(Sender: TObject); procedure tvCodeSystemColumnResize(Sender: TVTHeader; Column: TColumnIndex); procedure tvCodesColumnResize(Sender: TVTHeader; Column: TColumnIndex); procedure tvCodesInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure tvCodesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure tvCodesNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string); procedure tvCodesCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); procedure btnAddCodeClick(Sender: TObject); procedure btnDeleteCodeClick(Sender: TObject); procedure tvFiltersColumnResize(Sender: TVTHeader; Column: TColumnIndex); procedure tvCodeSystemInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure tvCodeSystemGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure tvCodeSystemCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); procedure GetAbstractList(context : string; list : TStrings); procedure btnAddDefineClick(Sender: TObject); procedure edtNameChange(Sender: TObject); procedure cbxStatusChange(Sender: TObject); procedure cbExperimentalClick(Sender: TObject); procedure edtIdentifierChange(Sender: TObject); procedure edtVersionChange(Sender: TObject); procedure edtPublisherChange(Sender: TObject); procedure edtCopyrightChange(Sender: TObject); procedure edtPhoneChange(Sender: TObject); procedure edtEmailChange(Sender: TObject); procedure edtWebChange(Sender: TObject); procedure txtDescriptionChange(Sender: TObject); procedure edtDefineURIChange(Sender: TObject); procedure edtDefineVersionChange(Sender: TObject); procedure tvCodeSystemNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string); procedure btnDeleteDefineClick(Sender: TObject); procedure btnDefineUpClick(Sender: TObject); procedure btnDefineDownClick(Sender: TObject); procedure btnDefineRightClick(Sender: TObject); procedure btnDefineLeftClick(Sender: TObject); procedure tvCodeSystemInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); procedure btnCodesUpClick(Sender: TObject); procedure btnCodesDownClick(Sender: TObject); procedure edtSystemReferenceChange(Sender: TObject); procedure edtSystemRefVersionChange(Sender: TObject); procedure tvFiltersGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure tvFiltersInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure tvFiltersCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); procedure btnAddFilterClick(Sender: TObject); procedure btnDeleteFilterClick(Sender: TObject); procedure btnFiltersUpClick(Sender: TObject); procedure btnFiltersDownClick(Sender: TObject); procedure tvFiltersNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string); procedure btnUndoClick(Sender: TObject); procedure btnRedoClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnSaveAsClick(Sender: TObject); procedure File1Click(Sender: TObject); procedure OSer1Click(Sender: TObject); procedure oServerasExisting1Click(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnNewClick(Sender: TObject); procedure tvExpansionColumnResize(Sender: TVTHeader; Column: TColumnIndex); procedure tvExpansionInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure tvExpansionGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure tvExpansionInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); procedure tvExpansionCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure Button2Click(Sender: TObject); procedure edtFilterChange(Sender: TObject); procedure tvPreviewColumnResize(Sender: TVTHeader; Column: TColumnIndex); procedure tvPreviewCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure tvPreviewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure tvPreviewInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); procedure tvPreviewInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure edtImportUriChange(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure miDocoClick(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure miCutClick(Sender: TObject); procedure miCopyClick(Sender: TObject); procedure miPasteClick(Sender: TObject); procedure tvCodeSystemEnter(Sender: TObject); procedure tvCodeSystemExit(Sender: TObject); procedure tvCodeSystemFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure tvCodeSystemEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean); procedure tvCodeSystemEdited(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure tvCodeSystemEditCancelled(Sender: TBaseVirtualTree; Column: TColumnIndex); procedure pmTreeViewPopup(Sender: TObject); procedure tvCodesEnter(Sender: TObject); procedure tvCodesExit(Sender: TObject); procedure tvStructureFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure tvCodesFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure tvFiltersFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure tvFiltersEnter(Sender: TObject); procedure tvFiltersExit(Sender: TObject); procedure tvCodeSystemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tvCodesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tvFiltersKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tvAllGetHint(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var LineBreakStyle: TVTTooltipLineBreakStyle; var HintText: string); procedure tvAllGetHintKind(sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Kind: TVTHintKind); procedure edtSystemReferenceEnter(Sender: TObject); procedure edtImportUriEnter(Sender: TObject); procedure LocationChange(Sender: TObject); procedure miAboutClick(Sender: TObject); procedure WelcomeScreen1Click(Sender: TObject); procedure FormActivate(Sender: TObject); procedure OpenfromUrl1Click(Sender: TObject); procedure tvCodeSystemBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); procedure tvCodesBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); procedure tvCodesDrawText(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; const Text: string; const CellRect: TRect; var DefaultDraw: Boolean); procedure pmtvStructurePopup(Sender: TObject); procedure btnAddRuleClick(sender : TObject); procedure btnDeleteRuleClick(sender : TObject); procedure btnRuleUpClick(sender : TObject); procedure btnRuleDownClick(sender : TObject); procedure btnEditCodesClick(Sender: TObject); procedure btnNewImportClick(Sender: TObject); procedure btnNewIncludeClick(Sender: TObject); procedure btnNewExcludeClick(Sender: TObject); procedure Servers1Click(Sender: TObject); procedure OpenfromURL2Click(Sender: TObject); procedure btnManageServersClick(Sender: TObject); private { Private declarations } Context : TValueSetEditorContext; loading : boolean; activated : boolean; FOnCheckButtons : TNotifyEvent; FFirstChar : String; procedure LoadValuesetPage; procedure Refresh; procedure ContextStateChange(sender : TObject); procedure ShowPreview(sender : TObject); procedure SetDocoVisibility(visible : boolean); procedure Validate(sender : TObject); procedure ValidateCombo(combo : TCombobox; outcome : TValidationOutcome); procedure ValidateEdit(edit : TEdit; outcome : TValidationOutcome); procedure ValidateMemo(memo : TMemo; outcome : TValidationOutcome); procedure noButtons(sender : TObject); procedure codeSystemCheckButtons(sender : TObject); procedure codesCheckButtons(sender : TObject); procedure filtersCheckButtons(sender: TObject); procedure doco(filename : String); function EditValue(text : String):String; procedure loadServerList; public { Public declarations } end; var ValueSetEditorForm: TValueSetEditorForm; implementation {$R *.dfm} uses ValueSetEditorWelcome; // --- general ----------------------------------------------------------------- procedure TValueSetEditorForm.File1Click(Sender: TObject); begin if svValueSet.Execute then Context.saveAsFile(svValueSet.FileName); end; procedure TValueSetEditorForm.FormActivate(Sender: TObject); begin if not activated then begin activated := true; loadServerList; if not Context.Settings.HasViewedWelcomeScreen then WelcomeScreen1Click(self); // else // begin // try // ServerOperation(Context.SetNominatedServer, Context.Settings.ServerURL, 'Connecting to Server '+Context.Settings.ServerURL, false); // Except // on e : Exception do // begin // if MessageDlg('Error contacting nominated server: '+e.Message+'. Change Server?', mtError, [mbYes, mbNo], 0) = mrNo then // close // else // WelcomeScreen1Click(self); // end; // end; // end; end; end; procedure TValueSetEditorForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Context.Close; FormResize(self); end; procedure TValueSetEditorForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if (Context <> nil) and (Context.Dirty) then CanClose := MessageDlg('Close and lose changes?', mtConfirmation, [mbYes, mbCancel], 0) = mrYes else CanClose := true; end; procedure TValueSetEditorForm.FormCreate(Sender: TObject); var l, t, h, w : integer; s : TWindowState; begin Context := TValueSetEditorContext.Create; Context.OnStateChange := ContextStateChange; Context.OnPreview := ShowPreview; Context.OnValidate := Validate; FOnCheckButtons := noButtons; if (Context.Settings.hasWindowState) then begin L := Context.Settings.WindowLeft; W := Context.Settings.WindowWidth; T := Context.Settings.WindowTop; H := Context.Settings.WindowHeight; S := TWindowState(Context.Settings.WindowState); Left := L; Width := W; Top := T; Height := H; WindowState := S; end; setDocoVisibility(Context.Settings.DocoVisible); if pnlDocumentation.visible then Constraints.MinWidth := 1100 else Constraints.MinWidth := 800; MakeFullyVisible; // btnNewClick(self); Refresh; ContextStateChange(nil); LocationChange(self); end; procedure TValueSetEditorForm.Exit1Click(Sender: TObject); begin Close; end; procedure TValueSetEditorForm.FormDestroy(Sender: TObject); begin Context.Free; Context := nil; webDoco.Free; webDoco := nil; end; procedure TValueSetEditorForm.FormResize(Sender: TObject); begin if (context <> nil) then begin Context.Settings.WindowState := ord(WindowState); Context.Settings.WindowLeft := Left; Context.Settings.WindowWidth := Width; Context.Settings.WindowTop := Top; Context.Settings.WindowHeight := Height; end; end; procedure TValueSetEditorForm.GetAbstractList(context: string; list: TStrings); begin list.Add(''); list.Add('abstract'); end; procedure TValueSetEditorForm.loadServerList; var server : TValueSetEditorServerCache; begin cbxServer.Items.clear; for server in context.Servers do begin cbxServer.Items.Add(server.Name); if server = Context.WorkingServer then cbxServer.ItemIndex := cbxServer.Items.Count - 1; end; end; procedure TValueSetEditorForm.Refresh; begin FOnCheckButtons(self); LoadValuesetPage; end; procedure TValueSetEditorForm.ShowPreview(sender: TObject); begin tvPreview.RootNodeCount := 0; if (Context.Preview <> nil) then tvPreview.RootNodeCount := Context.Preview.containsList.Count; end; procedure TValueSetEditorForm.Servers1Click(Sender: TObject); begin frmRegisterServer.Context := Context.Link; frmRegisterServer.ShowModal; end; procedure TValueSetEditorForm.SetDocoVisibility(visible : boolean); begin if visible then begin pnlDocumentation.Visible := true; Context.Settings.DocoVisible := true; Constraints.MinWidth := 1100; end else begin pnlDocumentation.Visible := false; Context.Settings.DocoVisible := false; Constraints.MinWidth := 800; end; end; procedure TValueSetEditorForm.miDocoClick(Sender: TObject); begin raise Exception.Create('test'); setDocoVisibility(not pnlDocumentation.Visible); end; procedure TValueSetEditorForm.miPasteClick(Sender: TObject); begin if ActiveControl is TEdit then TEdit(ActiveControl).PasteFromClipboard else if ActiveControl is TMemo then TMemo(ActiveControl).PasteFromClipboard; end; procedure TValueSetEditorForm.noButtons(sender: TObject); begin tbInsert.Enabled := false; tbDelete.Enabled := false; tbUp.Enabled := false; tbDown.Enabled := false; tbIn.Enabled := false; tbOut.Enabled := false; miTvInsert.Enabled := false; miTvDelete.Enabled := false; miTvUp.Enabled := false; miTvDown.Enabled := false; miTvIn.Enabled := false; miTvOut.Enabled := false; end; procedure TValueSetEditorForm.miAboutClick(Sender: TObject); begin ValueSetEditorAboutForm.showModal; end; procedure TValueSetEditorForm.miCopyClick(Sender: TObject); begin if ActiveControl is TEdit then TEdit(ActiveControl).CopyToClipboard else if ActiveControl is TMemo then TMemo(ActiveControl).CopyToClipboard; end; procedure TValueSetEditorForm.miCutClick(Sender: TObject); begin if ActiveControl is TEdit then TEdit(ActiveControl).CutToClipboard else if ActiveControl is TMemo then TMemo(ActiveControl).CutToClipboard; end; procedure TValueSetEditorForm.btnSaveAsClick(Sender: TObject); var button: TControl; lowerLeft: TPoint; begin if Sender is TControl then begin button := TControl(Sender); lowerLeft := Point(button.Left, button.Top + Button.Height); lowerLeft := ClientToScreen(lowerLeft); mnuSaveAs.Popup(lowerLeft.X, lowerLeft.Y); end; end; procedure TValueSetEditorForm.btnCloseClick(Sender: TObject); begin if not Context.Dirty or (MessageDlg('Close and lose unsaved edits, are you sure?', mtConfirmation, [mbyes, mbcancel], 0) = mrYes) then begin Context.Close; Refresh; end; end; // --- Welcome page ------------------------------------------------------------ procedure TValueSetEditorForm.btnOpenFileClick(Sender: TObject); begin if (not Context.Dirty or (MessageDlg('Lose unsaved edits, are you sure?', mtConfirmation, [mbyes, mbcancel], 0) = mrYes)) and opnValueSet.execute then begin context.openFromFile(nil, opnValueSet.filename); Refresh; end; end; procedure TValueSetEditorForm.btnOpenServerClick(Sender: TObject); begin if (not Context.Dirty or (MessageDlg('Lose unsaved edits, are you sure?', mtConfirmation, [mbyes, mbcancel], 0) = mrYes)) then begin ServerChooserForm.Context := Context.Link; if (ServerChooserForm.ShowModal = mrOk) and (ServerChooserForm.id <> '') then begin Context.Close; ServerOperation(Context.openFromServer, ServerChooserForm.id, 'Opening Value Set', true); Refresh; end; end; end; procedure TValueSetEditorForm.btnNewClick(Sender: TObject); begin if not Context.Dirty or (MessageDlg('Lose unsaved edits, are you sure?', mtConfirmation, [mbyes, mbcancel], 0) = mrYes) then begin Context.NewValueset; Refresh; end; end; procedure TValueSetEditorForm.btnNewExcludeClick(Sender: TObject); var n : PVirtualNode; begin n := tvStructure.RootNode.FirstChild; n := n.NextSibling.NextSibling.NextSibling.NextSibling; tvStructure.FocusedNode := n; btnAddRuleClick(self); end; procedure TValueSetEditorForm.btnRedoClick(Sender: TObject); begin if Context.Redo then LoadValuesetPage else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnSaveClick(Sender: TObject); begin if Context.Settings.ValueSetNew then btnSaveAsClick(Sender) else Context.Save end; procedure TValueSetEditorForm.OpenfromUrl1Click(Sender: TObject); begin btnOpenServerClick(self); end; procedure TValueSetEditorForm.OpenfromURL2Click(Sender: TObject); var s : String; clip : TClipboard; done : boolean; begin clip := TClipboard.Create; try s := clip.AsText; finally clip.free; end; if not IsURL(s) then s := ''; done := false; while not done and InputQuery('Open from URL', 'URL to open', s) do try ServerOperation(context.openFromURL, s, 'Opening', true); done := true; except on e : exception do begin if not (e is EAbort) then MessageDlg(e.Message, mtError, [mbok], 0); done := false; end; end; if done then Refresh; end; procedure TValueSetEditorForm.OSer1Click(Sender: TObject); begin Context.SaveAsServerNew; end; procedure TValueSetEditorForm.oServerasExisting1Click(Sender: TObject); begin raise Exception.Create('Not Done Yet'); end; procedure TValueSetEditorForm.LocationChange(Sender: TObject); begin case PageControl1.ActivePageIndex of 0:doco('metadata.htm'); 1:doco('definitions.htm'); 2:case Notebook2.PageIndex of 0:doco('composition.htm'); 1:doco('import.htm'); 2:doco('include.htm'); end; 3:doco('evaluation.htm'); else doco(''); end; end; procedure TValueSetEditorForm.pmTreeViewPopup(Sender: TObject); begin FOnCheckButtons(self); end; procedure TValueSetEditorForm.pmtvStructurePopup(Sender: TObject); var p : PTreeDataPointer; begin mnuStructureInsert.Enabled := false; mnuStructureDelete.Enabled := false; mnuStructureUp.Enabled := false; mnuStructureDown.Enabled := false; if tvStructure.FocusedNode <> nil then begin p := tvStructure.GetNodeData(tvStructure.FocusedNode); if Integer(p.obj) in [3..5] then // not a root or a (nil) holder begin mnuStructureInsert.Enabled := true; end else if p.obj = nil then mnuStructureInsert.Enabled := true else begin mnuStructureDelete.Enabled := true; mnuStructureUp.Enabled := tvStructure.FocusedNode.PrevSibling <> nil; mnuStructureDown.Enabled := tvStructure.FocusedNode.NextSibling <> nil; end; end; end; // --- Edit Page --------------------------------------------------------------- function displayMRU(s : String) : String; var l, r : String; begin if s.StartsWith('file:') then result := s.Substring(5) else if s.StartsWith('url:') then result := s.Substring(4) else if s.StartsWith('id:') then begin StringSplit(s.Substring(3), ':', l, r); result := l+' on '+r; end else result := '??'; end; procedure TValueSetEditorForm.LoadValuesetPage; var s : String; begin if Context.ValueSet = nil then begin Caption := 'ValueSet Editor'; Notebook2.PageIndex := 0; tvStructure.RootNodeCount := 0; PageControl1.ActivePage := TabStart; webMRU.Navigate('about:blank'); end else begin edtFilter.Text := Context.Settings.Filter; Caption := Context.EditName+' - ValueSet Editor'; Notebook2.PageIndex := 0; tvCodeSystem.Header.Columns[0].Width := Context.Settings.columnWidth('define', 'code', 100); tvCodeSystem.Header.Columns[1].Width := Context.Settings.columnWidth('define', 'abstract', 70); tvCodeSystem.Header.Columns[2].Width := Context.Settings.columnWidth('define', 'display', 200); tvCodeSystem.Header.Columns[3].Width := Context.Settings.columnWidth('define', 'definition', 200); tvCodes.Header.Columns[0].Width := Context.Settings.columnWidth('codes', 'code', 200); tvCodes.Header.Columns[1].Width := Context.Settings.columnWidth('codes', 'display', 200); tvCodes.Header.Columns[2].Width := Context.Settings.columnWidth('codes', 'comments', 200); tvFilters.Header.Columns[0].Width := Context.Settings.columnWidth('filters', 'property', 150); tvFilters.Header.Columns[1].Width := Context.Settings.columnWidth('filters', 'op', 70); tvFilters.Header.Columns[2].Width := Context.Settings.columnWidth('filters', 'value', 200); tvExpansion.Header.Columns[0].Width := Context.Settings.columnWidth('expansion', 'system', 150); tvExpansion.Header.Columns[1].Width := Context.Settings.columnWidth('expansion', 'code', 70); tvExpansion.Header.Columns[2].Width := Context.Settings.columnWidth('expansion', 'display', 200); tvPreview.Header.Columns[0].Width := Context.Settings.columnWidth('preview', 'system', 150); tvPreview.Header.Columns[1].Width := Context.Settings.columnWidth('preview', 'code', 70); tvPreview.Header.Columns[2].Width := Context.Settings.columnWidth('preview', 'display', 200); loading := true; try if Context.ValueSet = nil then begin edtName.Text := ''; cbxStatus.ItemIndex := 0; cbExperimental.Checked := false; edtIdentifier.Text := ''; edtVersion.Text := ''; edtPublisher.Text := ''; edtCopyright.Text := ''; edtPhone.Text := ''; edtEmail.Text := ''; edtWeb.Text := ''; txtDescription.Text := ''; end else begin edtName.Text := Context.ValueSet.name; cbxStatus.ItemIndex := Max(ord(Context.ValueSet.status) - 1, 0); cbExperimental.Checked := Context.ValueSet.experimental; edtIdentifier.Text := Context.ValueSet.url; edtVersion.Text := Context.ValueSet.version; edtPublisher.Text := Context.ValueSet.publisher; edtCopyright.Text := Context.ValueSet.copyright; edtPhone.Text := Context.ValueSet.contactList.System(ContactPointSystemPhone); edtEmail.Text := Context.ValueSet.contactList.System(ContactPointSystemEmail); edtWeb.Text := Context.ValueSet.contactList.System(ContactPointSystemOther); txtDescription.Text := Context.ValueSet.description; end; ValidateEdit(edtName, Context.validateName(edtName.Text)); ValidateMemo(txtDescription, Context.validateDescription(txtDescription.Text)); ValidateEdit(edtIdentifier, Context.validateIdentifier(edtIdentifier.Text)); if (Context.ValueSet <> nil) and (Context.ValueSet.codeSystem <> nil) then begin edtDefineURI.Text := Context.ValueSet.codeSystem.system; edtDefineVersion.Text := Context.ValueSet.codeSystem.version; cbDefineCase.Checked := Context.ValueSet.codeSystem.caseSensitive; tvCodeSystem.RootNodeCount := 0; tvCodeSystem.RootNodeCount := Context.ValueSet.codeSystem.conceptList.Count; ValidateEdit(edtDefineURI, context.validateSystem(edtDefineURI.Text)); end else begin edtDefineURI.Text := ''; edtDefineVersion.Text := ''; cbDefineCase.Checked := false; tvCodeSystem.RootNodeCount := 0; end; tvStructure.RootNodeCount := 0; tvStructure.RootNodeCount := 6; tvExpansion.RootNodeCount := 0; if Context.Expansion <> nil then tvExpansion.RootNodeCount := Context.Expansion.containsList.Count; tvStructureClick(self); PageControl1.ActivePage := tabInformation; ActiveControl := edtName; finally loading := false; end; end; end; procedure TValueSetEditorForm.btnUndoClick(Sender: TObject); begin if Context.Undo then LoadValuesetPage else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.cbExperimentalClick(Sender: TObject); begin if not loading then begin Context.ValueSet.experimental := cbExperimental.Checked; Context.commit('exp'); end; end; procedure TValueSetEditorForm.cbxStatusChange(Sender: TObject); begin if not loading then begin Context.ValueSet.status := TFhirConformanceResourceStatusEnum(cbxStatus.ItemIndex + 1); Context.commit('status'); end; end; procedure TValueSetEditorForm.ContextStateChange(sender: TObject); begin miUndo.Enabled := Context.CanUndo; miRedo.Enabled := Context.CanRedo; if Context.ValueSet = nil then Caption := 'Value Set Editor' else Caption := Context.EditName+' - Value Set Editor'; FOnCheckButtons(self); end; procedure TValueSetEditorForm.edtCopyrightChange(Sender: TObject); begin if not loading then begin Context.ValueSet.copyright := edtCopyright.Text; Context.commit('copy'); end; end; procedure TValueSetEditorForm.edtDefineURIChange(Sender: TObject); begin if not loading then begin if (Context.ValueSet.codeSystem = nil) then Context.ValueSet.codeSystem := TFhirValueSetCodeSystem.Create; Context.ValueSet.codeSystem.system := edtDefineURI.Text; Context.commit('defineURI'); ValidateEdit(edtDefineURI, context.validateSystem(edtDefineURI.Text)); end; end; procedure TValueSetEditorForm.edtDefineVersionChange(Sender: TObject); begin if not loading then begin if (Context.ValueSet.codeSystem = nil) then Context.ValueSet.codeSystem := TFhirValueSetCodeSystem.Create; Context.ValueSet.codeSystem.version := edtDefineVersion.Text; Context.commit('defineversion'); end; end; procedure TValueSetEditorForm.edtEmailChange(Sender: TObject); begin if not loading then begin Context.ValueSet.contactList.SetSystem(ContactPointSystemEmail, edtEmail.Text); Context.commit('email'); end; end; procedure TValueSetEditorForm.edtFilterChange(Sender: TObject); begin Context.Settings.Filter := edtFilter.Text; end; procedure TValueSetEditorForm.edtIdentifierChange(Sender: TObject); begin if not loading then begin Context.ValueSet.url := edtIdentifier.Text; Context.commit('identifier'); ValidateEdit(edtIdentifier, Context.validateIdentifier(edtIdentifier.Text)); end; end; procedure TValueSetEditorForm.edtImportUriChange(Sender: TObject); var pr : PTreeDataPointer; p : PTreeDataPointer; ctxt : TFhirUri; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); if (pr = nil) then ctxt := nil else ctxt := TFhirUri(pr.obj); if not loading and (ctxt <> nil) then begin ctxt.value := edtImportUri.text; ValidateCombo(edtImportUri, context.validateImport(edtImportUri.Text)); Context.commit('include'); tvStructure.Repaint; Context.GetPreview(edtImportUri.Text); end; end; procedure TValueSetEditorForm.edtImportUriEnter(Sender: TObject); begin Context.GetList(VS_LIST, edtImportUri.StoredItems); edtImportUri.Items.Assign(edtImportUri.StoredItems); end; procedure TValueSetEditorForm.edtNameChange(Sender: TObject); begin if not loading then begin Context.ValueSet.name := edtName.Text; Context.commit('name'); if edtName.Text = '' then edtName.Color := COLOUR_MANDATORY else edtName.Color := COLOUR_OK; end; end; procedure TValueSetEditorForm.edtPhoneChange(Sender: TObject); begin if not loading then begin Context.ValueSet.contactList.SetSystem(ContactPointSystemPhone, edtPhone.Text); Context.commit('phone'); end; end; procedure TValueSetEditorForm.edtPublisherChange(Sender: TObject); begin if not loading then begin Context.ValueSet.publisher := edtPublisher.Text; Context.commit('publisher'); end; end; procedure TValueSetEditorForm.edtSystemReferenceChange(Sender: TObject); var pr : PTreeDataPointer; p : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); if (pr = nil) then ctxt := nil else ctxt := TFhirValueSetComposeInclude(pr.obj); if not loading and (ctxt <> nil) then begin ctxt.system := edtSystemReference.text; ValidateCombo(edtSystemReference, context.validateReference(edtSystemReference.Text)); Context.commit('sysref'); tvStructure.Invalidate; end; end; procedure TValueSetEditorForm.edtSystemReferenceEnter(Sender: TObject); begin Context.GetList(CS_LIST, edtSystemReference.StoredItems); edtSystemReference.Items.Assign(edtSystemReference.StoredItems); end; procedure TValueSetEditorForm.edtSystemRefVersionChange(Sender: TObject); var pr : PTreeDataPointer; p : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); if (pr = nil) then ctxt := nil else ctxt := TFhirValueSetComposeInclude(pr.obj); if not loading and (ctxt <> nil) then begin ctxt.version := edtSystemRefVersion.text; Context.commit('sysrefver'); end; end; procedure TValueSetEditorForm.edtVersionChange(Sender: TObject); begin if not loading then begin Context.ValueSet.version := edtVersion.Text; Context.commit('version'); end; end; procedure TValueSetEditorForm.edtWebChange(Sender: TObject); begin if not loading then begin Context.ValueSet.contactList.SetSystem(ContactPointSystemOther, edtWeb.Text); Context.commit('web'); end; end; procedure TValueSetEditorForm.txtDescriptionChange(Sender: TObject); begin if not loading then begin Context.ValueSet.description := txtDescription.Text; Context.commit('desc'); if txtDescription.Text = '' then txtDescription.Color := COLOUR_MANDATORY else txtDescription.Color := COLOUR_OK; end; end; procedure TValueSetEditorForm.Validate(sender: TObject); begin FOnCheckButtons(self); ValidateEdit(edtIdentifier, Context.validateIdentifier(edtIdentifier.Text)); ValidateEdit(edtDefineURI, Context.validateSystem(edtDefineURI.Text)); ValidateCombo(edtImportUri, Context.validateImport(edtImportUri.Text)); ValidateCombo(edtSystemReference, Context.validateReference(edtSystemReference.Text)); ValidateEdit(edtName, Context.validateName(edtName.Text)); ValidateMemo(txtDescription, Context.validateDescription(txtDescription.Text)); end; procedure TValueSetEditorForm.ValidateEdit(edit: TEdit; outcome : TValidationOutcome); begin if outcome.kind = voOk then begin edit.ParentShowHint := false; edit.ShowHint := false; edit.Hint := ''; edit.Color := COLOUR_OK; end else begin edit.ParentShowHint := false; edit.ShowHint := true; edit.Hint := outcome.msg; case outcome.kind of voMissing: edit.Color := COLOUR_MANDATORY; voError: edit.Color := COLOUR_ERROR; voWarning: edit.Color := COLOUR_WARNING; voHint : edit.Color := COLOUR_HINT; end; end; end; procedure TValueSetEditorForm.ValidateCombo(combo: TCombobox; outcome : TValidationOutcome); begin if outcome.kind = voOk then begin combo.ParentShowHint := false; combo.ShowHint := false; combo.Hint := ''; combo.Color := COLOUR_OK; end else begin combo.ParentShowHint := false; combo.ShowHint := true; combo.Hint := outcome.msg; case outcome.kind of voMissing: combo.Color := COLOUR_MANDATORY; voError: combo.Color := COLOUR_ERROR; voWarning: combo.Color := COLOUR_WARNING; voHint : combo.Color := COLOUR_HINT; end; end; end; procedure TValueSetEditorForm.ValidateMemo(memo : TMemo; outcome : TValidationOutcome); begin if outcome.kind = voOk then begin memo.ParentShowHint := false; memo.ShowHint := false; memo.Hint := ''; memo.Color := COLOUR_OK; end else begin memo.ParentShowHint := false; memo.ShowHint := true; memo.Hint := outcome.msg; case outcome.kind of voMissing: memo.Color := COLOUR_MANDATORY; voError: memo.Color := COLOUR_ERROR; voWarning: memo.Color := COLOUR_WARNING; end; end; end; procedure TValueSetEditorForm.WelcomeScreen1Click(Sender: TObject); begin ValueSetEditorWelcomeForm.Context := Context.Link; ValueSetEditorWelcomeForm.showModal; end; procedure TValueSetEditorForm.tvCodeSystemBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); var p : PTreeDataPointer; c : TFhirValueSetCodeSystemConcept; kind : TValidationOutcomeKind; msg : String; begin p := Sender.GetNodeData(Node); c := TFhirValueSetCodeSystemConcept(p.obj); if Context.checkValidation(c, column, kind, msg) and (kind <> voOK) then begin case kind of voMissing: TargetCanvas.Brush.Color := COLOUR_MANDATORY; voError: TargetCanvas.Brush.Color := COLOUR_ERROR; voWarning: TargetCanvas.Brush.Color := COLOUR_WARNING; voHint : TargetCanvas.Brush.Color := COLOUR_HINT; end; TargetCanvas.Brush.Style := bsSolid; TargetCanvas.FillRect(CellRect); end; end; procedure TValueSetEditorForm.tvCodeSystemColumnResize(Sender: TVTHeader; Column: TColumnIndex); begin case column of 0 : Context.Settings.setColumnWidth('define', 'code', tvCodeSystem.Header.Columns[0].width); 1 : Context.Settings.setColumnWidth('define', 'abstract', tvCodeSystem.Header.Columns[1].width); 2 : Context.Settings.setColumnWidth('define', 'display', tvCodeSystem.Header.Columns[2].width); 3 : Context.Settings.setColumnWidth('define', 'definition', tvCodeSystem.Header.Columns[3].width); end; end; procedure TValueSetEditorForm.tvCodesBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); var p : PTreeDataPointer; c : TFhirCode; kind : TValidationOutcomeKind; msg : String; begin p := Sender.GetNodeData(Node); c := TFhirCode(p.obj); if Context.checkValidation(c, column, kind, msg) and (kind <> voOK) then begin case kind of voMissing: TargetCanvas.Brush.Color := COLOUR_MANDATORY; voError: TargetCanvas.Brush.Color := COLOUR_ERROR; voWarning: TargetCanvas.Brush.Color := COLOUR_WARNING; voHint : TargetCanvas.Brush.Color := COLOUR_HINT; end; TargetCanvas.Brush.Style := bsSolid; TargetCanvas.FillRect(CellRect); end; end; procedure TValueSetEditorForm.tvCodesColumnResize(Sender: TVTHeader; Column: TColumnIndex); begin case column of 0 : Context.Settings.setColumnWidth('codes', 'code', tvCodes.Header.Columns[0].width); 1 : Context.Settings.setColumnWidth('codes', 'display', tvCodes.Header.Columns[1].width); 2 : Context.Settings.setColumnWidth('codes', 'comments', tvCodes.Header.Columns[2].width); end; end; procedure TValueSetEditorForm.tvFiltersColumnResize(Sender: TVTHeader; Column: TColumnIndex); begin case column of 0 : Context.Settings.setColumnWidth('filters', 'property', tvFilters.Header.Columns[0].width); 1 : Context.Settings.setColumnWidth('filters', 'op', tvFilters.Header.Columns[1].width); 2 : Context.Settings.setColumnWidth('filters', 'value', tvFilters.Header.Columns[2].width); end; end; procedure TValueSetEditorForm.tvExpansionColumnResize(Sender: TVTHeader; Column: TColumnIndex); begin case column of 0 : Context.Settings.setColumnWidth('expansion', 'system', tvExpansion.Header.Columns[0].width); 1 : Context.Settings.setColumnWidth('expansion', 'code', tvExpansion.Header.Columns[1].width); 2 : Context.Settings.setColumnWidth('expansion', 'display', tvExpansion.Header.Columns[2].width); end; end; procedure TValueSetEditorForm.tvPreviewColumnResize(Sender: TVTHeader; Column: TColumnIndex); begin case column of 0 : Context.Settings.setColumnWidth('preview', 'system', tvPreview.Header.Columns[0].width); 1 : Context.Settings.setColumnWidth('preview', 'code', tvPreview.Header.Columns[1].width); 2 : Context.Settings.setColumnWidth('preview', 'display', tvPreview.Header.Columns[2].width); end; end; procedure TValueSetEditorForm.tvCodeSystemInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var list : TFhirValueSetCodeSystemConceptList; pp, p : PTreeDataPointer; begin if parentNode = nil then list := Context.ValueSet.codeSystem.conceptList else begin pp := tvCodeSystem.GetNodeData(parentNode); list := TFhirValueSetCodeSystemConcept(pp.obj).conceptList; end; p := tvCodeSystem.GetNodeData(Node); p.obj := list[Node.Index]; if list[node.Index].conceptList.Count > 0 then InitialStates := [ivsHasChildren]; end; procedure TValueSetEditorForm.tvCodeSystemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if CharInSet(AnsiChar(Key), ['A'..'Z', '0'..'9']) then begin if ssShift in shift then FFirstChar := AnsiChar(Key) else FFirstChar := lowercase(AnsiChar(Key)); tvCodeSystem.EditNode(tvCodeSystem.FocusedNode, tvCodeSystem.FocusedColumn); end; end; procedure TValueSetEditorForm.tvCodeSystemInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); var p : PTreeDataPointer; c : TFhirValueSetCodeSystemConcept; begin p := tvCodeSystem.GetNodeData(node); c := TFhirValueSetCodeSystemConcept(p.obj); ChildCount := c.conceptList.Count; end; procedure TValueSetEditorForm.tvAllGetHint(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var LineBreakStyle: TVTTooltipLineBreakStyle; var HintText: string); var p : PTreeDataPointer; c : TFhirValueSetCodeSystemConcept; kind : TValidationOutcomeKind; msg : String; begin p := Sender.GetNodeData(Node); c := TFhirValueSetCodeSystemConcept(p.obj); if Context.checkValidation(c, column, kind, msg) then HintText := msg; end; procedure TValueSetEditorForm.tvAllGetHintKind(sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Kind: TVTHintKind); begin Kind := vhkText; end; procedure TValueSetEditorForm.tvCodeSystemGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var p : PTreeDataPointer; c : TFhirValueSetCodeSystemConcept; begin p := tvCodeSystem.GetNodeData(Node); c := TFhirValueSetCodeSystemConcept(p.obj); case Column of 0: CellText := c.code; 1: if c.abstract then CellText := 'abstract' else CellText := ''; 2: CellText := c.display; 3: CellText := c.definition; end; end; procedure TValueSetEditorForm.codeSystemCheckButtons(sender : TObject); var p : PTreeDataPointer; ctxt : TFhirValueSetCodeSystemConceptList; begin tbInsert.Enabled := not tvCodeSystem.IsEditing and (Context.ValueSet <> nil); tbDelete.Enabled := not tvCodeSystem.IsEditing and (tvCodeSystem.FocusedNode <> nil); tbUp.Enabled := false; tbDown.Enabled := false; tbIn.Enabled := false; tbOut.Enabled := false; if not tvCodeSystem.IsEditing and (tvCodeSystem.FocusedNode <> nil) then begin tbIn.Enabled := false; p := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode.Parent); if (p = nil) then ctxt := Context.ValueSet.codeSystem.conceptList else begin ctxt := TFhirValueSetCodeSystemConcept(p.obj).conceptList; tbIn.Enabled := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode.Parent) <> nil; end; tbUp.Enabled := tvCodeSystem.FocusedNode.Index > 0; tbDown.Enabled := (tvCodeSystem.FocusedNode.Index < ctxt.Count - 1); tbOut.Enabled := tvCodeSystem.FocusedNode.Index > 0; end; miTvInsert.Enabled := tbInsert.Enabled; miTvDelete.Enabled := tbDelete.Enabled; miTvUp.Enabled := tbUp.Enabled; miTvDown.Enabled := tbDown.Enabled; miTvIn.Enabled := tbIn.Enabled; miTvOut.Enabled := tbOut.Enabled; end; procedure TValueSetEditorForm.doco(filename: String); var fn : String; begin fn := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(ExtractFilePath(paramstr(0)))+'doco')+filename; if not FileExists(fn) then fn := 'C:\work\com.healthintersections.fhir\ValueSetEditor\doco\'+filename; webDoco.Navigate2('file:'+fn); end; function TValueSetEditorForm.EditValue(text: String): String; begin if (FFirstChar <> '') then result := FFirstChar else result := text; end; procedure TValueSetEditorForm.btnAddDefineClick(Sender: TObject); var p : PTreeDataPointer; ctxt : TFhirValueSetCodeSystemConceptList; begin if not tvCodeSystem.IsEditing then begin if Context.ValueSet.codeSystem = nil then Context.ValueSet.codeSystem := TFhirValueSetCodeSystem.Create; if tvCodeSystem.FocusedNode = nil then ctxt := Context.ValueSet.codeSystem.conceptList else begin p := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode); ctxt := TFhirValueSetCodeSystemConcept(p.obj).conceptList; end; ctxt.Append.code := 'code'; Context.Commit(''); if (ctxt <> Context.ValueSet.codeSystem.conceptList) then tvCodeSystem.ReinitNode(tvCodeSystem.FocusedNode, true) else begin tvCodeSystem.RootNodeCount := 0; tvCodeSystem.RootNodeCount := Context.ValueSet.codeSystem.conceptList.Count; end; end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnDeleteDefineClick(Sender: TObject); var p : PTreeDataPointer; ctxt : TFhirValueSetCodeSystemConcept; begin if not tvCodeSystem.IsEditing and (tvCodeSystem.FocusedNode <> nil) then begin p := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode.Parent); if (p = nil) then ctxt := nil else ctxt := TFhirValueSetCodeSystemConcept(p.obj); if ctxt = nil then begin Context.ValueSet.codeSystem.conceptList.DeleteByIndex(tvCodeSystem.FocusedNode.Index); tvCodeSystem.RootNodeCount := 0; tvCodeSystem.RootNodeCount := Context.ValueSet.codeSystem.conceptList.Count; end else begin ctxt.conceptList.DeleteByIndex(tvCodeSystem.FocusedNode.Index); tvCodeSystem.ReInitNode(tvCodeSystem.FocusedNode.Parent, true); end; Context.commit(''); end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnDefineDownClick(Sender: TObject); var p : PTreeDataPointer; ctxt : TFhirValueSetCodeSystemConcept; begin if (tvCodeSystem.FocusedNode <> nil) then begin p := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode.Parent); if (p = nil) then ctxt := nil else ctxt := TFhirValueSetCodeSystemConcept(p.obj); if ctxt = nil then begin if (tvCodeSystem.FocusedNode.Index < Context.ValueSet.codeSystem.conceptList.Count - 1) then begin Context.ValueSet.codeSystem.conceptList.Exchange(tvCodeSystem.FocusedNode.Index + 1, tvCodeSystem.FocusedNode.Index); tvCodeSystem.RootNodeCount := 0; tvCodeSystem.RootNodeCount := Context.ValueSet.codeSystem.conceptList.Count; end else MessageBeep(MB_ICONEXCLAMATION); end else begin if (tvCodeSystem.FocusedNode.Index < ctxt.conceptList.Count - 1) then begin ctxt.conceptList.Exchange(tvCodeSystem.FocusedNode.Index + 1, tvCodeSystem.FocusedNode.Index); tvCodeSystem.ReinitNode(tvCodeSystem.FocusedNode.Parent, true); end else MessageBeep(MB_ICONEXCLAMATION); end; Context.commit(''); end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnDefineLeftClick(Sender: TObject); var p, pp : PTreeDataPointer; ctxt, pCtxt : TFhirValueSetCodeSystemConceptList; begin if (tvCodeSystem.FocusedNode <> nil) then begin p := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode.Parent); if (p <> nil) then begin ctxt := TFhirValueSetCodeSystemConcept(p.obj).ConceptList; pp := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode.Parent.Parent); if pp = nil then pCtxt := Context.Valueset.codeSystem.ConceptList else pctxt := TFhirValueSetCodeSystemConcept(pp.obj).ConceptList; pctxt.add(ctxt[tvCodeSystem.FocusedNode.Index].Link); ctxt.DeleteByIndex(tvCodeSystem.FocusedNode.Index); if pp = nil then begin tvCodeSystem.RootNodeCount := 0; tvCodeSystem.RootNodeCount := pCtxt.Count; end else tvCodeSystem.ReinitNode(tvCodeSystem.FocusedNode.Parent.Parent, true); Context.commit(''); end else MessageBeep(MB_ICONEXCLAMATION); end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnDefineRightClick(Sender: TObject); var p : PTreeDataPointer; ctxt : TFhirValueSetCodeSystemConcept; begin if (tvCodeSystem.FocusedNode <> nil) and (tvCodeSystem.FocusedNode.Index > 0) then begin p := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode.Parent); if (p = nil) then ctxt := nil else ctxt := TFhirValueSetCodeSystemConcept(p.obj); if ctxt = nil then begin Context.ValueSet.codeSystem.conceptList[tvCodeSystem.FocusedNode.Index - 1].conceptList.add(Context.ValueSet.codeSystem.conceptList[tvCodeSystem.FocusedNode.Index].Link); Context.ValueSet.codeSystem.conceptList.DeleteByIndex(tvCodeSystem.FocusedNode.Index); tvCodeSystem.RootNodeCount := 0; tvCodeSystem.RootNodeCount := Context.ValueSet.codeSystem.conceptList.Count; end else begin ctxt.conceptList[tvCodeSystem.FocusedNode.Index - 1].conceptList.add(ctxt.conceptList[tvCodeSystem.FocusedNode.Index].Link); ctxt.conceptList.DeleteByIndex(tvCodeSystem.FocusedNode.Index); tvCodeSystem.ReinitNode(tvCodeSystem.FocusedNode.Parent, true); end; Context.commit(''); end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnDefineUpClick(Sender: TObject); var p : PTreeDataPointer; ctxt : TFhirValueSetCodeSystemConcept; begin if (tvCodeSystem.FocusedNode <> nil) and (tvCodeSystem.FocusedNode.Index > 0) then begin p := tvCodeSystem.GetNodeData(tvCodeSystem.FocusedNode.Parent); if (p = nil) then ctxt := nil else ctxt := TFhirValueSetCodeSystemConcept(p.obj); if ctxt = nil then begin Context.ValueSet.codeSystem.conceptList.Exchange(tvCodeSystem.FocusedNode.Index - 1, tvCodeSystem.FocusedNode.Index); tvCodeSystem.RootNodeCount := 0; tvCodeSystem.RootNodeCount := Context.ValueSet.codeSystem.conceptList.Count; end else begin ctxt.conceptList.Exchange(tvCodeSystem.FocusedNode.Index - 1, tvCodeSystem.FocusedNode.Index); tvCodeSystem.ReinitNode(tvCodeSystem.FocusedNode.Parent, true); end; Context.commit(''); end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.tvCodeSystemCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); var p : PTreeDataPointer; c : TFhirValueSetCodeSystemConcept; begin p := tvCodeSystem.GetNodeData(Node); c := TFhirValueSetCodeSystemConcept(p.obj); case Column of 0: EditLink := TVirtualStringTreeEdit.Create(EditValue(c.code), FFirstChar <> ''); 1: if c.abstract then EditLink := TVirtualStringTreeComboBox.Create('abstract', true, GetAbstractList, '') else EditLink := TVirtualStringTreeComboBox.Create('', true, GetAbstractList, ''); 2: EditLink := TVirtualStringTreeEdit.Create(EditValue(c.display), FFirstChar <> ''); 3: EditLink := TVirtualStringTreeEdit.Create(EditValue(c.definition), FFirstChar <> ''); else EditLink := nil; end; FFirstChar := ''; end; procedure TValueSetEditorForm.tvCodeSystemEditCancelled(Sender: TBaseVirtualTree; Column: TColumnIndex); begin codeSystemCheckButtons(self); end; procedure TValueSetEditorForm.tvCodeSystemEdited(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin codeSystemCheckButtons(self); end; procedure TValueSetEditorForm.tvCodeSystemEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean); begin codeSystemCheckButtons(self); end; procedure TValueSetEditorForm.tvCodeSystemEnter(Sender: TObject); begin FOnCheckButtons := codeSystemCheckButtons; tbInsert.OnClick := btnAddDefineClick; tbDelete.OnClick := btnDeleteDefineClick; tbUp.OnClick := btnDefineUpClick; tbDown.OnClick := btnDefineDownClick; tbIn.OnClick := btnDefineLeftClick; tbOut.OnClick := btnDefineRightClick; miTvInsert.OnClick := tbInsert.OnClick; miTvDelete.OnClick := tbDelete.OnClick; miTvUp.OnClick := tbUp.OnClick; miTvDown.OnClick := tbDown.OnClick; miTvIn.OnClick := tbIn.OnClick; miTvOut.OnClick := tbOut.OnClick; codeSystemCheckButtons(self); end; procedure TValueSetEditorForm.tvCodeSystemExit(Sender: TObject); begin tbInsert.OnClick := nil; tbDelete.OnClick := nil; tbUp.OnClick := nil; tbDown.OnClick := nil; tbIn.OnClick := nil; tbOut.OnClick := nil; miTvInsert.OnClick := tbInsert.OnClick; miTvDelete.OnClick := tbDelete.OnClick; miTvUp.OnClick := tbUp.OnClick; miTvDown.OnClick := tbDown.OnClick; miTvIn.OnClick := tbIn.OnClick; miTvOut.OnClick := tbOut.OnClick; FOnCheckButtons := noButtons; FOnCheckButtons(self); end; procedure TValueSetEditorForm.tvCodeSystemFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin FOnCheckButtons(self); end; procedure TValueSetEditorForm.tvCodeSystemNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string); var p : PTreeDataPointer; c : TFhirValueSetCodeSystemConcept; begin p := tvCodeSystem.GetNodeData(Node); c := TFhirValueSetCodeSystemConcept(p.obj); case Column of 0: c.code := NewText; 1: c.abstract := NewText <> ''; 2: c.display := NewText; 3: c.definition := NewText; end; Context.commit(''); end; procedure TValueSetEditorForm.tvStructureInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var p, pp : PTreeDataPointer; c : integer; begin c := 0; p := tvStructure.GetNodeData(node); if ParentNode = nil then begin // one of the 6 parent nodes p.obj := TObject(node.Index+1); InitialStates := [ivsExpanded, ivsHasChildren]; end else begin pp := tvStructure.GetNodeData(parentnode); p.obj := nil; if (Context <> nil) and (Context.ValueSet <> nil) and (Context.ValueSet.Compose <> nil) then case integer(pp.obj) of 3: if Context.ValueSet.compose.importList.Count > node.index then p.obj := Context.ValueSet.compose.importList[node.Index]; 4: if Context.ValueSet.compose.includeList.Count > node.index then p.obj := Context.ValueSet.compose.includeList[node.Index]; 5: if Context.ValueSet.compose.excludeList.Count > node.index then p.obj := Context.ValueSet.compose.excludeList[node.Index]; end; end; end; procedure TValueSetEditorForm.tvStructureInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); var p : PTreeDataPointer; begin p := tvStructure.GetNodeData(node); ChildCount := 0; if (Context <> nil) and (Context.ValueSet <> nil) and (Context.ValueSet.Compose <> nil) then case integer(p.obj) of 3: ChildCount := Max(1, Context.ValueSet.compose.importList.Count); 4: ChildCount := Max(1, Context.ValueSet.compose.includeList.Count); 5: ChildCount := Max(1, Context.ValueSet.compose.excludeList.Count); end else if integer(p.obj) in [3..5] then ChildCount := 1; end; procedure TValueSetEditorForm.tvStructurePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); var p : PTreeDataPointer; begin p := tvStructure.GetNodeData(node); if integer(p.obj) < 10 then TargetCanvas.Font.Style := [fsBold] else TargetCanvas.Font.Style := []; end; procedure TValueSetEditorForm.tvStructureGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var p : PTreeDataPointer; elem : TFhirElement; begin p := tvStructure.GetNodeData(node); if p.obj = nil then CellText := '(nil)'; if integer(p.obj) < 10 then case integer(p.obj) of 1: CellText := NAME_INFORMATION; 2: CellText := NAME_DEFINE; 3: CellText := NAME_IMPORT+':'; 4: CellText := NAME_INCLUDE+':'; 5: CellText := NAME_EXCLUDE+':'; 6: CellText := NAME_EXPAND; end else begin elem := TFhirElement(p.obj); if elem is TFHIRURI then CellText := Context.NameValueSet(TFHIRURI(elem).value) else if elem is TFhirValueSetComposeInclude then CellText := Context.NameCodeSystem(TFhirValueSetComposeInclude(elem).system) else CellText := '??'; end; end; procedure TValueSetEditorForm.tvStructureFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin FOnCheckButtons(self); end; procedure TValueSetEditorForm.btnAddRuleClick(sender : TObject); var n : PVirtualNode; p : PTreeDataPointer; begin if (Context.ValueSet <> nil) and (tvStructure.FocusedNode <> nil) then begin n := tvStructure.FocusedNode; p := tvStructure.GetNodeData(n); if not (Integer(p.obj) in [3..5]) then begin n := tvStructure.FocusedNode.Parent; p := tvStructure.GetNodeData(n); end; if Context.ValueSet.compose = nil then Context.ValueSet.compose := TFhirValueSetCompose.Create; case integer(p.obj) of 3: Context.ValueSet.compose.importList.Append; 4: Context.ValueSet.compose.includeList.Append; 5: Context.ValueSet.compose.excludeList.Append; else MessageBeep(MB_ICONEXCLAMATION); end; Context.commit(''); tvStructure.ReinitNode(n, true); tvStructure.FocusedNode := n.LastChild; tvStructureClick(self); end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnDeleteRuleClick(sender : TObject); var n : PVirtualNode; p : PTreeDataPointer; begin if (Context.ValueSet <> nil) and (tvStructure.FocusedNode <> nil) then begin n := tvStructure.FocusedNode; p := tvStructure.GetNodeData(n); if not (Integer(p.obj) in [3..5]) then begin p := tvStructure.GetNodeData(tvStructure.FocusedNode.Parent); case integer(p.obj) of 3: Context.ValueSet.compose.importList.DeleteByIndex(n.Index); 4: Context.ValueSet.compose.includeList.DeleteByIndex(n.Index); 5: Context.ValueSet.compose.excludeList.DeleteByIndex(n.Index); end; Context.Commit(''); tvStructure.RootNodeCount := 0; tvStructure.RootNodeCount := 6; tvStructureClick(self); end; end; end; procedure TValueSetEditorForm.btnRuleUpClick(sender : TObject); begin raise Exception.Create('To Do'); end; procedure TValueSetEditorForm.btnRuleDownClick(sender : TObject); begin raise Exception.Create('To Do'); end; procedure TValueSetEditorForm.tvStructureClick(Sender: TObject); var p : PTreeDataPointer; elem : TFhirElement; begin Context.UndoBreak; p := tvStructure.GetNodeData(tvStructure.FocusedNode); if (p <> nil) then begin if p.obj = nil then begin PageControl1.ActivePage := tabComposition; Notebook2.PageIndex := 0; end else if integer(p.obj) > 10 then begin elem := TFhirElement(p.obj); if elem is TFHIRURI then begin PageControl1.ActivePage := tabComposition; Notebook2.PageIndex := 1; edtImportUri.Text := TFHIRURI(elem).value; ValidateCombo(edtImportUri, context.validateImport(edtImportUri.Text)); Context.GetPreview(edtImportUri.Text); end else // elem is TFhirValueSetComposeInclude then begin Notebook2.PageIndex := 2; loading := true; try edtSystemReference.Text := TFhirValueSetComposeInclude(elem).system; ValidateCombo(edtSystemReference, context.validateReference(edtSystemReference.Text)); edtSystemRefVersion.Text := TFhirValueSetComposeInclude(elem).version; Context.PrepareSystemContext(TFhirValueSetComposeInclude(elem).system, TFhirValueSetComposeInclude(elem).version); tvCodes.RootNodeCount := 0; tvCodes.RootNodeCount := TFhirValueSetComposeInclude(elem).conceptList.Count; tvFilters.RootNodeCount := 0; tvFilters.RootNodeCount := TFhirValueSetComposeInclude(elem).filterList.Count; if tvFilters.RootNodeCount > 0 then Context.PrepareSystemContext('http://hl7.org/fhir/filter-operator', ''); finally loading := false; end; end end else if integer(p.obj) = 1 then PageControl1.ActivePage := tabInformation else if integer(p.obj) = 2 then PageControl1.ActivePage := tabDefined else if integer(p.obj) = 6 then PageControl1.ActivePage := tabExpansion else begin PageControl1.ActivePage := tabComposition; Notebook2.PageIndex := 0; end; end; end; // up to here -------------------------------------------------------------------------------------- procedure TValueSetEditorForm.tvCodesEnter(Sender: TObject); begin FOnCheckButtons := codesCheckButtons; tbInsert.OnClick := btnAddCodeClick; tbDelete.OnClick := btnDeleteCodeClick; tbUp.OnClick := btnCodesUpClick; tbDown.OnClick := btnCodesDownClick; miTvInsert.OnClick := tbInsert.OnClick; miTvDelete.OnClick := tbDelete.OnClick; miTvUp.OnClick := tbUp.OnClick; miTvDown.OnClick := tbDown.OnClick; codesCheckButtons(self); end; procedure TValueSetEditorForm.tvCodesExit(Sender: TObject); begin tbInsert.OnClick := nil; tbDelete.OnClick := nil; tbUp.OnClick := nil; tbDown.OnClick := nil; tbIn.OnClick := nil; tbOut.OnClick := nil; miTvInsert.OnClick := tbInsert.OnClick; miTvDelete.OnClick := tbDelete.OnClick; miTvUp.OnClick := tbUp.OnClick; miTvDown.OnClick := tbDown.OnClick; miTvIn.OnClick := tbIn.OnClick; miTvOut.OnClick := tbOut.OnClick; FOnCheckButtons := noButtons; FOnCheckButtons(self); end; procedure TValueSetEditorForm.tvCodesFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin FOnCheckButtons(self); end; procedure TValueSetEditorForm.codesCheckButtons(sender : TObject); var p : PTreeDataPointer; begin tbInsert.Enabled := true; // never any reason not to tbDelete.Enabled := tvCodes.FocusedNode <> nil; tbUp.Enabled := false; tbDown.Enabled := false; if tvCodes.FocusedNode <> nil then begin tbUp.Enabled := tvCodes.FocusedNode.Index > 0; tbDown.Enabled := tvCodes.FocusedNode.Index < tvCodes.FocusedNode.Parent.ChildCount - 1; end; tbIn.Enabled := False; tbOut.Enabled := False; miTvInsert.Enabled := tbInsert.Enabled; miTvDelete.Enabled := tbDelete.Enabled; miTvUp.Enabled := tbUp.Enabled; miTvDown.Enabled := tbDown.Enabled; miTvIn.Enabled := tbIn.Enabled; miTvOut.Enabled := tbOut.Enabled; end; procedure TValueSetEditorForm.tvCodesInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var pr : PTreeDataPointer; p : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); p := tvCodes.GetNodeData(Node); p.obj := ctxt.conceptList[Node.Index]; end; procedure TValueSetEditorForm.tvCodesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if CharInSet(AnsiChar(Key), ['A'..'Z', '0'..'9']) then begin if ssShift in shift then FFirstChar := AnsiChar(Key) else FFirstChar := lowercase(AnsiChar(Key)); tvCodes.EditNode(tvCodes.FocusedNode, tvCodes.FocusedColumn); end; end; procedure TValueSetEditorForm.tvCodesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var p : PTreeDataPointer; pr : PTreeDataPointer; code : TFhirCode; ctxt : TFhirValueSetComposeInclude; begin p := tvCodes.GetNodeData(Node); code := TFhirCode(p.obj); case Column of 0: CellText := code.value; 1: begin CellText := code.getExtensionString('http://hl7.org/fhir/Profile/tools-extensions#display'); if CellText = '' then begin if code.Tags['value'] = '' then begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); code.Tags['value'] := Context.TryGetDisplay(ctxt.system, code.value); end; CellText := code.Tags['value']; end; end; 2: CellText := code.getExtensionString('http://hl7.org/fhir/Profile/tools-extensions#comment'); end; end; procedure TValueSetEditorForm.btnManageServersClick(Sender: TObject); begin frmRegisterServer.Context := Context.Link; frmRegisterServer.ShowModal; loadServerList; end; procedure TValueSetEditorForm.btnAddCodeClick(Sender: TObject); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); ctxt.conceptList.Append.code := 'code'; Context.commit(''); tvCodes.RootNodeCount := 0; tvCodes.RootNodeCount := ctxt.conceptList.Count; end; procedure TValueSetEditorForm.btnDeleteCodeClick(Sender: TObject); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); ctxt.conceptList.DeleteByIndex(tvCodes.FocusedNode.Index); Context.commit(''); tvCodes.RootNodeCount := 0; tvCodes.RootNodeCount := ctxt.conceptList.Count; end; procedure TValueSetEditorForm.btnCodesDownClick(Sender: TObject); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); if (tvCodes.FocusedNode <> nil) and (tvCodes.FocusedNode.Index < ctxt.conceptList.count - 1) then begin ctxt.conceptList.Exchange(tvCodes.FocusedNode.Index, tvCodes.FocusedNode.Index + 1); Context.commit(''); tvCodes.RootNodeCount := 0; tvCodes.RootNodeCount := ctxt.conceptList.Count; end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnCodesUpClick(Sender: TObject); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin if (tvCodes.FocusedNode <> nil) and (tvCodes.FocusedNode.Index > 0) then begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); ctxt.conceptList.Exchange(tvCodes.FocusedNode.Index - 1, tvCodes.FocusedNode.Index); Context.commit(''); tvCodes.RootNodeCount := 0; tvCodes.RootNodeCount := ctxt.conceptList.Count; end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.tvCodesCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; p : PTreeDataPointer; code : TFhirCode; s : String; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); p := tvCodes.GetNodeData(Node); code := TFhirCode(p.obj); if Column = 0 then EditLink := TVirtualStringTreeComboBox.create(EditValue(code.value), false, Context.GetList, ctxt.system) else if Column = 1 then EditLink := TVirtualStringTreeComboBox.create(EditValue(code.getExtensionString('http://hl7.org/fhir/Profile/tools-extensions#display')), false, Context.GetList, ctxt.system+'#'+code.value) else // comments EditLink := TVirtualStringTreeEdit.Create(EditValue(code.getExtensionString('http://hl7.org/fhir/Profile/tools-extensions#comment')), FFirstChar <> ''); FFirstChar := ''; end; procedure TValueSetEditorForm.tvCodesDrawText(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; const Text: string; const CellRect: TRect; var DefaultDraw: Boolean); var p : PTreeDataPointer; c : TFhirCode; begin p := Sender.GetNodeData(Node); c := TFhirCode(p.obj); if (Column = 1) and (c.getExtensionString('http://hl7.org/fhir/Profile/tools-extensions#display') = '') then begin TargetCanvas.Font.Color := clGray; TargetCanvas.Font.Style := [fsItalic]; end else begin TargetCanvas.Font.Color := clBlack; TargetCanvas.Font.Style := []; end; end; procedure TValueSetEditorForm.tvCodesNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; code : TFhirValueSetComposeIncludeConcept; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); code := ctxt.conceptList[node.Index]; case Column of 0: code.code := NewText; 1: code.display := NewText; 2: if NewText = '' then code.removeExtension('http://hl7.org/fhir/Profile/tools-extensions#comment') else code.setExtensionString('http://hl7.org/fhir/Profile/tools-extensions#comment', NewText); end; Context.commit(''); end; // ----------------------------------------------------------------------------- procedure TValueSetEditorForm.tvFiltersEnter(Sender: TObject); begin FOnCheckButtons := filtersCheckButtons; tbInsert.OnClick := btnAddFilterClick; tbDelete.OnClick := btnDeleteFilterClick; tbUp.OnClick := btnFiltersUpClick; tbDown.OnClick := btnFiltersDownClick; miTvInsert.OnClick := tbInsert.OnClick; miTvDelete.OnClick := tbDelete.OnClick; miTvUp.OnClick := tbUp.OnClick; miTvDown.OnClick := tbDown.OnClick; filtersCheckButtons(self); end; procedure TValueSetEditorForm.tvFiltersExit(Sender: TObject); begin tbInsert.OnClick := nil; tbDelete.OnClick := nil; tbUp.OnClick := nil; tbDown.OnClick := nil; tbIn.OnClick := nil; tbOut.OnClick := nil; miTvInsert.OnClick := tbInsert.OnClick; miTvDelete.OnClick := tbDelete.OnClick; miTvUp.OnClick := tbUp.OnClick; miTvDown.OnClick := tbDown.OnClick; miTvIn.OnClick := tbIn.OnClick; miTvOut.OnClick := tbOut.OnClick; FOnCheckButtons := noButtons; FOnCheckButtons(self); end; procedure TValueSetEditorForm.filtersCheckButtons(sender : TObject); var p : PTreeDataPointer; begin tbInsert.Enabled := true; // never any reason not to tbDelete.Enabled := tvFilters.FocusedNode <> nil; tbUp.Enabled := false; tbDown.Enabled := false; if tvFilters.FocusedNode <> nil then begin tbUp.Enabled := tvFilters.FocusedNode.Index > 0; tbDown.Enabled := tvFilters.FocusedNode.Index < tvFilters.FocusedNode.Parent.ChildCount - 1; end; tbIn.Enabled := False; tbOut.Enabled := False; miTvInsert.Enabled := tbInsert.Enabled; miTvDelete.Enabled := tbDelete.Enabled; miTvUp.Enabled := tbUp.Enabled; miTvDown.Enabled := tbDown.Enabled; miTvIn.Enabled := tbIn.Enabled; miTvOut.Enabled := tbOut.Enabled; end; procedure TValueSetEditorForm.tvFiltersFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin FOnCheckButtons(self); end; procedure TValueSetEditorForm.tvFiltersInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var pr : PTreeDataPointer; p : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); p := tvCodes.GetNodeData(Node); p.obj := ctxt.filterList[Node.Index]; end; procedure TValueSetEditorForm.tvFiltersKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if CharInSet(AnsiChar(Key), ['A'..'Z', '0'..'9']) then begin if ssShift in shift then FFirstChar := AnsiChar(Key) else FFirstChar := lowercase(AnsiChar(Key)); tvFilters.EditNode(tvFilters.FocusedNode, tvFilters.FocusedColumn); end; end; procedure TValueSetEditorForm.tvFiltersGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var p : PTreeDataPointer; filter : TFhirValueSetComposeIncludeFilter; begin p := tvFilters.GetNodeData(Node); filter := TFhirValueSetComposeIncludeFilter(p.obj); case Column of 0: CellText := filter.property_; 1: CellText := CODES_TFhirFilterOperatorEnum[filter.op]; 2: CellText := filter.value; end; end; procedure TValueSetEditorForm.tvFiltersCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; p : PTreeDataPointer; filter : TFhirValueSetComposeIncludeFilter; s : String; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); p := tvFilters.GetNodeData(Node); filter := TFhirValueSetComposeIncludeFilter(p.obj); if Column = 0 then EditLink := TVirtualStringTreeComboBox.create(EditValue(filter.property_), false, Context.GetList, ValueSetEditorCore.ExpressionProperty+'#'+ctxt.system) else if Column = 1 then EditLink := TVirtualStringTreeComboBox.create(CODES_TFhirFilterOperatorEnum[filter.op], true, Context.GetList, 'http://hl7.org/fhir/filter-operator') else // value - just a plain string editor EditLink := TVirtualStringTreeEdit.Create(EditValue(filter.value), FFirstChar <> ''); FFirstChar := ''; end; procedure TValueSetEditorForm.btnAddFilterClick(Sender: TObject); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); ctxt.filterList.Append.op := FilterOperatorEqual; Context.commit(''); tvFilters.RootNodeCount := 0; tvFilters.RootNodeCount := ctxt.FilterList.Count; end; procedure TValueSetEditorForm.btnDeleteFilterClick(Sender: TObject); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); ctxt.FilterList.DeleteByIndex(tvFilters.FocusedNode.Index); Context.commit(''); tvFilters.RootNodeCount := 0; tvFilters.RootNodeCount := ctxt.FilterList.Count; end; procedure TValueSetEditorForm.btnFiltersUpClick(Sender: TObject); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin if (tvFilters.FocusedNode <> nil) and (tvFilters.FocusedNode.Index > 0) then begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); ctxt.FilterList.Exchange(tvFilters.FocusedNode.Index - 1, tvFilters.FocusedNode.Index); Context.commit(''); tvFilters.RootNodeCount := 0; tvFilters.RootNodeCount := ctxt.FilterList.Count; end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.btnFiltersDownClick(Sender: TObject); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); if (tvFilters.FocusedNode <> nil) and (tvFilters.FocusedNode.Index < ctxt.FilterList.count - 1) then begin ctxt.FilterList.Exchange(tvFilters.FocusedNode.Index, tvFilters.FocusedNode.Index + 1); Context.commit(''); tvFilters.RootNodeCount := 0; tvFilters.RootNodeCount := ctxt.FilterList.Count; end else MessageBeep(MB_ICONEXCLAMATION); end; procedure TValueSetEditorForm.tvFiltersNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string); var pr : PTreeDataPointer; ctxt : TFhirValueSetComposeInclude; filter : TFhirValueSetComposeIncludeFilter; begin pr := tvStructure.GetNodeData(tvStructure.FocusedNode); ctxt := TFhirValueSetComposeInclude(pr.obj); filter := ctxt.filterList[node.Index]; case Column of 0: filter.property_ := NewText; 1: filter.op := TFhirFilterOperatorEnum(Max(0, StringArrayIndexOf(CODES_TFhirFilterOperatorEnum, NewText))); 2: filter.value := NewText; end; Context.commit(''); end; // expansion-------------- procedure TValueSetEditorForm.btnEditCodesClick(Sender: TObject); begin PageControl1.ActivePage := tabDefined; end; procedure TValueSetEditorForm.Button2Click(Sender: TObject); begin ServerOperation(Context.Expand, edtFilter.Text, 'Expanding', true); lblExpansion.Caption := inttostr(Context.Expansion.containsList.Count)+' codes'; tvExpansion.RootNodeCount := 0; tvExpansion.RootNodeCount := Max(1, Context.Expansion.containsList.Count); end; procedure TValueSetEditorForm.btnNewImportClick(Sender: TObject); var n : PVirtualNode; begin n := tvStructure.RootNode.FirstChild; n := n.NextSibling.NextSibling; tvStructure.FocusedNode := n; btnAddRuleClick(self); end; procedure TValueSetEditorForm.btnNewIncludeClick(Sender: TObject); var n : PVirtualNode; begin n := tvStructure.RootNode.FirstChild; n := n.NextSibling.NextSibling.NextSibling; tvStructure.FocusedNode := n; btnAddRuleClick(self); end; procedure TValueSetEditorForm.tvExpansionInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var list : TFhirValueSetExpansionContainsList; pp, p : PTreeDataPointer; begin if parentNode = nil then list := Context.Expansion.containsList else begin pp := tvExpansion.GetNodeData(parentNode); list := TFhirValueSetExpansionContains(pp.obj).containsList; end; p := tvExpansion.GetNodeData(Node); if Node.Index < list.Count then begin p.obj := list[Node.Index]; if list[node.Index].containsList.Count > 0 then InitialStates := [ivsHasChildren]; end; end; procedure TValueSetEditorForm.tvExpansionInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); var p : PTreeDataPointer; c : TFhirValueSetExpansionContains; begin p := tvExpansion.GetNodeData(node); c := TFhirValueSetExpansionContains(p.obj); if (c <> nil) then ChildCount := c.containsList.Count; end; procedure TValueSetEditorForm.tvExpansionGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var p : PTreeDataPointer; c : TFhirValueSetExpansionContains; begin p := tvExpansion.GetNodeData(Node); c := TFhirValueSetExpansionContains(p.obj); if (c <> nil) then case Column of 0: CellText := c.system; 1: CellText := c.code; 2: CellText := c.display; end else if Column = 0 then CellText := '(no entries)' else CellText := ''; end; procedure TValueSetEditorForm.tvExpansionCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var c1, c2 : TFhirValueSetExpansionContains; begin c1 := TFhirValueSetExpansionContains(PTreeDataPointer(tvExpansion.GetNodeData(node1)).obj); c2 := TFhirValueSetExpansionContains(PTreeDataPointer(tvExpansion.GetNodeData(node2)).obj); case column of 0 : result := CompareText(c1.system, c2.system); 1 : result := CompareText(c1.code, c2.code); 2 : result := CompareText(c1.display, c2.display); end; end; procedure TValueSetEditorForm.tvPreviewCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var c1, c2 : TFhirValueSetExpansionContains; begin c1 := TFhirValueSetExpansionContains(PTreeDataPointer(tvPreview.GetNodeData(node1)).obj); c2 := TFhirValueSetExpansionContains(PTreeDataPointer(tvPreview.GetNodeData(node2)).obj); case column of 0 : result := CompareText(c1.system, c2.system); 1 : result := CompareText(c1.code, c2.code); 2 : result := CompareText(c1.display, c2.display); end; end; procedure TValueSetEditorForm.tvPreviewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var p : PTreeDataPointer; c : TFhirValueSetExpansionContains; begin p := tvPreview.GetNodeData(Node); c := TFhirValueSetExpansionContains(p.obj); if (c <> nil) then case Column of 0: CellText := c.system; 1: CellText := c.code; 2: CellText := c.display; end else if Column = 0 then CellText := '(no entries)' else CellText := ''; end; procedure TValueSetEditorForm.tvPreviewInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); var p : PTreeDataPointer; c : TFhirValueSetExpansionContains; begin p := tvPreview.GetNodeData(node); c := TFhirValueSetExpansionContains(p.obj); if (c <> nil) then ChildCount := c.containsList.Count; end; procedure TValueSetEditorForm.tvPreviewInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var list : TFhirValueSetExpansionContainsList; pp, p : PTreeDataPointer; begin if parentNode = nil then list := Context.Preview.containsList else begin pp := tvPreview.GetNodeData(parentNode); list := TFhirValueSetExpansionContains(pp.obj).containsList; end; p := tvPreview.GetNodeData(Node); if Node.Index < list.Count then begin p.obj := list[Node.Index]; if list[node.Index].containsList.Count > 0 then InitialStates := [ivsHasChildren]; end; end; end.
unit lhelpstrconsts; {$mode objfpc}{$H+} interface resourcestring // GUI slhelp_About = 'About'; slhelp_LHelpCHMFileViewerVersionCopyrightCAndrewHainesLaz = 'LHelp (CHM file viewer)%sVersion %s%sCopyright (C) Andrew Haines, %sLazarus contributors'; slhelp_Ok = 'Ok'; slhelp_PleaseEnterAURL = 'Please enter a URL'; slhelp_SupportedURLTypeS = 'Supported URL type(s): (%s)'; slhelp_File = '&File'; slhelp_Open = '&Open ...'; slhelp_OpenRecent = 'Open Recent'; slhelp_OpenURL = 'Open &URL ...'; slhelp_Close = '&Close'; slhelp_EXit = 'E&xit'; slhelp_View = '&View'; slhelp_ShowContents = 'Show contents'; slhelp_OpenNewTabWithStatusBar = 'Open new tab with status bar'; slhelp_OpenNewFileInSeparateTab = 'Open new file in separate tab'; slhelp_Help = '&Help'; slhelp_About2 = '&About ...'; slhelp_OpenExistingFile = 'Open existing file'; slhelp_HelpFilesChmChmAllFiles = 'Help files (*.chm)|*.chm|All files (*.*)|*'; slhelp_LHelp = 'LHelp'; slhelp_LHelp2 = 'LHelp - %s'; slhelp_CannotHandleThisTypeOfContentForUrl = 'Cannot handle this type of content. "%s" for url:%s%s'; slhelp_CannotHandleThisTypeOfSubcontentForUrl = 'Cannot handle this type of subcontent. "%s" for url:%s%s'; slhelp_Loading = 'Loading: %s'; slhelp_NotFound = '%s not found!'; slhelp_LoadedInMs = 'Loaded: %s in %sms'; slhelp_TableOfContentsLoadingPleaseWait = 'Table of Contents Loading. Please Wait ...'; slhelp_TableOfContentsLoading = 'Table of Contents Loading ...'; slhelp_IndexLoading = 'Index Loading ...'; slhelp_Untitled = 'untitled'; slhelp_NoResults = 'No Results'; slhelp_Contents = 'Contents'; slhelp_Index = 'Index'; slhelp_Search = 'Search'; slhelp_Keyword = 'Keyword:'; slhelp_Find = 'Find'; slhelp_SearchResults = 'Search Results:'; slhelp_Copy = 'Copy'; slhelp_PageCannotBeFound = 'Page cannot be found!'; // --help slhelp_LHelpOptions = ' LHelp options:'; slhelp_UsageLhelpFilenameContextIdHideIpcnameLhelpMyapp = ' Usage: lhelp [[filename] [--context id] [--hide] [--ipcname lhelp-myapp]]'; slhelp_HelpShowThisInformation = ' --help : Show this information'; slhelp_HideStartHiddenButAcceptCommunicationsViaIPC = ' --hide : Start hidden but accept communications via IPC'; slhelp_ContextShowTheHelpInformationRelatedToThisContext = ' --context : Show the help information related to this context'; slhelp_IpcnameTheNameOfTheIPCServerToListenOnForProgramsW = ' --ipcname : The name of the IPC server to listen on for%s programs who wish to control the viewer'; implementation end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.TabControl, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Maps, FMX.ListView, System.Notification, FireDAC.UI.Intf, FireDAC.FMXUI.Wait, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Data.Bind.GenData, Fmx.Bind.GenData, Data.Bind.DBScope, Data.Bind.Components, Data.Bind.ObjectScope, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Comp.UI, Fmx.Bind.Editors, Data.DbxSqlite, Data.SqlExpr ,System.Android.Service, System.ImageList, FMX.ImgList, FMX.Objects, System.IOUtils; type TForm1 = class(TForm) pnlMain: TPanel; tbTop: TToolBar; TabControl1: TTabControl; Lista: TTabItem; Mapa: TTabItem; SpeedButton1: TSpeedButton; LVLinhas: TListView; MapView: TMapView; Notification: TNotificationCenter; FDGUIxWaitCursor1: TFDGUIxWaitCursor; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; Conexao: TFDConnection; BindSourceDB1: TBindSourceDB; FDQuery1: TFDQuery; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; TabItem1: TTabItem; LVParadas: TListView; BindSourceDB2: TBindSourceDB; FDQuery2: TFDQuery; ImageList1: TImageList; LinkFillControlToField2: TLinkFillControlToField; QryCreate: TFDQuery; FDQuery2ID_BUS_STOP: TFDAutoIncField; FDQuery2UUID: TWideStringField; FDQuery2LATITUDE: TFloatField; FDQuery2LONGITUDE: TFloatField; FDQuery2DESCRIPTION: TWideStringField; FDTransaction1: TFDTransaction; PrototypeBindSource1: TPrototypeBindSource; Image1: TImage; procedure FormCreate(Sender: TObject); procedure ConexaoBeforeConnect(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ConexaoAfterConnect(Sender: TObject); procedure LVParadasUpdateObjects(const Sender: TObject; const AItem: TListViewItem); private { Private declarations } FService : TLocalServiceConnection; procedure createTables; public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} {$R *.NmXhdpiPh.fmx ANDROID} procedure TForm1.ConexaoAfterConnect(Sender: TObject); begin createTables; FDQuery1.Open(); FDQuery2.Open(); end; procedure TForm1.ConexaoBeforeConnect(Sender: TObject); begin Conexao.Params.Values['Database'] := TPath.Combine(TPath.GetDocumentsPath, 'BusDB2.s3db'); end; procedure TForm1.createTables; begin with QryCreate do begin Transaction.StartTransaction; SQL.Clear; SQL.Add('CREATE TABLE IF NOT EXISTS BUS_LINE ( '+ 'ID_BUS_LINE INTEGER PRIMARY KEY AUTOINCREMENT '+ 'NOT NULL, '+ 'DESCRIPTION STRING '+ ');'); ExecSQL; Transaction.Commit; end; end; procedure TForm1.FormCreate(Sender: TObject); begin if not Conexao.Connected then Conexao.Connected := True; FService := TLocalServiceConnection.Create; FService.startService('TestDatabaseService'); end; procedure TForm1.FormDestroy(Sender: TObject); begin Conexao.Connected := False; end; procedure TForm1.FormShow(Sender: TObject); var MyMarker: TMapMarkerDescriptor; Position: TMapCoordinate; i : Integer; begin FDQuery2.First; while not FDQuery2.Eof do begin Position := TMapCoordinate.Create(FDQuery2LATITUDE.AsFloat, FDQuery2LONGITUDE.AsFloat); MyMarker := TMapMarkerDescriptor.Create(Position, FDQuery2DESCRIPTION.AsString); MyMarker.Draggable := True; MyMarker.Visible :=True; MapView.AddMarker(MyMarker); with LVParadas.Items.Add do begin Data['Description'] := FDQuery2DESCRIPTION.AsString; Data['StopId'] := FDQuery2ID_BUS_STOP.AsString; //Objects.FindObjectT<TListItemImage>('GotoMap').ImageIndex := 0; //ImageList1.Source.Items[0].MultiResBitmap[0].Bitmap; end; FDQuery2.Next; end; MapView.Location := TMapCoordinate.Create(-28.9360196, -49.482976); MapView.Zoom := 10; end; procedure TForm1.LVParadasUpdateObjects(const Sender: TObject; const AItem: TListViewItem); begin TListItemImage(AItem.View.FindDrawable('GotoMap')).Bitmap := Image1.Bitmap; end; end.
{ Copyright (C) <2005> <Andrew Haines> chmtypes.pas This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. } { See the file COPYING.FPC, included in this distribution, for details about the copyright. } unit chmtypes; {$mode objfpc}{$H+} interface uses Classes, SysUtils, xmlcfg; type TSectionName = (snMSCompressed, snUnCompressed); TSectionNames = set of TSectionName; { TDirectoryChunk } TDirectoryChunk = class(TObject) private FHeaderSize: Integer; FQuickRefEntries: Word; Buffer: array[0..$1000-1] of byte; CurrentPos: Integer; FItemCount: Word; FClearCount: Integer; public function CanHold(ASize: Integer): Boolean; function FreeSpace: Integer; procedure WriteHeader(AHeader: Pointer); procedure WriteEntry(Size: Integer; Data: Pointer); procedure WriteChunkToStream(Stream: TStream); overload; procedure Clear; property ItemCount: Word read FItemCount; constructor Create(AHeaderSize: Integer); end; { TPMGIDirectoryChunk } TPMGIDirectoryChunk = class(TDirectoryChunk) private FChunkLevelCount: Integer; FParentChunk: TPMGIDirectoryChunk; public procedure WriteChunkToStream(Stream: TStream; var AIndex: Integer; Final: Boolean = False); overload; property ParentChunk: TPMGIDirectoryChunk read FParentChunk write FParentChunk; property ChunkLevelCount: Integer read FChunkLevelCount write FChunkLevelCount; end; PFileEntryRec = ^TFileEntryRec; TFileEntryRec = record Path: String; Name: String; DecompressedOffset: QWord; DecompressedSize: QWord; Compressed: Boolean; // True means it goes in section1 False means section0 end; { TFileEntryList } TFileEntryList = class(TList) private FPaths: TStringList; function GetFileEntry(Index: Integer): TFileEntryRec; procedure SetFileEntry(Index: Integer; const AValue: TFileEntryRec); public function AddEntry(AFileEntry: TFileEntryRec; CheckPathIsAdded: Boolean = True): Integer; procedure Delete(Index: Integer); property FileEntry[Index: Integer]: TFileEntryRec read GetFileEntry write SetFileEntry; procedure Sort; constructor Create; destructor Destroy; override; end; TChmWindowEntry = packed record EntrySize: LongWord; // Size of the entry (188 in CHMs compiled with Compatibility set to 1.0, 196 in CHMs compiled with Compatibility set to 1.1 or later) IsUnicode: LongWord; // 0 (unknown) - but htmlhelp.h indicates that this is "BOOL fUniCodeStrings; // IN/OUT: TRUE if all strings are in UNICODE" WindowTypeStr: LongWord; // The window type. Offset in #STRINGS file. WindowFlags: LongWord; // Which window properties are valid & are to be used for this window. NavStyleFlags: LongWord; // A bit feild of navigation pane styles. TitleBarStr: LongWord; // The title bar text. Offset in #STRINGS file. StyleFlags: LongWord; // Style Flags. As set in the Win32 SetWindowLong & CreateWindow APIs. ExStyleFlags: LongWord; // Extended Style Flags. As set in the Win32 SetWindowLong & CreateWindowEx APIs WindowPosition: array [0..3] of LongWord; // Initial position of the window on the screen: [left, top, right, bottom]. WinShowState: LongWord; // Window show state. As set in the Win32 ShowWindow API. HelpHandle: LongWord; // Help window handle CallerHandle: LongWord; // who called this window InfoTypesPtr: LongWord; // Pointer to an array of Information Types ToolBarHandle: LongWord; // toolbar window in tri-pane window NavHandle: LongWord; // navigation window in tri-pane window HtmlHandle: LongWord; // window displaying HTML in tri-pane window NavWidth: LongWord; // Width of the navigation pane in pixels. TopicPaneRect: array [0..3] of LongWord; // Specifies the coordinates of the Topic pane. TocFileStr: LongWord; // The TOC file. Offset in #STRINGS file. IndexFileStr: LongWord; // The Index file. Offset in #STRINGS file. DefaultFileStr: LongWord; // The Default file. Offset in #STRINGS file. HomeFileStr: LongWord; // The file shown when the Home button is pressed. Offset in #STRINGS file. ButtonsFlags: LongWord; // A bit field of the buttons to show. IsNavPaneClosed: LongWord; // Whether or not the navigation pane is initially closed. 1 = closed, 0 = open NavPaneDefault: LongWord; // The default navigation pane. 0 = TOC, 1 = Index, 2 = Search, 3 = Favorites, 4 = History (not implemented by HH), 5 = Author, 11-19 = Custom panes. NavPaneLocation: LongWord; // Where the navigation pane tabs should be. 0 = Top, 1 = Left, 2 = Bottom & anything else makes the tabs appear to be behind the pane on Win95. WmNotifyId: LongWord; // ID to send in WM_NOTIFY messages. TabOrder: array [0..4] of LongWord; // tab order: Contents, Index, Search, History, Favorites, Reserved 1-5, Custom tabs HistoryDepth: LongWord; // number of history items to keep (default is 30) Jump1TextStr: LongWord; // The text of the Jump 1 button. Offset in #STRINGS file. Jump2TextStr: LongWord; // The text of the Jump 2 button. Offset in #STRINGS file. Jump1FileStr: LongWord; // The file shown when the Jump 1 button is pressed. Offset in #STRINGS file. Jump2FileStr: LongWord; // The file shown when the Jump 2 button is pressed. Offset in #STRINGS file. MinWindowSize: array [0..3] of LongWord; // Minimum size for window (ignored in version 1) // CHM 1.1 and later InfoTypeSize: LongWord; // size of paInfoTypes CustomTabs: LongWord; // multiple zero-terminated strings end; TValidWindowFieldsEnum = (valid_Unknown1 {:=1}, valid_Navigation_pane_style {:= 2}, valid_Window_style_flags {:= 4}, valid_Window_extended_style_flags {:= 8}, valid_Initial_window_position {:= $10}, valid_Navigation_pane_width {:= $20}, valid_Window_show_state {:= $40}, valid_Info_types {:= $80}, valid_Buttons {:= $100}, valid_Navigation_Pane_initially_closed_state {:= $200}, valid_Tab_position {:= $400}, valid_Tab_order {:= $800}, valid_History_count{ := $1000}, valid_Default_Pane {:= $2000}); TValidWindowFields = Set Of TValidWindowFieldsEnum; TCHMNavPaneStyle = bitpacked record AutoHide: Boolean; // False (recommended) KeepOnTop: Boolean; // False NoTitleBar: Boolean; // False NoDefaultStyles: Boolean; NoDefaultExtStyles: Boolean; UseNavPane: Boolean; // True NoTextOnButtons: Boolean; // True PostWmQuitOnClose: Boolean; // False AutoSyncOnTopicChange: Boolean; // True SendTrackingMessages: Boolean; // False IncludeSearchTab: Boolean; // True IncludeHistoryTab: Boolean; // False IncludeFavoritesTab: Boolean; // True ShowTopicTitle: Boolean; // True ShowEmptyPane: Boolean; // False DisableToolbar: Boolean; // False MSDNMenu: Boolean; // False AdvancedFTS_UI: Boolean; // True AllowChangePaneRect: Boolean; // True UseCustomTab1: Boolean; // False UseCustomTab2: Boolean; // False UseCustomTab3: Boolean; // False UseCustomTab4: Boolean; // False UseCustomTab5: Boolean; // False UseCustomTab6: Boolean; // False UseCustomTab7: Boolean; // False UseCustomTab8: Boolean; // False UseCustomTab9: Boolean; // False EnableMargin: Boolean; // True Unknown1: Boolean; Unknown2: Boolean; Unknown3: Boolean; end; TCHMToolbarButtons = bitpacked record Unknown1: Boolean; // True (recommended) HideShowBtn: Boolean; // True BackBtn: Boolean; // True ForwardBtn: Boolean; // True StopBtn: Boolean; // True RefreshBtn: Boolean; // True HomeBtn: Boolean; // True NextBtn: Boolean; // False PreviousBtn: Boolean; // False NotesBtn: Boolean; // False ContentsBtn: Boolean; // False LocateBtn: Boolean; // True OptionsBtn: Boolean; // True PrintBtn: Boolean; // True IndexBtn: Boolean; // False SearchBtn: Boolean; // False HistoryBtn: Boolean; // False FavoritesBtn: Boolean; // False Jump1Btn: Boolean; Jump2Btn: Boolean; FontBtn: Boolean; // True NextTopicBtn: Boolean; // True PreviousTopicBtn: Boolean; // True Unknown2: Boolean; Unknown3: Byte; end; { TCHMWindow } TCHMWindow = class public window_type, Title_bar_text, Toc_file, index_file, Default_File, Home_button_file, Jumpbutton_1_File, Jumpbutton_1_Text, Jumpbutton_2_File, Jumpbutton_2_Text : string; nav_style : integer; // overlay with bitfields (next 2 also) navpanewidth : integer; buttons : integer; left, top, right, bottom : integer; styleflags , xtdstyleflags, window_show_state, navpane_initially_closed, navpane_default, navpane_location, wm_notify_id : integer; flags : TValidWindowFields; // bitset that keeps track of which fields are filled. // of certain fields. Needs to be inserted into #windows stream constructor Create(s: string = ''); procedure load_from_ini(txt: string); deprecated; procedure SaveToXml(cfg: TXMLConfig; key: string); procedure LoadFromXml(cfg: TXMLConfig; key: string); procedure SaveToIni(out s: string); procedure LoadFromIni(s: string); procedure Assign(obj: TCHMWindow); end; { TCHMWindowList } TCHMWindowList = class(TList) protected procedure PutItem(Index: Integer; AValue: TCHMWindow); function GetItem(Index: Integer): TCHMWindow; procedure Notify(Ptr: Pointer; Action: TListNotification); override; public OwnsObjects: Boolean; property Items[Index: Integer]: TCHMWindow read GetItem write PutItem; default; end; TTOCIdxHeader = record BlockSize: DWord; // 4096 EntriesOffset: DWord; EntriesCount: DWord; TopicsOffset: DWord; EmptyBytes: array[0..4079] of byte; end; const TOC_ENTRY_HAS_NEW = 2; TOC_ENTRY_HAS_CHILDREN = 4; TOC_ENTRY_HAS_LOCAL = 8; type PTOCEntryPageBookInfo = ^TTOCEntryPageBookInfo; TTOCEntryPageBookInfo = record Unknown1: Word; // = 0 EntryIndex: Word; // multiple entry info's can have this value but the TTocEntry it points to points back to the first item with this number. Wierd. Props: DWord; // BitField. See TOC_ENTRY_* TopicsIndexOrStringsOffset: DWord; // if TOC_ENTRY_HAS_LOCAL is in props it's the Topics Index // else it's the Offset In Strings of the Item Text ParentPageBookInfoOffset: DWord; NextPageBookOffset: DWord; // same level of tree only // Only if TOC_ENTRY_HAS_CHILDREN is set are these written FirstChildOffset: DWord; Unknown3: DWord; // = 0 end; TTocEntry = record PageBookInfoOffset: DWord; IncrementedInt: DWord; // first is $29A TopicsIndex: DWord; // Index of Entry in #TOPICS file end; TTopicEntry = record TocOffset: DWord; StringsOffset: DWord; URLTableOffset: DWord; InContents: Word;// 2 = in contents 6 = not in contents Unknown: Word; // 0,2,4,8,10,12,16,32 end; TBtreeHeader = packed record Ident : array[0..1] of AnsiChar; // $3B $29 Flags : Word; // bit $2 is always 1, bit $0400 1 if dir? (always on) BlockSize : Word; // size of blocks (2048) DataFormat : array[0..15] of AnsiChar; // "X44" always the same, see specs. Unknown0 : DWord; // always 0 LastLstBlock : DWord; // index of last listing block in the file; IndexRootBlock : DWord; // Index of the root block in the file. Unknown1 : DWord; // always -1 NrBlock : DWord; // Number of blocks TreeDepth : Word; // The depth of the tree of blocks (1 if no index blocks, 2 one level of index blocks, ...) NrKeyWords : DWord; // number of keywords in the file. CodePage : DWord; // Windows code page identifier (usually 1252 - Windows 3.1 US (ANSI)) LCID : DWord; // LCID from the HHP file. IsChm : DWord; // 0 if this a BTREE and is part of a CHW file, 1 if it is a BTree and is part of a CHI or CHM file Unknown2 : DWord; // Unknown. Almost always 10031. Also 66631 (accessib.chm, ieeula.chm, iesupp.chm, iexplore.chm, msoe.chm, mstask.chm, ratings.chm, wab.chm). Unknown3 : DWord; // unknown 0 Unknown4 : DWord; // unknown 0 Unknown5 : DWord; // unknown 0 end; PBTreeBlockHeader = ^TBtreeBlockHeader; TBtreeBlockHeader = packed record Length : Word; // Length of free space at the end of the block. NumberOfEntries : Word; // Number of entries in the block. IndexOfPrevBlock : DWord; // Index of the previous block. -1 if this is the first listing block. IndexOfNextBlock : DWord; // Index of the next block. -1 if this is the last listing block. end; PBtreeBlockEntry = ^TBtreeBlockEntry; TBtreeBlockEntry = packed record IsSeeAlso : Word; // 2 if this keyword is a See Also keyword, 0 if it is not. EntryDepth : Word; // Depth of this entry into the tree. CharIndex : DWord;// Character index of the last keyword in the ", " separated list. Unknown0 : DWord;// 0 (unknown) NrPairs : DWord;// Number of Name, Local pairs end; PBtreeIndexBlockHeader = ^TBtreeIndexBlockHeader; TBtreeIndexBlockHeader = packed record Length : Word; // Length of free space at the end of the block. NumberOfEntries : Word; // Number of entries in the block. IndexOfChildBlock : DWord; // Index of Child Block end; PBtreeIndexBlockEntry = ^TBtreeIndexBlockEntry; TBtreeIndexBlockEntry = packed record IsSeeAlso : Word; // 2 if this keyword is a See Also keyword, 0 if it is not. EntryDepth : Word; // Depth of this entry into the tree. CharIndex : DWord;// Character index of the last keyword in the ", " separated list. Unknown0 : DWord;// 0 (unknown) NrPairs : DWord;// Number of Name, Local pairs end; const IdxHdrMagic = 'T#SM'; type // #IDXHDR TIdxHdr = packed record IdxHdrSig: array [0..3] of AnsiChar; // 'T#SM' Unknown_04: LongWord; // Unknown timestamp/checksum Unknown_08: LongWord; // 1 (unknown) TopicsCount: LongWord; // Number of topic nodes including the contents & index files Unknown_10: LongWord; // 0 (unknown) ImageListStr: LongWord; // Offset in the #STRINGS file of the ImageList param of the "text/site properties" object of the sitemap contents (0/-1 = none) Unknown_18: LongWord; // 0 (unknown) ImageType: LongWord; // 1 if the value of the ImageType param of the "text/site properties" object of the sitemap contents is Folder. 0 otherwise. Background: LongWord; // The value of the Background param of the "text/site properties" object of the sitemap contents Foreground: LongWord; // The value of the Foreground param of the "text/site properties" object of the sitemap contents FontStr: LongWord; // Offset in the #STRINGS file of the Font param of the "text/site properties" object of the sitemap contents (0/-1 = none) WindowStyles: LongWord; // The value of the Window Styles param of the "text/site properties" object of the sitemap contents ExWindowStyles: LongWord; // The value of the ExWindow Styles param of the "text/site properties" object of the sitemap contents Unknown_34: LongWord; // Unknown. Often -1. Sometimes 0. FrameNameStr: LongWord; // Offset in the #STRINGS file of the FrameName param of the "text/site properties" object of the sitemap contents (0/-1 = none) WindowNameStr: LongWord; // Offset in the #STRINGS file of the WindowName param of the "text/site properties" object of the sitemap contents (0/-1 = none) InfoTypesCount: LongWord; // Number of information types Unknown_44: LongWord; // Unknown. Often 1. Also 0, 3. MergeFilesCount: LongWord; // Number of files in the [MERGE FILES] list. Unknown_4C: LongWord; // Unknown. Often 0. Non-zero mostly in files with some files in the merge files list. MergeFilesList: array [0..1003] of LongWord; // List of offsets in the #STRINGS file that are the [MERGE FILES] list. Zero terminated, but don't count on it. end; { [ALIAS] and [MAP] section items pairs } TContextItem = class(TObject) public ContextID: THelpContext; UrlAlias: String; Url: String; end; { TContextList } TContextList = class(TList) protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public function AddContext(AContextID: THelpContext; const AAlias, AUrl: String): TContextItem; { Add Alias to ContextID assignment from [MAP] section } procedure AddAliasContext(const AAlias: String; AContextID: THelpContext); { Add Alias to Url assignment from [ALIAS] section } procedure AddAliasUrl(const AAlias, AUrl: String); function GetURL(AContextID: THelpContext): String; function GetItem(AIndex: Integer): TContextItem; end; function PageBookInfoRecordSize(ARecord: PTOCEntryPageBookInfo): Integer; const DefValidFlags = [valid_Navigation_pane_style, valid_Window_style_flags, valid_Initial_window_position, valid_Navigation_pane_width, valid_Buttons, valid_Tab_position]; implementation uses chmbase; function PageBookInfoRecordSize(ARecord: PTOCEntryPageBookInfo): Integer; begin if (TOC_ENTRY_HAS_CHILDREN and ARecord^.Props) > 0 then Result := 28 else Result := 20; end; { TContextList } procedure TContextList.Notify(Ptr: Pointer; Action: TListNotification); begin inherited Notify(Ptr, Action); if Action = lnDeleted then TContextItem(Ptr).Free(); end; function TContextList.AddContext(AContextID: THelpContext; const AAlias, AUrl: String): TContextItem; begin Result := TContextItem.Create(); Add(Result); Result.ContextID := AContextID; Result.UrlAlias := AAlias; Result.Url := AUrl; end; procedure TContextList.AddAliasContext(const AAlias: String; AContextID: THelpContext); var Item: TContextItem; i: Integer; UpcaseAlias: string; begin UpcaseAlias := UpperCase(AAlias); for i := 0 to Count-1 do begin Item := TContextItem(Get(i)); if UpperCase(Item.UrlAlias) = UpcaseAlias then begin Item.ContextID := AContextID; Exit; end; end; Item := TContextItem.Create(); Add(Item); Item.ContextID := AContextID; Item.UrlAlias := AAlias; Item.Url := ''; end; procedure TContextList.AddAliasUrl(const AAlias, AUrl: String); var Item: TContextItem; i: Integer; UpcaseAlias: string; begin UpcaseAlias := UpperCase(AAlias); for i := 0 to Count-1 do begin Item := TContextItem(Get(i)); if UpperCase(Item.UrlAlias) = UpcaseAlias then begin Item.Url := AUrl; Exit; end; end; Item := TContextItem.Create(); Add(Item); Item.ContextID := 0; Item.UrlAlias := AAlias; Item.Url := AUrl; end; function TContextList.GetURL(AContextID: THelpContext): String; var i: Integer; Item: TContextItem; begin Result := ''; for i := 0 to Count-1 do begin Item := TContextItem(Get(i)); if Item.ContextID = AContextID then begin Result := Item.Url; Exit; end; end; end; function TContextList.GetItem(AIndex: Integer): TContextItem; begin if (AIndex >= 0) and (AIndex < Count) then Result := TContextItem(Get(AIndex)) else Result := nil; end; { TCHMWindowList } procedure TCHMWindowList.PutItem(Index: Integer; AValue: TCHMWindow); begin Put(Index, AValue); end; procedure TCHMWindowList.Notify(Ptr: Pointer; Action: TListNotification); begin inherited Notify(Ptr, Action); if (Action = lnDeleted) and OwnsObjects then TCHMWindow(Ptr).Free(); end; function TCHMWindowList.GetItem(Index: Integer): TCHMWindow; begin Result := TCHMWindow(Get(Index)); end; { TDirectoryChunk } function TDirectoryChunk.CanHold(ASize: Integer): Boolean; begin Result := CurrentPos < $1000 - ASize - (SizeOf(Word) * (FQuickRefEntries+2)); end; function TDirectoryChunk.FreeSpace: Integer; begin Result := $1000 - CurrentPos; end; procedure TDirectoryChunk.WriteHeader(AHeader: Pointer); begin Move(AHeader^, Buffer[0], FHeaderSize); end; procedure TDirectoryChunk.WriteEntry(Size: Integer; Data: Pointer); var ReversePos: Integer; Value: Word; begin if not CanHold(Size) then Raise Exception.Create('Trying to write past the end of the buffer'); Move(Data^, Buffer[CurrentPos], Size); Inc(CurrentPos, Size); Inc(FItemCount); // now put a quickref entry if needed if ItemCount mod 5 = 0 then begin Inc(FQuickRefEntries); ReversePos := ($1000) - SizeOf(Word) - (SizeOf(Word)*FQuickRefEntries); Value := NtoLE(Word(CurrentPos - Size - FHeaderSize)); Move(Value, Buffer[ReversePos], SizeOf(Word)); end; end; procedure TDirectoryChunk.WriteChunkToStream(Stream: TStream); var ReversePos: Integer; TmpItemCount: Word; begin ReversePos := $1000 - SizeOf(Word); TmpItemCount := NtoLE(Word(FItemCount)); Move(TmpItemCount, Buffer[ReversePos], SizeOf(Word)); Stream.Write(Buffer[0], $1000); {$IFDEF DEBUG_CHM_CHUNKS} WriteLn('Writing ', Copy(PChar(@Buffer[0]),0,4),' ChunkToStream'); {$ENDIF} end; procedure TDirectoryChunk.Clear(); begin FillChar(Buffer, $1000, 0); FItemCount := 0; CurrentPos := FHeaderSize; FQuickRefEntries := 0; Inc(FClearCount); end; constructor TDirectoryChunk.Create(AHeaderSize: Integer); begin FHeaderSize := AHeaderSize; CurrentPos := FHeaderSize; end; { TFileEntryList } function TFileEntryList.GetFileEntry(Index: Integer): TFileEntryRec; begin Result := PFileEntryRec(Items[Index])^; end; procedure TFileEntryList.SetFileEntry(Index: Integer; const AValue: TFileEntryRec); begin PFileEntryRec(Items[Index])^ := AValue; end; function TFileEntryList.AddEntry(AFileEntry: TFileEntryRec; CheckPathIsAdded: Boolean = True): Integer; var TmpEntry: PFileEntryRec; begin New(TmpEntry); //WriteLn('Adding: ', AFileEntry.Path+AFileEntry.Name,' Size = ', AFileEntry.DecompressedSize,' Offset = ', AFileEntry.DecompressedOffset); if CheckPathIsAdded and (FPaths.IndexOf(AFileEntry.Path) < 0) then begin // all paths are included in the list of files in section 0 with a size and offset of 0 FPaths.Add(AFileEntry.Path); TmpEntry^.Path := AFileEntry.Path; TmpEntry^.Name := ''; TmpEntry^.DecompressedOffset := 0; TmpEntry^.DecompressedSize := 0; TmpEntry^.Compressed := False; (Self as TList).Add(TmpEntry); New(TmpEntry); end; TmpEntry^ := AFileEntry; Result := (Self as TList).Add(TmpEntry); end; procedure TFileEntryList.Delete(Index: Integer); begin Dispose(PFileEntryRec(Items[Index])); Inherited Delete(Index); end; function FileEntrySortFunc(Item1, Item2: PFileEntryRec): Integer; var Str1, Str2: String; begin Str1 := Item1^.Path + Item1^.Name; Str2 := Item2^.Path + Item2^.Name; Result := ChmCompareText(Str1, Str2); end; procedure TFileEntryList.Sort; begin inherited Sort(TListSortCompare(@FileEntrySortFunc)); end; constructor TFileEntryList.Create; begin inherited Create; FPaths := TStringList.Create; end; destructor TFileEntryList.Destroy; var I: Integer; begin for I := Count-1 downto 0 do Delete(I); FPaths.Free; inherited Destroy; end; { TPMGIDirectoryChunk } procedure TPMGIDirectoryChunk.WriteChunkToStream(Stream: TStream; var AIndex: Integer ; Final: Boolean = False); var NewBuffer: array[0..512] of byte; EntryLength, WriteSize: Integer; OldPos, NewPos, NewStart: Int64; procedure FinishBlock(); var Header: TPMGIIndexChunk; begin Inc(AIndex); Header.PMGIsig := 'PMGI'; Header.UnusedSpace := FParentChunk.FreeSpace; FParentChunk.WriteHeader(@Header); FParentChunk.WriteChunkToStream(Stream, AIndex, Final); FParentChunk.Clear(); end; begin if FItemCount < 1 then begin {$ifdef chm_debug} WriteLn('WHAT ARE YOU DOING!!'); {$endif} Dec(AIndex); Exit; end; OldPos := Stream.Position; WriteChunkToStream(Stream); NewPos := Stream.Position; Inc(FChunkLevelCount); if Final and (ChunkLevelCount < 2) then begin FParentChunk.Free(); FParentChunk := nil; Exit; end; if FParentChunk = nil then FParentChunk := TPMGIDirectoryChunk.Create(FHeaderSize); NewStart := OldPos+FHeaderSize; Stream.Position := NewStart; EntryLength := GetCompressedInteger(Stream); WriteSize := (Stream.Position - NewStart) + EntryLength; Move(Buffer[FHeaderSize], NewBuffer[0], WriteSize); Inc(WriteSize, WriteCompressedInteger(@NewBuffer[WriteSize], AIndex)); Stream.Position := NewPos; if not FParentChunk.CanHold(WriteSize) then begin FinishBlock(); end; FParentChunk.WriteEntry(WriteSize, @NewBuffer[0]); if Final then FinishBlock(); //WriteLn(ChunkLevelCount); end; function GetNext(const s: string; var i: Integer; len: Integer): string; var ind: integer; begin if i > len then Exit(''); ind := i; if s[ind] = '"' then begin Inc(ind); while (ind <= len) and (s[ind] <> '"') do Inc(ind); Result := Copy(s, i+1, ind-i-1); Inc(ind); // skip " end else begin while (ind <= len) and (s[ind] <> ',') do Inc(ind); Result := Copy(s, i, ind-i); end; i := ind + 1; // skip , end; function GetNextInt(const txt: string; var ind: Integer; len: Integer; var flags: TValidWindowFields; x: TValidWindowFieldsEnum): Integer; var s: string; i: Integer; begin i := ind; s := GetNext(txt, ind, len); // set a flag if the field was empty (,,) if (ind = (i+1)) and (x <> valid_Unknown1) then Include(flags, x); Result := StrToIntDef(s, 0); // I think this does C style hex, if not fixup here. end; procedure TCHMWindow.load_from_ini(txt: string); begin LoadFromIni(txt); end; procedure TCHMWindow.SaveToXml(cfg: TXMLConfig; key: string); begin cfg.SetValue(key+'window_type', window_type); cfg.SetValue(key+'title_bar_text', title_bar_text); cfg.SetValue(key+'toc_file', Toc_file); cfg.SetValue(key+'index_file', index_file); cfg.SetValue(key+'default_file', Default_File); cfg.SetValue(key+'home_button_file', Home_button_file); cfg.SetValue(key+'jumpbutton_1_file', Jumpbutton_1_File); cfg.SetValue(key+'jumpbutton_1_text', Jumpbutton_1_Text); cfg.SetValue(key+'jumpbutton_2_file', Jumpbutton_2_File); cfg.SetValue(key+'jumpbutton_2_text', Jumpbutton_2_Text); cfg.SetValue(key+'nav_style', nav_style); cfg.SetValue(key+'navpanewidth', navpanewidth); cfg.SetValue(key+'buttons', buttons); cfg.SetValue(key+'left', left); cfg.SetValue(key+'top', top); cfg.SetValue(key+'right', right); cfg.SetValue(key+'bottom', bottom); cfg.SetValue(key+'styleflags', styleflags); cfg.SetValue(key+'xtdstyleflags', xtdstyleflags); cfg.SetValue(key+'window_show_state', window_show_state); cfg.SetValue(key+'navpane_initially_closed', navpane_initially_closed); cfg.SetValue(key+'navpane_default', navpane_default); cfg.SetValue(key+'navpane_location', navpane_location); cfg.SetValue(key+'wm_notify_id', wm_notify_id); end; procedure TCHMWindow.LoadFromXml(cfg: TXMLConfig; key: string); begin window_type := cfg.GetValue(key+'window_type',''); Title_bar_text := cfg.GetValue(key+'title_bar_text',''); Toc_file := cfg.GetValue(key+'toc_file',''); Index_file := cfg.GetValue(key+'index_file',''); Default_File := cfg.GetValue(key+'default_file',''); Home_button_file := cfg.GetValue(key+'home_button_file',''); Jumpbutton_1_File := cfg.GetValue(key+'jumpbutton_1_file',''); Jumpbutton_1_Text := cfg.GetValue(key+'jumpbutton_1_text',''); Jumpbutton_2_File := cfg.GetValue(key+'jumpbutton_2_file',''); Jumpbutton_2_Text := cfg.GetValue(key+'jumpbutton_2_text',''); nav_style := cfg.GetValue(key+'nav_style',0); navpanewidth := cfg.GetValue(key+'navpanewidth',0); buttons := cfg.GetValue(key+'buttons',0); left := cfg.GetValue(key+'left',0); top := cfg.GetValue(key+'top',0); right := cfg.GetValue(key+'right',0); bottom := cfg.GetValue(key+'bottom',0); styleflags := cfg.GetValue(key+'styleflags',0); xtdstyleflags := cfg.GetValue(key+'xtdstyleflags',0); window_show_state := cfg.GetValue(key+'window_show_state',0); navpane_initially_closed := cfg.GetValue(key+'navpane_initially_closed',0); navpane_default := cfg.GetValue(key+'navpane_default',0); navpane_location := cfg.GetValue(key+'navpane_location',0); wm_notify_id := cfg.GetValue(key+'wm_notify_id',0); end; procedure TCHMWindow.SaveToIni(out s: string); begin s := window_type + '='; s := s + '"' + Title_bar_text + '"'; s := s + ',"' + Toc_file + '"'; s := s + ',"' + index_file + '"'; s := s + ',"' + Default_File + '"'; s := s + ',"' + Home_button_file + '"'; s := s + ',"' + Jumpbutton_1_File + '"'; s := s + ',"' + Jumpbutton_1_Text + '"'; s := s + ',"' + Jumpbutton_2_File + '"'; s := s + ',"' + Jumpbutton_2_Text + '"'; s := s + ',0x' + IntToHex(nav_style, 1); s := s + ',' + IntToStr(navpanewidth); s := s + ',0x' + IntToHex(buttons, 1); s := s + ',[' + IntToStr(left); s := s + ',' + IntToStr(top); s := s + ',' + IntToStr(right); s := s + ',' + IntToStr(bottom) + ']'; s := s + ',0x' + IntToHex(styleflags, 1); if xtdstyleflags <> 0 then s := s + ',0x' + IntToHex(xtdstyleflags, 1) else s := s + ','; s := s + ',0x' + IntToHex(window_show_state, 1); s := s + ',' + IntToStr(navpane_initially_closed); s := s + ',' + IntToStr(navpane_default); s := s + ',' + IntToStr(navpane_location); //s := s + ',' + IntToStr(wm_notify_id); end; procedure TCHMWindow.LoadFromIni(s: string); var ind,len, j,k : integer; arr : array[0..3] of integer; s2 : string; bArr : Boolean; begin j := Pos('=', s); if j > 0 then s[j] := ','; ind := 1; len := Length(s); window_type := GetNext(s, ind, len); Title_bar_text := GetNext(s, ind, len); Toc_file := GetNext(s, ind, len); index_file := GetNext(s, ind, len); Default_File := GetNext(s, ind, len); Home_button_file := GetNext(s, ind, len); Jumpbutton_1_File := GetNext(s, ind, len); Jumpbutton_1_Text := GetNext(s, ind, len); Jumpbutton_2_File := GetNext(s, ind, len); Jumpbutton_2_Text := GetNext(s, ind, len); nav_style := GetNextInt(s, ind, len, flags, valid_navigation_pane_style); navpanewidth := GetNextInt(s, ind, len, flags, valid_navigation_pane_width); buttons := GetNextInt(s, ind, len, flags, valid_buttons); (* initialize arr[] *) arr[0] := 0; arr[1] := 0; arr[2] := 0; arr[3] := 0; k := 0; bArr := False; (* "[" int,int,int,int "]", |, *) s2 := GetNext(s, ind, len); if Length(s2) > 0 then begin (* check if first chart is "[" *) if (s2[1] = '[') then begin Delete(s2, 1, 1); bArr := True; end; (* looking for a max 4 int followed by a closing "]" *) repeat if k > 0 then s2 := GetNext(s, ind, len); j := Pos(']', s2); if j > 0 then Delete(s2, j, 1); if Length(Trim(s2)) > 0 then Include(flags, valid_tab_position); arr[k] := StrToIntDef(s2, 0); Inc(k); until (bArr <> True) or (j <> 0) or (ind > len); end; left := arr[0]; top := arr[1]; right := arr[2]; bottom := arr[3]; styleflags := GetNextInt(s, ind, len, flags, valid_buttons); xtdstyleflags := GetNextInt(s, ind, len, flags, valid_window_style_flags); window_show_state := GetNextInt(s, ind, len, flags, valid_window_extended_style_flags); navpane_initially_closed := GetNextInt(s, ind, len, flags, valid_navigation_pane_initially_closed_state); navpane_default := GetNextInt(s, ind, len, flags, valid_default_pane); navpane_location := GetNextInt(s, ind, len, flags, valid_tab_position); wm_notify_id := GetNextInt(s, ind, len, flags, valid_unknown1); end; constructor TCHMWindow.Create(s: string = ''); begin inherited Create; flags := DefValidFlags; if s <> '' then LoadFromIni(s); end; procedure TCHMWindow.Assign(obj: TCHMWindow); begin window_type := obj.window_type; Title_bar_text := obj.Title_bar_text; Toc_file := obj.Toc_file; Index_file := obj.Index_file; Default_File := obj.Default_File; Home_button_file := obj.Home_button_file; Jumpbutton_1_File:= obj.Jumpbutton_1_File; Jumpbutton_1_Text:= obj.Jumpbutton_1_Text; Jumpbutton_2_File:= obj.Jumpbutton_2_File; Jumpbutton_2_Text:= obj.Jumpbutton_2_Text; nav_style := obj.nav_style; navpanewidth := obj.navpanewidth; buttons := obj.buttons; left := obj.left; top := obj.top; right := obj.right; bottom := obj.bottom; styleflags := obj.styleflags; xtdstyleflags := obj.xtdstyleflags; window_show_state:= obj.window_show_state; navpane_initially_closed := obj.navpane_initially_closed; navpane_default := obj.navpane_default; navpane_location := obj.navpane_location; wm_notify_id := obj.wm_notify_id; end; end.
unit uInputUserInfo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxButtons, ExtCtrls, uGlobal, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinCaramel, cxTextEdit, cxCheckBox, ADODB, dxSkinOffice2007Blue; type TfrmInputUserInfo = class(TForm) btnOK: TcxButton; btnClose: TcxButton; Panel1: TPanel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; txtUserID: TcxTextEdit; txtPassword: TcxTextEdit; txtPassword2: TcxTextEdit; chkWorker: TcxCheckBox; chkDoctor: TcxCheckBox; chkAdmin: TcxCheckBox; chkUsed: TcxCheckBox; txtUserName: TcxTextEdit; procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure ClearControls; procedure SetControls; function isValidInput: Boolean; function isDuplicatedUserID(nHospitalID: integer; sUserID: string): Boolean; function isDuplicatedUserName(nHospitalID: integer; sUserName: string): Boolean; public Mode: TEditMode; UserInfo: TUserInfo; { Public declarations } end; var frmInputUserInfo: TfrmInputUserInfo; implementation uses uDB; {$R *.dfm} { TfrmInputUserInfo } procedure TfrmInputUserInfo.btnOKClick(Sender: TObject); begin if isValidInput then begin UserInfo.UserID := trim(txtUserID.Text); UserInfo.UserName := trim(txtUserName.Text); UserInfo.Password := trim(txtPassword.Text); UserInfo.Worker := chkWorker.Checked; UserInfo.Doctor := chkDoctor.Checked; UserInfo.Admin := chkAdmin.Checked; UserInfo.Used := chkUsed.Checked; ModalResult := mrOK; end; end; procedure TfrmInputUserInfo.ClearControls; begin txtUserID.Clear; txtUserName.Clear; txtPassword.Clear; txtPassword2.Clear; chkWorker.Checked := False; chkDoctor.Checked := False; chkAdmin.Checked := False; chkUsed.Checked := True; end; procedure TfrmInputUserInfo.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfrmInputUserInfo.FormShow(Sender: TObject); begin ClearControls; SetControls; if Mode = emAppend then txtUserID.SetFocus else txtUserName.SetFocus; end; function TfrmInputUserInfo.isDuplicatedUserID(nHospitalID: integer; sUserID: string): Boolean; var adoT: TAdoQuery; begin adoT := TAdoQuery.Create(self); adoT.Connection := dbMain.adoSocialWorkDB; try adoT.SQL.Text := 'SELECT * FROM USERS' + ' WHERE HOSPITALID=' + inttostr(nHospitalID) + ' AND USERID=''' + sUserID + ''''; adoT.Open; finally result := not adoT.IsEmpty; end; adoT.Close; adoT.Free; end; function TfrmInputUserInfo.isDuplicatedUserName(nHospitalID: integer; sUserName: string): Boolean; var adoT: TAdoQuery; begin adoT := TAdoQuery.Create(self); adoT.Connection := dbMain.adoSocialWorkDB; try adoT.SQL.Text := 'SELECT * FROM USERS' + ' WHERE HOSPITALID=' + inttostr(nHospitalID) + ' AND USERNAME=''' + sUserName + ''''; adoT.Open; finally result := not adoT.IsEmpty; end; adoT.Close; adoT.Free; end; function TfrmInputUserInfo.isValidInput: Boolean; begin result := false; if Mode = emAppend then begin if oGlobal.isNullStr(txtUserID.Text) then begin oGlobal.Msg('사용자번호를 입력하십시오!'); txtUserID.SetFocus; Exit; end; if oGlobal.isNullStr(txtUserName.Text) then begin oGlobal.Msg('사용자이름을 입력하십시오!'); txtUserName.SetFocus; Exit; end; if oGlobal.isNullStr(txtPassword.Text) and oGlobal.isNullStr(txtPassword2.Text) then begin oGlobal.Msg('암호를 입력하십시오!'); txtPassword.Text; Exit; end; end; if (pos('[', trim(txtUserName.Text)) > 0) or (pos(']', trim(txtUserName.Text)) > 0) or (pos(';', trim(txtUserName.Text)) > 0) then begin oGlobal.Msg('사용자이름에는 (''['','']'','';'') 문자를 사용할 수 없습니다!'); Exit; end; if trim(txtPassword.Text) <> trim(txtPassword2.Text) then begin oGlobal.Msg('암호를 정확히 입력해 주십시오!'); txtPassword.SetFocus; Exit; end; if (Mode=emAppend) or ((Mode=emUpdate) and (UserInfo.UserID <> trim(txtUserID.Text))) then begin if isDuplicatedUserID(UserInfo.HospitalID, trim(txtUserID.Text)) then begin oGlobal.Msg('중복된 User ID 가 있습니다!'); Exit; end; end; if (Mode=emAppend) or ((Mode=emUpdate) and (UserInfo.UserName <> trim(txtUserName.Text))) then begin if isDuplicatedUserName(UserInfo.HospitalID, trim(txtUserName.Text)) then begin oGlobal.Msg('중복된 사용자이름이 있습니다!'); Exit; end; end; result := True; end; procedure TfrmInputUserInfo.SetControls; begin txtUserID.Enabled := (Mode = emAppend); if not UserInfo.isEmpty then begin txtUserID.Text := UserInfo.UserID; txtUserName.Text := UserInfo.UserName; txtPassword.Clear; txtPassword2.Clear; chkWorker.Checked := UserInfo.Worker; chkDoctor.Checked := UserInfo.Doctor; chkAdmin.Checked := UserInfo.Admin; chkUsed.Checked := UserInfo.Used; end; end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Actions, System.IOUtils, System.ImageList, System.Types, System.Math, Vcl.ComCtrls, Vcl.Dialogs, Vcl.ToolWin, Vcl.ExtCtrls, Vcl.ActnList, Vcl.Menus, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.ImgList, Vcl.Samples.Spin, Pengine.Vector, Pengine.Utility, Pengine.JSON, Pengine.Collections, Pengine.IntMaths, DisplayView, GraphDefine, MiniDialogGenerateGrid, AntDefine, Vcl.Grids, VclTee.TeeGDIPlus, VCLTee.TeEngine, VCLTee.Series, VCLTee.TeeProcs, VCLTee.Chart; type TfrmMain = class(TForm) mmMain: TMainMenu; miFile: TMenuItem; miNew: TMenuItem; miOpen: TMenuItem; miSave: TMenuItem; miSaveAs: TMenuItem; miExit: TMenuItem; N1: TMenuItem; alMain: TActionList; actNew: TAction; actOpen: TAction; actSave: TAction; actSaveAs: TAction; actExit: TAction; N2: TMenuItem; sbMain: TStatusBar; pnlMain: TPanel; sbSidebar: TScrollBox; gbSimulation: TGroupBox; miView: TMenuItem; actEditorActive: TAction; miEditMode: TMenuItem; pbDisplay: TPaintBox; tbDisplay: TToolBar; tbClear: TToolButton; tbSplit: TToolButton; actClear: TAction; ilIcons: TImageList; tbPointTool: TToolButton; tbConnectionTool: TToolButton; tbGenerateGrid: TToolButton; actGenerateGrid: TAction; actResetView: TAction; miResetView: TMenuItem; miEdit: TMenuItem; miClear: TMenuItem; miGenerateGrid: TMenuItem; actPointTool: TAction; actConnectionTool: TAction; N5: TMenuItem; PunktWerkzeug1: TMenuItem; VerbindungsWerkzeug1: TMenuItem; actSelectionTool: TAction; tbSelectionTool: TToolButton; KameraTool1: TMenuItem; tbStartTool: TToolButton; tbFinishTool: TToolButton; actStartTool: TAction; actFinishTool: TAction; StartWerkzeug1: TMenuItem; actFinishTool1: TMenuItem; N6: TMenuItem; actGenerate: TAction; actStart: TAction; lbBatchSize: TLabel; seBatchSize: TSpinEdit; lbPheromoneDissipation: TLabel; edtPheromoneDissipation: TEdit; lbPheromoneDissipationUnit: TLabel; gbPopulation: TGroupBox; seBatch: TSpinEdit; lbBatch: TLabel; gbStatistics: TGroupBox; splStatistics: TSplitter; dlgSave: TSaveDialog; dlgOpen: TOpenDialog; tmrUpdate: TTimer; actReset: TAction; gbControl: TGroupBox; btnReset: TButton; btnStart: TButton; btnGenerate: TButton; Label1: TLabel; edtInfluenceFactor: TEdit; Label2: TLabel; lvAnts: TListView; btnHidePath: TButton; actHidePath: TAction; sgStatistics: TStringGrid; ToolButton1: TToolButton; ToolButton2: TToolButton; actTriangulate: TAction; actTriangulateDelaunay: TAction; cbReturnToStart: TCheckBox; tcStatistics: TChart; csBest: TFastLineSeries; csAverage: TFastLineSeries; csMedian: TFastLineSeries; csWorst: TFastLineSeries; procedure actClearExecute(Sender: TObject); procedure actConnectionToolExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actEditorActiveExecute(Sender: TObject); procedure actExitExecute(Sender: TObject); procedure actFinishToolExecute(Sender: TObject); procedure actGenerateGridExecute(Sender: TObject); procedure actOpenExecute(Sender: TObject); procedure actSelectionToolExecute(Sender: TObject); procedure actPointToolExecute(Sender: TObject); procedure actResetExecute(Sender: TObject); procedure actResetViewExecute(Sender: TObject); procedure actSaveAsExecute(Sender: TObject); procedure actGenerateExecute(Sender: TObject); procedure actGenerateUpdate(Sender: TObject); procedure actHidePathExecute(Sender: TObject); procedure actHidePathUpdate(Sender: TObject); procedure actStartExecute(Sender: TObject); procedure actStartToolExecute(Sender: TObject); procedure actStartUpdate(Sender: TObject); procedure actTriangulateDelaunayExecute(Sender: TObject); procedure actTriangulateExecute(Sender: TObject); procedure cbReturnToStartClick(Sender: TObject); procedure edtInfluenceFactorExit(Sender: TObject); procedure edtPheromoneDissipationExit(Sender: TObject); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure lvAntsColumnClick(Sender: TObject; Column: TListColumn); procedure lvAntsCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure lvAntsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure seBatchChange(Sender: TObject); procedure seBatchExit(Sender: TObject); procedure seBatchSizeExit(Sender: TObject); procedure tmrUpdateTimer(Sender: TObject); private FDisplay: TDisplay; FSimulation: TSimulation; FSortColumn: Integer; procedure DisplayToolChange; function GetEditorDisplay: TEditorDisplay; function GetSimulationDisplay: TSimulationDisplay; function GetEditable: Boolean; procedure SetEditable(const Value: Boolean); function GetPheromoneData: TPheromoneData; procedure SyncSimulationData; procedure GenerateAntList; public property EditorDisplay: TEditorDisplay read GetEditorDisplay; property SimulationDisplay: TSimulationDisplay read GetSimulationDisplay; property PheromoneData: TPheromoneData read GetPheromoneData; property Editable: Boolean read GetEditable write SetEditable; end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.actClearExecute(Sender: TObject); begin EditorDisplay.Graph.Clear; end; procedure TfrmMain.actConnectionToolExecute(Sender: TObject); begin EditorDisplay.Tool := etConnection; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin FSimulation.Free; FDisplay.Free; end; procedure TfrmMain.FormCreate(Sender: TObject); begin Editable := False; DisplayToolChange; SyncSimulationData; sgStatistics.Cells[0, 0] := 'Best'; sgStatistics.Cells[1, 0] := 'Worst'; sgStatistics.Cells[2, 0] := 'Average'; sgStatistics.Cells[3, 0] := 'Median'; csBest.Clear; csAverage.Clear; csMedian.Clear; csWorst.Clear; end; procedure TfrmMain.actEditorActiveExecute(Sender: TObject); begin Editable := not Editable; end; procedure TfrmMain.actExitExecute(Sender: TObject); begin Close; end; procedure TfrmMain.actFinishToolExecute(Sender: TObject); begin EditorDisplay.Tool := etFinish; end; procedure TfrmMain.actGenerateGridExecute(Sender: TObject); begin mdlgGenerateGrid.Execute(EditorDisplay.Graph); end; procedure TfrmMain.actOpenExecute(Sender: TObject); var JGraph: TJObject; Graph: TGraphEditable; begin if not dlgOpen.Execute then Exit; actResetExecute(nil); Graph := nil; JGraph := nil; try Graph := TGraphEditable.Create; JGraph := TJObject.CreateFromFile(dlgOpen.FileName); TJSerializer.Unserialize(Graph, JGraph); if Editable then begin EditorDisplay.Graph := Graph; end else begin FSimulation.Free; FSimulation := TSimulation.Create(Graph); SimulationDisplay.PheromoneData := FSimulation.PheromoneData; SyncSimulationData; end; pbDisplay.Invalidate; finally JGraph.Free; Graph.Free; end; TPath.GetInvalidFileNameChars end; procedure TfrmMain.actSelectionToolExecute(Sender: TObject); begin EditorDisplay.Tool := etSelection; end; procedure TfrmMain.actPointToolExecute(Sender: TObject); begin EditorDisplay.Tool := etPoint; end; procedure TfrmMain.actResetExecute(Sender: TObject); begin if FSimulation = nil then Exit; SimulationDisplay.VisibleAnt := nil; seBatch.MaxValue := 1; seBatch.Value := 1; seBatch.Enabled := False; FSimulation.Clear; SyncSimulationData; GenerateAntList; pbDisplay.Invalidate; csBest.Clear; csAverage.Clear; csMedian.Clear; csWorst.Clear; end; procedure TfrmMain.actResetViewExecute(Sender: TObject); begin FDisplay.Camera.Reset; end; procedure TfrmMain.actSaveAsExecute(Sender: TObject); var Serialized: TJObject; begin if not dlgSave.Execute then Exit; Serialized := TJSerializer.Serialize(EditorDisplay.Graph); try ForceDirectories(ExtractFilePath(dlgSave.FileName)); Serialized.SaveToFile(dlgSave.FileName); finally Serialized.Free; end; end; procedure TfrmMain.actGenerateExecute(Sender: TObject); var Stats: TSimulation.TStatistic; begin FSimulation.GenerateBatch; seBatch.MaxValue := FSimulation.Batches.Count; seBatch.Value := FSimulation.Batches.Count; seBatch.Enabled := FSimulation.Batches.Count > 1; GenerateAntList; pbDisplay.Invalidate; Stats := FSimulation.Batches.Last.GetPathLengthStatistic; csBest.Add(Stats[stBest]); csAverage.Add(Stats[stAverage]); csMedian.Add(Stats[stMedian]); csWorst.Add(Stats[stWorst]); end; procedure TfrmMain.actGenerateUpdate(Sender: TObject); begin actGenerate.Enabled := PheromoneData.Graph.HasStart; end; procedure TfrmMain.actHidePathExecute(Sender: TObject); begin SimulationDisplay.VisibleAnt := nil; end; procedure TfrmMain.actHidePathUpdate(Sender: TObject); begin actHidePath.Enabled := not Editable and (SimulationDisplay.VisibleAnt <> nil); end; procedure TfrmMain.actStartExecute(Sender: TObject); begin tmrUpdate.Enabled := not tmrUpdate.Enabled; GenerateAntList; end; procedure TfrmMain.actStartToolExecute(Sender: TObject); begin EditorDisplay.Tool := etStart; end; procedure TfrmMain.actStartUpdate(Sender: TObject); begin actStart.Enabled := PheromoneData.Graph.HasStart; if tmrUpdate.Enabled then actStart.Caption := 'Stop' else actStart.Caption := 'Start'; end; procedure TfrmMain.actTriangulateDelaunayExecute(Sender: TObject); var Triangulator: TGraphEditable.TDelaunayTriangulator; begin Triangulator := TGraphEditable.TDelaunayTriangulator.Create(EditorDisplay.Graph); try Triangulator.Generate; finally Triangulator.Free; end; pbDisplay.Invalidate; end; procedure TfrmMain.actTriangulateExecute(Sender: TObject); var Generator: TGraphEditable.TTriangulator; begin Generator := TGraphEditable.TTriangulator.Create(EditorDisplay.Graph); try Generator.Generate; finally Generator.Free; end; pbDisplay.Invalidate; end; procedure TfrmMain.cbReturnToStartClick(Sender: TObject); begin if Editable then Exit; FSimulation.MustReturn := cbReturnToStart.Checked; cbReturnToStart.Checked := FSimulation.MustReturn; end; procedure TfrmMain.DisplayToolChange; begin if not Editable then Exit; actSelectionTool.Checked := EditorDisplay.Tool = etSelection; actPointTool.Checked := EditorDisplay.Tool = etPoint; actConnectionTool.Checked := EditorDisplay.Tool = etConnection; actStartTool.Checked := EditorDisplay.Tool = etStart; actFinishTool.Checked := EditorDisplay.Tool = etFinish; end; procedure TfrmMain.edtInfluenceFactorExit(Sender: TObject); var Value: Single; begin if FSimulation = nil then Exit; if Single.TryParse(edtInfluenceFactor.Text, Value, TFormatSettings.Invariant) then FSimulation.InfluencedFactor := EnsureRange(Value / 100, 0, 1); edtInfluenceFactor.Text := PrettyFloat(Single(FSimulation.InfluencedFactor * 100)); end; procedure TfrmMain.edtPheromoneDissipationExit(Sender: TObject); var Value: Single; begin if FSimulation = nil then Exit; if Single.TryParse(edtPheromoneDissipation.Text, Value, TFormatSettings.Invariant) then FSimulation.PheromoneDissipation := EnsureRange(Value / 100, 0, 1); edtPheromoneDissipation.Text := PrettyFloat(Single(FSimulation.PheromoneDissipation * 100)); end; procedure TfrmMain.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin MousePos := MousePos - pbDisplay.ClientToScreen(Point(0, 0)); if Rect(0, 0, pbDisplay.Width, pbDisplay.Height).Contains(MousePos) then begin FDisplay.MouseWheel(Shift, WheelDelta, MousePos); Handled := True; end; end; procedure TfrmMain.GenerateAntList; var Batch: TSimulation.TBatch; I: Integer; Item: TListItem; S: TSimulation.TStatisticType; Stats: TSimulation.TStatistic; begin if FSimulation.Batches.RangeCheck(seBatch.Value - 1) then SimulationDisplay.PheromoneData := FSimulation.Batches[seBatch.Value - 1].PheromoneData else SimulationDisplay.PheromoneData := FSimulation.PheromoneData; if FSimulation.Batches.Empty then begin for S := Low(TSimulation.TStatisticType) to High(TSimulation.TStatisticType) do sgStatistics.Cells[Ord(S), 1] := '-'; end else begin Stats := FSimulation.Batches.Last.GetPathLengthStatistic; for S := Low(TSimulation.TStatisticType) to High(TSimulation.TStatisticType) do sgStatistics.Cells[Ord(S), 1] := Round(Stats[S]).ToString; end; if tmrUpdate.Enabled then Exit; lvAnts.Items.BeginUpdate; try lvAnts.Items.Clear; if FSimulation.Batches.Empty then Exit; Batch := FSimulation.Batches[seBatch.Value - 1]; for I := 0 to Batch.Ants.MaxIndex do begin Item := lvAnts.Items.Add; Item.Caption := (I + 1).ToString; Item.Data := Batch.Ants[I]; if Batch.Ants[I].Success then Item.SubItems.Add(Round(Batch.Ants[I].PathLength).ToString) else Item.SubItems.Add('failed'); end; finally lvAnts.Items.EndUpdate; end; end; function TfrmMain.GetEditable: Boolean; begin Result := FDisplay is TEditorDisplay; end; function TfrmMain.GetEditorDisplay: TEditorDisplay; begin Result := FDisplay as TEditorDisplay; end; function TfrmMain.GetPheromoneData: TPheromoneData; begin Result := FSimulation.PheromoneData; end; procedure TfrmMain.SyncSimulationData; begin seBatchSizeExit(nil); edtInfluenceFactorExit(nil); edtPheromoneDissipationExit(nil); cbReturnToStartClick(nil); end; function TfrmMain.GetSimulationDisplay: TSimulationDisplay; begin Result := FDisplay as TSimulationDisplay; end; procedure TfrmMain.lvAntsColumnClick(Sender: TObject; Column: TListColumn); begin if FSortColumn = Column.Index + 1 then FSortColumn := -FSortColumn else FSortColumn := Column.Index + 1; lvAnts.AlphaSort; end; procedure TfrmMain.lvAntsCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); var Ant1, Ant2: TAnt; begin Ant1 := Item1.Data; Ant2 := Item2.Data; case Abs(FSortColumn) of 1: Compare := CompareValue(Item1.Caption.ToInteger, Item2.Caption.ToInteger); 2: if not Ant1.Success or not Ant2.Success then Compare := IfThen(Ant1.Success, -1, 1) else Compare := CompareValue(Ant1.PathLength, Ant2.PathLength); end; Compare := Compare * Sign(FSortColumn); end; procedure TfrmMain.lvAntsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); var Ant: TAnt; begin Ant := Item.Data; if Selected then SimulationDisplay.VisibleAnt := Ant else SimulationDisplay.VisibleAnt := nil; end; procedure TfrmMain.seBatchChange(Sender: TObject); var Batch: Integer; begin if not Integer.TryParse(seBatch.Text, Batch) then Exit; if FSimulation.Batches.RangeCheck(Batch - 1) then GenerateAntList; end; procedure TfrmMain.seBatchExit(Sender: TObject); var Batch: Integer; begin if not Integer.TryParse(seBatch.Text, Batch) then seBatch.Value := 1; end; procedure TfrmMain.seBatchSizeExit(Sender: TObject); var Value: Integer; begin if FSimulation = nil then Exit; if Integer.TryParse(seBatchSize.Text, Value) then FSimulation.BatchSize := Value else seBatchSize.Text := FSimulation.BatchSize.ToString; end; procedure TfrmMain.SetEditable(const Value: Boolean); var Camera: TCamera; Graph: TGraphEditable; begin if FDisplay <> nil then begin if Editable = Value then Exit; Camera := FDisplay.Camera.Copy; Graph := FDisplay.Graph.Copy; end else begin Camera := nil; // default graph Graph := TGraphEditable.Create; end; if Value then begin actResetExecute(nil); FreeAndNil(FSimulation); FDisplay.Free; FDisplay := TEditorDisplay.Create(pbDisplay); EditorDisplay.OnToolChange.Add(DisplayToolChange); EditorDisplay.Graph := Graph; end else begin FDisplay.Free; FDisplay := TSimulationDisplay.Create(pbDisplay); FSimulation := TSimulation.Create(Graph); SimulationDisplay.PheromoneData := FSimulation.PheromoneData; SyncSimulationData; end; Graph.Free; if Camera <> nil then begin FDisplay.Camera := Camera; Camera.Free; end; if Value then actEditorActive.Caption := 'Editor deaktivieren' else actEditorActive.Caption := 'Editor aktivieren'; tbDisplay.Visible := Editable; sbSidebar.Visible := not Editable; gbStatistics.Height := IfThen(Editable, 0, 200); alMain.EnumByCategory( procedure(const Action: TContainedAction; var Done: Boolean) begin Action.Enabled := Editable or (Action = actEditorActive); end, 'Editor'); end; procedure TfrmMain.tmrUpdateTimer(Sender: TObject); begin if Editable then begin tmrUpdate.Enabled := False; Exit; end; actGenerateExecute(nil); end; end.
unit newMainMenu; {$mode objfpc}{$H+} interface uses jwawindows, windows, Classes, SysUtils, Controls, StdCtrls, Menus, Graphics; type TNewMenuItem=class(TMenuItem) private fCustomFontColor: TColor; protected function DoDrawItem(ACanvas: TCanvas; ARect: TRect; AState: TOwnerDrawState): Boolean; override; procedure setCustomFontColor(newcolor: TColor); virtual; public constructor Create(TheOwner: TComponent); override; published property FontColor: TColor read fCustomFontColor write setCustomFontColor; end; TNewMainMenu=class(TMainMenu) private procedure firstshow(sender: TObject); protected procedure SetParentComponent(Value: TComponent); override; public end; implementation uses betterControls, forms, LCLType; procedure TNewMainMenu.firstshow(sender: TObject); var m: Hmenu; mi: windows.MENUINFO; c: tcanvas; mia: windows.LPCMENUINFO; // mbi: ENUBARINFO ; b: TBrush; begin if ShouldAppsUseDarkMode then begin m:=GetMenu(TCustomForm(sender).handle); // m:=handle; mi.cbSize:=sizeof(mi); mi.fMask := MIM_BACKGROUND or MIM_APPLYTOSUBMENUS; b:=TBrush.Create; b.color:=$2b2b2b; b.Style:=bsSolid; mi.hbrBack:=b.handle; //GetSysColorBrush(DKGRAY_BRUSH); //b.Handle; mia:=@mi; if windows.SetMenuInfo(m,mia) then begin AllowDarkModeForWindow(m,1); SetWindowTheme(m,'',nil); end; end; end; procedure TNewMainMenu.SetParentComponent(Value: TComponent); begin inherited SetParentComponent(value); if ShouldAppsUseDarkMode and (value is tcustomform) then tcustomform(value).AddHandlerFirstShow(@firstshow); end; function TNewMenuItem.DoDrawItem(ACanvas: TCanvas; ARect: TRect; AState: TOwnerDrawState): Boolean; var oldc: tcolor; bmp: Tbitmap; ts: TTextStyle; i: integer; lastvisible: integer; begin result:=inherited DoDrawItem(ACanvas, ARect, AState); if ShouldAppsUseDarkMode() and (result=false) then begin result:=Parent.Menu is TMainMenu; oldc:=acanvas.Brush.color; if result then begin acanvas.Brush.color:=$313131; lastvisible:=-1; for i:=parent.count-1 downto 0 do if parent[i].Visible then begin lastvisible:=i; break; end; if MenuIndex=lastvisible then //name='MenuItem3' then begin if owner is TCustomForm then ARect.Width:=tcustomform(owner).width else begin ARect.Width:=acanvas.width-arect.Left; end; end; acanvas.FillRect(arect); if fCustomFontColor=clDefault then acanvas.font.color:=clWhite else acanvas.font.color:=fCustomFontColor; ts:=acanvas.TextStyle; ts.ShowPrefix:=true; acanvas.Brush.Style:=bsSolid; acanvas.TextRect(arect,arect.left,arect.top,caption, ts); acanvas.Brush.color:=oldc; end; if (not result) and (caption='-') then begin acanvas.Brush.color:=$2b2b2b; acanvas.FillRect(arect); ts:=acanvas.TextStyle; ts.ShowPrefix:=true; acanvas.Brush.Style:=bsSolid; acanvas.pen.color:=clGray; acanvas.pen.Width:=1; acanvas.Line(arect.left+acanvas.TextWidth(' '), arect.CenterPoint.Y,arect.right-acanvas.TextWidth(' '), arect.CenterPoint.Y); acanvas.Brush.color:=oldc; result:=true; end; end; end; procedure TNewMenuItem.setCustomFontColor(newcolor: TColor); begin fCustomFontColor:=newcolor; enabled:=not enabled; //repaints it enabled:=not enabled; end; constructor TNewMenuItem.Create(TheOwner: TComponent); begin inherited Create(TheOwner); fCustomFontColor:=clDefault; end; end.
unit PasswordUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons; type TDlgPassword = class(TForm) BtnOk: TBitBtn; BtnCancel: TBitBtn; PassWordEdit: TEdit; Bevel1: TBevel; Label1: TLabel; cbShowChar: TCheckBox; procedure cbShowCharClick(Sender: TObject); private { Private declarations } public { Public declarations } end; Function GetPassword(AOwner:TComponent;Var PassWord:string):Boolean; var DlgPassword: TDlgPassword; implementation {$R *.dfm} Function GetPassword(AOwner:TComponent;Var PassWord:string):Boolean; begin DlgPassword:=TDlgPassword.Create(AOwner); if DlgPassword.ShowModal=mrOk then begin PassWord:=DlgPassword.PassWordEdit.Text; Result:=True; end else Result:=False; DlgPassword.Free; end; procedure TDlgPassword.cbShowCharClick(Sender: TObject); begin if cbShowChar.Checked then PassWordEdit.PasswordChar:=#0 else PassWordEdit.PasswordChar:='*'; end; end.
unit DevMax.Utils.Marshalling; interface uses System.SysUtils, System.Classes, System.Rtti, System.TypInfo, Data.DB, Data.FmtBcd, System.JSON, System.IOUtils; type { 필드이름 정의 특성 - JSON Marshalling 시 구조체 필드이름으로 JSON 속성 매칭 필드이름과 JSON 속성 명이 다른 경우, 필드 위에 (JSON 속성명으로)특성 선언 - e.g. ViewPages -> Pages [FieldNameDef('Pages')] ViewPages: TArray<TViewPageInfo>; } FieldNameDefAttribute = class(TCustomAttribute) private FFieldName: string; public constructor Create(const AFieldName: string); property FieldName: string read FFieldName; end; TJSONObjectEvent = reference to procedure(AObj: TJSONObject); TMarshall = class private /// 구조체(ARecord, ARecordInstance)의 필드(AField)에 JSON값으로 값을 채운다. class procedure SetRecordFieldFromJSONValue(var ARecord; AField: TRttiField; AJSONValue: TJSONValue; AValueName: string = ''); overload; class procedure SetRecordFieldFromJSONValue(ARecordInstance: Pointer; AField: TRttiField; AJSONValue: TJSONValue; AValueName: string = ''); overload; class procedure SetRecordFieldsFromJSONValue(ARecordInstance: Pointer; AField: TRttiField; AJSONValue: TJSONValue); overload; /// 구조체의 동적 배열 필드에 JSON배열의 값으로 길이 설정 후 값을 채운다. class procedure SetRecordDynArrayFromJSONArray(ARecordInstance: Pointer; AArrField: TRttiField; AJSONArray: TJSONArray); /// 필드 이름을 특성(FieldNameAttribute) 또는 Field.Name으로 반환 class function GetFieldName(AField: TRttiField): string; public // DataSet & JSON /// 하나의 레코드를 JSONObject로 변환 class procedure DataSetToJSONObject(ADataSet: TDataSet; AJSONObject: TJSONObject); overload; class procedure DataSetToJSONObject(ADataSet: TDataSet; AFields: TArray<string>; AJSONObject: TJSONObject); overload; // 데이터셋의 모든 레코드를 JSONArray로 변환 class procedure DataSetToJSONArray(ADataSet: TDataSet; AJSONArray: TJSONArray; AJSONObjectProc: TJSONObjectEvent = nil); overload; class procedure DataSetToJSONArray(ADataSet: TDataSet; AFields: TArray<string>; AJSONArray: TJSONArray; AJSONObjectProc: TJSONObjectEvent = nil); overload; // JSON & Record /// JSON의 데이터로 구조체에 값을 채운다(동적 배열 포함) class procedure JSONToRecord<T>(AJSONValue: TJSONValue; var ARecord: T); end; implementation { FieldNameAttribute } constructor FieldNameDefAttribute.Create(const AFieldName: string); begin FFieldName := AFieldName; end; { TDataConverter } class procedure TMarshall.DataSetToJSONArray(ADataSet: TDataSet; AJSONArray: TJSONArray; AJSONObjectProc: TJSONObjectEvent = nil); var I: Integer; Fields: TArray<string>; begin SetLength(Fields, ADataSet.FieldCount); for I := 0 to ADataSet.FieldCount - 1 do Fields[I] := ADataSet.Fields[I].FieldName; DataSetToJSONArray(ADataSet, Fields, AJSONArray, AJSONObjectProc); end; class procedure TMarshall.DataSetToJSONArray(ADataSet: TDataSet; AFields: TArray<string>; AJSONArray: TJSONArray; AJSONObjectProc: TJSONObjectEvent = nil); var Obj: TJSONObject; begin { TODO : 열려있지 않은 경우 예외처리 필요 } ADataSet.First; while not ADataSet.Eof do begin Obj := TJSONObject.Create; DataSetToJSONObject(ADataSet, AFields, Obj); AJSONArray.AddElement(Obj); if Assigned(AJSONObjectProc) then AJSONObjectProc(Obj); ADataSet.Next; end; end; class procedure TMarshall.DataSetToJSONObject(ADataSet: TDataSet; AJSONObject: TJSONObject); var I: Integer; Fields: TArray<string>; begin SetLength(Fields, ADataSet.FieldCount); for I := 0 to ADataSet.FieldCount - 1 do Fields[I] := ADataSet.Fields[I].FieldName; DataSetToJSONObject(ADataSet, Fields, AJSONObject); end; class procedure TMarshall.DataSetToJSONObject(ADataSet: TDataSet; AFields: TArray<string>; AJSONObject: TJSONObject); var I: Integer; Field: TField; begin for I := 0 to Length(AFields) - 1 do begin Field := ADataSet.FieldByName(AFields[I]); if not Assigned(Field) then Continue; if Field.IsNull then begin AJSONObject.AddPair(Field.FieldName, TJSONNull.Create); Continue; end; case Field.DataType of // Numeric TFieldType.ftInteger, TFieldType.ftLongWord, TFieldType.ftAutoInc, TFieldType.ftSmallint, TFieldType.ftShortint: AJSONObject.AddPair(Field.FieldName, TJSONNumber.Create(Field.AsInteger)); TFieldType.ftLargeint: AJSONObject.AddPair(Field.FieldName, TJSONNumber.Create(Field.AsLargeInt)); // Float TFieldType.ftSingle, TFieldType.ftFloat: AJSONObject.AddPair(Field.FieldName, TJSONNumber.Create(Field.AsFloat)); TFieldType.ftCurrency: AJSONObject.AddPair(Field.FieldName, TJSONNumber.Create(Field.AsCurrency)); TFieldType.ftBCD, TFieldType.ftFMTBcd: AJSONObject.AddPair(Field.FieldName, TJSONNumber.Create(BcdToDouble(Field.AsBcd))); // string ftWideString, ftMemo, ftWideMemo: AJSONObject.AddPair(Field.FieldName, Field.AsWideString); ftString: AJSONObject.AddPair(Field.FieldName, Field.AsString); // Date TFieldType.ftDate: AJSONObject.AddPair(Field.FieldName, FormatDateTime('YYYY-MM-DD', Field.AsDateTime)); TFieldType.ftDateTime: AJSONObject.AddPair(Field.FieldName, FormatDateTime('YYYY-MM-DD HH:NN:SS', Field.AsDateTime)); // Boolean TFieldType.ftBoolean: if Field.AsBoolean then AJSONObject.AddPair(Field.FieldName, TJSONTrue.Create) else AJSONObject.AddPair(Field.FieldName, TJSONFalse.Create); end; end; end; // 구조체의 이름과 JSON 포맷의 이름이 다른 경우 FileNameAttribute에 JSON 포맷의 이름 지정 할 것 class function TMarshall.GetFieldName(AField: TRttiField): string; var Attr: TCustomAttribute; begin Result := AField.Name; for Attr in AField.GetAttributes do begin if Attr is FieldNameDefAttribute then Result := FieldNameDefAttribute(Attr).FieldName end; end; // Dynamic Array에 JSON Array 데이터 담기 { TViewInfo = reocord // Record Pages: TArray<TViewPage>; // Dynamic Array(ElmType: TViewPage) end; } class procedure TMarshall.SetRecordDynArrayFromJSONArray(ARecordInstance: Pointer; AArrField: TRttiField; AJSONArray: TJSONArray); var I: Integer; Len: NativeInt; // 꼭 NativeInt로 적용(64비트 대응: iOS64 등) Ctx: TRttiContext; RecVal, ItemVal: TValue; JSONVal: TJSONValue; RecRawData, ItemRawData: Pointer; ElmType: PTypeInfo; Field: TRttiField; FieldName: string; begin RecVal := AArrField.GetValue(ARecordInstance); if not RecVal.IsArray then Exit; RecRawData := RecVal.GetReferenceToRawData; // 배열의 데이터 포인터 Len := AJSONArray.Count; // 동적배열 길이 설정 DynArraySetLength(PPointer(RecRawData)^, RecVal.TypeInfo, 1, @Len); AArrField.SetValue(ARecordInstance, RecVal); // SetValue 설정 안하면 원래 레코드에 적용 안됨 // 배열 요소의 타입 ElmType := RecVal.TypeData.DynArrElType^; Ctx := TRttiContext.Create; try for I := 0 to Len - 1 do begin JSONVal := AJSONArray.Items[I]; ItemVal := RecVal.GetArrayElement(I); ItemRawData := ItemVal.GetReferenceToRawData; for Field in Ctx.GetType(ElmType).GetFields do begin FieldName := GetFieldName(Field); SetRecordFieldFromJSONValue(ItemRawData, Field, JSONVal, FieldName); end; RecVal.SetArrayElement(I, ItemVal); // SetArrayElement 안하면 원래 레코드에 적용 안됨 end; finally Ctx.Free; end; end; /// SetRecordFieldFromJSONValue class procedure TMarshall.SetRecordFieldFromJSONValue(ARecordInstance: Pointer; AField: TRttiField; AJSONValue: TJSONValue; AValueName: string); var OrdValue: Integer; begin case AField.FieldType.TypeKind of tkString, tkLString, tkWString, tkUString: AField.SetValue(ARecordInstance, TValue.From<string>(AJSONValue.GetValue<string>(AValueName))); tkInteger, tkInt64: AField.SetValue(ARecordInstance, TValue.From<Integer>(AJSONValue.GetValue<Integer>(AValueName, -1))); tkFloat: AField.SetValue(ARecordInstance, TValue.From<Single>(AJSONValue.GetValue<Single>(AValueName, -1))); tkEnumeration: begin if not AJSONValue.TryGetValue<Integer>(AValueName, OrdValue) then begin // 열거형 문자열인 경우 처리(taRight 등) OrdValue := GetEnumValue(AField.FieldType.Handle, AJSONValue.GetValue<string>(AValueName)); // 열거형 문자열을 숫자로 전환 end; if OrdValue < 0 then Exit; AField.SetValue(ARecordInstance, TValue.FromOrdinal(AField.FieldType.Handle, OrdValue)); end; tkDynArray: begin // JSON Array if AValueName <> '' then AJSONValue := AJSONValue.GetValue<TJSONValue>(AValueName, nil); if Assigned(AJSONValue) then SetRecordDynArrayFromJSONArray(ARecordInstance, AField, AJSONValue as TJSONArray); end; tkRecord: begin if AValueName <> '' then AJSONValue := AJSONValue.GetValue<TJSONValue>(AValueName, nil); if Assigned(AJSONValue) then SetRecordFieldsFromJSONValue(ARecordInstance, AField, AJSONValue); end; { TODO: 필요한 필드타입 추가 구현 할 것 } else raise Exception.Create('Not support type: ' + AField.FieldType.ToString); end; end; class procedure TMarshall.SetRecordFieldsFromJSONValue(ARecordInstance: Pointer; AField: TRttiField; AJSONValue: TJSONValue); var Ctx: TRttiContext; Field: TRttiField; FieldName: string; RecVal: TValue; // JSONValue: TJSONValue; begin Ctx := TRttiContext.Create; try RecVal := AField.GetValue(ARecordInstance); for Field in Ctx.GetType(RecVal.TypeInfo).GetFields do begin FieldName := GetFieldName(Field); SetRecordFieldFromJSONValue(RecVal.GetReferenceToRawData, Field, AJSONValue, FieldName); end; AField.SetValue(ARecordInstance, RecVal); finally Ctx.Free; end; end; class procedure TMarshall.SetRecordFieldFromJSONValue(var ARecord; AField: TRttiField; AJSONValue: TJSONValue; AValueName: string = ''); begin SetRecordFieldFromJSONValue(@ARecord, AField, AJSONValue, AValueName); end; class procedure TMarshall.JSONToRecord<T>(AJSONValue: TJSONValue; var ARecord: T); var Ctx: TRttiContext; Field: TRttiField; Value: TJSONValue; FieldName: string; begin Ctx := TRttiContext.Create; try for Field in Ctx.GetType(TypeInfo(T)).GetFields do begin FieldName := GetFieldName(Field); if not AJSONValue.TryGetValue<TJSONValue>(FieldName, Value) then Continue; SetRecordFieldFromJSONValue(ARecord, Field, Value); end; finally Ctx.Free; end; end; end.
unit Unit1; interface //////////////////////////////////////////////////////////////////////////////// // NNTP Server Protocol DEMONSTRATION // .. // Author: Ozz Nixon // .. // This is a simple demo (as far as the message bases are concerned!), that will // track all the newsgroups via NNTPSVC.INI (in your Windows Directory). It can // be expanded to contain more newsgroups than what is automatically generated! // // Instead of designing this demo to be limited to one "root" directory and all // the newsgroups being stored below them, I allow you to point each newsgroup // to different drives and subdirectories! // // NNTPSVC.INI {layout definition} // [SETUP] // Number of Newsgroups // Port number to listen to {defaults to IPPORT_NNTP=119} // [GROUP1] {note the 1 is dynamic, it is based upon the # of news groups!} // Newsgroup Name // News Group Directory {no trailing backslash!} // Date of Last Post // Time of Last Post // // I do not keep track of # of posts in the INI, just incase you want to run // multiple NNTP Servers, they can share the same INI file and/or directories. // // Next, If you want the Listener Component to parse the commands and fire // events to you, do not implement the OnExecute event! If you want to do all // of the parsing for some reason, then Implement the OnExecute event, and do // not implement any of the OnCommand* events. // // If you plan to develop a server using this type of file layout, the following // features could improve your performance: // // 1. Tracking the Highest/Lowest Message Numbers in the [GROUP#] section would // allow you to bypass the physical scan this demo does. // 2. Using a bit-array, you could set a bit to 1 if the message exists, and 0 // if it does not. This could be saved into the INI file, but I would suggest // that if you do not implement the previous tweak that you implement this // one. Each bit is basically tracking does the file exist, then with simple // math you would know what the next/previous message numbers are. Basically // a real simple index to avoid a lot of wasted "fileexists" calls. // //////////////////////////////////////////////////////////////////////////////// { Date Author Change. -------------------------------------------------------------------------------- 08-AUG-1999 Mark Added the Mode,Check and Takethis methods. [streaming nntp] 08-AUG-1999 Mark Added some code to disconnect active connections when server is shutdown } uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Winshoes, serverwinshoe, ServerWinshoeNNTP, GlobalWinshoe, Buttons, ExtCtrls, ComCtrls, StdCtrls; Const IniFilename = 'NNTPSVC.INI'; ServerID = 'news.yourdomain.com'; type // This Object is stored per thread, for tracking purposes! UniqPerThread = class(TObject) public CurrentMessageNumber:Integer; CurrentGroupLoMsg:Integer; CurrentGroupHiMsg:Integer; CurrentGroupAvail:Integer; CurrentNewsGroup:String; CurrentGroupPath:String; End; TForm1 = class(TForm) WinshoeNNTPListener1: TWinshoeNNTPListener; StatusBar1: TStatusBar; Panel1: TPanel; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; ListBox1: TListBox; Bevel1: TBevel; Bevel2: TBevel; ListBox2: TListBox; SpeedButton3: TSpeedButton; procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure WinshoeNNTPListener1Connect(Thread: TWinshoeServerThread); procedure WinshoeNNTPListener1Disconnect(Thread: TWinshoeServerThread); procedure FormShow(Sender: TObject); procedure WinshoeNNTPListener1CommandList(Thread: TWinshoeServerThread; Parm: String); procedure WinshoeNNTPListener1CommandGroup( Thread: TWinshoeServerThread; Group: String); procedure WinshoeNNTPListener1CommandListgroup( Thread: TWinshoeServerThread; Parm: String); procedure WinshoeNNTPListener1CommandHeadNo( Thread: TWinshoeServerThread; ActualNumber: Integer); procedure WinshoeNNTPListener1CommandBodyNo( Thread: TWinshoeServerThread; ActualNumber: Integer); procedure WinshoeNNTPListener1CommandArticleNo( Thread: TWinshoeServerThread; ActualNumber: Integer); procedure WinshoeNNTPListener1CommandQuit( Thread: TWinshoeServerThread); procedure WinshoeNNTPListener1CommandStatNo( Thread: TWinshoeServerThread; ActualNumber: Integer); procedure WinshoeNNTPListener1CommandHelp( Thread: TWinshoeServerThread); procedure WinshoeNNTPListener1CommandPost(Thread: TWinshoeServerThread); procedure WinshoeNNTPListener1CommandDate( Thread: TWinshoeServerThread); procedure WinshoeNNTPListener1CommandXOver( Thread: TWinshoeServerThread; Parm: String); procedure WinshoeNNTPListener1CommandNext( Thread: TWinshoeServerThread); procedure WinshoeNNTPListener1CommandLast( Thread: TWinshoeServerThread); procedure WinshoeNNTPListener1CommandIHave( Thread: TWinshoeServerThread; ActualID: String); procedure WinshoeNNTPListener1CommandXHDR(Thread: TWinshoeServerThread; Parm: String); procedure SpeedButton3Click(Sender: TObject); procedure WinshoeNNTPListener1CommandOther( Thread: TWinshoeServerThread; Command, Parm: String; var Handled: Boolean); procedure WinshoeNNTPListener1CommandArticleID( Thread: TWinshoeServerThread; ActualID: String); procedure WinshoeNNTPListener1CommandHeadID( Thread: TWinshoeServerThread; ActualID: String); procedure WinshoeNNTPListener1CommandCheck( Thread: TWinshoeServerThread; ActualID: String); procedure WinshoeNNTPListener1CommandTakeThis( Thread: TWinshoeServerThread; ActualID: String); procedure WinshoeNNTPListener1CommandMode(Thread: TWinshoeServerThread; Parm: String); private { Private declarations } NumberOfConnections:Integer; NumberOfNewsgroups:Integer; public { Public declarations } end; var Form1: TForm1; implementation Uses FileCtrl, StringsWinshoe, IniFiles, Unit2; {$R *.DFM} Function GetHighestMsgNumber(S1:String):Integer; Var Err:Integer; SRec:TSearchRec; Begin Result:=0; Err:=FindFirst(S1+'\*.HDR',faAnyFile,SRec); While Err=0 do Begin try If StrToInt(Copy(SRec.Name,1,Pos('.',SRec.Name)-1))>Result then Result:=StrToInt(Copy(SRec.Name,1,Pos('.',SRec.Name)-1)); except end; Err:=FindNext(SRec); End; FindClose(SRec); End; Function SendListResponse(Path:String):String; Var Err:Integer; SRec:TSearchRec; TmpInt:Integer; CurrentGroupHiMsg:Integer; CurrentGroupLoMsg:Integer; Begin Err:=FindFirst(Path+'\*.hdr',faAnyFile,SRec); CurrentGroupHiMsg:=0; CurrentGroupLoMsg:=1; While Err=0 do Begin If SRec.Attr and faDirectory=0 then Begin TmpInt:=StrToInt(Copy(SRec.Name,1,Pos('.',SRec.Name)-1)); If TmpInt>CurrentGroupHiMsg then CurrentGroupHiMsg:=TmpInt; If CurrentGroupLoMsg>TmpInt then CurrentGroupLoMsg:=TmpInt; End; Err:=FindNext(SRec); End; {the 'y' on the end means writable!} Result:=Pad10(CurrentGroupHiMsg)+CHAR32+Pad10(CurrentGroupLoMsg)+CHAR32+'y'; FindClose(SRec); End; Function SendGroupResponse(Thread: TWinshoeServerThread;Path,Group:String):String; Var Err:Integer; SRec:TSearchRec; TmpInt:Integer; Begin With Thread.SessionData as UniqPerThread do Begin CurrentNewsGroup:=Group; CurrentGroupPath:=Path; CurrentGroupLoMsg:=0; CurrentGroupHiMsg:=0; CurrentGroupAvail:=0; CurrentMessageNumber:=0; Err:=FindFirst(Path+'\*.hdr',faAnyFile,SRec); While Err=0 do Begin If SRec.Attr and faDirectory=0 then Begin TmpInt:=StrToInt(Copy(SRec.Name,1,Pos('.',SRec.Name)-1)); {if you wanted to do a bit array of available msgs it would go here!} If TmpInt>CurrentGroupHiMsg then CurrentGroupHiMsg:=TmpInt; If CurrentGroupLoMsg=0 then CurrentGroupLoMsg:=TmpInt Else If CurrentGroupLoMsg>TmpInt then CurrentGroupLoMsg:=TmpInt; CurrentGroupAvail:=CurrentGroupAvail+1; End; Err:=FindNext(SRec); End; Result:='211 '+ IntToStr(CurrentGroupAvail)+CHAR32+ IntToStr(CurrentGroupLoMsg)+CHAR32+ IntToStr(CurrentGroupHiMsg)+CHAR32+Group; CurrentMessageNumber:=CurrentGroupLoMsg; FindClose(SRec); End; End; //////////////////////////////////////////////////////////////////////////////// // START THE SERVER //////////////////////////////////////////////////////////////////////////////// procedure TForm1.SpeedButton1Click(Sender: TObject); begin Form2.ListBox1.Items.Clear; try WinshoeNNTPListener1.Active:=True; StatusBar1.SimpleText:='Server Ready for Clients!'; SpeedButton1.Enabled:=False; SpeedButton2.Enabled:=True; NumberOfConnections:=0; except StatusBar1.SimpleText:='Server failed to Initialize!'; end; end; //////////////////////////////////////////////////////////////////////////////// // STOP THE SERVER //////////////////////////////////////////////////////////////////////////////// procedure TForm1.SpeedButton2Click(Sender: TObject); Var TmpTList : TList; Count : Integer; {do it this way!} I : Integer; begin TmpTList:=WinshoeNNTPListener1.Threads.LockList; Count := TmpTList.Count; WinshoeNNTPListener1.Threads.UnlockList; If Count > 0 then Begin If Windows.MessageBox(0, PChar('There are '+IntToStr(Count)+ ' connections active!'+#13+ 'Do you wish to continue?'), 'Warning!', MB_ICONEXCLAMATION or MB_YESNO)= IDNO then Exit else begin // disconnect the connections TmpTList := WinshoeNNTPListener1.Threads.LockList; try for I := 0 to TmpTList.Count -1 do TWinshoeServerThread(TmpTList.Items[I]).Connection.Disconnect; finally WinshoeNNTPListener1.Threads.UnLockList; end; end; end; try WinShoeNNTPListener1.Active:=False; except end; StatusBar1.SimpleText:='Server is now offline!'; SpeedButton1.Enabled:=True; SpeedButton2.Enabled:=False; NumberOfConnections:=0; end; //////////////////////////////////////////////////////////////////////////////// // UNKNOWN COMMAND TO THE SERVER COMPONENT //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandOther( Thread: TWinshoeServerThread; Command, Parm: String; var Handled: Boolean); begin Form2.ListBox1.Items.Append('UNKNOWN: ['+Command+'] '+Parm); ListBox2.Items.Add(Command+CHAR32+Parm); If command='MODE' then Begin Handled:=True; Thread.Connection.Writeln('200 OK'); end Else Handled:=False; end; //////////////////////////////////////////////////////////////////////////////// // POST Received - SAVE A MESSAGE (HEADER AND BODY) TO DISK //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandPost( Thread: TWinshoeServerThread); Var Msg:TStringList; Body:TStringList; Newsgroups:String; S:String; Loop:Integer; IniFile:TIniFile; Path:String; CurrentGroupHiMsg:Integer; W1,W2,W3,W4:Word; Ws:String; begin Form2.ListBox1.Items.Append('POST'); Thread.Connection.Writeln('340 send article to be posted. End with <CR-LF>.<CR-LF>'); Msg:=TStringList.Create; Thread.Connection.CaptureHeader(Msg,''); {should always be blank} {fields we add on the fly we have to add "=" to mimic capture!} If Msg.Values['Message-ID']='' then Begin DecodeDate(Now,W1,W2,W3); Ws:=IntToHex(W1,4)+IntToHex(W2,2)+IntToHex(W3,2); DecodeTime(Now,W1,W2,W3,W4); Ws:=Ws+IntToHex(W1,2)+IntToHex(W2,2)+IntToHex(W3,2)+IntToHex(W4,2); Msg.Insert(0,'Message-ID=<'+WS+'@'+ServerID+'>'); End; If Msg.Values['Path']='' then Msg.Insert(0,'Path='+ServerID); Newsgroups:=Msg.Values['Newsgroups']; If Newsgroups='' then Newsgroups:= UniqPerThread(Thread.SessionData).CurrentNewsGroup; If NewsGroups='' then Begin Thread.Connection.Writeln('412 no newsgroup has been selected'); Msg.Free; Exit; End; Body:=TStringList.Create; Thread.Connection.Capture(Body, ['.']); IniFile:=TIniFile.Create(IniFilename); Newsgroups:=Lowercase(Newsgroups)+','; S:=Fetch(Newsgroups,','); While S<>'' do Begin Path:=''; For Loop:=1 to NumberOfNewsgroups do Begin With IniFile do Begin Path:=ReadString('GROUP'+IntToStr(Loop),'Name',''); If lowercase(Path)=S then Begin Path:=ReadString('GROUP'+IntToStr(Loop),'Path',''); Break End; End; End; If Path<>'' then Begin CurrentGroupHiMsg:=GetHighestMsgNumber(Path); If Msg.Values['Lines']='' then Msg.Append('Lines='+IntToStr(Body.Count)); Msg.SaveToFile(Path+'\'+Pad10(CurrentGroupHiMsg+1)+'.HDR'); Body.SaveToFile(Path+'\'+Pad10(CurrentGroupHiMsg+1)+'.BDY'); End; S:=Fetch(Newsgroups,','); End; Msg.Free; Body.Free; IniFile.Free; Thread.Connection.Writeln('240 article posted ok'); end; //////////////////////////////////////////////////////////////////////////////// // NEW CLIENT HAS CONNECTED TO THE SERVER! //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1Connect(Thread: TWinshoeServerThread); begin ListBox1.Items.Add('Connect: '+ DateToStr(Date)+CHAR32+TimeToStr(Time)); {if login is required then send a different 200 number!} Thread.Connection.WriteLn('200 '+ServerID+' NNTP_Sample/1.0 ready. (posting ok)'); Inc(NumberOfConnections); StatusBar1.SimpleText:='There are '+IntToStr(NumberOfConnections)+' connections...'; Thread.SessionData:=UniqPerThread.Create; With Thread.SessionData as UniqPerThread do begin CurrentMessageNumber:=-1; CurrentNewsGroup:=''; CurrentGroupPath:=''; CurrentGroupLoMsg:=0; CurrentGroupHiMsg:=0; CurrentGroupAvail:=0; End; end; //////////////////////////////////////////////////////////////////////////////// // AN EXISTING CLIENT SESSION HAS DROPPED //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1Disconnect( Thread: TWinshoeServerThread); begin ListBox1.Items.Add('Disconnect: '+ DateToStr(Date)+CHAR32+TimeToStr(Time)); Dec(NumberOfConnections); StatusBar1.SimpleText:='There are '+IntToStr(NumberOfConnections)+' connections...'; end; //////////////////////////////////////////////////////////////////////////////// // APPLICATION STARTED, LOAD DEFAULT SETTINGS //////////////////////////////////////////////////////////////////////////////// procedure TForm1.FormShow(Sender: TObject); Var IniFile:TIniFile; begin IniFile:=TIniFile.Create(IniFilename); If IniFile.ReadInteger('SETUP','Groups',0)=0 then Begin With IniFile do Begin WriteInteger('SETUP','Groups',3); WriteInteger('SETUP','Port', WSPORT_NNTP); WriteString('GROUP1','Name','public.news.test'); WriteString('GROUP1','Path',ExtractFilePath(Paramstr(0))+'public.news.test'); ForceDirectories(ExtractFilePath(Paramstr(0))+'public.news.test'); WriteString('GROUP1','Date','800101'); {1980/01/01} WriteString('GROUP1','Time','000000'); {midnight} WriteString('GROUP2','Name','public.news.announcements'); WriteString('GROUP2','Path',ExtractFilePath(Paramstr(0))+'public.news.announcements'); ForceDirectories(ExtractFilePath(Paramstr(0))+'public.news.announcements'); WriteString('GROUP2','Date','800101'); {1980/01/01} WriteString('GROUP2','Time','000000'); {midnight} WriteString('GROUP3','Name','public.other.news'); WriteString('GROUP3','Path',ExtractFilePath(Paramstr(0))+'public.other.news'); ForceDirectories(ExtractFilePath(Paramstr(0))+'public.other.news'); WriteString('GROUP3','Date','800101'); {1980/01/01} WriteString('GROUP3','Time','000000'); {midnight} End; End; With IniFile do Begin WinShoeNNTPListener1.Port:=ReadInteger('SETUP','Port', WSPORT_NNTP); NumberOfNewsGroups:=ReadInteger('SETUP','Groups',0); StatusBar1.SimpleText:='Server is supporting '+ IntToStr(NumberOfNewsgroups)+' message area(s).'; End; IniFile.Free; end; //////////////////////////////////////////////////////////////////////////////// // LIST Received - send a list of newsgroup names //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandList( Thread: TWinshoeServerThread; Parm: String); Var Loop:Integer; IniFile:TInifile; begin Form2.ListBox1.Items.Append('LIST ('+Parm+')'); If Parm<>'' then Begin If lowercase(parm)='extensions' then Begin Thread.Connection.Writeln('202 Extensions supported:'); Thread.Connection.Writeln(' OVER'); Thread.Connection.Writeln(' HDR'); Thread.Connection.Writeln(' PAT'); Thread.Connection.Writeln(' LISTGROUP'); Thread.Connection.Writeln(' DATE'); Thread.Connection.Writeln(' AUTHINFO'); Thread.Connection.Writeln('.'); Exit; end; End; IniFile:=TIniFile.Create(IniFilename); Thread.Connection.Writeln('215 list of newsgroups follows'); With IniFile do Begin For Loop:=1 to NumberOfNewsGroups do Begin Thread.Connection.WriteLn( lowercase(IniFile.ReadString('GROUP'+IntToStr(Loop),'Name',''))+CHAR32+ SendListResponse( IniFile.ReadString('GROUP'+IntToStr(Loop),'Path',''))); End; End; Thread.Connection.Writeln('.'); IniFile.Free; StatusBar1.SimpleText:='List of Newsgroups requested...'; end; //////////////////////////////////////////////////////////////////////////////// // GROUP Received - Select the Newsgroup //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandGroup( Thread: TWinshoeServerThread; Group: String); Var IniFile:TIniFile; Loop:Integer; begin Form2.ListBox1.Items.Append('GROUP ('+Group+')'); If Group<>'' then Begin IniFile:=TIniFile.Create(IniFilename); With IniFile do Begin For Loop:=1 to NumberOfNewsGroups do Begin If lowercase(ReadString('GROUP'+IntToStr(Loop),'Name',''))= lowercase(group) then Begin Thread.Connection.Writeln( SendGroupResponse(Thread, ReadString('GROUP'+IntToStr(Loop),'Path',''),Group)); StatusBar1.SimpleText:=Group+' selected.'; IniFile.Free; Exit; End; End; End; IniFile.Free; End; Thread.Connection.Writeln('431 no such news group') end; //////////////////////////////////////////////////////////////////////////////// // LISTGROUP Received - Send a list of active message numbers //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandListgroup( Thread: TWinshoeServerThread; Parm: String); Var Loop:Integer; IniFile:TInifile; Procedure SendSortedArticleList(Path:String); Var Err:Integer; SRec:TSearchRec; SortList:TStringList; Begin SortList:=TStringList.Create; Err:=FindFirst(Path+'\*.HDR',faAnyFile,SRec); While Err=0 do Begin try SortList.Add(IntToStr(StrToInt(Copy(SRec.Name,1,Pos('.',SRec.Name)-1)))); except end; Err:=FindNext(SRec); End; FindClose(SRec); SortList.Sort; While SortList.Count>0 do Begin Thread.Connection.WriteLn(SortList[0]); SortList.Delete(0); End; SortList.Free; End; begin Form2.ListBox1.Items.Append('LISTGROUP ('+Parm+')'); If Parm='' then Begin Parm:=UniqPerThread(Thread.SessionData).CurrentNewsGroup; If Parm='' then Begin Thread.Connection.Writeln('412 no newsgroup has been selected'); Exit; End; End; Parm:=lowercase(parm); IniFile:=TIniFile.Create(IniFilename); Thread.Connection.Writeln('211 list of article numbers follows'); With IniFile do Begin For Loop:=1 to NumberOfNewsGroups do Begin If lowercase(IniFile.ReadString('GROUP'+IntToStr(Loop),'Name',''))= Parm then Begin SendSortedArticleList(IniFile.ReadString('GROUP'+IntToStr(Loop),'Path','')); Break; End; End; End; Thread.Connection.Writeln('.'); IniFile.Free; StatusBar1.SimpleText:='List of article in '+Parm; end; //////////////////////////////////////////////////////////////////////////////// // HEAD # Received - Send the appropriate Header //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandHeadNo( Thread: TWinshoeServerThread; ActualNumber: Integer); Var Msg:TStringList; MsgID:String; begin Form2.ListBox1.Items.Append('HEAD ('+IntToStr(ActualNumber)+')'); If UniqPerThread(Thread.SessionData).CurrentGroupPath='' then Begin Thread.Connection.Writeln('412 no newsgroup has been selected'); Exit; End; MsgID:=Pad10(ActualNumber); Msg:=TStringList.Create; Msg.LoadFromFile(UniqPerThread(Thread.SessionData).CurrentGroupPath+'\'+ Pad10(ActualNumber)+'.HDR'); MsgID:=lowercase(Msg.Values['Message-ID']); Thread.Connection.Writeln('221 '+IntToStr(ActualNumber)+CHAR32+ MsgID+CHAR32+'head'); While Msg.Count>0 do Begin Thread.Connection.Writeln(Msg.Names[0]+': '+Msg.Values[Msg.Names[0]]); Msg.Delete(0); End; Msg.Free; Thread.Connection.Writeln('.'); StatusBar1.SimpleText:='Head Command issued for message #'+IntToStr(ActualNumber); end; //////////////////////////////////////////////////////////////////////////////// // BODY # Received - Send the appropriate body //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandBodyNo( Thread: TWinshoeServerThread; ActualNumber: Integer); Var Msg:TStringList; MsgID:String; begin Form2.ListBox1.Items.Append('BODY ('+IntToStr(ActualNumber)+')'); If UniqPerThread(Thread.SessionData).CurrentGroupPath='' then Begin Thread.Connection.Writeln('412 no newsgroup has been selected'); Exit; End; MsgID:=Pad10(ActualNumber); Msg:=TStringList.Create; Msg.LoadFromFile(UniqPerThread(Thread.SessionData).CurrentGroupPath+'\'+ Pad10(ActualNumber)+'.HDR'); MsgID:=lowercase(Msg.Values['Message-ID']); Msg.LoadFromFile(UniqPerThread(Thread.SessionData).CurrentGroupPath+'\'+ Pad10(ActualNumber)+'.BDY'); Thread.Connection.Writeln('222 '+IntToStr(ActualNumber)+CHAR32+ MsgID+CHAR32+'head'); While Msg.Count>0 do Begin Thread.Connection.Writeln(Msg[0]); Msg.Delete(0); End; Msg.Free; Thread.Connection.Writeln('.'); StatusBar1.SimpleText:='Body Command issued for message #'+IntToStr(ActualNumber); end; //////////////////////////////////////////////////////////////////////////////// // ARTICLE # Received - Send the appropriate header and body //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandArticleNo( Thread: TWinshoeServerThread; ActualNumber: Integer); Var Msg:TStringList; MsgID:String; begin Form2.ListBox1.Items.Append('ARTICLE ('+IntToStr(ActualNumber)+')'); If UniqPerThread(Thread.SessionData).CurrentGroupPath='' then Begin Thread.Connection.Writeln('412 no newsgroup has been selected'); Exit; End; MsgID:=Pad10(ActualNumber); Msg:=TStringList.Create; Msg.LoadFromFile(UniqPerThread(Thread.SessionData).CurrentGroupPath+'\'+ Pad10(ActualNumber)+'.HDR'); MsgID:=lowercase(Msg.Values['Message-ID']); Thread.Connection.Writeln('220 '+IntToStr(ActualNumber)+CHAR32+ MsgID+CHAR32+'head'); While Msg.Count>0 do Begin Thread.Connection.Writeln(Msg.Names[0]+': '+Msg.Values[Msg.Names[0]]); Msg.Delete(0); End; Msg.LoadFromFile(UniqPerThread(Thread.SessionData).CurrentGroupPath+'\'+ Pad10(ActualNumber)+'.BDY'); Thread.Connection.Writeln(''); {end of header marker!} While Msg.Count>0 do Begin Thread.Connection.Writeln(Msg[0]); Msg.Delete(0); End; Msg.Free; Thread.Connection.Writeln('.'); StatusBar1.SimpleText:='Article Command issued for message #'+IntToStr(ActualNumber); end; //////////////////////////////////////////////////////////////////////////////// // QUIT Received - Say Goodbye //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandQuit( Thread: TWinshoeServerThread); begin Form2.ListBox1.Items.Append('QUIT'); StatusBar1.SimpleText:='Connection terminated by user!'; Thread.Connection.WriteLn('205 Goodbye'); end; //////////////////////////////////////////////////////////////////////////////// // STAT # Received - Show the Status of the message //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandStatNo( Thread: TWinshoeServerThread; ActualNumber: Integer); Var Msg:TStringList; Loop:Integer; Ws:String; MsgID:String; begin Form2.ListBox1.Items.Append('STAT ('+IntToStr(ActualNumber)+')'); If UniqPerThread(Thread.SessionData).CurrentGroupPath='' then Begin Thread.Connection.Writeln('412 no newsgroup has been selected'); Exit; End; MsgID:=Pad10(ActualNumber); Msg:=TStringList.Create; Msg.LoadFromFile(UniqPerThread(Thread.SessionData).CurrentGroupPath+'\'+ Pad10(ActualNumber)+'.HDR'); For Loop:=1 to Msg.Count do Begin Ws:=Msg[Loop-1]; Ws:=lowercase(Fetch(Ws,CHAR32)); If Copy(Ws,1,10)='message-id' then Begin MsgID:=Ws; Break; End; End; Thread.Connection.Writeln('223 '+IntToStr(ActualNumber)+CHAR32+ MsgID+CHAR32+'status'); Msg.Free; //Thread.Connection.Writeln('.'); StatusBar1.SimpleText:='Status Command issued for message #'+IntToStr(ActualNumber); end; //////////////////////////////////////////////////////////////////////////////// // HELP Received - Send a list of commands we support //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandHelp( Thread: TWinshoeServerThread); begin Form2.ListBox1.Items.Append('HELP'); With Thread.Connection do Begin Writeln('100 Legal commands'); Writeln(' authinfo user Name|pass Password'); Writeln(' article [MessageID|Number]'); Writeln(' body [MessageID|Number]'); Writeln(' date'); Writeln(' group newsgroup'); Writeln(' head [MessageID|Number]'); Writeln(' help'); Writeln(' ihave'); Writeln(' last'); Writeln(' list [active|xactive|newsgroups|distributions|overview.fmt|searches|searchable'); Writeln('|srchfields|extensions|motd|prettynames|subscriptions]'); Writeln(' listgroup newsgroup'); // Writeln(' newgroups yymmdd hhmmss ["GMT"] [<distributions>]'); // Writeln(' newnews newsgroups yymmdd hhmmss ["GMT"] [<distributions>]'); Writeln(' next'); Writeln(' post'); // Writeln(' slave'); Writeln(' stat [MessageID|Number]'); Writeln(' xover [range]'); Writeln(' check <MessageID>'); Writeln(' takethis <MessageID>'); Writeln('Report problems to <name@yourdomain.com>'); Writeln('.'); End; end; //////////////////////////////////////////////////////////////////////////////// // DATE Received - Send YYYYMMDDHHNNSS //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandDate( Thread: TWinshoeServerThread); begin Form2.ListBox1.Items.Append('DATE'); Thread.Connection.Writeln('111 '+ FormatDateTime('yyyymmddhhnnss',Now)); end; //////////////////////////////////////////////////////////////////////////////// // XOVER [RANGE] Received - Send the Tab Padded Overview //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandXOver( Thread: TWinshoeServerThread; Parm: String); Var StartNo,StopNo:Integer; Loop:Integer; Msg:TStringList; SRec:TSearchRec; TmpInt:Integer; begin Form2.ListBox1.Items.Append('XOVER ('+Parm+')'); If UniqPerThread(Thread.SessionData).CurrentGroupPath='' then Begin Thread.Connection.Writeln('412 no newsgroup has been selected'); Exit; End; If Pos('-',Parm)>0 then Begin try StartNo:=StrToInt(Fetch(Parm,'-')); except StartNo:=1; end; try StopNo:=StrToInt(Parm); except StopNo:=StartNo; end; End Else Begin try StartNo:=StrToInt(Parm); except StartNo:=1; end; StopNo:=StartNo; End; Thread.Connection.Writeln('224 overview information follows'); Msg:=TStringList.Create; For Loop:=StartNo to StopNo do Begin If FileExists(UniqPerThread(Thread.SessionData).CurrentGroupPath+ '\'+Pad10(Loop)+'.HDR') then Begin Msg.LoadFromFile(UniqPerThread(Thread.SessionData).CurrentGroupPath+ '\'+Pad10(Loop)+'.HDR'); FindFirst(UniqPerThread(Thread.SessionData).CurrentGroupPath+ '\'+Pad10(Loop)+'.HDR',faAnyFile,SRec); TmpInt:=SRec.Size; FindClose(SRec); FindFirst(UniqPerThread(Thread.SessionData).CurrentGroupPath+ '\'+Pad10(Loop)+'.BDY',faAnyFile,SRec); TmpInt:=TmpInt+SRec.Size; FindClose(SRec); Thread.Connection.Writeln( IntToStr(Loop)+#9+ Msg.Values['Subject']+#9+ Msg.Values['From']+#9+ Msg.Values['Date']+#9+ Msg.Values['Message-ID']+#9+ Msg.Values['References']+#9+ IntToStr(TmpInt)+#9+ Msg.Values['Lines']); End; End; Msg.Free; Thread.Connection.Writeln('.'); end; //////////////////////////////////////////////////////////////////////////////// // NEXT Received - Move the counter to the next message # //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandNext( Thread: TWinshoeServerThread); begin Form2.ListBox1.Items.Append('NEXT'); If UniqPerThread(Thread.SessionData).CurrentGroupPath<>'' then Begin If UniqPerThread(Thread.SessionData).CurrentMessageNumber= UniqPerThread(Thread.SessionData).CurrentGroupHiMsg then Thread.Connection.Writeln('420 no current article has been selected') Else Begin UniqPerThread(Thread.SessionData).CurrentMessageNumber:= UniqPerThread(Thread.SessionData).CurrentMessageNumber+1; Thread.Connection.Writeln('223 '+ IntToStr(UniqPerThread(Thread.SessionData).CurrentMessageNumber)+ CHAR32+'<> article retreived'); End; End Else Thread.Connection.Writeln('412 no news group selected'); end; //////////////////////////////////////////////////////////////////////////////// // LAST Received - Move the counter to the last message # //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandLast( Thread: TWinshoeServerThread); begin Form2.ListBox1.Items.Append('LAST'); If UniqPerThread(Thread.SessionData).CurrentGroupPath<>'' then Begin UniqPerThread(Thread.SessionData).CurrentMessageNumber:= UniqPerThread(Thread.SessionData).CurrentMessageNumber+1; Thread.Connection.Writeln('223 '+ IntToStr(UniqPerThread(Thread.SessionData).CurrentMessageNumber)+ CHAR32+'<> article retreived'); End Else Thread.Connection.Writeln('412 no news group selected'); end; //////////////////////////////////////////////////////////////////////////////// // IHAVE Received - Accept the message if CurrentGroup is defined! //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandIHave( Thread: TWinshoeServerThread; ActualID: String); Var Msg:TStringList; Body:TStringList; Newsgroups:String; S:String; Loop:Integer; IniFile:TIniFile; Path:String; CurrentGroupHiMsg:Integer; W1,W2,W3,W4:Word; Ws:String; begin Form2.ListBox1.Items.Append('IHAVE ('+ActualID+')'); Thread.Connection.Writeln('335 send article to be posted. End with <CR-LF>.<CR-LF>'); Msg:=TStringList.Create; Thread.Connection.CaptureHeader(Msg,''); {should *NOT* be blank} {fields we add on the fly we have to add "=" to mimic capture!} If Msg.Values['Message-ID']='' then Begin DecodeDate(Now,W1,W2,W3); Ws:=IntToHex(W1,4)+IntToHex(W2,2)+IntToHex(W3,2); DecodeTime(Now,W1,W2,W3,W4); Ws:=Ws+IntToHex(W1,2)+IntToHex(W2,2)+IntToHex(W3,2)+IntToHex(W4,2); Msg.Insert(0,'Message-ID=<'+WS+'@'+ServerID+'>'); End; If Msg.Values['Path']='' then Msg.Insert(0,'Path='+ServerID) Else {update it!} Newsgroups:=Msg.Values['Newsgroups']; If Newsgroups='' then Newsgroups:= UniqPerThread(Thread.SessionData).CurrentNewsGroup; If NewsGroups='' then Begin Thread.Connection.Writeln('437 article rejected - do not try again'); Msg.Free; Exit; End; Body:=TStringList.Create; Thread.Connection.Capture(Body, ['.']); IniFile:=TIniFile.Create(IniFilename); Newsgroups:=Lowercase(Newsgroups)+','; S:=Fetch(Newsgroups,','); While S<>'' do Begin Path:=''; For Loop:=1 to NumberOfNewsgroups do Begin With IniFile do Begin Path:=ReadString('GROUP'+IntToStr(Loop),'Name',''); If lowercase(Path)=S then Begin Path:=ReadString('GROUP'+IntToStr(Loop),'Path',''); Break End; End; End; If Path<>'' then Begin CurrentGroupHiMsg:=GetHighestMsgNumber(Path); Msg.SaveToFile(Path+'\'+Pad10(CurrentGroupHiMsg+1)+'.HDR'); Body.SaveToFile(Path+'\'+Pad10(CurrentGroupHiMsg+1)+'.BDY'); End; S:=Fetch(Newsgroups,','); End; Msg.Free; Body.Free; IniFile.Free; Thread.Connection.Writeln('235 article transferred ok'); end; //////////////////////////////////////////////////////////////////////////////// // XHDR Received - Send the requested header field //////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandXHDR( Thread: TWinshoeServerThread; Parm: String); Var Header:String; StartNo,StopNo:Integer; Msg:TStringList; Loop:Integer; begin Form2.ListBox1.Items.Append('XHDR ('+Parm+')'); If UniqPerThread(Thread.SessionData).CurrentGroupPath='' then Begin Thread.Connection.Writeln('412 no news group selected'); Exit; End; Header:=lowercase(Fetch(Parm,CHAR32)); If (Header<>'subject') and (Header<>'from') and (Header<>'date') and (Header<>'lines') and (Header<>'references') and (Header<>'message-id') then Begin Thread.Connection.Writeln('501 usage: xhdr header [range|message-id]'); Exit; End; If Pos('-',Parm)>0 then Begin try StartNo:=StrToInt(Fetch(Parm,'-')); except StartNo:=1; end; try StopNo:=StrToInt(Parm); except StopNo:=StartNo; end; End Else Begin try StartNo:=StrToInt(Parm); except StartNo:=1; end; StopNo:=StartNo; End; Thread.Connection.Writeln('221 '+Header+' follows'); Msg:=TStringList.Create; For Loop:=StartNo to StopNo do Begin If FileExists(UniqPerThread(Thread.SessionData).CurrentGroupPath+ '\'+Pad10(Loop)+'.HDR') then Begin Msg.LoadFromFile(UniqPerThread(Thread.SessionData).CurrentGroupPath+ '\'+Pad10(Loop)+'.HDR'); Thread.Connection.Writeln(IntToStr(Loop)+CHAR32+ Msg.Values[Header]); End; End; Thread.Connection.Writeln('.'); end; procedure TForm1.SpeedButton3Click(Sender: TObject); begin Form2.Show; end; procedure TForm1.WinshoeNNTPListener1CommandArticleID( Thread: TWinshoeServerThread; ActualID: String); begin WinshoeNNTPListener1CommandArticleNo(Thread,UniqPerThread(Thread.SessionData).CurrentMessageNumber+1) end; procedure TForm1.WinshoeNNTPListener1CommandHeadID( Thread: TWinshoeServerThread; ActualID: String); begin WinshoeNNTPListener1CommandHeadNo(Thread,UniqPerThread(Thread.SessionData).CurrentMessageNumber+1) end; /////////////////////////////////////////////////////////////////////////////// // CHECK /////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandCheck( Thread: TWinshoeServerThread; ActualID: String); begin Form2.ListBox1.Items.Append('CHECK ('+ActualID+')'); { The whole point of the Check <messag-id> command is to have the method determine whether the server wants the article from the peer. If the the server desires the article at this time then the server sends the response of 238 followed by the message id. This demo doesn't actually employ what is commonly known as a "History" file... the place where some implementations store the list of message id's of messages currently on the server or messages that are gone but we still don't want again. It should be remembered that the peer will not wait for a response before it sends the next check command. The peer will gather the responses after all the current check commands and then send out a series of Takethis <message-id> commands.} // Here we just accept everything but you should write code which checks your // database of stored message id's and respond accordingly. // if MessageID Not in Database then Thread.Connection.Writeln('238 '+ActualID); // else // Thread.Connection.Writeln('438 '+ActualID); // There are other responses as well { 400 not accepting articles 431 try sending it again later 438 already have it, please don't send it to me 480 Transfer permission denied 500 Command not understood } end; /////////////////////////////////////////////////////////////////////////////// // TAKETHIS /////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandTakeThis( Thread: TWinshoeServerThread; ActualID: String); var Msg : TStringList; Body : TStringList; Newsgroups : String; S : String; Loop : Integer; Path : String; W1,W2,W3,W4 : Word; Ws : String; MesgID : String; Loc : Integer; IniFile : TInifile; CurrentGroupHiMsg : Integer; begin { The difference between IHAVE and TAKETHIS is when the peer issues the TAKETHIS command it will not expect any handshaking. It issues the TAKETHIS command and immediately sends the complete article and it doesn't have to wait for successful or other than successful completion before it issues the next TAKETHIS. You should reply though after you have completed your posting and crossposting. So... this is "Streaming NNTP" shoot first don't ask questions and if the person you shot says something... keep shooting :-) There are restrictions of course those response listed at the bottom of this routine} Form2.ListBox1.Items.Append('TAKETHIS ('+ActualID+')'); { unfortunately you'll have to check your history database again to determine whether you really want the message or not since there is no guarantee that the peer will send the check command first. Even though they should} // insert history database checking code here Msg := TStringList.Create; Thread.Connection.CaptureHeader(Msg,''); {should *NOT* be blank} {fields we add on the fly we have to add "=" to mimic capture!} if Msg.Values['Message-ID']='' then begin DecodeDate(Now,W1,W2,W3); Ws := IntToHex(W1,4)+IntToHex(W2,2)+IntToHex(W3,2); DecodeTime(Now,W1,W2,W3,W4); Ws := Ws+IntToHex(W1,2)+IntToHex(W2,2)+IntToHex(W3,2)+IntToHex(W4,2); Msg.Insert(0,'Message-ID=<'+WS+'@'+ServerID+'>'); end; if Msg.Values['Path']='' then Msg.Insert(0,'Path='+ServerID) else {update it!} Newsgroups := Msg.Values['Newsgroups']; if Newsgroups = '' then Newsgroups := UniqPerThread(Thread.SessionData).CurrentNewsGroup; if NewsGroups = '' then Begin Thread.Connection.Writeln('439 '+ActualID); Msg.Free; Exit; end; Body := TStringList.Create; Thread.Connection.Capture(Body, ['.']); Newsgroups := Lowercase(Newsgroups)+','; S := Fetch(Newsgroups,','); while (S <> '') do begin Path:=''; for Loop:=1 to NumberOfNewsgroups do begin with IniFile do begin Path := ReadString('GROUP'+IntToStr(Loop),'Name',''); if lowercase(Path)= S then begin Path:=ReadString('GROUP'+IntToStr(Loop),'Path',''); Break end; end; end; if Path <> '' then begin CurrentGroupHiMsg := GetHighestMsgNumber(Path); Msg.SaveToFile(Path+'\'+Pad10(CurrentGroupHiMsg+1)+'.HDR'); Body.SaveToFile(Path+'\'+Pad10(CurrentGroupHiMsg+1)+'.BDY'); end; S := Fetch(Newsgroups,','); End; {remember to add the successfully posted message id to your history database} Msg.Free; Body.Free; IniFile.Free; Thread.Connection.Writeln('239 '+ActualID); // Here are other potential responses { 400 not accepting articles 439 article transfer failed 480 Transfer permission denied 500 Command not understood } end; /////////////////////////////////////////////////////////////////////////////// // MODE /////////////////////////////////////////////////////////////////////////////// procedure TForm1.WinshoeNNTPListener1CommandMode( Thread: TWinshoeServerThread; Parm: String); begin Form2.ListBox1.Items.Append('MODE ('+Parm+')'); if Uppercase(parm) = 'READER' then begin Thread.Connection.Writeln('200 Hello, you can post'); end else if Uppercase(parm) = 'STREAM' then Thread.Connection.Writeln('203 Row row row your boat'); end; end.
unit ViewConfig; interface uses XMLDoc, XMLIntf, Classes, SysUtils, Generics.Collections, Rest.Json, IOUtils; type TTabSettings = class private FLocation: string; FSecondBible: string; FStrongNotesCode: UInt64; FTitle: string; FActive: boolean; public property Location: string read FLocation write FLocation; property SecondBible: string read FSecondBible write FSecondBible; property StrongNotesCode: UInt64 read FStrongNotesCode write FStrongNotesCode; property Title: string read FTitle write FTitle; property Active: boolean read FActive write FActive; end; type TModuleViewSettings = class private FTabSettingsList: TList<TTabSettings>; FActive: boolean; FViewName: string; FDocked: boolean; FLeft, FTop: integer; FWidth, FHeight: integer; public property TabSettingsList: TList<TTabSettings> read FTabSettingsList write FTabSettingsList; property Active: boolean read FActive write FActive; property ViewName: string read FViewName write FViewName; property Docked: boolean read FDocked write FDocked; property Left: integer read FLeft write FLeft; property Top: integer read FTop write FTop; property Width: integer read FWidth write FWidth; property Height: integer read FHeight write FHeight; constructor Create(); end; type TViewConfig = class private FModuleViews: TList<TModuleViewSettings>; public property ModuleViews: TList<TModuleViewSettings> read FModuleViews write FModuleViews; constructor Create(); procedure Save(fileName: string); class function Load(fileName: string) : TViewConfig; end; implementation constructor TModuleViewSettings.Create(); begin TabSettingsList := TList<TTabSettings>.Create(); Active := false; end; constructor TViewConfig.Create(); begin ModuleViews := TList<TModuleViewSettings>.Create(); end; class function TViewConfig.Load(fileName: string): TViewConfig; var json: string; begin json := TFile.ReadAllText(fileName); Result := TJson.JsonToObject<TViewConfig>(json); end; procedure TViewConfig.Save(fileName: string); var json: string; begin json := TJson.ObjectToJsonString(self); TFile.WriteAllText(fileName, json); end; end.
{ pascal allows you to persist variables in files. and later restore and use them in your program. } program fileVariables; const MAX = 4; type cashdata = file of real; var cashfile : cashdata; filename : string; procedure writedata(var f: cashdata); var data : real; i : integer; begin rewrite(f, sizeof(data)); for i := 1 to MAX do begin write('Enter cash data: '); readln(data); write(f, data); writeln; end; close(f); end; procedure performSum(var x: cashdata); var d, sum: real; begin reset(x); sum := 0.0; { note 1 } while not eof(x) do begin read(x, d); sum := sum + d; end; close(x); writeln('Total cash: ', sum:7:2); end; begin writeln('Enter wallet (file) name: '); readln(filename); assign(cashfile, filename); writedata(cashfile); performSum(cashfile); end. { note 1: pascal does forces you to use the first digit before the decimal sign. whereas several languages would allow you to just type -> .1234, pascal requires you to add the zero -> 0.1234 at least "FreePascal" the compiler I'm using. }
(*******************************************************) (* *) (* Engine Paulovich DirectX *) (* Win32-DirectX API Unit *) (* *) (* Copyright (c) 2003-2004, Ivan Paulovich *) (* *) (* iskatrek@hotmail.com uin#89160524 *) (* *) (* Unit: gl3DGraphics *) (* *) (*******************************************************) unit gl3DGraphics; interface uses Windows, SysUtils, Classes, glError, glConst, glWindow, D3DX8, {$IFDEF DXG_COMPAT}DirectXGraphics{$ELSE}Direct3D8{$ENDIF}; type (* TReferer *) PGraphicsReferer = ^TGraphicsReferer; TGraphicsReferer = class of TGraphics; (* TVertex *) TVertex = record Pos: TD3DXVector3; Normal: TD3DXVector3; Tu, Tv: Single; end; PVertex = array[0..0] of TVertex; (* TGraphics *) PGraphics = ^TGraphics; TGraphics = class private FHandle: HWND; FClient: TRect; FD3D: IDirect3D8; FDevice: IDirect3DDevice8; FVertexBuffer: IDirect3DVertexBuffer8; FD3DDM: TD3DDisplayMode; FD3DPP: TD3DPresent_Parameters; FBackSurface: IDirect3DSurface8; FBpp: Integer; FWindowed: Boolean; FOnInitialize: TNotifyEvent; FOnFinalize: TNotifyEvent; procedure DestroyAll; protected procedure DoInitialize; virtual; procedure DoFinalize; virtual; public constructor Create; destructor Destroy; procedure Run; procedure Clear; procedure BeginScene; procedure EndScene; procedure Flip; procedure Restore; property OnInitialize: TNotifyEvent read FOnInitialize write FOnInitialize; property OnFinalize: TNotifyEvent read FOnFinalize write FOnFinalize; property Handle: HWND read FHandle write FHandle; property D3D: IDirect3D8 read FD3D write FD3D; property Device: IDirect3DDevice8 read FDevice write FDevice; property VertexBuffer: IDirect3DVertexBuffer8 read FVertexBuffer write FVertexBuffer; property BackBuffer: IDirect3DSurface8 read FBackSurface write FBackSurface; property Parameters: TD3DPresent_Parameters read FD3DPP write FD3DPP; property DisplayMode: TD3DDisplayMode read FD3DDM write FD3DDM; property Width: Integer read FClient.Right write FClient.Right; property Height: Integer read FClient.Bottom write FClient.Bottom; property Bpp: Integer read FBpp write FBpp; property Windowed: Boolean read FWindowed write FWindowed; end; const D3DFVFVERTEX = D3DFVF_XYZ or D3DFVF_NORMAL or D3DFVF_TEX1; function Vertex(Pos: TD3DXVector3; Normal: TD3DXVector3; Tu, Tv: Single): TVertex; var Graphics: TGraphics; implementation uses glCanvas; function Vertex(Pos: TD3DXVector3; Normal: TD3DXVector3; Tu, Tv: Single): TVertex; begin Result.Pos := Pos; Result.Normal := Normal; Result.tu := tu; Result.tv := tv; end; (* TGraphics *) constructor TGraphics.Create; begin SaveLog(Format(EVENT_TALK, ['TGraphics.Create'])); if Assigned(Graphics) then raise ELogError.Create(Format(ERROR_EXISTS, ['TGraphics'])) else SaveLog(Format(EVENT_CREATE, ['TGraphics'])); Graphics := Self; FHandle := 0; FD3D := nil; FDevice := nil; FBackSurface := nil; SetRect(FClient, 0, 0, Window.Width, Window.Height); FBpp := 32; FWindowed := True; end; procedure TGraphics.DestroyAll; begin if Assigned(FBackSurface) then begin FBackSurface._Release; FBackSurface := nil; end; if Assigned(FDevice) then begin FDevice._Release; FDevice := nil; end; if Assigned(FD3D) then begin FD3D._Release; FD3D := nil; end; end; destructor TGraphics.Destroy; begin DoFinalize; DestroyAll; end; procedure TGraphics.Flip; begin FDevice.Present(nil, nil, 0, nil); end; procedure TGraphics.Restore; var MatProj, MatView: TD3DXMatrix; begin SetRect(FClient, 0, 0, Window.Width, Window.Height); D3DXMatrixIdentity(MatView); FDevice.SetTransform(D3DTS_VIEW, MatView); D3DXMatrixOrthoLH(MatProj, Width, Height, 0, 1); end; procedure TGraphics.Run; var Hr: HResult; MatProj, MatView: TD3DXMatrix; pVertices: ^PVertex; K: Integer; begin SaveLog(Format(EVENT_TALK, ['TWindow.Create'])); FD3D := Direct3DCreate8(D3D_SDK_VERSION); if FD3D = nil then raise EError.Create(Format(ERROR_EXISTS, ['Direct3D8'])) else SaveLog(Format(EVENT_CREATE, ['Direct3D8'])); Fillchar(FD3DPP, SizeOf(FD3DPP), 0); FD3DPP.Windowed := Windowed; FD3DPP.hDeviceWindow := FHandle; FD3DPP.EnableAutoDepthStencil := False; FD3DPP.BackBufferCount := 1; FD3DPP.Flags := D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; if not Windowed then begin FD3DPP.BackBufferWidth := Width; FD3DPP.BackBufferHeight := Height; case Bpp of 8: FD3DPP.BackBufferFormat := D3DFMT_R3G3B2; 15: FD3DPP.BackBufferFormat := D3DFMT_X1R5G5B5; 16: FD3DPP.BackBufferFormat := D3DFMT_R5G6B5; 24: FD3DPP.BackBufferFormat := D3DFMT_X8R8G8B8; 32: FD3DPP.BackBufferFormat := D3DFMT_A8R8G8B8; else FD3DPP.BackBufferFormat := D3DFMT_A8R8G8B8; end; FD3DPP.SwapEffect := D3DSWAPEFFECT_COPY; FD3DPP.MultiSampleType := D3DMULTISAMPLE_NONE; FD3DPP.EnableAutoDepthStencil := False; FD3DPP.AutoDepthStencilFormat := D3DFMT_D16; FD3DPP.FullScreen_RefreshRateInHz := D3DPRESENT_RATE_DEFAULT; FD3DPP.FullScreen_PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE; end else begin if Failed(FD3D.GetAdapterDisplayMode(D3DADAPTER_DEFAULT, FD3DDM)) then raise EError.Create(Format(ERROR_SITE, ['TGraphics.Initialize'])) else SaveLog(EVENT_DISPLAYMODE); FD3DPP.BackBufferFormat := FD3DDM.Format; FD3DPP.SwapEffect := D3DSWAPEFFECT_DISCARD; end; Hr := FD3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, FHandle, D3DCREATE_HARDWARE_VERTEXPROCESSING, FD3DPP, FDevice); if Failed(hr) then begin Hr := FD3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, FHandle, D3DCREATE_MIXED_VERTEXPROCESSING, FD3DPP, FDevice); if Failed(Hr) then begin Hr := FD3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, FHandle, D3DCREATE_SOFTWARE_VERTEXPROCESSING, FD3DPP, FDevice); if FAILED(Hr) then Hr := FD3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, FHandle, D3DCREATE_SOFTWARE_VERTEXPROCESSING, FD3DPP, FDevice); end; end; SetRect(FClient, 0, 0, Width, Height); D3DXMatrixIdentity(MatView); FDevice.SetTransform(D3DTS_VIEW, MatView); D3DXMatrixOrthoLH(MatProj, Width, Height, 0, 1); FDevice.SetTransform(D3DTS_PROJECTION, MatProj); FDevice.SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); FDevice.SetRenderState(D3DRS_LIGHTING, iFalse); FDevice.SetRenderState(D3DRS_ZENABLE, iFalse); FDevice.SetRenderState(D3DRS_ZWRITEENABLE, iFalse); if Failed(FDevice.CreateVertexBuffer(4 * Sizeof(TVertex), 0, D3DFVFVERTEX, D3DPOOL_DEFAULT, FVertexBuffer)) then Exit; if FAILED(FVertexBuffer.Lock(0, 0, PByte(pVertices), 0)) then Exit; K := 1; pVertices[0 * K] := Vertex(D3DXVECTOR3(0.0, 0.0, 0.0), D3DXVECTOR3(0.0, 0.0, 1.0), 0.0, 1.0); pVertices[1 * K] := Vertex(D3DXVECTOR3(0.0, 1.0, 0.0), D3DXVECTOR3(0.0, 0.0, 1.0), 0.0, 0.0); pVertices[2 * K] := Vertex(D3DXVECTOR3(1.0, 0.0, 0.0), D3DXVECTOR3(0.0, 0.0, 1.0), 1.0, 1.0); pVertices[3 * K] := Vertex(D3DXVECTOR3(1.0, 1.0, 0.0), D3DXVECTOR3(0.0, 0.0, 1.0), 1.0, 0.0); FVertexBuffer.Unlock; FDevice.GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, FBackSurface); Canvas := TCanvas.Create(Self); DoInitialize; end; procedure TGraphics.Clear; begin FDevice.Clear(0, nil, D3DCLEAR_TARGET, Canvas.Brush.Color, 1.0, 0); end; procedure TGraphics.BeginScene; begin FDevice.BeginScene; end; procedure TGraphics.EndScene; begin FDevice.EndScene; end; procedure TGraphics.DoInitialize; begin if Assigned(FOnInitialize) then FOnInitialize(Self); end; procedure TGraphics.DoFinalize; begin if Assigned(FOnFinalize) then FOnFinalize(Self); 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvInterpreter_Contnrs.PAS, released on 2002-07-04. The Initial Developers of the Original Code are: Andrei Prygounkov <a dott prygounkov att gmx dott de> Copyright (c) 1999, 2002 Andrei Prygounkov All Rights Reserved. Contributor(s): You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Description : adapter unit - converts JvInterpreter calls to delphi calls Known Issues: -----------------------------------------------------------------------------} // $Id: JvInterpreter_Contnrs.pas 12461 2009-08-14 17:21:33Z obones $ unit JvInterpreter_Contnrs; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} JvInterpreter; procedure RegisterJvInterpreterAdapter(JvInterpreterAdapter: TJvInterpreterAdapter); {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvInterpreter_Contnrs.pas $'; Revision: '$Revision: 12461 $'; Date: '$Date: 2009-08-14 19:21:33 +0200 (ven. 14 août 2009) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses Classes, Contnrs; { TObjectList } { constructor Create } procedure TObjectList_Create(var Value: Variant; Args: TJvInterpreterArgs); begin Value := O2V(TObjectList.Create); end; { constructor Create(AOwnsObjects: Boolean) } procedure TObjectList_CreateOwns(var Value: Variant; Args: TJvInterpreterArgs); begin Value := O2V(TObjectList.Create(Args.Values[0])); end; { function Add(AObject: TObject): Integer; } procedure TObjectList_Add(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TObjectList(Args.Obj).Add(V2O(Args.Values[0])); end; { function Remove(AObject: TObject): Integer; } procedure TObjectList_Remove(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TObjectList(Args.Obj).Remove(V2O(Args.Values[0])); end; { function IndexOf(AObject: TObject): Integer; } procedure TObjectList_IndexOf(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TObjectList(Args.Obj).IndexOf(V2O(Args.Values[0])); end; { function FindInstanceOf(AClass: TClass; AExact: Boolean = True; AStartAt: Integer = 0): Integer; } procedure TObjectList_FindInstanceOf(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TObjectList(Args.Obj).FindInstanceOf(V2C(Args.Values[0]), Args.Values[1], Args.Values[2]); end; { procedure Insert(Index: Integer; AObject: TObject); } procedure TObjectList_Insert(var Value: Variant; Args: TJvInterpreterArgs); begin TObjectList(Args.Obj).Insert(Args.Values[0], V2O(Args.Values[1])); end; { property Read OwnsObjects: Boolean } procedure TObjectList_Read_OwnsObjects(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TObjectList(Args.Obj).OwnsObjects; end; { property Write OwnsObjects(Value: Boolean) } procedure TObjectList_Write_OwnsObjects(const Value: Variant; Args: TJvInterpreterArgs); begin TObjectList(Args.Obj).OwnsObjects := Value; end; { property Read Items[Integer]: TObject } procedure TObjectList_Read_Items(var Value: Variant; Args: TJvInterpreterArgs); begin Value := O2V(TObjectList(Args.Obj).Items[Args.Values[0]]); end; { property Write Items[Integer]: TObject } procedure TObjectList_Write_Items(const Value: Variant; Args: TJvInterpreterArgs); begin TObjectList(Args.Obj).Items[Args.Values[0]] := V2O(Value); end; { TComponentList } { function Add(AComponent: TComponent): Integer; } procedure TComponentList_Add(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TComponentList(Args.Obj).Add(V2O(Args.Values[0]) as TComponent); end; { function Remove(AComponent: TComponent): Integer; } procedure TComponentList_Remove(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TComponentList(Args.Obj).Remove(V2O(Args.Values[0]) as TComponent); end; { function IndexOf(AComponent: TComponent): Integer; } procedure TComponentList_IndexOf(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TComponentList(Args.Obj).IndexOf(V2O(Args.Values[0]) as TComponent); end; { procedure Insert(Index: Integer; AComponent: TComponent); } procedure TComponentList_Insert(var Value: Variant; Args: TJvInterpreterArgs); begin TComponentList(Args.Obj).Insert(Args.Values[0], V2O(Args.Values[1]) as TComponent); end; { property Read Items[Integer]: TComponent } procedure TComponentList_Read_Items(var Value: Variant; Args: TJvInterpreterArgs); begin Value := O2V(TComponentList(Args.Obj).Items[Args.Values[0]]); end; { property Write Items[Integer]: TComponent } procedure TComponentList_Write_Items(const Value: Variant; Args: TJvInterpreterArgs); begin TComponentList(Args.Obj).Items[Args.Values[0]] := V2O(Value) as TComponent; end; { TClassList } { function Add(aClass: TClass): Integer; } procedure TClassList_Add(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TClassList(Args.Obj).Add(V2C(Args.Values[0])); end; { function Remove(aClass: TClass): Integer; } procedure TClassList_Remove(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TClassList(Args.Obj).Remove(V2C(Args.Values[0])); end; { function IndexOf(aClass: TClass): Integer; } procedure TClassList_IndexOf(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TClassList(Args.Obj).IndexOf(V2C(Args.Values[0])); end; { procedure Insert(Index: Integer; aClass: TClass); } procedure TClassList_Insert(var Value: Variant; Args: TJvInterpreterArgs); begin TClassList(Args.Obj).Insert(Args.Values[0], V2C(Args.Values[1])); end; { property Read Items[Integer]: TClass } procedure TClassList_Read_Items(var Value: Variant; Args: TJvInterpreterArgs); begin Value := C2V(TClassList(Args.Obj).Items[Args.Values[0]]); end; { property Write Items[Integer]: TClass } procedure TClassList_Write_Items(const Value: Variant; Args: TJvInterpreterArgs); begin TClassList(Args.Obj).Items[Args.Values[0]] := V2C(Value); end; { TOrderedList } { function Count: Integer; } procedure TOrderedList_Count(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TOrderedList(Args.Obj).Count; end; { function AtLeast(ACount: Integer): Boolean; } procedure TOrderedList_AtLeast(var Value: Variant; Args: TJvInterpreterArgs); begin Value := TOrderedList(Args.Obj).AtLeast(Args.Values[0]); end; { procedure Push(AItem: Pointer); } procedure TOrderedList_Push(var Value: Variant; Args: TJvInterpreterArgs); begin TOrderedList(Args.Obj).Push(V2P(Args.Values[0])); end; { function Pop: Pointer; } procedure TOrderedList_Pop(var Value: Variant; Args: TJvInterpreterArgs); begin Value := P2V(TOrderedList(Args.Obj).Pop); end; { function Peek: Pointer; } procedure TOrderedList_Peek(var Value: Variant; Args: TJvInterpreterArgs); begin Value := P2V(TOrderedList(Args.Obj).Peek); end; { TStack } { TObjectStack } { procedure Push(AObject: TObject); } procedure TObjectStack_Push(var Value: Variant; Args: TJvInterpreterArgs); begin TObjectStack(Args.Obj).Push(V2O(Args.Values[0])); end; { function Pop: TObject; } procedure TObjectStack_Pop(var Value: Variant; Args: TJvInterpreterArgs); begin Value := O2V(TObjectStack(Args.Obj).Pop); end; { function Peek: TObject; } procedure TObjectStack_Peek(var Value: Variant; Args: TJvInterpreterArgs); begin Value := O2V(TObjectStack(Args.Obj).Peek); end; { TQueue } { TObjectQueue } { procedure Push(AObject: TObject); } procedure TObjectQueue_Push(var Value: Variant; Args: TJvInterpreterArgs); begin TObjectQueue(Args.Obj).Push(V2O(Args.Values[0])); end; { function Pop: TObject; } procedure TObjectQueue_Pop(var Value: Variant; Args: TJvInterpreterArgs); begin Value := O2V(TObjectQueue(Args.Obj).Pop); end; { function Peek: TObject; } procedure TObjectQueue_Peek(var Value: Variant; Args: TJvInterpreterArgs); begin Value := O2V(TObjectQueue(Args.Obj).Peek); end; procedure RegisterJvInterpreterAdapter(JvInterpreterAdapter: TJvInterpreterAdapter); const cContnrs = 'Contnrs'; begin with JvInterpreterAdapter do begin { TObjectList } AddClass(cContnrs, TObjectList, 'TObjectList'); AddGet(TObjectList, 'Create', TObjectList_Create, 0, [varEmpty], varEmpty); AddGet(TObjectList, 'CreateOwns', TObjectList_CreateOwns, 1, [varBoolean], varEmpty); AddGet(TObjectList, 'Add', TObjectList_Add, 1, [varObject], varEmpty); AddGet(TObjectList, 'Remove', TObjectList_Remove, 1, [varObject], varEmpty); AddGet(TObjectList, 'IndexOf', TObjectList_IndexOf, 1, [varObject], varEmpty); AddGet(TObjectList, 'FindInstanceOf', TObjectList_FindInstanceOf, 3, [varEmpty, varBoolean, varInteger], varEmpty); AddGet(TObjectList, 'Insert', TObjectList_Insert, 2, [varInteger, varObject], varEmpty); AddGet(TObjectList, 'OwnsObjects', TObjectList_Read_OwnsObjects, 0, [varEmpty], varEmpty); AddSet(TObjectList, 'OwnsObjects', TObjectList_Write_OwnsObjects, 0, [varEmpty]); AddGet(TObjectList, 'Items', TObjectList_Read_Items, 1, [varEmpty], varEmpty); AddSet(TObjectList, 'Items', TObjectList_Write_Items, 1, [varNull]); { TComponentList } AddClass(cContnrs, TComponentList, 'TComponentList'); AddGet(TComponentList, 'Add', TComponentList_Add, 1, [varObject], varEmpty); AddGet(TComponentList, 'Remove', TComponentList_Remove, 1, [varObject], varEmpty); AddGet(TComponentList, 'IndexOf', TComponentList_IndexOf, 1, [varObject], varEmpty); AddGet(TComponentList, 'Insert', TComponentList_Insert, 2, [varInteger, varObject], varEmpty); AddGet(TComponentList, 'Items', TComponentList_Read_Items, 1, [varEmpty], varEmpty); AddSet(TComponentList, 'Items', TComponentList_Write_Items, 1, [varNull]); { TClassList } AddClass(cContnrs, TClassList, 'TClassList'); AddGet(TClassList, 'Add', TClassList_Add, 1, [varEmpty], varEmpty); AddGet(TClassList, 'Remove', TClassList_Remove, 1, [varEmpty], varEmpty); AddGet(TClassList, 'IndexOf', TClassList_IndexOf, 1, [varEmpty], varEmpty); AddGet(TClassList, 'Insert', TClassList_Insert, 2, [varInteger, varEmpty], varEmpty); AddGet(TClassList, 'Items', TClassList_Read_Items, 1, [varEmpty], varEmpty); AddSet(TClassList, 'Items', TClassList_Write_Items, 1, [varNull]); { TOrderedList } AddClass(cContnrs, TOrderedList, 'TOrderedList'); AddGet(TOrderedList, 'Count', TOrderedList_Count, 0, [varEmpty], varEmpty); AddGet(TOrderedList, 'AtLeast', TOrderedList_AtLeast, 1, [varInteger], varEmpty); AddGet(TOrderedList, 'Push', TOrderedList_Push, 1, [varPointer], varEmpty); AddGet(TOrderedList, 'Pop', TOrderedList_Pop, 0, [varEmpty], varEmpty); AddGet(TOrderedList, 'Peek', TOrderedList_Peek, 0, [varEmpty], varEmpty); { TStack } AddClass(cContnrs, TStack, 'TStack'); { TObjectStack } AddClass(cContnrs, TObjectStack, 'TObjectStack'); AddGet(TObjectStack, 'Push', TObjectStack_Push, 1, [varObject], varEmpty); AddGet(TObjectStack, 'Pop', TObjectStack_Pop, 0, [varEmpty], varEmpty); AddGet(TObjectStack, 'Peek', TObjectStack_Peek, 0, [varEmpty], varEmpty); { TQueue } AddClass(cContnrs, TQueue, 'TQueue'); { TObjectQueue } AddClass(cContnrs, TObjectQueue, 'TObjectQueue'); AddGet(TObjectQueue, 'Push', TObjectQueue_Push, 1, [varObject], varEmpty); AddGet(TObjectQueue, 'Pop', TObjectQueue_Pop, 0, [varEmpty], varEmpty); AddGet(TObjectQueue, 'Peek', TObjectQueue_Peek, 0, [varEmpty], varEmpty); end; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit FHIRLang; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface function GetFhirMessage(id, lang : String):String; overload; function GetFhirMessage(id, lang, def : String):String; overload; procedure LoadMessages; var FHIRExeModuleName : String; implementation {$R FHIRTranslations.res} uses SysUtils, classes, Generics.Collections, StringSupport, TextUtilities, AdvObjects, AdvGenerics, AdvExceptions, {$IFDEF MSWINDOWS}AfsResourceVolumes, AfsVolumes,{$ENDIF} MXML; Type TFHIRMessage = class (TAdvObject) private FMessages : TDictionary<String,String>; public constructor Create; override; Destructor Destroy; override; end; var GMessages : TAdvMap<TFHIRMessage>; Function LoadSource : TBytes; {$IFDEF MACOS} begin result := TextUtilities.FileToBytes(IncludeTrailingPathDelimiter(ExtractFilePath(paramstr(0)))+'translations.xml'); end; {$ELSE} var LRes : TAfsResourceVolume; LHnd : TAfsHandle; begin LRes := TAfsResourceVolume.create; try LHnd := LRes.Open(FHIRExeModuleName, 'FHIR_Translations,#10', amRead, asRead); try SetLength(result, LRes.GetSize(LHnd)); LRes.Read(LHnd, result[0], length(result)); finally LRes.Close(LHnd); end; finally LRes.Free; end; end; {$ENDIF} procedure LoadMessages; var source : TMXmlDocument; child, lang : TMXmlElement; msg : TFHIRMessage; begin if FHIRExeModuleName = '##' then exit; source := TMXmlParser.parse(LoadSource, [xpDropWhitespace, xpDropComments]); try GMessages := TAdvMap<TFHIRMessage>.create; child := source.document.firstElement; while child <> nil do begin msg := TFHIRMessage.Create; GMessages.Add(child.attribute['id'], msg); lang := child.firstElement; while lang <> nil do begin msg.FMessages.add(lang.attribute['lang'], lang.text); lang := lang.nextElement; end; child := child.nextElement; end; finally source.free; end; end; function GetFhirMessage(id, lang : String):String; var msg : TFHIRMessage; l : string; begin result := ''; if GMessages = nil then LoadMessages; if GMessages = nil then exit(id); if not GMessages.ContainsKey(id) then result := 'Unknown message '+id else begin msg := GMessages[id]; while (result = '') and (lang <> '') do begin StringSplit(lang, [';', ','], l, lang); if msg.FMessages.ContainsKey(l) then result := msg.FMessages[l]; end; if result = '' then result := msg.FMessages['en']; if result = '' then result := '??'; end; end; function GetFhirMessage(id, lang, def : String):String; var msg : TFHIRMessage; l : string; begin result := ''; if GMessages = nil then LoadMessages; if not GMessages.ContainsKey(id) then result := def else begin msg := GMessages[id]; while (result = '') and (lang <> '') do begin StringSplit(lang, [';', ','], l, lang); if msg.FMessages.ContainsKey(l) then result := msg.FMessages[l]; end; if result = '' then result := msg.FMessages['en']; if result = '' then result := '??'; if result = '' then result := def; end; end; { TFHIRMessage } constructor TFHIRMessage.Create; begin inherited; FMessages := TDictionary<String,String>.create; end; destructor TFHIRMessage.Destroy; begin FMessages.Free; inherited; end; initialization GMessages := nil; finalization GMessages.Free; end.
unit roFiles; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, IniFiles; type TECsiFileTimeType = (ftCreation, ftLastWrite, ftLastAccess); function CsiClearDir(const pDirName: string; pBypassChecks: Boolean = False): Boolean; function CsiConcatFile(const pSrcFileName: string; const pDestFileName: string): Boolean; function CsiCopyDir(const pExistingDirName: string; const pNewDirName: string; pForceCopy: Boolean = False; pBypassChecks: Boolean = False): Boolean; function CsiCopyFile(const pExistingFileName: string; const pNewFileName: string; pForceCopy: Boolean = False; pBypassChecks: Boolean = False): Boolean; function CsiCreateDir(const pDirName: string): Boolean; function CsiCreateFile(const pFileName: string; pForceCreate: Boolean = False; pBypassChecks: Boolean = False): Boolean; function CsiDeleteDir(const pDirName: string; pBypassChecks: Boolean = False): Boolean; function CsiDeleteFile(const pFileName: string; pBypassChecks: Boolean = False): Boolean; function CsiExpandDirName(const pDirName: string): string; function CsiExpandFileName(const pFileName: string): string; function CsiExtractFileDir(const pFileName: string; pIncludePathDelimiter: Boolean = True): string; function CsiExtractFileDrive(const pFileName: string; pIncludePathDelimiter: Boolean = True): string; function CsiFileByteCount(const pFileName: string): Int64; {function CsiFileLineCount(const pFileName: string): Integer; function CsiGetFileTime(const pFileName: string; pTimeType: TECsiFileTimeType): TDateTime; function CsiGetWriteableFileName(const pBaseFileName: string; pCanExist: Boolean = True): string; function CsiIsFileReadable(const pFileName: string): Boolean; } function CsiIsFileWriteable(const pFileName: string): Boolean; function CsiMoveDir(const pExistingDirName: string; const pNewDirName: string; pForceMove: Boolean = False; pBypassChecks: Boolean = False): Boolean; function CsiMoveFile(const pExistingFileName: string; const pNewFileName: string; pForceMove: Boolean = False; pBypassChecks: Boolean = False): Boolean; procedure GetDirs(const Path : string; Items : TStrings); procedure GetFiles(const DirPath, FileExt: string; FileList: TStringList); function NormalDir(const DirName: string): string; function DirExists(const DirName: string): Boolean; function CreateDir(const DirName: string): Boolean; function RemoveDir(const DirName: string): Boolean; function SetCurrentDir(const DirName: string): Boolean; function GetCurrentDir: string; function ClearDir(const Path: string; Delete: Boolean): Boolean; function CopyFile(const ExistingFileName, NewFileName: string; bFailIfExists: Boolean): Boolean; function DeleteFile(const FileName: string): Boolean; function FileGetAttr(const FileName: string): Cardinal; function FileSetAttr(const FileName: string; Attr: Cardinal): Integer; function GetIconForFile(const FullFileName: string; Flag : integer): TIcon; function ValidFileName(const FileName: string): Boolean; function ShortToLongFileName(const ShortName: string): string; function LongToShortFileName(const LongName: string): string; function ShortToLongPath(ShortName: string): string; function LongToShortPath(LongName: string): string; procedure CopyFiles(SrcMask, SrcDir: string; DstDir: string); function RemoveEmptyFolders(const rootFolder: string): boolean; function WriteTextToFile(const filename, text: string; Append: Boolean): Boolean; {procedure CsiSetFileTime(const pFileName: string; pTimeType: TECsiFileTimeType; pFileTime: TDateTime); procedure CsiLoadFromFile(const pFileName: string; out pData: TByteDynArray); overload; procedure CsiLoadFromFile(const pFileName: string; pIdValuePairs: TCsiIdValuePairs; pWithKeyChars: Boolean = False; pStringEncoding: TECsiStringEncoding = seAuto); overload; procedure CsiLoadFromFile(const pFileName: string; pStrings: TStrings; pStringEncoding: TECsiStringEncoding = seAuto); overload; procedure CsiLoadFromFile(const pFileName: string; out pText: string; pStringEncoding: TECsiStringEncoding = seAuto); overload;} implementation uses ShellAPI, roShell, roStrings; function CanAppendFile(const pFileName: string): Boolean; forward; function IsProtectedDir(const pDirName: string): Boolean; forward; const // file extension EXT_TEXT = '.txt'; function CanAppendFile(const pFileName: string): Boolean; begin if FileExists(pFileName) then // check whether we can open the file for writing Result := CsiIsFileWriteable(pFileName) else // assume we can append to a file that does not already exist Result := True; end; function IsProtectedDir(const pDirName: string): Boolean; var lDirName: string; lRootDir: string; lWindowsDir: string; lSystemDir: string; begin // get the root, windows, and system directories lDirName := CsiExpandDirName(pDirName); lRootDir := CsiExtractFileDrive(lDirName, False); lWindowsDir := GetWindowsDir; lSystemDir := GetSystemDir; // check if the directory is the root directory or derived from the windows or // system directories if SameText(lDirName, lRootDir) or SameText(lDirName, lWindowsDir) or StartsStr(IncludeTrailingPathDelimiter(lWindowsDir), lDirName, False) or SameText(lDirName, lSystemDir) or StartsStr(IncludeTrailingPathDelimiter(lSystemDir), lDirName, False) then Result := True else Result := False; end; //------------------------------------------------------------------------------ // CsiClearDir // // Deletes all files in the directory given by pDirName. The return value is // true if the files were successfully deleted or false if an error occurred. // Use pBypassChecks to bypass all file deletion checks //------------------------------------------------------------------------------ function CsiClearDir(const pDirName: string; pBypassChecks: Boolean): Boolean; var lDirName: string; lSearchRec: TSearchRec; begin // it is painful to deal with the double sloshes unless we do it up front lDirName := CsiExpandDirName(pDirName); if StartsStr('\\', lDirName) then begin Result := False; Exit; end; // let us not clear a directory we will regret! if IsProtectedDir(lDirName) then begin Result := False; Exit; end; Result := True; lDirName := IncludeTrailingPathDelimiter(lDirName); if FindFirst(lDirName + '*', faAnyFile, lSearchRec) = 0 then try repeat with lSearchRec do if (Name <> '.') and (Name <> '..') then if (Attr and faDirectory) = 0 then // delete the files in the directory Result := CsiDeleteFile(lDirName + Name, pBypassChecks) and Result; until FindNext(lSearchRec) <> 0; finally SysUtils.FindClose(lSearchRec); end; end; //------------------------------------------------------------------------------ // CsiConcatFile // // Concatenates the file given by pSrcFileName to the file given by // pDestFileName. The return value is true if the file was successfully // concatenated or false if an error occurred //------------------------------------------------------------------------------ function CsiConcatFile(const pSrcFileName: string; const pDestFileName: string): Boolean; var lSrcFileName: string; lDestFileName: string; lSrcStream: TFileStream; lAttr: Integer; lResetAttr: Boolean; lDestStream: TFileStream; begin lSrcFileName := CsiExpandFileName(pSrcFileName); lDestFileName := CsiExpandFileName(pDestFileName); if not SameText(lDestFileName, lSrcFileName) and FileExists(lSrcFileName) and FileExists(lDestFileName) then begin lSrcStream := nil; lAttr := 0; lResetAttr := False; lDestStream := nil; try try lSrcStream := TFileStream.Create(lSrcFileName, fmOpenRead or fmShareDenyWrite); // remove any attributes that might prevent concatenation lAttr := FileGetAttr(lDestFileName); FileSetAttr(lDestFileName, 0); lResetAttr := True; lDestStream := TFileStream.Create(lDestFileName, fmOpenReadWrite or fmShareDenyWrite); lDestStream.Seek(0, soEnd); lDestStream.CopyFrom(lSrcStream, 0); Result := True; finally lDestStream.Free; lSrcStream.Free; // restore the file's attributes to what they were before if lResetAttr then FileSetAttr(lDestFileName, lAttr); end; except on EFileStreamError do // convert exceptions to a result of false Result := False; end; end else // cannot concatenate the files if they are not different and either does // not exist Result := False; end; //------------------------------------------------------------------------------ // CsiCopyDir // // Copies the directory given by pExistingDirName to the directory given by // pNewDirName. The return value is true if the directory was successfully // copied or false if an error occurred. Use pForceCopy to overwrite the files // if they already exist. Use pBypassChecks to bypass all file copying checks //------------------------------------------------------------------------------ function CsiCopyDir(const pExistingDirName: string; const pNewDirName: string; pForceCopy: Boolean; pBypassChecks: Boolean): Boolean; var lExistingDirName: string; lNewDirName: string; lSearchRec: TSearchRec; begin // it is painful to deal with the double sloshes unless we do it up front lExistingDirName := CsiExpandDirName(pExistingDirName); lNewDirName := CsiExpandDirName(pNewDirName); if StartsStr('\\', lExistingDirName) or StartsStr('\\', lNewDirName) then begin Result := False; Exit; end; if not SameText(lNewDirName, lExistingDirName) then if not StartsStr(IncludeTrailingPathDelimiter(lNewDirName), lExistingDirName, False) and not StartsStr(IncludeTrailingPathDelimiter(lExistingDirName), lNewDirName, False) and DirectoryExists(lExistingDirName) and CsiCreateDir(lNewDirName) then begin Result := True; lExistingDirName := IncludeTrailingPathDelimiter(lExistingDirName); lNewDirName := IncludeTrailingPathDelimiter(lNewDirName); if FindFirst(lExistingDirName + '*', faAnyFile, lSearchRec) = 0 then try repeat with lSearchRec do if (Name <> '.') and (Name <> '..') then if (Attr and faDirectory) <> 0 then // recursively copy the sub-directories first Result := CsiCopyDir(lExistingDirName + Name, lNewDirName + Name, pForceCopy, pBypassChecks) and Result else // copy the files in the directory Result := CsiCopyFile(lExistingDirName + Name, lNewDirName + Name, pForceCopy, pBypassChecks) and Result; until FindNext(lSearchRec) <> 0; finally SysUtils.FindClose(lSearchRec); end end else // cannot copy the directory if it does not exist, or we cannot create the // destination directory, or the destination and source directories // overlap Result := False else // cannot copy the directory if it does not exist Result := DirectoryExists(lExistingDirName); end; //------------------------------------------------------------------------------ // CsiCopyFile // // Copies the file given by pExistingFileName to the name given by pNewFileName. // The return value is true if the file was successfully copied or false if an // error occurred. Use pForceCopy to overwrite the file if it already exists. // Use pBypassChecks to bypass all file copying checks //------------------------------------------------------------------------------ function CsiCopyFile(const pExistingFileName: string; const pNewFileName: string; pForceCopy: Boolean; pBypassChecks: Boolean): Boolean; var lExistingFileName: string; lNewFileName: string; begin lExistingFileName := CsiExpandFileName(pExistingFileName); lNewFileName := CsiExpandFileName(pNewFileName); if not pBypassChecks and pForceCopy and not SameText(lNewFileName, lExistingFileName) then // ensure that the destination file does not exist Result := CsiDeleteFile(lNewFileName, pBypassChecks) else Result := True; if Result then if not SameText(lNewFileName, lExistingFileName) then if FileExists(lExistingFileName) and not FileExists(lNewFileName) and not DirectoryExists(lNewFileName) then begin if not pBypassChecks then Result := CsiCreateDir(CsiExtractFileDir(lNewFileName, False)); Result := Result and CopyFile(PChar(lExistingFileName), PChar(lNewFileName), True); end else // cannot copy the file if it does not exist or the destination file // already exists Result := False else if not FileExists(lExistingFileName) then // cannot copy the file if it does not exist Result := False; end; //------------------------------------------------------------------------------ // CsiCreateDir // // Creates the directory given by pDirName. The return value is true if the // directory was successfully created or false if an error occurred //------------------------------------------------------------------------------ function CsiCreateDir(const pDirName: string): Boolean; var lDirName: string; lCurrentDir: string; lBaseDir: string; lDrive: string; begin // it is painful to deal with the double sloshes unless we do it up front lDirName := CsiExpandDirName(pDirName); if StartsStr('\\', lDirName) then begin Result := False; Exit; end; // optimised directory checking prior to additional processing if DirectoryExists(lDirName) then begin Result := True; Exit; end; lCurrentDir := lDirName; lBaseDir := CsiExtractFileDir(lCurrentDir, False); lDrive := CsiExtractFileDrive(lBaseDir, False); if lBaseDir <> lDrive then // recursively create the base directories first Result := CsiCreateDir(lBaseDir) else Result := True; if Result then begin lCurrentDir := ExcludeTrailingPathDelimiter(lCurrentDir); if not (DirectoryExists(lCurrentDir) or FileExists(lCurrentDir)) then begin // create the actual directory Result := (lCurrentDir <> '') and CreateDir(lCurrentDir); end else if FileExists(lCurrentDir) then // cannot create the directory if it is a file Result := False; end; end; //------------------------------------------------------------------------------ // CsiCreateFile // // Creates the file given by pFileName. The return value is true if the file was // successfully created or false if an error occurred. Use pForceCreate to // overwrite the file if it already exists. Use pBypassChecks to bypass all file // creation checks //------------------------------------------------------------------------------ function CsiCreateFile(const pFileName: string; pForceCreate: Boolean; pBypassChecks: Boolean): Boolean; var lFileName: string; lFileHandle: Integer; begin lFileName := CsiExpandFileName(pFileName); if not pBypassChecks and pForceCreate then // ensure that the file does not exist Result := CsiDeleteFile(lFileName, pBypassChecks) else Result := True; if Result then if not (FileExists(lFileName) or DirectoryExists(lFileName)) then begin if not pBypassChecks then Result := CsiCreateDir(CsiExtractFileDir(lFileName, False)); if Result then begin lFileHandle := FileCreate(lFileName); if lFileHandle > 0 then begin FileClose(lFileHandle); Result := True; end else // failed if the handle returned is not valid Result := False; end; end else // cannot create the file if it already exists Result := False; end; //------------------------------------------------------------------------------ // CsiDeleteDir // // Deletes the directory given by pDirName. The return value is true if the // directory was successfully deleted or false if an error occurred. Use // pBypassChecks to bypass all file deletion checks //------------------------------------------------------------------------------ function CsiDeleteDir(const pDirName: string; pBypassChecks: Boolean): Boolean; var lDirName: string; lSearchRec: TSearchRec; begin // it is painful to deal with the double sloshes unless we do it up front lDirName := CsiExpandDirName(pDirName); if StartsStr('\\', lDirName) then begin Result := False; Exit; end; // let us not delete a directory we will regret! if IsProtectedDir(lDirName) then begin Result := False; Exit; end; Result := True; lDirName := IncludeTrailingPathDelimiter(lDirName); if FindFirst(lDirName + '*', faAnyFile, lSearchRec) = 0 then try repeat with lSearchRec do if (Name <> '.') and (Name <> '..') then if (Attr and faDirectory) <> 0 then // recursively delete the sub-directories first Result := CsiDeleteDir(lDirName + Name, pBypassChecks) and Result else // delete the files in the directory Result := CsiDeleteFile(lDirName + Name, pBypassChecks) and Result; until FindNext(lSearchRec) <> 0; finally SysUtils.FindClose(lSearchRec); end; if Result then if DirectoryExists(lDirName) then // delete the actual directory Result := RemoveDir(lDirName) else if FileExists(ExcludeTrailingPathDelimiter(lDirName)) then // cannot delete the directory if it is a file Result := False; end; //------------------------------------------------------------------------------ // CsiDeleteFile // // Deletes the file given by pFileName. The return value is true if the file was // successfully deleted or false if an error occurred. Use pBypassChecks to // bypass all file deletion checks //------------------------------------------------------------------------------ function CsiDeleteFile(const pFileName: string; pBypassChecks: Boolean): Boolean; var lFileName: string; begin lFileName := CsiExpandFileName(pFileName); if FileExists(lFileName) then begin if not pBypassChecks then // remove any attributes that might prevent deletion FileSetAttr(lFileName, 0); Result := SysUtils.DeleteFile(lFileName); end else if DirectoryExists(lFileName) then // cannot delete the file if it is a directory Result := False else Result := lFileName <> ''; end; //------------------------------------------------------------------------------ // CsiExpandDirName // // Returns the full path name for the directory given by pDirName //------------------------------------------------------------------------------ function CsiExpandDirName(const pDirName: string): string; begin if pDirName <> '' then begin Result := CsiExpandFileName(IncludeTrailingPathDelimiter(pDirName) + 'File' + EXT_TEXT); Result := CsiExtractFileDir(Result, False); end else // return an empty result Result := ''; end; //------------------------------------------------------------------------------ // CsiExpandFileName // // Returns the full path name for the file given by pFileName //------------------------------------------------------------------------------ function CsiExpandFileName(const pFileName: string): string; begin if pFileName <> '' then Result := ExpandFileName(pFileName) else // return an empty result Result := ''; end; //------------------------------------------------------------------------------ // CsiExtractFileDir // // Returns the drive and directory parts of the file given by pFileName. The // pIncludePathDelimiter flag indicates whether the return value includes a // trailing path delimiter //------------------------------------------------------------------------------ function CsiExtractFileDir(const pFileName: string; pIncludePathDelimiter: Boolean): string; begin if pFileName <> '' then begin Result := ExtractFileDir(CsiExpandFileName(pFileName)); if pIncludePathDelimiter then Result := IncludeTrailingPathDelimiter(Result) else Result := ExcludeTrailingPathDelimiter(Result); end else // return an empty result Result := ''; end; //------------------------------------------------------------------------------ // CsiExtractFileDrive // // Returns the drive part of the file given by pFileName. The // pIncludePathDelimiter flag indicates whether the return value includes a // trailing path delimiter //------------------------------------------------------------------------------ function CsiExtractFileDrive(const pFileName: string; pIncludePathDelimiter: Boolean): string; begin if pFileName <> '' then begin Result := ExtractFileDrive(CsiExpandFileName(pFileName)); if pIncludePathDelimiter then Result := IncludeTrailingPathDelimiter(Result) else Result := ExcludeTrailingPathDelimiter(Result); end else // return an empty result Result := ''; end; //------------------------------------------------------------------------------ // CsiFileByteCount // // Returns the size of the file given by pFileName //------------------------------------------------------------------------------ function CsiFileByteCount(const pFileName: string): Int64; var lFileStream: TFileStream; begin lFileStream := TFileStream.Create(pFileName, fmOpenRead or fmShareDenyWrite); try Result := lFileStream.Size; finally lFileStream.Free; end; end; //------------------------------------------------------------------------------ // CsiFileLineCount // // Returns the line count of the file given by pFileName //------------------------------------------------------------------------------ {function CsiFileLineCount(const pFileName: string): Integer; var lStringList: TStringList; begin lStringList := TStringList.Create; with lStringList do try CaseSensitive := False; CsiLoadFromFile(pFileName, lStringList); Result := Count; finally Free; end; end; } //------------------------------------------------------------------------------ // CsiGetFileTime // // Returns the corresponding file time of the type pTimeType for the file given // by pFileName //------------------------------------------------------------------------------ {function CsiGetFileTime(const pFileName: string; pTimeType: TECsiFileTimeType): TDateTime; var lFileHandle: THandle; lFindData: TWin32FindData; begin lFileHandle := FindFirstFile(PChar(pFileName), lFindData); if lFileHandle = INVALID_HANDLE_VALUE then raise ECsiFile.Create('Cannot find file <' + pFileName + '>', slError, 1); FindClose(lFileHandle); case pTimeType of ftCreation: Result := CsiUtcFileTimeToDateTime(lFindData.ftCreationTime); ftLastWrite: Result := CsiUtcFileTimeToDateTime(lFindData.ftLastWriteTime); ftLastAccess: Result := CsiUtcFileTimeToDateTime(lFindData.ftLastAccessTime); else raise ECsiFile.Create('Invalid file time type <' + IntToStr(Ord(pTimeType)) + '>', slError, 2); end; end; } //------------------------------------------------------------------------------ // CsiGetWriteableFileName // // Returns the file name of a file that can be written based on the base file // name pBaseFileName. The pCanExist flag indicates whether the file can already // exist //------------------------------------------------------------------------------ {function CsiGetWriteableFileName(const pBaseFileName: string; pCanExist: Boolean): string; var lBaseFileName: string; lBaseDirName: string; lBaseFileExt: string; lIndex: Integer; begin if pBaseFileName = '' then raise ECsiFile.Create('Empty base writeable file name', slError, 3); // break the file name down into its constituent parts lBaseFileName := CsiExpandFileName(pBaseFileName); Result := lBaseFileName; lBaseDirName := CsiExtractFileDir(lBaseFileName); lBaseFileName := ExtractFileName(lBaseFileName); lBaseFileExt := ExtractFileExt(lBaseFileName); lBaseFileName := CsiLeftStr(lBaseFileName, Length(lBaseFileName) - Length(lBaseFileExt)); // get a file that can be written lIndex := 1; while not ((pCanExist and CanAppendFile(Result)) or (not pCanExist and not FileExists(Result))) do begin Result := lBaseDirName + lBaseFileName + '_' + IntToStr(lIndex) + lBaseFileExt; Inc(lIndex); end; end;} //------------------------------------------------------------------------------ // CsiIsFileReadable // // Returns whether the file given by pFileName is readable //------------------------------------------------------------------------------ function CsiIsFileReadable(const pFileName: string): Boolean; var lFileHandle: Integer; begin lFileHandle := FileOpen(pFileName, fmOpenRead or fmShareDenyWrite); if lFileHandle > 0 then begin FileClose(lFileHandle); Result := True; end else Result := False; end; //------------------------------------------------------------------------------ // CsiIsFileWriteable // // Returns whether the file given by pFileName is writeable //------------------------------------------------------------------------------ function CsiIsFileWriteable(const pFileName: string): Boolean; var lFileHandle: Integer; begin lFileHandle := FileOpen(pFileName, fmOpenReadWrite or fmShareDenyWrite); if lFileHandle > 0 then begin FileClose(lFileHandle); Result := True; end else Result := False; end; //------------------------------------------------------------------------------ // CsiMoveDir // // Moves the directory given by pExistingDirName to the directory given by // pNewDirName. The return value is true if the directory was successfully moved // or false if an error occurred. Use pForceMove to overwrite the files if they // already exist. Use pBypassChecks to bypass all file moving checks //------------------------------------------------------------------------------ function CsiMoveDir(const pExistingDirName: string; const pNewDirName: string; pForceMove: Boolean; pBypassChecks: Boolean): Boolean; var lExistingDirName: string; lNewDirName: string; lSearchRec: TSearchRec; begin // it is painful to deal with the double sloshes unless we do it up front lExistingDirName := CsiExpandDirName(pExistingDirName); lNewDirName := CsiExpandDirName(pNewDirName); if StartsStr('\\', lExistingDirName) or StartsStr('\\', lNewDirName) then begin Result := False; Exit; end; // let us not move a directory we will regret! if IsProtectedDir(lExistingDirName) then begin Result := False; Exit; end; if not SameText(lNewDirName, lExistingDirName) then if not StartsStr(IncludeTrailingPathDelimiter(lNewDirName), lExistingDirName, False) and not StartsStr(IncludeTrailingPathDelimiter(lExistingDirName), lNewDirName, False) and DirectoryExists(lExistingDirName) and CsiCreateDir(lNewDirName) then begin Result := True; lExistingDirName := IncludeTrailingPathDelimiter(lExistingDirName); lNewDirName := IncludeTrailingPathDelimiter(lNewDirName); if FindFirst(lExistingDirName + '*', faAnyFile, lSearchRec) = 0 then try repeat with lSearchRec do if (Name <> '.') and (Name <> '..') then if (Attr and faDirectory) <> 0 then // recursively move the sub-directories first Result := CsiMoveDir(lExistingDirName + Name, lNewDirName + Name, pForceMove) and Result else // move the files in the directory Result := CsiMoveFile(lExistingDirName + Name, lNewDirName + Name, pForceMove, pBypassChecks) and Result; until FindNext(lSearchRec) <> 0; finally SysUtils.FindClose(lSearchRec); end; if Result and not SameText(lNewDirName, lExistingDirName) then // delete the current directory Result := CsiDeleteDir(lExistingDirName, pBypassChecks); end else // cannot move the directory if it does not exist, or we cannot create the // destination directory, or the destination and source directories // overlap Result := False else // cannot move the directory if it does not exist Result := DirectoryExists(lExistingDirName); end; //------------------------------------------------------------------------------ // CsiMoveFile // // Moves the file given by pExistingFileName to the name given by pNewFileName. // The return value is true if the file was successfully moved or false if an // error occurred. Use pForceMove to overwrite the file if it already exists. // Use pBypassChecks to bypass all file moving checks //------------------------------------------------------------------------------ function CsiMoveFile(const pExistingFileName: string; const pNewFileName: string; pForceMove: Boolean; pBypassChecks: Boolean): Boolean; var lExistingFileName: string; lNewFileName: string; begin lExistingFileName := CsiExpandFileName(pExistingFileName); lNewFileName := CsiExpandFileName(pNewFileName); if not pBypassChecks and pForceMove and not SameText(lNewFileName, lExistingFileName) then // ensure that the destination file does not exist Result := CsiDeleteFile(lNewFileName, pBypassChecks) else Result := True; if Result then if not SameText(lNewFileName, lExistingFileName) then if FileExists(lExistingFileName) and not FileExists(lNewFileName) and not DirectoryExists(lNewFileName) then begin if not pBypassChecks then Result := CsiCreateDir(CsiExtractFileDir(lNewFileName, False)); Result := Result and RenameFile(lExistingFileName, lNewFileName); end else // cannot move the file if it does not exist or the destination file // already exists Result := False else if not FileExists(lExistingFileName) then // cannot move the file if it does not exist Result := False; end; //------------------------------------------------------------------------------ // CsiSetFileTime // // Sets the corresponding file time to pFileTime of the type pTimeType for the // file given by pFileName //------------------------------------------------------------------------------ {procedure CsiSetFileTime(const pFileName: string; pTimeType: TECsiFileTimeType; pFileTime: TDateTime); var lFileHandle: Integer; lUtcFileTime: TFileTime; begin lFileHandle := FileOpen(pFileName, fmOpenReadWrite or fmShareDenyWrite); if lFileHandle < 0 then raise ECsiFile.Create('Cannot open file <' + pFileName + '>', slError, 4); try lUtcFileTime := CsiDateTimeToUtcFileTime(pFileTime); case pTimeType of ftCreation: SetFileTime(lFileHandle, @lUtcFileTime, nil, nil); ftLastWrite: SetFileTime(lFileHandle, nil, nil, @lUtcFileTime); ftLastAccess: SetFileTime(lFileHandle, nil, @lUtcFileTime, nil); else raise ECsiFile.Create('Invalid file time type <' + IntToStr(Ord(pTimeType)) + '>', slError, 5); end; finally FileClose(lFileHandle); end; end; } { //------------------------------------------------------------------------------ // CsiLoadFromFile // // Loads pFileName into pData, an array of bytes pData //------------------------------------------------------------------------------ procedure CsiLoadFromFile(const pFileName: string; out pData: TByteDynArray); var lFileStream: TFileStream; lSize: Integer; begin lFileStream := TFileStream.Create(pFileName, fmOpenRead or fmShareDenyWrite); with lFileStream do try lSize := Size; SetLength(pData, lSize); if Length(pData) > 0 then ReadBuffer(pData[0], lSize); finally Free; end; end; //------------------------------------------------------------------------------ // CsiLoadFromFile // // Loads pFileName into pIdValuePairs using the string encoding pStringEncoding // (one of automatic, Ansi, UTF-16, or UTF-8) which includes the byte order mark // if the string encoding is automatic (pWithKeyChars indicates whether // pFileName has the id-value pairs key characters in the first line of the // file) //------------------------------------------------------------------------------ procedure CsiLoadFromFile(const pFileName: string; pIdValuePairs: TCsiIdValuePairs; pWithKeyChars: Boolean; pStringEncoding: TECsiStringEncoding); var lStrings: TCsiStringList; lKeyChars: string; lKeyChar: Char; begin lStrings := TCsiStringList.Create; try lStrings.CaseSensitive := False; CsiLoadFromFile(pFileName, lStrings, pStringEncoding); if pWithKeyChars and (lStrings.Count >= 1) then begin // read the key characters from the first line lKeyChars := lStrings.Strings[0]; if lKeyChars <> '' then begin pIdValuePairs.DelimiterChar := lKeyChars[1]; if Length(lKeyChars) >= 2 then begin lKeyChar := lKeyChars[2]; pIdValuePairs.AssignmentChar := lKeyChar; lStrings.NameValueSeparator := lKeyChar; end; end; lStrings.Delete(0); end; pIdValuePairs.Assign(lStrings); finally lStrings.Free; end; end; //------------------------------------------------------------------------------ // CsiLoadFromFile // // Loads pFileName into pStrings using the string encoding pStringEncoding (one // of automatic, Ansi, UTF-16, or UTF-8) which includes the byte order mark if // the string encoding is automatic //------------------------------------------------------------------------------ procedure CsiLoadFromFile(const pFileName: string; pStrings: TStrings; pStringEncoding: TECsiStringEncoding); var lText: string; begin CsiLoadFromFile(pFileName, lText, pStringEncoding); pStrings.Text := lText; end; //------------------------------------------------------------------------------ // CsiLoadFromFile // // Loads pFileName into pText using the string encoding pStringEncoding (one of // automatic, Ansi, UTF-16, or UTF-8) which includes the byte order mark if the // string encoding is automatic //------------------------------------------------------------------------------ procedure CsiLoadFromFile(const pFileName: string; out pText: string; pStringEncoding: TECsiStringEncoding); var lData: TByteDynArray; begin CsiLoadFromFile(pFileName, lData); pText := CsiBytesToStr(lData, pStringEncoding); end; } procedure GetDirs(const Path : string; Items : TStrings); var FileInfo: TSearchRec; DosCode: Integer; S: string; begin Items.Clear; if DirectoryExists(Path) then begin s := Path + '\*.*'; DosCode := FindFirst(s, faDirectory, FileInfo); try while DosCode = 0 do begin if (FileInfo.Name[1] <> '.') and (FileInfo.Attr and faDirectory = faDirectory) then begin Items.Add(FileInfo.Name); end; DosCode := FindNext(FileInfo); end; finally SysUtils.FindClose(FileInfo); end; end; end; procedure GetFiles(const DirPath, FileExt: string; FileList: TStringList); var Status: THandle; FindData: TWin32FindData; begin Status := FindFirstFileW(PWideChar(DirPath + FileExt), FindData); if Status <> INVALID_HANDLE_VALUE then repeat if (FindData.cFileName[0] <> '.') and (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0) then FileList.Add(FindData.cFileName); until not FindNextFile(Status, FindData); Windows.FindClose(Status); end; function NormalDir(const DirName: string): string; begin Result := DirName; if (Result <> '') and not (Result[Length(Result)] = '\') then begin if Result[Length(Result)] = '/' then Result[Length(Result)] := '\' else begin if (Length(Result) = 1) then Result := Result + ':\' else Result := Result + '\'; end; end; end; function DirExists(const DirName: string): Boolean; begin Result := DirectoryExists(DirName); end; function CreateDir(const DirName: string): Boolean; begin Result := CreateDirectoryW(PWideChar(DirName), nil); end; function RemoveDir(const DirName: string): Boolean; begin Result := RemoveDirectoryW(PWideChar(DirName)); end; function SetCurrentDir(const DirName: string): Boolean; begin Result := SetCurrentDirectoryW(PWideChar(DirName)); end; function GetCurrentDir: string; var Buf: array[0..MAX_PATH] of WideChar; begin GetCurrentDirectoryW(MAX_PATH, Buf); Result := Buf; end; function DeleteFile(const FileName: string): Boolean; begin Result := DeleteFileW(PWideChar(FileName)); end; function CopyFile(const ExistingFileName, NewFileName: string; bFailIfExists: Boolean): Boolean; begin Result := CopyFileW(PWideChar(ExistingFileName), PWideChar(NewFileName), bFailIfExists); end; procedure CopyFiles(SrcMask, SrcDir: string; DstDir: string); var FileInfo: TSearchRec; DosCode: Integer; begin if not DirExists(DstDir) then CreateDir(DstDir); DstDir := NormalDir(DstDir); SrcDir := NormalDir(SrcDir); DosCode := FindFirst(SrcDir + SrcMask, faAnyFile, FileInfo); try while DosCode = 0 do begin if (FileInfo.Name[1] <> '.') and (FileInfo.Attr <> faVolumeID) then begin if (FileInfo.Attr and faVolumeID <> faVolumeID) then CopyFile(SrcDir + FileInfo.Name, DstDir + FileInfo.Name, False); end; DosCode := FindNext(FileInfo); end; finally FindClose(FileInfo); end; end; function FileSetAttr(const FileName: string; Attr: Cardinal): Integer; begin Result := 0; if not SetFileAttributesW(PWideChar(FileName), Attr) then Result := Integer(GetLastError); end; function FileGetAttr(const FileName: string): Cardinal; begin Result := GetFileAttributesW(PWideChar(FileName)); end; function ClearDir(const Path: string; Delete: Boolean): Boolean; const FileNotFound = 18; var FileInfo: TSearchRec; DosCode: Integer; begin Result := DirExists(Path); if not Result then Exit; DosCode := FindFirst(NormalDir(Path) + '*.*', faAnyFile, FileInfo); try while DosCode = 0 do begin if (FileInfo.Name[1] <> '.') and (FileInfo.Attr <> faVolumeID) then begin if (FileInfo.Attr and faDirectory = faDirectory) then begin Result := ClearDir(NormalDir(Path) + FileInfo.Name, Delete) and Result end else if (FileInfo.Attr and faVolumeID <> faVolumeID) then begin if (FileInfo.Attr and faReadOnly = faReadOnly) then begin FileSetAttr(NormalDir(Path) + FileInfo.Name, faArchive); end; Result := DeleteFile(NormalDir(Path) + FileInfo.Name) and Result; end; end; DosCode := FindNext(FileInfo); end; finally FindClose(FileInfo); end; if Delete and Result and (DosCode = FileNotFound) and not ((Length(Path) = 2) and (Path[2] = ':')) then begin Result := RemoveDir(Path) and Result; end; end; function GetIconForFile(const FullFileName: string; Flag : integer): TIcon; var SH: TSHFileInfo; begin Result := nil; if FileExists(FullFileName) then begin FillChar(SH, SizeOf(SH), 0); if SHGetFileInfo(PWideChar(FullFileName), 0, SH, SizeOf(SH), SHGFI_ICON or Flag) <> 0 then begin Result := TIcon.Create; Result.Handle := SH.hIcon; if Result.Empty then FreeAndNil(Result); end; end; end; function ValidFileName(const FileName: string): Boolean; function HasAny(const Str, Substr: string): Boolean; var I: Integer; begin Result := False; for I := 1 to Length(Substr) do begin if Pos(Substr[I], Str) > 0 then begin Result := True; Break; end; end; end; begin Result := (FileName <> '') and (not HasAny(FileName, '<>"|*?/')); if Result then Result := Pos('\', ExtractFileName(FileName)) = 0; end; function ShortToLongFileName(const ShortName: string): string; var Temp: TWin32FindDataW; SearchHandle: THandle; begin SearchHandle := FindFirstFileW(PWideChar(ShortName), Temp); if SearchHandle <> INVALID_HANDLE_VALUE then begin Result := string(Temp.cFileName); if Result = '' then Result := string(Temp.cAlternateFileName); end else Result := ''; Windows.FindClose(SearchHandle); end; function LongToShortFileName(const LongName: string): string; var Temp: TWin32FindDataW; SearchHandle: THandle; begin SearchHandle := FindFirstFileW(PWideChar(LongName), Temp); if SearchHandle <> INVALID_HANDLE_VALUE then begin Result := string(Temp.cAlternateFileName); if Result = '' then Result := string(Temp.cFileName); end else Result := ''; Windows.FindClose(SearchHandle); end; function ShortToLongPath(ShortName: string): string; var LastSlash: PWideChar; TempPathPtr: PWideChar; begin Result := ''; TempPathPtr := PWideChar(ShortName); UniqueString (ShortName); LastSlash := StrScan(TempPathPtr, '\'); while LastSlash <> nil do begin Result := '\' + ShortToLongFileName(TempPathPtr) + Result; if LastSlash <> nil then begin LastSlash^ := #0; LastSlash := StrScan(TempPathPtr, '\'); end; end; Result := TempPathPtr + Result; end; function LongToShortPath(LongName: string): string; var LastSlash: PWideChar; TempPathPtr: PWideChar; begin Result := ''; UniqueString (LongName); TempPathPtr := PWideChar(LongName); LastSlash := StrScan(TempPathPtr, '\'); while LastSlash <> nil do begin Result := '\' + LongToShortFileName(TempPathPtr) + Result; if LastSlash <> nil then begin LastSlash^ := #0; LastSlash := StrScan(TempPathPtr, '\'); end; end; Result := TempPathPtr + Result; end; function RemoveEmptyFolders(const rootFolder: string): boolean; var iRet: integer; bRemove: boolean; sr: TSearchRec; begin RemoveEmptyFolders := False; bRemove := True; iRet := FindFirst(rootFolder + '\*.*', faAnyFile, sr) ; while (iRet = 0) do begin if (sr.Name[1] <> '.') then begin if (sr.Attr and faDirectory) <> 0 then begin if not RemoveEmptyFolders(rootFolder + '\' + sr.Name) then bRemove := False; end else begin bRemove := False; end; end; iRet := FindNext(sr) ; end; FindClose(sr) ; if bRemove then RemoveEmptyFolders := RemoveDir(rootFolder) ; end; function WriteTextToFile(const filename, text: string; Append: Boolean): Boolean; begin with TStreamWriter.Create(filename, Append) do begin Write(text); Flush; Close; end; end; function DeleteFiles(const FileMask: String): Boolean; var SRec : TSearchRec; Path : String; begin Result := FindFirst(FileMask, faAnyFile, SRec) = 0; if not Result then exit; try Path := ExtractFilePath(FileMask); repeat if (SRec.Name <> '') and (SRec.Name <> '.') and (SRec.Name <> '..') and (SRec.Attr and (faVolumeID + faDirectory) = 0) then begin Result := DeleteFile(Path + SRec.Name); if not Result then break; end; until FindNext(SRec) <> 0; finally FindClose(SRec); end; end; end.
unit DmMainRtc; interface uses System.SysUtils, System.Classes, rtcInfo, rtcConn, rtcDataCli, rtcHttpCli, RtcSqlQuery, rtcCliModule, commoninterface, Dialogs, Forms, Variants, SettingsStorage, DCPsha256, Rtti, rtcFunction, RtcFuncResult, RtcQueryDataSet, u_xmlinit, vkvariable; type TMainRtcDm = class(TDataModule) RtcHttpClient1: TRtcHttpClient; RtcClientModule1: TRtcClientModule; RtcResult1: TRtcResult; procedure DataModuleCreate(Sender: TObject); procedure RtcHttpClient1ConnectLost(Sender: TRtcConnection); procedure RtcClientModule1ConnectLost(Sender: TRtcConnection); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } DCP_sha2561: TDCP_sha256; FUserInfo: PUserInfo; query: TRtcQuery; FXmlIni: TXmlIni; FUserAccessTypes: TVkVariableCollection; FUserAccessValues: TVkVariableCollection; FStorage: TSettingsStorage; procedure test; function rtcLogin(): Boolean; public { Public declarations } // procedure test(); function getPasswordHash(const pwd: String): UTF8String; function Login(const userName, password: String): Boolean; function NewRtcQueryDataSet: TRtcQueryDataSet; function Gen_ID(const key:String):Int64; function GetTypeGroup( AId: LargeInt): LargeInt; function RtcQueryValue(const SQL:String; params: array of Variant):IRtcFuncResult; function RtcQueryValues(const SQL:String; params: array of Variant):IRtcFuncResult; function QueryValue(const SQL:String; params: array of Variant):Variant; procedure QueryValues(const AVarList:TVkVariableCollection; const SQL:String; params: array of Variant); procedure DoRequest(const ASql:String;const AParams: TVariants; AOnRequest: TOnRequest = nil); procedure SetUser(Param: TRtcFunctionInfo); // class function rtcExecute(clientModule:TRtcClientModule;func: TRtcFunctionInfo): variant; overload; class procedure CloneComponent(const aSource, aDestination: TComponent); class function rtcExecute(clientModule:TRtcClientModule;func: TRtcFunctionInfo): IRtcFuncResult; overload; property UserAccessTypes: TVkVariableCollection read FUserAccessTypes; property UserAccessValues: TVkVariableCollection read FUserAccessValues; property XmlInit: TXmlIni read FXmlIni; property UserInfo:PUserInfo read FUserInfo; end; var MainRtcDm: TMainRtcDm; implementation { %CLASSGROUP 'Vcl.Controls.TControl' } {$R *.dfm} procedure TMainRtcDm.DataModuleCreate(Sender: TObject); begin DCP_sha2561 := TDCP_sha256.Create(self); FStorage := TSettingsStorage.Create(TSettingsStorage.GetDefaultStorageName); FStorage.Read; RtcHttpClient1.ServerAddr := fStorage.GetVariable('SEREVR','host','localhost').AsString; RtcHttpClient1.ServerPort := fStorage.GetVariable('SEREVR','port','6476').AsString; RtcHttpClient1.Connect(); FXmlIni := TXmlIni.Create(self,ChangeFileExt(Application.ExeName,'.xml')); FUserAccessTypes := TVkVariableCollection.Create(self); FUserAccessValues := TVkVariableCollection.Create(self); end; procedure TMainRtcDm.DataModuleDestroy(Sender: TObject); begin FreeAndNil(FXmlIni); FreeAndNil(FStorage); end; procedure TMainRtcDm.DoRequest(const ASql: String; const AParams: TVariants; AOnRequest: TOnRequest); var qr: TRtcQuery; i: Integer; begin qr := TRtcQuery.Create(RtcClientModule1, FUserInfo); try qr.SQL.Text := ASql; if Assigned(AParams) then for i:=Low(AParams) to High(AParams) do qr.Params[i].Value := AParams[i]; qr.DoRequest(AOnRequest); finally qr.Free; end; end; function TMainRtcDm.Gen_ID(const key: String): Int64; begin with RtcClientModule1 do begin try with Prepare('RtcGen_ID') do begin Param.asWideString['username'] := FUserInfo.user_name; Param.asWideString['password'] := FUserInfo.user_password; Param.asWideString['ID_NAME'] := key; Result := rtcExecute(RtcClientModule1, RtcClientModule1.Data.asFunction).getRtcValue.asLargeInt; end; finally // FreeAndNil(Retval); end; end; end; function TMainRtcDm.getPasswordHash(const pwd: String): UTF8String; var buf: UTF8String; digest: array [0 .. 31] of byte; I: Integer; begin buf := UTF8String(pwd); DCP_sha2561.Init(); DCP_sha2561.UpdateStr(buf); DCP_sha2561.Final(digest); Result := StringOfChar(#0, 64); for I := 0 to length(digest) - 1 do begin buf := Int2Hex(digest[I], 2).ToUpper; Result[I * 2 + 1] := buf[1]; Result[I * 2 + 2] := buf[2]; end; end; function TMainRtcDm.Login(const userName, password: String): Boolean; begin FUserInfo := new(PUserInfo); FUserInfo.user_name := userName; FUserInfo.user_password := getPasswordHash(password); Result := rtcLogin(); // query := TRtcQuery.Create(RtcClientModule1, FUserInfo ); // query.QueryValue('SELECT CAST(HASH(CAST(:pas as CHAR(20))) as CHAR(20)) as pwd FROM rdb$database', [password]); end; function TMainRtcDm.NewRtcQueryDataSet: TRtcQueryDataSet; begin Result := TRtcQueryDataSet.Create(RtcClientModule1,FUserInfo); end; function TMainRtcDm.QueryValue(const SQL: String; params: array of Variant): Variant; var i: Integer; retval: IRtcFuncResult; begin retval := RtcQueryValue(SQL, params); if Assigned(retval) then begin if (retval.RtcValue.isType = rtc_Array) then begin Result := VarArrayCreate([0,retval.RtcValue.asArray.Count], varVariant); for I := 0 to retval.RtcValue.asArray.Count-1 do Result[i] := retval.RtcValue.asArray.asValue[i]; end else Result := retval.RtcValue.asValue; end else Result := null; end; procedure TMainRtcDm.QueryValues(const AVarList: TVkVariableCollection; const SQL: String; params: array of Variant); var i: Integer; retval: IRtcFuncResult; _v: TVkVariable; begin retval := RtcQueryValue(SQL, params); if Assigned(retval) then begin if (retval.RtcValue.isType = rtc_Record) then begin for i := 0 to retval.RtcValue.asRecord.Count - 1 do begin _v := TVkVariable.Create(AVarList); _v.Name := retval.RtcValue.asRecord.FieldName[i]; _v.Value := retval.RtcValue.asRecord.asValue[_v.Name]; end; end else if (retval.RtcValue.isType = rtc_Array) then begin for i := 0 to retval.RtcValue.asArray.Count - 1 do begin _v := TVkVariable.Create(AVarList); _v.Name := retval.RtcValue.asArray.asRecord[i].asString['name']; _v.Value := retval.RtcValue.asArray.asRecord[i].asValue['value']; end; end; end; end; procedure TMainRtcDm.RtcClientModule1ConnectLost(Sender: TRtcConnection); begin // RtcHTTPClient1.Disconnect; // RtcHTTPClient1.Connect(); RtcClientModule1.Release; end; class function TMainRtcDm.rtcExecute(clientModule:TRtcClientModule;func: TRtcFunctionInfo): IRtcFuncResult; var retval: TRtcValue; begin retval := nil; try with func do begin retval := clientModule.Execute(False, 0, False); if retval.isType = rtc_Exception then begin Raise Exception.Create(retval.asException); end; Result := TRtcFuncResult.Create(retval); end; finally // FreeAndNil(retval); end; end; {class function TMainRtcDm.rtcExecute(clientModule: TRtcClientModule; func: TRtcFunctionInfo): TRtcDataSet;overload; var retval: TRtcValue; begin retval := nil; try with func do begin retval := clientModule.Execute(False, 0, False); if retval.isType = rtc_Exception then begin Raise Exception.Create(retval.asException); end; Result:= retval.asDataSet ; end; finally FreeAndNil(retval); end; end;} procedure TMainRtcDm.RtcHttpClient1ConnectLost(Sender: TRtcConnection); begin // RtcHTTPClient1.Disconnect; ShowMessage('LOST'); end; function TMainRtcDm.rtcLogin: Boolean; var Retval: TRtcValue; func: TRtcFunctionInfo; begin with RtcClientModule1 do begin try with Prepare('RtcConnect') do begin Param.asWideString['username'] := FUserInfo.user_name; Param.asWideString['password'] := FUserInfo.user_password; Retval := rtcExecute(RtcClientModule1, RtcClientModule1.Data.asFunction).getRtcValue; Result := Retval.asRecord.asInteger['RESULT'] = 0; TUtils.RtcToVkVariableColections(Retval.asRecord.asRecord['USERACCESSTYPES'], FUserAccessTypes); TUtils.RtcToVkVariableColections(Retval.asRecord.asRecord['USERACCESSVALUES'], FUserAccessValues); TUtils.RtcValueToRecord(Retval.asRecord.asRecord['USERINFO'],FUserInfo, TypeInfo(RUserInfo)); end; finally // FreeAndNil(Retval); end; end; end; function TMainRtcDm.RtcQueryValue(const SQL: String; params: array of Variant): IRtcFuncResult; var i: Integer; begin // Result := null; with RtcClientModule1 do begin with Prepare('RtcQueryValue') do begin Param.asWideString['username'] := FUserInfo.user_name; Param.asWideString['password'] := FUserInfo.user_password; Param.asWideString['SQL'] := SQL; Param.NewArray('SQL_PARAMS'); //:= TRtcArray.Create(); // Param.asInteger['Param_count'] := High(AParams); for I := 0 to High(params) do Param.asArray['SQL_PARAMS'][i] := params[i]; // Result := TRtcFuncResult.Create(retval); Result := rtcExecute(RtcClientModule1, RtcClientModule1.Data.asFunction); end; end; end; function TMainRtcDm.RtcQueryValues(const SQL: String; params: array of Variant): IRtcFuncResult; var i: Integer; begin // Result := null; with RtcClientModule1 do begin with Prepare('RtcQueryValues') do begin Param.asWideString['username'] := FUserInfo.user_name; Param.asWideString['password'] := FUserInfo.user_password; Param.asWideString['SQL'] := SQL; Param.NewArray('SQL_PARAMS'); //:= TRtcArray.Create(); // Param.asInteger['Param_count'] := High(AParams); for I := 0 to High(params) do Param.asArray['SQL_PARAMS'][i] := params[i]; // Result := TRtcFuncResult.Create(retval); Result := rtcExecute(RtcClientModule1, RtcClientModule1.Data.asFunction); end; end; end; procedure TMainRtcDm.SetUser(Param: TRtcFunctionInfo); begin Param.asWideString['username'] := FUserInfo.user_name; Param.asWideString['password'] := FUserInfo.user_password; end; procedure TMainRtcDm.test; begin RtcHttpClient1.Connect(); ShowMessage(query.QueryValue ('SELECT name FROM objects WHERE idobject=:id_object', [4])); end; class procedure TMainRtcDm.CloneComponent(const aSource, aDestination: TComponent); var ctx: TRttiContext; RttiType, DestType: TRttiType; RttiProperty: TRttiProperty; Buffer: TStringlist; begin if aSource.ClassType <> aDestination.ClassType then raise Exception.Create('Source and destiantion must be the same class'); Buffer := TStringlist.Create; try Buffer.Sorted := True; Buffer.Add('Name'); Buffer.Add('Handle'); RttiType := ctx.GetType(aSource.ClassType); DestType := ctx.GetType(aDestination.ClassType); for RttiProperty in RttiType.GetProperties do begin if not RttiProperty.IsWritable then continue; if Buffer.IndexOf(RttiProperty.Name) >= 0 then continue; DestType.GetProperty(RttiProperty.Name).SetValue(aDestination, RttiProperty.GetValue(aSource)); end; finally Buffer.Free; end; end; function TMainRtcDm.GetTypeGroup( AId: LargeInt): LargeInt; var id : LargeInt; retval:Variant; begin id := -1; Result := -1; if AId=0 then Exit; retval := QueryValue('SELECT idgroup, idobject FROM objects WHERE idobject=:idobject',[AId]); { FDQuerySelect.Active := False; FDQuerySelect.SQL.Clear; FDQuerySelect.SQL.Add('SELECT idgroup, idobject FROM objects WHERE idobject=:idobject'); FDQuerySelect.ParamByName('idobject').AsLargeInt := AId;} while id<>0 do begin if (not VarIsEmpty(retval)) and (VarIsArray(retval)) and (VarArrayHighBound(retval,1)>=1) then begin id := retval[0]; Result := retval[1]; if (id <> 0) then retval := QueryValue('SELECT idgroup, idobject FROM objects WHERE idobject=:idobject',[id]); end else begin Result := 0; Exit; end; // raise Exception.Create('Error group'); end; end; {procedure TMainDm.InitConstsList(var AVarList: TVkVariableCollection; const ATableName, AIdName: String); begin if Assigned(AVarList) then AVarList.Clear else AVarList := TVkVariableCollection.Create(self); with VkUIBQuerySelect do begin Active := False; SQL.Clear; SQL.Add('SELECT * FROM '+ATableName); Open; try while not Eof do begin AVarList.CreateVkVariable(FieldByName('CONSTNAME').AsString,FieldByName(AIdName).Value); Next; end; finally Close; end; end; end;} end.
(** * $Id: dco.rpc.Serializer.pas 840 2014-05-24 06:04:58Z QXu $ * * 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. *) unit dco.rpc.Serializer; interface uses superobject { An universal object serialization framework with Json support }, dco.rpc.ErrorObject, dco.rpc.Identifier, dco.rpc.RPCHandler; type /// <summary>This interface defines the obligation of RPC data serialization.</summary> ISerializer = interface /// <summary>Encodes a request.</summary> function EncodeRequest(const Method: string; const Params: ISuperObject; const Id: TIdentifier): string; /// <summary>Encodes a notification.</summary> function EncodeNotification(const Method: string; const Params: ISuperObject): string; /// <summary>Encodes a valid response.</summary> function EncodeResponse(const Result_: ISuperObject; const Id: TIdentifier): string; overload; /// <summary>Encodes an error response.</summary> function EncodeResponse(const Error: TErrorObject; const Id: TIdentifier): string; overload; /// <summary>Decodes a message and executes it with specified handler.</summary> /// <exception cref="ERPCException">Specified message does not represent a valid request or response.</exception> procedure Decode(const Message_: string; const Handler: IRPCHandler); end; implementation end.
unit WMSMapDefs; {$writeableconst on} interface uses ShareTools, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Contnrs, ExtCtrls, ComCtrls, ToolWin; type TCoordinateSystem = class Identifier : string; end; TBoundingBox = class private _Changing : boolean; fMinE, fMinN, fMaxE, fMaxN : Double; fOnChange : TNotifyEvent; procedure SetMinE(v : Double); procedure SetMinN(v : Double); procedure SetMaxE(v : Double); procedure SetMaxN(v : Double); procedure Changed; virtual; protected procedure BeginChanges; procedure CommitChanges; public CoordinateSystem : TCoordinateSystem; property MinE : Double read fMinE write SetMinE; property MinN : Double read fMinN write SetMinN; property MaxE : Double read fMaxE write SetMaxE; property MaxN : Double read fMaxN write SetMaxN; property OnChange : TNotifyEvent read fOnChange write fOnChange; constructor Create(aMinE, aMinN, aMaxE, aMaxN : Double); destructor Destroy; override; end; TViewArea = class(TBoundingBox) private fWidth, fHeight : integer; FWUperRPelE : Double; // horizontal size of Canvas pixel in projected meters FWUperRPelN : Double; // vertical size of Canvas pixel in projected meters procedure SetWidth(v : integer); procedure SetHeight(v : integer); public property WUperRPelE : Double read FWUperRPelE write fWUperRPelE; // width resolution in working units property WUperRPelN : Double read FWUperRPelN write fWUperRPelN; // height resolution in working units property Width : integer read fWidth write SetWidth; property Height : integer read fHeight write SetHeight; procedure ViewArea(UserMinE, UserMinN, UserMaxE, UserMaxN : Double; aGeoSystem : TCoordinateSystem = nil); procedure NewCenter(const AboutE, AboutN: Double); function WUfromEIndex(const EIndex : LongInt) : Double; // Returns world E coordinate from canvas column function WUfromNIndex(const NIndex : LongInt) : Double; // Returns world N coordinate from canvas row function NIndexFromWU(N : Double) : Int64; // Returns canvas row from N world coordinate function EIndexFromWU(E : Double) : Int64; // Returns canvas column from E world coordinate procedure Changed; override; constructor Create(aMinE, aMinN, aMaxE, aMaxN : Double; aWidth, aHeight : integer); end; TLayer = class end; TLayers = class(TObjectList) private function GetItem(i : integer) : TLayer; public property Item[i : integer] : TLayer read GetItem; default; function Add : TLayer; end; TMap = class(TPanel) private procedure ResizeProc(Sender: TObject); procedure ShowWorld; public Img : TImage; Area : TViewArea; constructor Create(aOwner : TComponent); destructor Destroy; override; end; TWMSMapForm = class(TForm) ToolBar1: TToolBar; ToolButton1: TToolButton; StatusBar1: TStatusBar; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure OnMapViewChanged(Sender: TObject); procedure FormShow(Sender: TObject); procedure ToolButton1Click(Sender: TObject); private { Private declarations } public { Public declarations } Map : TMap; end; var WMSMapForm: TWMSMapForm; implementation {$R *.dfm} // ************************************************************** // TBoundingBox // ************************************************************** constructor TBoundingBox.Create; begin inherited Create; _Changing := false; BeginChanges; try MinE := aMinE; MinN := aMinN; MaxE := aMaxE; MaxN := aMaxN; finally CommitChanges; end; CoordinateSystem := TCoordinateSystem.Create; end; procedure TBoundingBox.BeginChanges; begin _Changing := true; end; procedure TBoundingBox.CommitChanges; begin _Changing := false; Changed; end; procedure TBoundingBox.Changed; begin if _Changing then Exit; if Assigned(OnChange) then OnChange(Self); end; procedure TBoundingBox.SetMinE(v : Double); begin fMinE := v; Changed; end; procedure TBoundingBox.SetMinN(v : Double); begin fMinN := v; Changed; end; procedure TBoundingBox.SetMaxE(v : Double); begin fMaxE := v; Changed; end; procedure TBoundingBox.SetMaxN(v : Double); begin fMaxN := v; Changed; end; destructor TBoundingBox.Destroy; begin CoordinateSystem.Free; inherited; end; // ************************************************************** // TViewArea // ************************************************************** constructor TViewArea.Create(aMinE, aMinN, aMaxE, aMaxN : Double; aWidth, aHeight : integer); begin inherited Create(aMinE, aMinN, aMaxE, aMaxN); Width := aWidth; Height := aHeight; ViewArea(aMinE, aMinN, aMaxE, aMaxN); end; procedure TViewArea.ViewArea(UserMinE, UserMinN, UserMaxE, UserMaxN : Double; aGeoSystem : TCoordinateSystem = nil); var hMinE, hMinN, hMaxE, hMaxN : Double; SizeE, SizeN, dE, dN : DOuble; PredChanging : boolean; begin if aGeoSystem = nil then begin PredChanging := _Changing; try _Changing := true; SortDouble(UserMinE, UserMaxE); SortDouble(UserMinN, UserMaxN); dE := UserMaxE - UserMinE; dN := UserMaxN - UserMinN; if (dE <> 0) and (dN <> 0) and (Width <> 0) and (Height <> 0) then begin SizeN := dN/Height; SizeE := dE/Width; if SizeN > SizeE then begin { shodna se zadanou bude svisla hrana } WUPerRPelN := -SizeN; WUPerRPelE := SizeN; end else begin { shodna se zadanou bude vodorovna hrana } WUPerRPelE := SizeE; WUPerRPelN := -SizeE; end; MaxN := UserMaxN; MinE := UserMinE; NewCenter((UserMinE + UserMaxE)/2, (UserMinN + UserMaxN)/2); end; finally _Changing := PredChanging; Changed; end; end else begin end; end; procedure TViewArea.NewCenter(const AboutE, AboutN: Double); { Tato metoda nastaví pohled tak, že bude mít střed v bodě AboutE, AboutN. Velikost a zvětšení pohledu zůstane nezměněno. } var PredChanging : boolean; begin PredChanging := _Changing; try _Changing := true; MinE := AboutE - WUPerRPelE*(Width div 2); MaxN := AboutN - WUPerRPelN*(Height div 2); finally _Changing := PredChanging; Changed; end; end; function TViewArea.WUfromEIndex; { Tato metoda vrací souřadnici pixelu EIndex převedenou na metry. } begin {$O-} Result := MinE + EIndex*WUPerRPelE; end; function TViewArea.WUfromNIndex; { Tato metoda vrací souřadnici pixelu NIndex převedenou na metry. } begin {$O-} Result := MaxN + NIndex*WUPerRPelN; end; function TViewArea.NIndexFromWU; // Tato funkce vrací souřadnici N v metrech převedenou na pixely. var Pom : Double; begin {$O-} Pom := -(N-MinN)/fWUperRPelN; if Pom > 9223372036854775807 then Pom := 9223372036854775807; if Pom < -9223372036854775807 then Pom := -9223372036854775807; NIndexFromWU := Trunc(Pom); end; function TViewArea.EIndexfromWU; // Tato funkce vrací souřadnici E v metrech převedenou na pixely. var Pom : Double; begin {$O-} Pom := (E-MinE)/fWUperRPelE; if Pom > 9223372036854775807 then Pom := 9223372036854775807; if Pom < -9223372036854775807 then Pom := -9223372036854775807; EIndexfromWU := Trunc(Pom); end; procedure TViewArea.SetWidth(v : integer); begin fWidth := v; Changed; end; procedure TViewArea.SetHeight(v : integer); begin fHeight := v; Changed; end; procedure TViewArea.Changed; begin if _Changing then Exit; inherited Changed; fMinN := WUfromNIndex(Height); fMaxE := WUfromEIndex(Width); end; // ************************************************************** // TLayers // ************************************************************** function TLayers.GetItem(i : integer) : TLayer; begin Result := pointer(Items[i]); end; function TLayers.Add : TLayer; begin inherited Add(TLayer.Create); Result := Pointer(Items[Count - 1]); end; // ************************************************************** // TMap // ************************************************************** constructor TMap.Create; begin inherited Create(aOwner); Cursor := crCross; Area := TViewArea.Create(-180, -90, +180, +90, Width, Height); Img := TImage.Create(Self); Img.Parent := Self; Img.Align := alClient; OnResize := ResizeProc; end; procedure TMap.ShowWorld; var bmp : TBitmap; r : TRect; begin bmp := TBitmap.Create; try bmp.LoadFromFile('C:\Temp\WorldBmps\WORLD01_Normal.bmp'); r.Left := Area.EIndexFromWU(-180); r.Right := Area.EIndexFromWU(+180); r.Bottom := Area.NIndexFromWU(+90); r.Top := Area.NIndexFromWU(-90); with img.Picture.Bitmap.Canvas do begin Brush.Color := clWhite; Pen.Color := clWhite; Rectangle(0, 0, img.Picture.Bitmap.Width, img.Picture.Bitmap.Height); StretchDraw(r, bmp); end; finally bmp.Free; end; end; destructor TMap.Destroy; begin Img.Free; Area.Free; inherited; end; procedure TMap.ResizeProc(Sender: TObject); var MaxE, MinN : Double; begin Img.Picture.Bitmap.Width := Img.Width; Img.Picture.Bitmap.Height := Img.Height; Area.BeginChanges; try MaxE := Area.MaxE; MinN := Area.MinN; Area.Width := Img.Width; Area.Height := Img.Height; Area.ViewArea(Area.MinE, MinN, MaxE, Area.MaxN); finally Area.CommitChanges; end; end; procedure TWMSMapForm.FormCreate(Sender: TObject); begin Map := TMap.Create(Self); Map.Parent := Self; Map.Align := alClient; Map.Area.OnChange := OnMapViewChanged; end; procedure TWMSMapForm.FormDestroy(Sender: TObject); begin Map.Free; end; procedure TWMSMapForm.OnMapViewChanged(Sender: TObject); var y, dy : integer; procedure DisplayFloat(Msg : string; Value : Double); begin Map.Img.Picture.Bitmap.Canvas.TextOut(5, y, ' ' + Msg + FloatToStr(Value) + ' '); y := y + dy; end; begin Map.ShowWorld; with Map.Img.Picture.Bitmap.Canvas, Map.Area do begin dy := Map.Img.Picture.Bitmap.Canvas.TextHeight('X'); TextOut(5, 5, Format(' %dx%d ', [Map.Area.Width, Map.Area.Height])); y := 5 + dy; DisplayFloat('MinE:', MinE); DisplayFloat('MaxN:', MaxN); DisplayFloat('MaxE:', MaxE); DisplayFloat('MinN:', MinN); end; end; procedure TWMSMapForm.FormShow(Sender: TObject); const FirstCall : boolean = true; begin if FirstCall then begin Map.Area.ViewArea(-180, -90, +180, +90); FirstCall := false; end; end; procedure TWMSMapForm.ToolButton1Click(Sender: TObject); begin Map.Area.ViewArea(-180, -90, +180, +90); end; end.
program jeu_des_allumettes_2J_V1 (input, output); uses crt; const NbAlluMax=21; //Nombre maximum d'allumettes type CaracJoueur=record //Caracteristiques du joueur NumeroJoueur:integer; //Numero du joueur Choix:integer; //Nombre d'allumettes prises par le joueur AlluMain:integer; //Nombre d'allumettes dans la main du joueur end; type Allumettes=record //Enregistrement pour le tas d'allumettes NbTas:integer; //Nombre d'allumettes sur le tas end; type Scores=record //Tableau des scores Gagnant:integer; //Gagnant du jeu NbTours:integer; //Nombre de tours passes pour terminer la partie end; //Creation des deux joueurs et initialisation de leur numero et de leur main procedure SetJoueurs (var Joueur1, Joueur2:CaracJoueur); begin //Joueur 1 Joueur1.NumeroJoueur:=1; Joueur1.AlluMain:=0; //Joueur 2 Joueur2.NumeroJoueur:=2; Joueur2.AlluMain:=0; end; procedure TourDeJeu (var Joueur1, Joueur2:CaracJoueur; Tour:integer;var Scoreboard:Scores); var Tas:Allumettes; begin //Initialisation du nombre d allumettes du tas d allumettes Tas.NbTas:=NbAlluMax; //Initialisation du tour Tour:=1; //Boucle de jeu REPEAT clrscr; //Pour le 1er joueur IF (Tour MOD 2<>0) THEN begin //Affichage du numero du joueur qui doit jouer writeln('Tour du joueur : ',Joueur1.NumeroJoueur); writeln; //Affichage de la main des joueurs writeln('Le joueur 1 a ',Joueur1.AlluMain,' allumettes'); writeln('Le joueur 2 a ',Joueur2.AlluMain,' allumettes'); writeln; //Affichage du nombre d'allumettes sur le tas writeln('Il y a ',Tas.NbTas,' allumettes sur le tas'); writeln; //Entree du choix du joueur writeln('Retirez 1, 2 ou 3 allumettes : '); IF (Tas.NbTas>=3) THEN begin REPEAT readln(Joueur1.Choix); UNTIL (Joueur1.Choix=1) OR (Joueur1.Choix=2) OR (Joueur1.Choix=3); end ELSE begin IF (Tas.NbTas=2) THEN begin REPEAT readln(Joueur1.Choix); UNTIL (Joueur1.Choix=1) OR (Joueur1.Choix=2); end ELSE begin REPEAT readln(Joueur1.Choix); UNTIL (Joueur1.Choix=1); end; end; //Decrementation du tas Tas.NbTas:=Tas.NbTas-Joueur1.Choix; //Incrementation de la main du joueur Joueur1.AlluMain:=Joueur1.AlluMain+Joueur1.Choix; //Enregistre le numero du joueur gagnant IF (Tas.NbTas=0) THEN begin Scoreboard.Gagnant:=Joueur2.NumeroJoueur; end; end; //Pour le 2eme joueur IF (Tour MOD 2=0) THEN begin //Affichage du numero du joueur qui doit jouer writeln('Tour du joueur : ',Joueur2.NumeroJoueur); writeln; //Affichage de la main des joueurs writeln('Le joueur 1 a ',Joueur1.AlluMain,' allumettes'); writeln('Le joueur 2 a ',Joueur2.AlluMain,' allumettes'); writeln; //Affichage du nombre d'allumettes sur le tas writeln('Il y a ',Tas.NbTas,' allumettes sur le tas'); writeln; //Entree du choix du joueur writeln('Retirez 1, 2 ou 3 allumettes : '); IF (Tas.NbTas>=3) THEN begin REPEAT readln(Joueur2.Choix); UNTIL (Joueur2.Choix=1) OR (Joueur2.Choix=2) OR (Joueur2.Choix=3); end ELSE begin IF (Tas.NbTas=2) THEN begin REPEAT readln(Joueur2.Choix); UNTIL (Joueur2.Choix=1) OR (Joueur2.Choix=2); end ELSE begin REPEAT readln(Joueur2.Choix); UNTIL (Joueur2.Choix=1); end; end; //Decrementation du tas Tas.NbTas:=Tas.NbTas-Joueur2.Choix; //Incrementation de la main du joueur Joueur2.AlluMain:=Joueur2.AlluMain+Joueur2.Choix; //Enregistre le numero du joueur gagnant IF (Tas.NbTas=0) THEN begin Scoreboard.Gagnant:=Joueur1.NumeroJoueur; end; end; //Incrementation du tour Tour:=Tour+1; UNTIL (Tas.NbTas=0); //Enregistre le nombre de tours de la partie Scoreboard.NbTours:=Tour; end; procedure TabScores (var Scoreboard:scores); begin clrscr; writeln('.____________________________.'); writeln('| FIN DE LA PARTIE |'); writeln('|____________________________|'); writeln('| Le gagnant est le joueur ', Scoreboard.Gagnant,' |'); writeln('|____________________________|'); writeln('| Nombre de tours joues : ', Scoreboard.NbTours,' |'); writeln('|____________________________|'); end; var Joueur1, Joueur2:CaracJoueur; //Variables contenant ce qui caracterise les 2 joueurs TasAll:Allumettes; //Variable contenant ce qui caract‚rise le tas d'allumettes Tour:integer; //Tour de jeu Scoreboard:Scores; //Tableau des scores //Programme principal BEGIN clrscr; writeln('Programme : jeu des allumettes'); writeln('Appuyez sur ''entrer'' pour continuer'); clrscr; //Initialisation des joueurs SetJoueurs(Joueur1,Joueur2); //Tour de jeu TourDeJeu(Joueur1,Joueur2,Tour,Scoreboard); //Tableau des scores TabScores(Scoreboard); readln; END.
program testbugfix03(output); {Bug reported Jan 19, 2020; Fixed Jan 28 2020. validate that succ() succeeds when called on a variable with type subrange of an enumerated type, where both the subrange and the type have over 128 items, and the original value of the variable has an ordinal value of greater than 128. Basically, ensure we're doing an unsigned comparison after the succ() rather than signed.} type largeEnum = (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10, a11,a12,a13,a14,a15,a16,a17,a18,a19,a20, a21,a22,a23,a24,a25,a26,a27,a28,a29,a30, a31,a32,a33,a34,a35,a36,a37,a38,a39,a40, a41,a42,a43,a44,a45,a46,a47,a48,a49,a50, a51,a52,a53,a54,a55,a56,a57,a58,a59,a60, a61,a62,a63,a64,a65,a66,a67,a68,a69,a70, a71,a72,a73,a74,a75,a76,a77,a78,a79,a80, a81,a82,a83,a84,a85,a86,a87,a88,a89,a90, a91,a92,a93,a94,a95,a96,a97,a98,a99,a100, a101,a102,a103,a104,a105,a106,a107,a108,a109,a110, a111,a112,a113,a114,a115,a116,a117,a118,a119,a120, a121,a122,a123,a124,a125,a126,a127,a128,a129,a130, a131,a132,a133,a134,a135,a136,a137,a138,a139,a140, a141,a142,a143,a144,a145,a146,a147,a148,a149,a150, a151,a152,a153,a154,a155,a156,a157,a158,a159,a160, a161,a162,a163,a164,a165,a166,a167,a168,a169,a170, a171,a172,a173,a174,a175,a176,a177,a178,a179,a180, a181,a182,a183,a184,a185,a186,a187,a188,a189,a190, a191,a192,a193,a194,a195,a196,a197,a198,a199,a200, a201,a202,a203,a204,a205,a206,a207,a208,a209,a210, a211,a212,a213,a214,a215,a216,a217,a218,a219,a220, a221,a222,a223,a224,a225,a226,a227,a228,a229,a230, a231,a232,a233,a234,a235,a236,a237,a238,a239,a240, a241,a242,a243,a244,a245,a246,a247,a248,a249,a250, a251,a252,a253,a254,a255); largeSubrange = a1..a254; var mysubr:largeSubrange; begin mysubr := a252; mysubr := succ(mysubr); writeln('success!'); end.
{+--------------------------------------------------------------------------+ | GEMBASE Syntax Parser v0.51 | +--------------------------------------------------------------------------+ | Description: GEMBASE syntax parser for use with mwCustomEdit. | Ross Systems is a leading provider of enterprise business solutions | for some of the most prestigious process manufacturing, healthcare and | public sector organizations in the world. | Their software Renaissance CS, is an integrated enterprise resource | planning (ERP) and supply chain management (SCM) solution. | (Just like Baan, JD-Edwards OneWorld, SAP, PeopleSoft) | Gembase is a 4GL programming language of Renaissance CS. | For more info please visit: www.rossinc.com +--------------------------------------------------------------------------+ | Unit: mwDMLSyn | Created: 1999-10-04 | Last change: 1999-11-14 | Author: Peter Adam (adamp@extra.hu) | Copyright (c) 1999 All rights reserved | (Large!) Portions Copyright Martin Waldenburg | Version: 0.52 | Status: Public Domain | DISCLAIMER: This is provided as is, expressly without a warranty of any | kind. You use it at your own risc. +--------------------------------------------------------------------------+ | Known problems: There are no metadata qualifiers +--------------------------------------------------------------------------+ | Revision History: | 0.50: Initial version. | 0.51: Optimisations, thanks to Michael Hieke | 0.52: Made compatible with pointer type checking +--------------------------------------------------------------------------+} {$I MWEDIT.INC} unit mwDmlSyn; interface uses SysUtils, Windows, Messages, Classes, Controls, Graphics, Registry, mwHighlighter, mwLocalStr, mwExport; type TtkTokenKind = ( tkBlock, tkComment, tkForm, tkKey, tkQualifier, tkFunction, tkVariable, tkString, tkIdentifier, tkNumber, tkSpecial, tkNull, tkSpace, tkSymbol, tkUnknown); TRangeState = (rsANil, rsAdd, rsFind, rsUnKnown); TProcTableProc = procedure of object; PIdentFuncTableFunc = ^TIdentFuncTableFunc; TIdentFuncTableFunc = function: TtkTokenKind of object; TmwDmlSyn = class(TmwCustomHighLighter) private fRange: TRangeState; fLine: PChar; fLineNumber: Integer; fProcTable: array[#0..#255] of TProcTableProc; Run: LongInt; Temp: PChar; fStringLen: Integer; fToIdent: PChar; fIdentFuncTable: array[0..327] of TIdentFuncTableFunc; fTokenPos: Integer; FTokenID: TtkTokenKind; fFormAttri: TmwHighLightAttributes; fBlockAttri: TmwHighLightAttributes; fKeyAttri: TmwHighLightAttributes; fQualiAttri: TmwHighLightAttributes; fCommentAttri: TmwHighLightAttributes; fFunctionAttri: TmwHighLightAttributes; fVariableAttri: TmwHighLightAttributes; fSpecialAttri: TmwHighLightAttributes; fStringAttri: TmwHighLightAttributes; fNumberAttri: TmwHighLightAttributes; fSymbolAttri: TmwHighLightAttributes; fIdentifierAttri: TmwHighLightAttributes; fSpaceAttri: TmwHighLightAttributes; function KeyHash(ToHash: PChar): Integer; function KeyComp(const aKey: String): Boolean; function Func9: TtkTokenKind; function Func15: TtkTokenKind; function Func17: TtkTokenKind; function Func19: TtkTokenKind; function Func22: TtkTokenKind; function Func23: TtkTokenKind; function Func24: TtkTokenKind; function Func26: TtkTokenKind; function Func27: TtkTokenKind; function Func28: TtkTokenKind; function Func29: TtkTokenKind; function Func30: TtkTokenKind; function Func31: TtkTokenKind; function Func32: TtkTokenKind; function Func33: TtkTokenKind; function Func34: TtkTokenKind; function Func35: TtkTokenKind; function Func36: TtkTokenKind; function Func37: TtkTokenKind; function Func38: TtkTokenKind; function Func40: TtkTokenKind; function Func41: TtkTokenKind; function Func42: TtkTokenKind; function Func43: TtkTokenKind; function Func45: TtkTokenKind; function Func47: TtkTokenKind; function Func48: TtkTokenKind; function Func49: TtkTokenKind; function Func50: TtkTokenKind; function Func51: TtkTokenKind; function Func52: TtkTokenKind; function Func53: TtkTokenKind; function Func54: TtkTokenKind; function Func56: TtkTokenKind; function Func57: TtkTokenKind; function Func58: TtkTokenKind; function Func60: TtkTokenKind; function Func62: TtkTokenKind; function Func64: TtkTokenKind; function Func65: TtkTokenKind; function Func66: TtkTokenKind; function Func67: TtkTokenKind; function Func68: TtkTokenKind; function Func69: TtkTokenKind; function Func70: TtkTokenKind; function Func71: TtkTokenKind; function Func72: TtkTokenKind; function Func73: TtkTokenKind; function Func74: TtkTokenKind; function Func75: TtkTokenKind; function Func76: TtkTokenKind; function Func77: TtkTokenKind; function Func78: TtkTokenKind; function Func79: TtkTokenKind; function Func81: TtkTokenKind; function Func82: TtkTokenKind; function Func83: TtkTokenKind; function Func84: TtkTokenKind; function Func85: TtkTokenKind; function Func86: TtkTokenKind; function Func87: TtkTokenKind; function Func89: TtkTokenKind; function Func91: TtkTokenKind; function Func92: TtkTokenKind; function Func93: TtkTokenKind; function Func94: TtkTokenKind; function Func96: TtkTokenKind; function Func97: TtkTokenKind; function Func98: TtkTokenKind; function Func99: TtkTokenKind; function Func100: TtkTokenKind; function Func101: TtkTokenKind; function Func102: TtkTokenKind; function Func103: TtkTokenKind; function Func104: TtkTokenKind; function Func106: TtkTokenKind; function Func108: TtkTokenKind; function Func110: TtkTokenKind; function Func111: TtkTokenKind; function Func113: TtkTokenKind; function Func116: TtkTokenKind; function Func117: TtkTokenKind; function Func120: TtkTokenKind; function Func121: TtkTokenKind; function Func122: TtkTokenKind; function Func123: TtkTokenKind; function Func124: TtkTokenKind; function Func125: TtkTokenKind; function Func126: TtkTokenKind; function Func127: TtkTokenKind; function Func128: TtkTokenKind; function Func129: TtkTokenKind; function Func131: TtkTokenKind; function Func132: TtkTokenKind; function Func134: TtkTokenKind; function Func135: TtkTokenKind; function Func136: TtkTokenKind; function Func137: TtkTokenKind; function Func138: TtkTokenKind; function Func139: TtkTokenKind; function Func140: TtkTokenKind; function Func141: TtkTokenKind; function Func142: TtkTokenKind; function Func144: TtkTokenKind; function Func146: TtkTokenKind; function Func148: TtkTokenKind; function Func150: TtkTokenKind; function Func152: TtkTokenKind; function Func153: TtkTokenKind; function Func154: TtkTokenKind; function Func155: TtkTokenKind; function Func156: TtkTokenKind; function Func157: TtkTokenKind; function Func163: TtkTokenKind; function Func164: TtkTokenKind; function Func166: TtkTokenKind; function Func169: TtkTokenKind; function Func173: TtkTokenKind; function Func174: TtkTokenKind; function Func175: TtkTokenKind; function Func176: TtkTokenKind; function Func178: TtkTokenKind; function Func179: TtkTokenKind; function Func182: TtkTokenKind; function Func183: TtkTokenKind; function Func184: TtkTokenKind; function Func185: TtkTokenKind; function Func187: TtkTokenKind; function Func188: TtkTokenKind; function Func203: TtkTokenKind; function Func206: TtkTokenKind; function Func216: TtkTokenKind; function Func219: TtkTokenKind; function Func221: TtkTokenKind; function Func232: TtkTokenKind; function Func234: TtkTokenKind; function Func235: TtkTokenKind; function Func243: TtkTokenKind; function Func244: TtkTokenKind; function Func255: TtkTokenKind; function Func313: TtkTokenKind; function Func327: TtkTokenKind; function AltFunc: TtkTokenKind; procedure InitIdent; function IdentKind(MayBe: PChar): TtkTokenKind; procedure MakeMethodTables; procedure SymbolProc; procedure AddressOpProc; procedure AsciiCharProc; procedure CRProc; procedure GreaterProc; procedure IdentProc; procedure LFProc; procedure LowerProc; procedure NullProc; procedure NumberProc; procedure PointProc; procedure SpaceProc; procedure StringProc; procedure UnknownProc; procedure RemProc; function IsQuali: boolean; function IsSpecial: Boolean; protected function GetIdentChars: TIdentChars; override; function GetLanguageName: string; override; function GetCapability: THighlighterCapability; override; public constructor Create(AOwner: TComponent); override; procedure ExportNext;override; procedure SetLineForExport(NewValue: String);override; function GetEol: Boolean; override; function GetRange: Pointer; override; function GetTokenID: TtkTokenKind; procedure SetLine(NewValue: String; LineNumber:Integer); override; function GetToken: String; override; function GetTokenAttribute: TmwHighLightAttributes; override; function GetTokenKind: integer; override; function GetTokenPos: Integer; override; procedure Next; override; procedure SetRange(Value: Pointer); override; procedure ReSetRange; override; published property FormAttri: TmwHighLightAttributes read fFormAttri write fFormAttri; property BlockAttri: TmwHighLightAttributes read fBlockAttri write fBlockAttri; property KeyAttri: TmwHighLightAttributes read fKeyAttri write fKeyAttri; property QualiAttri: TmwHighLightAttributes read fQualiAttri write fQualiAttri; property CommentAttri: TmwHighLightAttributes read fCommentAttri write fCommentAttri; property FunctionAttri: TmwHighLightAttributes read fFunctionAttri write fFunctionAttri; property VariableAttri: TmwHighLightAttributes read fVariableAttri write fVariableAttri; property SpecialAttri: TmwHighLightAttributes read fSpecialAttri write fSpecialAttri; property IdentifierAttri: TmwHighLightAttributes read fIdentifierAttri write fIdentifierAttri; property NumberAttri: TmwHighLightAttributes read fNumberAttri write fNumberAttri; property SpaceAttri: TmwHighLightAttributes read fSpaceAttri write fSpaceAttri; property StringAttri: TmwHighLightAttributes read fStringAttri write fStringAttri; property SymbolAttri: TmwHighLightAttributes read fSymbolAttri write fSymbolAttri; end; procedure Register; implementation var Identifiers: array[#0..#255] of ByteBool; mHashTable: array[#0..#255] of Integer; procedure Register; begin RegisterComponents(MWS_HighlightersPage, [TmwDmlSyn]); end; procedure MakeIdentTable; var I, J: Char; begin for I := #0 to #255 do begin Case I of '_', '0'..'9', 'a'..'z', 'A'..'Z': Identifiers[I] := True; else Identifiers[I] := False; end; J := UpCase(I); Case I of 'a'..'z', 'A'..'Z', '_': mHashTable[I] := Ord(J) - 64; else mHashTable[Char(I)] := 0; end; end; end; procedure TmwDmlSyn.InitIdent; var I: Integer; pF: PIdentFuncTableFunc; begin pF := PIdentFuncTableFunc(@fIdentFuncTable); for I := Low(fIdentFuncTable) to High(fIdentFuncTable) do begin pF^ := AltFunc; Inc(pF); end; fIdentFuncTable[9] := Func9; fIdentFuncTable[15] := Func15; fIdentFuncTable[17] := Func17; fIdentFuncTable[19] := Func19; fIdentFuncTable[22] := Func22; fIdentFuncTable[23] := Func23; fIdentFuncTable[24] := Func24; fIdentFuncTable[26] := Func26; fIdentFuncTable[27] := Func27; fIdentFuncTable[28] := Func28; fIdentFuncTable[29] := Func29; fIdentFuncTable[30] := Func30; fIdentFuncTable[31] := Func31; fIdentFuncTable[32] := Func32; fIdentFuncTable[33] := Func33; fIdentFuncTable[34] := Func34; fIdentFuncTable[35] := Func35; fIdentFuncTable[36] := Func36; fIdentFuncTable[37] := Func37; fIdentFuncTable[38] := Func38; fIdentFuncTable[40] := Func40; fIdentFuncTable[41] := Func41; fIdentFuncTable[42] := Func42; fIdentFuncTable[43] := Func43; fIdentFuncTable[45] := Func45; fIdentFuncTable[47] := Func47; fIdentFuncTable[48] := Func48; fIdentFuncTable[49] := Func49; fIdentFuncTable[50] := Func50; fIdentFuncTable[51] := Func51; fIdentFuncTable[52] := Func52; fIdentFuncTable[53] := Func53; fIdentFuncTable[54] := Func54; fIdentFuncTable[56] := Func56; fIdentFuncTable[57] := Func57; fIdentFuncTable[58] := Func58; fIdentFuncTable[60] := Func60; fIdentFuncTable[62] := Func62; fIdentFuncTable[64] := Func64; fIdentFuncTable[65] := Func65; fIdentFuncTable[66] := Func66; fIdentFuncTable[67] := Func67; fIdentFuncTable[68] := Func68; fIdentFuncTable[69] := Func69; fIdentFuncTable[70] := Func70; fIdentFuncTable[71] := Func71; fIdentFuncTable[72] := Func72; fIdentFuncTable[73] := Func73; fIdentFuncTable[74] := Func74; fIdentFuncTable[75] := Func75; fIdentFuncTable[76] := Func76; fIdentFuncTable[77] := Func77; fIdentFuncTable[78] := Func78; fIdentFuncTable[79] := Func79; fIdentFuncTable[81] := Func81; fIdentFuncTable[82] := Func82; fIdentFuncTable[83] := Func83; fIdentFuncTable[84] := Func84; fIdentFuncTable[85] := Func85; fIdentFuncTable[86] := Func86; fIdentFuncTable[87] := Func87; fIdentFuncTable[89] := Func89; fIdentFuncTable[91] := Func91; fIdentFuncTable[92] := Func92; fIdentFuncTable[93] := Func93; fIdentFuncTable[94] := Func94; fIdentFuncTable[96] := Func96; fIdentFuncTable[97] := Func97; fIdentFuncTable[98] := Func98; fIdentFuncTable[99] := Func99; fIdentFuncTable[100] := Func100; fIdentFuncTable[101] := Func101; fIdentFuncTable[102] := Func102; fIdentFuncTable[103] := Func103; fIdentFuncTable[104] := Func104; fIdentFuncTable[106] := Func106; fIdentFuncTable[108] := Func108; fIdentFuncTable[110] := Func110; fIdentFuncTable[111] := Func111; fIdentFuncTable[113] := Func113; fIdentFuncTable[116] := Func116; fIdentFuncTable[117] := Func117; fIdentFuncTable[120] := Func120; fIdentFuncTable[121] := Func121; fIdentFuncTable[122] := Func122; fIdentFuncTable[123] := Func123; fIdentFuncTable[124] := Func124; fIdentFuncTable[125] := Func125; fIdentFuncTable[126] := Func126; fIdentFuncTable[127] := Func127; fIdentFuncTable[128] := Func128; fIdentFuncTable[129] := Func129; fIdentFuncTable[131] := Func131; fIdentFuncTable[132] := Func132; fIdentFuncTable[134] := Func134; fIdentFuncTable[135] := Func135; fIdentFuncTable[136] := Func136; fIdentFuncTable[137] := Func137; fIdentFuncTable[138] := Func138; fIdentFuncTable[139] := Func139; fIdentFuncTable[140] := Func140; fIdentFuncTable[141] := Func141; fIdentFuncTable[142] := Func142; fIdentFuncTable[144] := Func144; fIdentFuncTable[146] := Func146; fIdentFuncTable[148] := Func148; fIdentFuncTable[150] := Func150; fIdentFuncTable[152] := Func152; fIdentFuncTable[153] := Func153; fIdentFuncTable[154] := Func154; fIdentFuncTable[155] := Func155; fIdentFuncTable[156] := Func156; fIdentFuncTable[157] := Func157; fIdentFuncTable[163] := Func163; fIdentFuncTable[164] := Func164; fIdentFuncTable[166] := Func166; fIdentFuncTable[169] := Func169; fIdentFuncTable[173] := Func173; fIdentFuncTable[174] := Func174; fIdentFuncTable[175] := Func175; fIdentFuncTable[176] := Func176; fIdentFuncTable[178] := Func178; fIdentFuncTable[179] := Func179; fIdentFuncTable[182] := Func182; fIdentFuncTable[183] := Func183; fIdentFuncTable[184] := Func184; fIdentFuncTable[185] := Func185; fIdentFuncTable[187] := Func187; fIdentFuncTable[188] := Func188; fIdentFuncTable[203] := Func203; fIdentFuncTable[206] := Func206; fIdentFuncTable[216] := Func216; fIdentFuncTable[219] := Func219; fIdentFuncTable[221] := Func221; fIdentFuncTable[232] := Func232; fIdentFuncTable[234] := Func234; fIdentFuncTable[235] := Func235; fIdentFuncTable[243] := Func243; fIdentFuncTable[244] := Func244; fIdentFuncTable[255] := Func255; fIdentFuncTable[313] := Func313; fIdentFuncTable[327] := Func327; end; function TmwDmlSyn.IsQuali: boolean; begin Result:= False; if Run > 0 then if fLine[Run-1]= '/' then Result:= True; end; function TmwDmlSyn.IsSpecial: boolean; begin Result:= False; if Run > 0 then if fLine[Run-1]= '%' then Result:= True; end; function TmwDmlSyn.KeyHash(ToHash: PChar): Integer; begin Result := 0; while ToHash^ in ['a'..'z', 'A'..'Z', '_'] do begin inc(Result, mHashTable[ToHash^]); inc(ToHash); end; if ToHash^ in ['_', '0'..'9'] then inc(ToHash); fStringLen := ToHash - fToIdent; end; { KeyHash } function TmwDmlSyn.KeyComp(const aKey: String): Boolean; var I: Integer; begin Temp := fToIdent; if Length(aKey) = fStringLen then begin Result := True; for i := 1 to fStringLen do begin if mHashTable[Temp^] <> mHashTable[aKey[i]] then begin Result := False; break; end; inc(Temp); end; end else Result := False; end; { KeyComp } function TmwDmlSyn.Func9: TtkTokenKind; begin if KeyComp('Add') then begin if IsSpecial then Result := tkSpecial else begin Result := tkKey; fRange := rsAdd; end; end else Result := tkIdentifier; end; function TmwDmlSyn.Func15: TtkTokenKind; begin if KeyComp('If') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func17: TtkTokenKind; begin if KeyComp('Back') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func19: TtkTokenKind; begin if KeyComp('Dcl') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func22: TtkTokenKind; begin if KeyComp('Abs') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func23: TtkTokenKind; begin if KeyComp('In') and (fRange = rsFind) then begin Result := tkKey; fRange:= rsUnKnown; end else Result := tkIdentifier; end; function TmwDmlSyn.Func24: TtkTokenKind; begin if KeyComp('Cli') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func26: TtkTokenKind; begin if KeyComp('Mid') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func27: TtkTokenKind; begin if KeyComp('Base') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func28: TtkTokenKind; begin if KeyComp('Tag') and IsQuali then Result := tkQualifier else if KeyComp('Case') then Result := tkKey else if KeyComp('Call') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func29: TtkTokenKind; begin if KeyComp('Chr') then Result := tkFunction else if KeyComp('Ceil') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func30: TtkTokenKind; begin if KeyComp('Check') and IsQuali then Result := tkQualifier else if KeyComp('Col') then begin if IsQuali then Result := tkQualifier else if IsSpecial then Result := tkSpecial else Result := tkIdentifier; end else if KeyComp('Date') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func31: TtkTokenKind; begin if KeyComp('Len') then begin if IsQuali then Result := tkQualifier else Result := tkFunction; end else if KeyComp('Dir') then Result := tkKey else if KeyComp('Bell') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func32: TtkTokenKind; begin if KeyComp('Mod') then Result := tkFunction else if KeyComp('Load') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func33: TtkTokenKind; begin if KeyComp('Find') then begin Result := tkKey; fRange := rsFind; end else Result := tkIdentifier; end; function TmwDmlSyn.Func34: TtkTokenKind; begin if KeyComp('Log') then begin if IsQuali then Result := tkQualifier else Result := tkFunction; end else if KeyComp('Batch') and IsQuali then Result := tkQualifier else if KeyComp('Log10') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func35: TtkTokenKind; begin if KeyComp('Tan') then Result := tkFunction else if KeyComp('To') and (fRange=rsAdd) then begin Result := tkKey; fRange := rsUnKnown; end else if KeyComp('Mail') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func36: TtkTokenKind; begin if KeyComp('Atan2') then Result := tkFunction else if KeyComp('Atan') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func37: TtkTokenKind; begin if KeyComp('Break') and IsQuali then Result := tkQualifier else if KeyComp('Break0') and IsQuali then Result := tkQualifier else if KeyComp('Cos') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func38: TtkTokenKind; begin if KeyComp('Acos') then Result := tkFunction else if KeyComp('Edit') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func40: TtkTokenKind; begin if KeyComp('Line') then Result := tkKey else if KeyComp('Table') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func41: TtkTokenKind; begin if KeyComp('Else') then Result := tkKey else if KeyComp('Lock') and IsQuali then Result := tkQualifier else if KeyComp('Ascii') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func42: TtkTokenKind; begin if KeyComp('Send') then Result := tkKey else if KeyComp('Sin') then Result := tkFunction else if KeyComp('New') and IsQuali then Result := tkQualifier else if KeyComp('Fetch') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func43: TtkTokenKind; begin if KeyComp('Asin') then Result := tkFunction else if KeyComp('Int') then Result := tkFunction else if KeyComp('Left') then Result := tkFunction else if KeyComp('Tanh') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func45: TtkTokenKind; begin if KeyComp('Cosh') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func47: TtkTokenKind; begin if KeyComp('Item') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func48: TtkTokenKind; begin if KeyComp('Heading') and IsQuali then Result := tkQualifier else if KeyComp('Erase') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func49: TtkTokenKind; begin if KeyComp('Days') then Result := tkFunction else if KeyComp('Lov') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func50: TtkTokenKind; begin if KeyComp('Pos') and IsQuali then Result := tkQualifier else if KeyComp('Sinh') then Result := tkFunction else if KeyComp('Open') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func51: TtkTokenKind; begin if KeyComp('Files') then Result := tkKey else if KeyComp('Opt') and IsQuali then Result := tkQualifier else if KeyComp('Delete') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func52: TtkTokenKind; begin if KeyComp('Form') then begin if IsSpecial then Result := tkSpecial else Result := tkForm; end else Result := tkIdentifier; end; function TmwDmlSyn.Func53: TtkTokenKind; begin if KeyComp('Wait') and IsQuali then Result := tkQualifier else if KeyComp('Menu') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func54: TtkTokenKind; begin if KeyComp('Close') then Result := tkKey else if KeyComp('Search') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func56: TtkTokenKind; begin if KeyComp('Domain') and IsQuali then Result := tkQualifier else if KeyComp('Row') and IsQuali then Result := tkQualifier else if KeyComp('Row') and IsSpecial then Result := tkSpecial else Result := tkIdentifier; end; function TmwDmlSyn.Func57: TtkTokenKind; begin if KeyComp('While') then Result := tkKey else if KeyComp('Height') and IsQuali then Result := tkQualifier else if KeyComp('Goto') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func58: TtkTokenKind; begin if KeyComp('Exit') and IsQuali then Result := tkQualifier else if KeyComp('Exit') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func60: TtkTokenKind; begin if KeyComp('List') then Result := tkKey else if KeyComp('With') and IsQuali then Result := tkQualifier else if KeyComp('Trim') then Result := tkFunction else if KeyComp('Nobell') and IsQuali then Result := tkFunction else if KeyComp('Lheading') and IsQuali then Result := tkQualifier else if KeyComp('Remain') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func62: TtkTokenKind; begin if KeyComp('Right') then Result := tkFunction else if KeyComp('Pause') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func64: TtkTokenKind; begin if KeyComp('Width') and IsQuali then Result := tkQualifier else if KeyComp('Expand') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func65: TtkTokenKind; begin if KeyComp('Finish') then Result := tkKey else if KeyComp('Release') then Result := tkKey else if KeyComp('Random') then Result := tkKey else if KeyComp('Repeat') then begin if IsQuali then Result := tkQualifier else Result := tkKey; end else Result := tkIdentifier; end; function TmwDmlSyn.Func66: TtkTokenKind; begin if KeyComp('Rheading') and IsQuali then Result := tkQualifier else if KeyComp('Floor') then Result := tkKey else if KeyComp('Title') then begin if IsQuali then Result := tkQualifier else Result := tkKey; end else Result := tkIdentifier; end; function TmwDmlSyn.Func67: TtkTokenKind; begin if KeyComp('Unload') then Result := tkKey else if KeyComp('Receive') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func68: TtkTokenKind; begin if KeyComp('Total') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func69: TtkTokenKind; begin if KeyComp('Message') then Result := tkKey else if KeyComp('End_if') then Result := tkKey else if KeyComp('Text') then begin if IsSpecial then Result := tkSpecial else Result := tkKey; end else if KeyComp('End_if') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func70: TtkTokenKind; begin if KeyComp('Using') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func71: TtkTokenKind; begin if KeyComp('Target') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func72: TtkTokenKind; begin if KeyComp('First') and IsQuali then Result := tkQualifier else if KeyComp('Failure') then begin if IsQuali then Result := tkQualifier else if IsSpecial then Result := tkSpecial else Result := tkIdentifier; end else if KeyComp('Ltrim') then Result := tkFunction else if KeyComp('Round') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func73: TtkTokenKind; begin if KeyComp('Commit') then Result := tkKey else if KeyComp('Compile') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func74: TtkTokenKind; begin if KeyComp('Sqrt') then Result := tkFunction else if KeyComp('Error') then begin if IsQuali then Result := tkQualifier else Result := tkKey; end else if KeyComp('Rollback') then Result := tkKey else if KeyComp('Connect') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func75: TtkTokenKind; begin if KeyComp('Generate') then Result := tkKey else if KeyComp('Write') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func76: TtkTokenKind; begin if KeyComp('Invoke') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func77: TtkTokenKind; begin if KeyComp('Noerase') and IsQuali then Result := tkQualifier else if KeyComp('Noheading') and IsQuali then Result := tkQualifier else if KeyComp('Account') and IsSpecial then Result := tkSpecial else if KeyComp('Print') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func78: TtkTokenKind; begin if KeyComp('Confirm') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func79: TtkTokenKind; begin if KeyComp('Seconds') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func81: TtkTokenKind; begin if KeyComp('Source') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func82: TtkTokenKind; begin if KeyComp('End_case') then Result := tkKey else if KeyComp('Switch') and IsQuali then Result := tkQualifier else if KeyComp('Nowait') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func83: TtkTokenKind; begin if KeyComp('Execute') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func84: TtkTokenKind; begin if KeyComp('Trigger') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func85: TtkTokenKind; begin if KeyComp('Facility') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func86: TtkTokenKind; begin if KeyComp('Footing') and IsQuali then Result := tkQualifier else if KeyComp('Query') then Result := tkKey else if KeyComp('Display') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func87: TtkTokenKind; begin if KeyComp('String') then Result := tkFunction else if KeyComp('Else_if') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func89: TtkTokenKind; begin if KeyComp('Sequence') and IsQuali then Result := tkQualifier else if KeyComp('Success') then begin if IsQuali then Result := tkQualifier else if IsSpecial then Result := tkSpecial else Result := tkIdentifier; end else Result := tkIdentifier; end; function TmwDmlSyn.Func91: TtkTokenKind; begin if KeyComp('Perform') then Result := tkKey else if KeyComp('Use_if') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func92: TtkTokenKind; begin if KeyComp('Report') then Result := tkKey else if KeyComp('Add_form') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func93: TtkTokenKind; begin if KeyComp('Item_if') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func94: TtkTokenKind; begin if KeyComp('Norepeat') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func96: TtkTokenKind; begin if KeyComp('Begin_case') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func97: TtkTokenKind; begin if KeyComp('Protect') and IsQuali then Result := tkQualifier else if KeyComp('End_block') then Result := tkBlock else Result := tkIdentifier; end; function TmwDmlSyn.Func98: TtkTokenKind; begin if KeyComp('Lfooting') and IsQuali then Result := tkQualifier else if KeyComp('Prompt') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func99: TtkTokenKind; begin if KeyComp('Identifier') and IsQuali then Result := tkQualifier else if KeyComp('Send_data') then Result := tkKey else if KeyComp('Read_line') then Result := tkKey else if KeyComp('External') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func100: TtkTokenKind; begin if KeyComp('Status') then begin if IsQuali then Result := tkQualifier else if IsSpecial then Result := tkSpecial else Result := tkIdentifier; end else Result := tkIdentifier; end; function TmwDmlSyn.Func101: TtkTokenKind; begin if KeyComp('Continue') and IsQuali then Result := tkQualifier else if KeyComp('System') and IsQuali then Result := tkQualifier else if KeyComp('Transfer') then Result := tkKey else if KeyComp('Lowercase') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func102: TtkTokenKind; begin if KeyComp('Selection') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func103: TtkTokenKind; begin if KeyComp('Noerror') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func104: TtkTokenKind; begin if KeyComp('Secondary') and IsQuali then Result := tkQualifier else if KeyComp('Uppercase') then Result := tkFunction else if KeyComp('Rfooting') then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func106: TtkTokenKind; begin if KeyComp('End_form') then Result := tkForm else if KeyComp('Lov_data') and IsQuali then Result := tkQualifier else if KeyComp('Disconnect') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func108: TtkTokenKind; begin if KeyComp('Options') and IsQuali then Result := tkQualifier else if KeyComp('Compress') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func110: TtkTokenKind; begin if KeyComp('End_row') and IsQuali then Result := tkQualifier else if KeyComp('Lov_col') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func111: TtkTokenKind; begin if KeyComp('End_while') then Result := tkKey else if KeyComp('Begin_block') then Result := tkBlock else Result := tkIdentifier; end; function TmwDmlSyn.Func113: TtkTokenKind; begin if KeyComp('Send_table') then Result := tkKey else if KeyComp('Output') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func116: TtkTokenKind; begin if KeyComp('Find_form') and IsQuali then Result := tkQualifier else if KeyComp('Nototals') and IsSpecial then Result := tkSpecial else if KeyComp('No_domain') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func117: TtkTokenKind; begin if KeyComp('Check_domain') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func120: TtkTokenKind; begin if KeyComp('Statistic') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func121: TtkTokenKind; begin if KeyComp('Item_block') then Result := tkBlock else Result := tkIdentifier; end; function TmwDmlSyn.Func122: TtkTokenKind; begin if KeyComp('Top_line') and IsSpecial then Result := tkSpecial else Result := tkIdentifier; end; function TmwDmlSyn.Func123: TtkTokenKind; begin if KeyComp('Severity') and IsQuali then Result := tkQualifier else if KeyComp('Joined_to') and IsQuali then Result := tkQualifier else if KeyComp('Table_form') then Result := tkForm else Result := tkIdentifier; end; function TmwDmlSyn.Func124: TtkTokenKind; begin if KeyComp('Begin_row') and IsQuali then Result := tkQualifier else if KeyComp('Utilities') then Result := tkKey else if KeyComp('Receive_data') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func125: TtkTokenKind; begin if KeyComp('Read_only') and IsQuali then Result := tkQualifier else if KeyComp('Table_search') then Result := tkKey else if KeyComp('Tag_length') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func126: TtkTokenKind; begin if KeyComp('Reduced_to') and IsQuali then Result := tkQualifier else if KeyComp('Actual_break') and IsSpecial then Result := tkSpecial else Result := tkIdentifier; end; function TmwDmlSyn.Func127: TtkTokenKind; begin if KeyComp('Source_if') and IsQuali then Result := tkQualifier else if KeyComp('Menu_block') then Result := tkBlock else Result := tkIdentifier; end; function TmwDmlSyn.Func128: TtkTokenKind; begin if KeyComp('Clear_buffer') then Result := tkKey else if KeyComp('Default_tag') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func129: TtkTokenKind; begin if KeyComp('Nostatus') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func131: TtkTokenKind; begin if KeyComp('Heading_form') then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func132: TtkTokenKind; begin if KeyComp('Description') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func134: TtkTokenKind; begin if KeyComp('Delete_form') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func135: TtkTokenKind; begin if KeyComp('Nolov_data') and IsQuali then Result := tkQualifier else if KeyComp('Attributes') and IsQuali then Result := tkQualifier else if KeyComp('User_key') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func136: TtkTokenKind; begin if KeyComp('Menu_form') then Result := tkForm else if KeyComp('Pause_block') then Result := tkBlock else if KeyComp('Lov_row') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func137: TtkTokenKind; begin if KeyComp('Lov_height') and IsQuali then Result := tkQualifier else if KeyComp('End_execute') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func138: TtkTokenKind; begin if KeyComp('Receive_table') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func139: TtkTokenKind; begin if KeyComp('Sorted_by') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func140: TtkTokenKind; begin if KeyComp('Date_seconds') then Result := tkFunction else if KeyComp('Reposition') then Result := tkKey else if KeyComp('Switch_base') and IsQuali then Result := tkQualifier else if KeyComp('Lines_after') and IsQuali then Result := tkQualifier else if KeyComp('Lov_with') and IsQuali then Result := tkQualifier else if KeyComp('Lines_after') and IsSpecial then Result := tkSpecial else if KeyComp('Stream_name') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func141: TtkTokenKind; begin if KeyComp('Lines_before') and IsQuali then Result := tkQualifier else if KeyComp('Lines_after') and IsSpecial then Result := tkSpecial else Result := tkIdentifier; end; function TmwDmlSyn.Func142: TtkTokenKind; begin if KeyComp('Send_message') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func144: TtkTokenKind; begin if KeyComp('Grouped_by') and IsQuali then Result := tkQualifier else if KeyComp('Lov_width') and IsQuali then Result := tkQualifier else if KeyComp('Row_height') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func146: TtkTokenKind; begin if KeyComp('Write_line') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func148: TtkTokenKind; begin if KeyComp('Commit_rate') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func150: TtkTokenKind; begin if KeyComp('Open_text') then Result := tkKey else if KeyComp('Nounderlines') then begin if IsQuali then Result := tkQualifier else if IsSpecial then Result := tkSpecial else Result := tkIdentifier; end else Result := tkIdentifier; end; function TmwDmlSyn.Func152: TtkTokenKind; begin if KeyComp('Lov_first') and IsQuali then Result := tkQualifier else if KeyComp('Yesno_block') then Result := tkBlock else Result := tkIdentifier; end; function TmwDmlSyn.Func153: TtkTokenKind; begin if KeyComp('Tsuppress') and IsSpecial then Result := tkSpecial else Result := tkIdentifier; end; function TmwDmlSyn.Func154: TtkTokenKind; begin if KeyComp('Documentation') then Result := tkKey else if KeyComp('Input_block') then Result := tkBlock else if KeyComp('Close_text') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func155: TtkTokenKind; begin if KeyComp('Modify_form') and IsQuali then Result := tkQualifier else if KeyComp('Input_mask') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func156: TtkTokenKind; begin if KeyComp('Bottom_line') and IsSpecial then Result := tkSpecial else Result := tkIdentifier; end; function TmwDmlSyn.Func157: TtkTokenKind; begin if KeyComp('Lov_noheading') and IsQuali then Result := tkQualifier else if KeyComp('Noclear_buffer') and IsQuali then Result := tkQualifier else if KeyComp('Day_of_week') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func163: TtkTokenKind; begin if KeyComp('Lov_nosearch') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func164: TtkTokenKind; begin if KeyComp('Compress_all') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func166: TtkTokenKind; begin if KeyComp('Text_only') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func169: TtkTokenKind; begin if KeyComp('Query_form') then Result := tkForm else if KeyComp('Footing_form') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func173: TtkTokenKind; begin if KeyComp('Nodeadlock_exit') and IsQuali then Result := tkQualifier else if KeyComp('Rewind_text') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func174: TtkTokenKind; begin if KeyComp('Exit_forward') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func175: TtkTokenKind; begin if KeyComp('Report_form') then Result := tkForm else Result := tkIdentifier; end; function TmwDmlSyn.Func176: TtkTokenKind; begin if KeyComp('Column_headings') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func178: TtkTokenKind; begin if KeyComp('Column_spacing') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func179: TtkTokenKind; begin if KeyComp('Alternate_form') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func182: TtkTokenKind; begin if KeyComp('Lov_selection') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func183: TtkTokenKind; begin if KeyComp('Display_length') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func184: TtkTokenKind; begin if KeyComp('Lov_secondary') and IsQuali then Result := tkQualifier else if KeyComp('Cross_reference') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func185: TtkTokenKind; begin if KeyComp('Start_stream') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func187: TtkTokenKind; begin if KeyComp('Output_block') then Result := tkBlock else Result := tkIdentifier; end; function TmwDmlSyn.Func188: TtkTokenKind; begin if KeyComp('Output_mask') and IsQuali then Result := tkQualifier else if KeyComp('Procedure_form') then Result := tkForm else Result := tkIdentifier; end; function TmwDmlSyn.Func203: TtkTokenKind; begin if KeyComp('Noexit_forward') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func206: TtkTokenKind; begin if KeyComp('Lov_reduced_to') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func216: TtkTokenKind; begin if KeyComp('Receive_arguments') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func219: TtkTokenKind; begin if KeyComp('Lov_sorted_by') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func221: TtkTokenKind; begin if KeyComp('End_disable_trigger') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func232: TtkTokenKind; begin if KeyComp('Lov_auto_select') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func234: TtkTokenKind; begin if KeyComp('Binary_to_poly') then Result := tkFunction else if KeyComp('Poly_to_binary') then Result := tkFunction else Result := tkIdentifier; end; function TmwDmlSyn.Func235: TtkTokenKind; begin if KeyComp('Begin_disable_trigger') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func243: TtkTokenKind; begin if KeyComp('Start_transaction') then Result := tkKey else if KeyComp('Absolute_position') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func244: TtkTokenKind; begin if KeyComp('Column_heading_row') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func255: TtkTokenKind; begin if KeyComp('Input_row_height') and IsQuali then Result := tkQualifier else Result := tkIdentifier; end; function TmwDmlSyn.Func313: TtkTokenKind; begin if KeyComp('End_signal_to_status') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.Func327: TtkTokenKind; begin if KeyComp('Begin_signal_to_status') then Result := tkKey else Result := tkIdentifier; end; function TmwDmlSyn.AltFunc: TtkTokenKind; begin Result := tkIdentifier; end; function TmwDmlSyn.IdentKind(MayBe: PChar): TtkTokenKind; var HashKey: Integer; begin fToIdent := MayBe; HashKey := KeyHash(MayBe); if HashKey < 328 then Result := fIdentFuncTable[HashKey] else Result := tkIdentifier; end; procedure TmwDmlSyn.MakeMethodTables; var I: Char; begin for I := #0 to #255 do case I of #0: fProcTable[I] := NullProc; #10: fProcTable[I] := LFProc; #13: fProcTable[I] := CRProc; #1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc; '#': fProcTable[I] := AsciiCharProc; '"': fProcTable[I] := StringProc; '0'..'9': fProcTable[I] := NumberProc; 'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc; '{': fProcTable[I] := SymbolProc; '}': fProcTable[I] := SymbolProc; '!': fProcTable[I] := RemProc; '.': fProcTable[I] := PointProc; '<': fProcTable[I] := LowerProc; '>': fProcTable[I] := GreaterProc; '@': fProcTable[I] := AddressOpProc; #39, '&', '('..'-', '/', ':', ';', '=', '?', '['..'^', '`', '~': fProcTable[I] := SymbolProc; else fProcTable[I] := UnknownProc; end; end; constructor TmwDmlSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); fFormAttri:= TmwHighLightAttributes.Create(MWS_AttrForm); fFormAttri.Style:= [fsBold]; fFormAttri.Foreground:= clBlue; AddAttribute(fFormAttri); fBlockAttri:= TmwHighLightAttributes.Create(MWS_AttrBlock); fBlockAttri.Style:= [fsBold]; fBlockAttri.Foreground:= clGreen; AddAttribute(fBlockAttri); fKeyAttri := TmwHighLightAttributes.Create(MWS_AttrKey); fKeyAttri.Style:= [fsBold]; AddAttribute(fKeyAttri); fCommentAttri := TmwHighLightAttributes.Create(MWS_AttrComment); fCommentAttri.Style:= [fsBold]; fCommentAttri.Foreground:= clRed; AddAttribute(fCommentAttri); fQualiAttri:= TmwHighLightAttributes.Create(MWS_AttrQualifier); fQualiAttri.Style:= [fsItalic]; fQualiAttri.Foreground:= clGreen; AddAttribute(fQualiAttri); fFunctionAttri:= TmwHighLightAttributes.Create(MWS_AttrFunction); fFunctionAttri.Style:= [fsItalic]; fFunctionAttri.Foreground:= clBlack; AddAttribute(fFunctionAttri); fVariableAttri:= TmwHighLightAttributes.Create(MWS_AttrVariable); fVariableAttri.Style:= [fsBold, fsItalic]; fVariableAttri.Foreground:= clBlack; AddAttribute(fVariableAttri); fSpecialAttri:= TmwHighLightAttributes.Create(MWS_AttrSpecialVariable); fSpecialAttri.Style:= [fsItalic]; fSpecialAttri.Foreground:= clBlack; AddAttribute(fSpecialAttri); fIdentifierAttri := TmwHighLightAttributes.Create(MWS_AttrIdentifier); AddAttribute(fIdentifierAttri); fNumberAttri := TmwHighLightAttributes.Create(MWS_AttrNumber); AddAttribute(fNumberAttri); fSpaceAttri := TmwHighLightAttributes.Create(MWS_AttrSpace); AddAttribute(fSpaceAttri); fStringAttri := TmwHighLightAttributes.Create(MWS_AttrString); AddAttribute(fStringAttri); fSymbolAttri := TmwHighLightAttributes.Create(MWS_AttrSymbol); AddAttribute(fSymbolAttri); SetAttributesOnChange(DefHighlightChange); InitIdent; MakeMethodTables; fRange := rsUnknown; fDefaultFilter := MWS_FilterGembase; end; procedure TmwDmlSyn.SetLine(NewValue: String; LineNumber:Integer); begin fLine := PChar(NewValue); Run := 0; fLineNumber := LineNumber; Next; end; procedure TmwDmlSyn.AddressOpProc; begin fTokenID := tkSymbol; Inc(Run); if fLine[Run] = '@' then Inc(Run); end; procedure TmwDmlSyn.AsciiCharProc; begin // variables... fTokenID := tkVariable; repeat inc(Run); until not (FLine[Run] in ['_', '0'..'9', 'a'..'z', 'A'..'Z']); end; procedure TmwDmlSyn.SymbolProc; begin inc(Run); fTokenId := tkSymbol; end; procedure TmwDmlSyn.CRProc; begin fTokenID := tkSpace; inc(Run); if FLine[Run] = #10 then inc(Run); end; procedure TmwDmlSyn.GreaterProc; begin fTokenID := tkSymbol; Inc(Run); if FLine[Run] = '=' then Inc(Run); end; procedure TmwDmlSyn.IdentProc; begin fTokenID := IdentKind((fLine + Run)); inc(Run, fStringLen); while Identifiers[fLine[Run]] do inc(Run); end; procedure TmwDmlSyn.LFProc; begin fTokenID := tkSpace; inc(Run); end; procedure TmwDmlSyn.LowerProc; begin fTokenID := tkSymbol; inc(Run); if (fLine[Run]= '=') or (fLine[Run]= '>') then Inc(Run); end; procedure TmwDmlSyn.NullProc; begin fTokenID := tkNull; end; procedure TmwDmlSyn.NumberProc; begin inc(Run); fTokenID := tkNumber; while FLine[Run] in ['0'..'9', '.'] do begin case FLine[Run] of '.': if FLine[Run + 1] = '.' then break; end; inc(Run); end; end; procedure TmwDmlSyn.PointProc; begin fTokenID := tkSymbol; inc(Run); if (fLine[Run]='.') or (fLine[Run]=')') then inc(Run); end; procedure TmwDmlSyn.RemProc; var p: PChar; begin p := PChar(@fLine[Run - 1]); while p >= fLine do begin if not (p^ in [#9, #32]) then begin inc(Run); fTokenID := tkSymbol; exit; end; Dec(p); end; // it is a comment... fTokenID := tkComment; p := PChar(@fLine[Run]); repeat Inc(p); until p^ in [#0, #10, #13]; Run := p - fLine; end; procedure TmwDmlSyn.SpaceProc; var p: PChar; begin fTokenID := tkSpace; p := PChar(@fLine[Run]); repeat Inc(p); until (p^ > #32) or (p^ in [#0, #10, #13]); Run := p - fLine; end; procedure TmwDmlSyn.StringProc; begin fTokenID := tkString; if (FLine[Run + 1] = '"') and (FLine[Run + 2] = '"') then inc(Run, 2); repeat inc(Run); until (FLine[Run] in ['"', #0, #10, #13]); if FLine[Run] <> #0 then inc(Run); end; procedure TmwDmlSyn.UnknownProc; begin inc(Run); fTokenID := tkUnknown; end; procedure TmwDmlSyn.Next; begin fTokenPos := Run; fProcTable[fLine[Run]]; end; function TmwDmlSyn.GetEol: Boolean; begin Result := fTokenID = tkNull; end; function TmwDmlSyn.GetToken: String; var Len: LongInt; begin Len := Run - fTokenPos; SetString(Result, (FLine + fTokenPos), Len); end; function TmwDmlSyn.GetTokenID: TtkTokenKind; begin Result:= fTokenId; end; function TmwDmlSyn.GetTokenAttribute: TmwHighLightAttributes; begin case GetTokenID of tkForm: Result := fFormAttri; tkBlock: Result := fBlockAttri; tkKey: Result := fKeyAttri; tkComment: Result := fCommentAttri; tkQualifier: Result := fQualiAttri; tkFunction: Result := fFunctionAttri; tkIdentifier: Result := fIdentifierAttri; tkNumber: Result := fNumberAttri; tkSpecial: Result := fSpecialAttri; tkSpace: Result := fSpaceAttri; tkString: Result := fStringAttri; tkVariable: Result := fVariableAttri; tkSymbol: Result := fSymbolAttri; tkUnknown: Result := fSymbolAttri; else Result := nil; end; end; function TmwDmlSyn.GetTokenKind: integer; begin Result := Ord(GetTokenID); end; function TmwDmlSyn.GetTokenPos: Integer; begin Result := fTokenPos; end; function TmwDmlSyn.GetRange: Pointer; begin Result := Pointer(fRange); end; procedure TmwDmlSyn.SetRange(Value: Pointer); begin fRange := TRangeState(Value); end; procedure TmwDmlSyn.ReSetRange; begin fRange:= rsUnknown; end; function TmwDmlSyn.GetLanguageName: string; begin Result := MWS_LangGembase; end; function TmwDmlSyn.GetIdentChars: TIdentChars; begin Result := ['_', '0'..'9', 'a'..'z', 'A'..'Z']; end; function TmwDmlSyn.GetCapability: THighlighterCapability; begin Result := inherited GetCapability + [hcUserSettings]; end; procedure TmwDmlSyn.SetLineForExport(NewValue: String); begin fLine := PChar(NewValue); Run := 0; ExportNext; end; procedure TmwDmlSyn.ExportNext; begin fTokenPos := Run; fProcTable[fLine[Run]]; if Assigned(Exporter) then with TmwCustomExport(Exporter) do begin Case GetTokenID of tkBlock: FormatToken(GetToken, fBlockAttri, False, False); tkComment: FormatToken(GetToken, fCommentAttri, True, False); tkForm: FormatToken(GetToken, fFormAttri, False,False); tkKey: FormatToken(GetToken, fKeyAttri, False,False); tkQualifier: FormatToken(GetToken, fQualiAttri, False,False); tkFunction: FormatToken(GetToken, fFunctionAttri, False,False); tkVariable: FormatToken(GetToken, fVariableAttri, False,False); tkString: FormatToken(GetToken, fStringAttri, True,False); tkIdentifier: FormatToken(GetToken, fIdentifierAttri, False,False); tkNumber: FormatToken(GetToken, fNumberAttri, False,False); tkSpecial: FormatToken(GetToken, fSpecialAttri, False,False); tkSpace: FormatToken(GetToken, fSpaceAttri, False,True); tkSymbol: FormatToken(GetToken, fSymbolAttri, False,False); end; end; //with end; initialization MakeIdentTable; end.
interface uses Windows, Forms, Classes, Controls, Messages, Graphics, SysUtils; const cvNone = -1; cvBlack = 0; cvMaroon = 1; cvGreen = 2; cvOlive = 3; cvNavy = 4; cvPurple = 5; cvTeal = 6; cvGray = 7; cvSilver = 8; cvRed = 9; cvLime = 10; cvYellow = 11; cvBlue = 12; cvFuchsia = 13; cvAqua = 14; cvWhite = 15; cvHighColor = 8; cvLowColor = 7; cvBlink = 128; SymbolSet: set of Char = [' ','-'(*,'.',',','!','-',')','}',']',':',';','>'*)]; MaxLineLen: Integer = 1000; WM_MOUSEWHEEL = $020A; type TColorTable = array[0..15] of TColor; TFollowMode = (cfOff, cfOn, cfAuto); TChatView = class(TCustomControl) private fCharHeight: Integer; fCharWidth: Integer; fFontAttr: TFontStyles; fNeedScrollUpdate: Boolean; fTopLine: Integer; // Number of first visible line fLeftChar: Integer; fLineCount: Integer; // Number of lines in window fWidthCount: Integer; // Width in characters fLines: TStringList; fFollowMode: TFollowMode; fSeenLine: Integer; // Used for UserActivity (Auto-Follow) fLastTime: TTimeStamp; fXOffset: Integer; fClientWidth: Integer; fMaxLines: Integer; fBoldMode, fBlinkMode: Boolean; fBlinkOn: Byte; { 0 = paintall, 1 = paintnormal, 2 = painthidden } fFgColor, fBkColor: Byte; fBlinkFont: Boolean; // used by DoPaint fColorTable: TColorTable; fUpdateLock: Integer; fMouseWheelAccumulator: integer; fSelected: Boolean; procedure PaintLine(Line, Location: Integer); procedure WMHScroll(var Message: TWMScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMScroll); message WM_VSCROLL; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; procedure WMMouseWheel(var Msg: TMessage); message WM_MOUSEWHEEL; procedure UpdateScrollBars; function GetColor: Byte; procedure SetAttrs(const S: string); function GetAnsiMode(S: string): string; procedure SetFontColor(C: Byte); procedure DoScroll; procedure DelLine(I: Integer); function IsAway: Boolean; procedure FontChange(Sender: TObject); procedure DoPaint; function SkipFont(Line: Integer; S: string): string; public fSelStart: TPoint; fSelEnd: TPoint; AnsiColors: Boolean; AutoAwayTime: Integer; // Time in seconds WordWrap: Integer; ClientFollow: TFollowMode; NormalFg: Byte; NormalBg: Byte; constructor Create(AOwner: TComponent); override; procedure SizeOrFontChanged; procedure Paint; override; (*procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;*) procedure UserActivity; // Called when useractivity is detected (eg keypress) procedure AddLine(S: string); procedure SetTopLine(Value: Integer); procedure SetLeftChar(Value: Integer); procedure BeginUpdate; procedure EndUpdate; procedure Clear; procedure ChangeFont(AFont: TFont); procedure SetColor(Nr: Byte; Color: TColor); procedure DoColor(Fg, Bk: Byte); procedure DoBlink(BlinkOn: Boolean); procedure ScrollPageUp; procedure ScrollPageDown; property TopLine: Integer read fTopLine write SetTopLine; property LeftChar: Integer read fLeftChar write SetLeftChar; property MaxLines: Integer read fMaxLines write fMaxLines; property ColorTable: TColorTable read fColorTable write fColorTable; property LineLen: Integer read fCharWidth; published property FollowMode: TFollowMode read fFollowMode write fFollowMode; property Font; protected procedure CreateParams(var Params: TCreateParams); override; end; function DoColor(Fg, Bk: Byte): string; implementation function DoColor(Fg, Bk: Byte): string; begin Result:=#27'[0;'; if Fg and cvHighColor>0 then Result:=Result+'1;'; if Bk and cvBlink>0 then Result:=Result+'5;'; Result:=Result+IntToStr((Fg and cvLowColor)+30)+';'+IntToStr((Bk and cvLowColor)+40)+'m'; end; constructor TChatView.Create(AOwner: TComponent); begin inherited Create(AOwner); AnsiColors:=True; AutoAwayTime:=0; //AutoAwayTime:=10; fMaxLines:=500; fTopLine:=0; fLeftChar:=0; fFollowMode:=cfAuto; fSeenLine:=0; fXOffset:=3; Font.Name:='Courier New'; Font.Size:=10; fNeedScrollUpdate:=True; fLines:=TStringList.Create; fUpdateLock:=0; NormalFg:=cvGray; NormalBg:=cvBlack; fBoldMode:=False; fFgColor:=NormalFg; fBkColor:=NormalBg; fBlinkMode:=False; fColorTable[cvBlack]:=clBlack; fColorTable[cvMaroon]:=clMaroon; fColorTable[cvGreen]:=clGreen; fColorTable[cvOlive]:=clOlive; fColorTable[cvNavy]:=clNavy; fColorTable[cvPurple]:=clPurple; fColorTable[cvTeal]:=clTeal; fColorTable[cvGray]:=clGray; fColorTable[cvSilver]:=clSilver; fColorTable[cvRed]:=clRed; fColorTable[cvLime]:=clLime; fColorTable[cvYellow]:=clYellow; fColorTable[cvBlue]:=clBlue; fColorTable[cvFuchsia]:=clFuchsia; fColorTable[cvAqua]:=clAqua; fColorTable[cvWhite]:=clWhite; Font.Color:=ColorTable[NormalFg]; Color:=ColorTable[NormalBg]; Font.OnChange:=FontChange; WordWrap:=1; fSelected:=False; fSelStart.X:=-1; fSelEnd.X:=-1; fSelStart.Y:=-1; fSelEnd.Y:=-1; end; procedure TChatView.DoColor(Fg, Bk: Byte); begin fBlinkMode:=Bk and cvHighColor>0; fBoldMode:=Fg and cvHighColor>0; fFgColor:=Fg and cvLowColor; fBkColor:=Bk and cvLowColor; end; procedure TChatView.SetColor(Nr: Byte; Color: TColor); begin fColorTable[Nr]:=Color; end; procedure TChatView.Clear; begin BeginUpdate; fLines.Clear; fSeenLine:=0; fTopLine:=0; fNeedScrollUpdate:=True; EndUpdate; end; procedure TChatView.BeginUpdate; begin Inc(fUpdateLock); fLines.BeginUpdate; end; procedure TChatView.EndUpdate; begin fLines.EndUpdate; Dec(fUpdateLock); if fUpdateLock=0 then Invalidate;//Repaint; end; function TChatView.IsAway: Boolean; begin Result:=Int64(DateTimeToTimeStamp(Now))-Int64(fLastTime)>(AutoAwayTime*1000); end; procedure TChatView.UserActivity; begin fLastTime:=DateTimeToTimeStamp(Now); fSeenLine:=fLines.Count-1; end; function TChatView.GetColor: Byte; begin if fBoldMode then fFgColor:=fFgColor or cvHighColor else fFgColor:=fFgColor and cvLowColor; fBkColor:=fBkColor and cvLowColor; if fBlinkMode then Result:=(fFgColor+(fBkColor shl 4)) or cvBlink else Result:=fFgColor+(fBkColor shl 4); end; procedure TChatView.SetAttrs(const S: string); var Temp: Byte; begin // Misc if S='0' then begin DoColor(NormalFg,NormalBg); {fFgColor:=cvNormalFg; fBkColor:=cvNormalBg; fBoldMode:=False; fBlinkMode:=False;} end; if S='1' then fBoldMode:=True; if S='5' then fBlinkMode:=True; if S='7' then begin Temp:=fFgColor; fFgColor:=fBkColor; fBkColor:=Temp; end; // Foreground if S='30' then fFgColor:=cvBlack; if S='31' then fFgColor:=cvMaroon; if S='32' then fFgColor:=cvGreen; if S='33' then fFgColor:=cvOlive; if S='34' then fFgColor:=cvNavy; if S='35' then fFgColor:=cvPurple; if S='36' then fFgColor:=cvTeal; if S='37' then fFgColor:=cvGray; // Background if S='40' then fBkColor:=cvBlack; if S='41' then fBkColor:=cvMaroon; if S='42' then fBkColor:=cvGreen; if S='43' then fBkColor:=cvOlive; if S='44' then fBkColor:=cvNavy; if S='45' then fBkColor:=cvPurple; if S='46' then fBkColor:=cvTeal; if S='47' then fBkColor:=cvGray; end; function TChatView.GetAnsiMode(S: string): string; var P: Integer; begin Result:=''; repeat P:=Pos(';',S); if P>0 then begin SetAttrs(Copy(S,1,P-1)); S:=Copy(S,P+1,Length(S)); end; until P=0; SetAttrs(S); Result:=#254+Chr(GetColor); end; procedure TChatView.DelLine(I: Integer); begin if (I<0) or (I>=fLines.Count) then Exit; fLines.Delete(I); Dec(fSeenLine); if fSeenLine<0 then fSeenLine:=0; Dec(fTopLine); if fTopLine<0 then fTopLine:=0; end; procedure TChatView.AddLine(S: string); var I, Mode, LineStart, LineColor, TokenStart, BreakPos, RealLen: Integer; begin { TODO -omartin -cchatview : Linelen sjekken } { TODO -omartin -cchatview : Tabs implementeren } BeginUpdate; Mode:=0; RealLen:=0; BreakPos:=1; TokenStart:=1; LineStart:=1; LineColor:=GetColor; I:=1; S:=S+' '; // Trick to get simple wordwrap while I<=Length(S) do begin if Mode=1 then // Ansi color if S[I]='[' then begin Mode:=2; TokenStart:=I+1; end else Mode:=0 else if Mode=2 then begin if S[I]='m' then // End of ansi color begin S:=Copy(S,1,TokenStart-3) +GetAnsiMode(Copy(S,TokenStart,I-TokenStart)) +Copy(S,I+1,Length(S)); I:=TokenStart-1; Mode:=0; end end else if (S[I]=#27) and AnsiColors then Mode:=1 else if (S[I] in [#7]) then begin S:=Copy(S,1,I-1)+Copy(S,I+1,Length(S)); Dec(I); end else begin Inc(RealLen); if S[I] in SymbolSet then BreakPos:=I; if (WordWrap>0) and (((S[I]=' ') and (RealLen>fWidthCount)) or (RealLen>=fWidthCount)) then // Wordwrap begin fLines.AddObject(Copy(S,LineStart,BreakPos-LineStart+1),Pointer(LineColor)); DoScroll; LineStart:=BreakPos+1; LineColor:=GetColor; RealLen:=0; BreakPos:=I; end; end; Inc(I); end; fLines.AddObject(Copy(S,LineStart,I-LineStart+1),Pointer(LineColor)); while fLines.Count>MaxLines do DelLine(0); DoScroll; EndUpdate; end; (*procedure TChatView.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited SetBounds(ALeft, ATop, AWidth, AHeight); fNeedScrollUpdate:=True; end;*) procedure TChatView.SizeOrFontChanged; begin // Initialize canvas Canvas.Font.Assign(Font); Canvas.Brush.Color:=Color; // Initialize vars fCharHeight:=Canvas.TextHeight('H'); fCharWidth:=Abs(Canvas.TextWidth('W')); fFontAttr:=Font.Style; fClientWidth:=ClientWidth; fLineCount:=Trunc(ClientHeight/fCharHeight); fWidthCount:=Trunc((fClientWidth-fXOffset)/fCharWidth); Canvas.Brush.Color:=Color; Canvas.FillRect(ClientRect); Repaint; fNeedScrollUpdate:=True; end; procedure TChatView.UpdateScrollBars; var ScrollInfo: TScrollInfo; begin // Show scrollbars ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.fMask := SIF_ALL or SIF_DISABLENOSCROLL; ScrollInfo.nMin := 0; ScrollInfo.nTrackPos := 0; ScrollInfo.nMax := fLines.Count-1; ScrollInfo.nPage := fLineCount; ScrollInfo.nPos := fTopLine; SetScrollInfo(Handle, SB_VERT, ScrollInfo, True); ScrollInfo.nMax := MaxLineLen; ScrollInfo.nPage := fWidthCount; ScrollInfo.nPos := fLeftChar; SetScrollInfo(Handle, SB_HORZ, ScrollInfo, True); fNeedScrollUpdate:=False; end; procedure TChatView.DoScroll; var TL: Integer; begin fNeedScrollUpdate:=True; if fFollowMode=cfOff then Exit; if (fLines.Count>fLineCount) then if (fFollowMode=cfAuto) and (fTopLine<fLines.Count-fLineCount-1) then Exit; TL:=fLines.Count-fLineCount; if fFollowMode=cfAuto then if not IsAway then fSeenLine:=fLines.Count-1 else if (TL>fSeenLine) then TL:=fSeenLine; if TL<0 then TL:=0; if TopLine<TL then TopLine:=TL; end; procedure TChatView.SetFontColor(C: Byte); begin fBlinkFont:=C and cvBlink>0; if fBlinkFont and (fBlinkOn=2) then Canvas.Font.Color:=fColorTable[(C shr 4) and cvLowColor] else Canvas.Font.Color:=fColorTable[C and 15]; Canvas.Brush.Color:=fColorTable[(C shr 4) and cvLowColor]; end; function TChatView.SkipFont(Line: Integer; S: string): string; var W, I, L: Integer; begin L:=Length(S); I:=1; W:=0; while I<=L do begin if S[I]=#254 then begin Inc(I); if I<=L then SetFontColor(Ord(S[I])); end else begin Inc(W); if W>=fLeftChar then begin Result:=Copy(S,I+1,L); Exit; end; end; Inc(I); end; Result:=''; end; procedure TChatView.PaintLine(Line, Location: Integer); var R: TRect; P, I, L, E, X: Integer; S: string; C: TColor; SwapColors: Boolean; begin if (Line<0) or (Location<0) then Exit; R.Top:=Location*fCharHeight; R.Bottom:=R.Top+fCharHeight; if Line>=fLines.Count then begin Canvas.Brush.Color:=fColorTable[NormalBg]; R.Left:=0; R.Right:=fClientWidth; if fBlinkOn=0 then Canvas.FillRect(R); end else begin Canvas.Brush.Color:=fColorTable[NormalBg]; R.Left:=0; R.Right:=fXOffset; if fBlinkOn=0 then Canvas.FillRect(R); Canvas.MoveTo(fXOffset,R.Top); SetFontColor(Integer(fLines.Objects[Line])); S:=fLines[Line]; if fLeftChar>0 then S:=SkipFont(Line, S); if (Line<fSelStart.Y) or (Line>fSelEnd.Y) then SwapColors:=False else if (Line>fSelStart.Y) and (Line<fSelEnd.Y) then SwapColors:=True else if (fSelStart.Y=fSelEnd.Y) then SwapColors:=(fLeftChar>=fSelStart.X) and (fLeftChar-1<=fSelEnd.X) else if Line=fSelStart.Y then SwapColors:=fLeftChar>=fSelStart.X else SwapColors:=fLeftChar-1<=fSelEnd.X; if SwapColors then begin C:=Canvas.Font.Color; Canvas.Font.Color:=Canvas.Brush.Color; Canvas.Brush.Color:=C; end; { if ((Line>fSelStart.Y) and (Line<fSelEnd.Y)) or ((Line=fSelStart.Y) and (fLeftChar>=fSelStart.X)) or ((Line=fSelEnd.Y) and (fLeftChar<fSelEnd.X)) then // Swap colors: begin C:=Canvas.Font.Color; Canvas.Font.Color:=Canvas.Brush.Color; Canvas.Brush.Color:=C; end;} P:=1; X:=0; L:=Length(S); repeat I:=P; while (I<L) and (S[I]<>#254) and (not ((Line=fSelStart.Y) and (I=fSelStart.X))) and (not ((Line=fSelEnd.Y) and (I=fSelEnd.X))) do begin Inc(I); if S[I]<>#254 then Inc(X); end; if I<=L then begin if S[I]=#254 then E:=0 else E:=1; if (fBlinkOn=0) or fBlinkFont then Canvas.TextOut(Canvas.PenPos.X,R.Top,Copy(S,P,I-P+E)) else Canvas.MoveTo(Canvas.PenPos.X+Canvas.TextWidth(Copy(S,P,I-P+E)),Canvas.PenPos.Y); if (Line<fSelStart.Y) or (Line>fSelEnd.Y) then SwapColors:=False else if (Line>fSelStart.Y) and (Line<fSelEnd.Y) then SwapColors:=True else if (fSelStart.Y=fSelEnd.Y) then SwapColors:=(X>=fSelStart.X) and (X-1<=fSelEnd.X) else if Line=fSelStart.Y then SwapColors:=X>=fSelStart.X else SwapColors:=X-1<=fSelEnd.X; // SwapColors:=((Line>fSelStart.Y) and (Line<fSelEnd.Y)) or // ((Line=fSelStart.Y) and (I>=fSelStart.X)); // if (Line=fSelEnd.Y) and (I>=fSelEnd.X) then SwapColors:=False; if S[I]=#254 then begin SetFontColor(Ord(S[I+1])); P:=I+2; Inc(I,2); end else begin P:=I+1; Inc(I); end; if SwapColors then begin C:=Canvas.Font.Color; Canvas.Font.Color:=Canvas.Brush.Color; Canvas.Brush.Color:=C; end; end; if Canvas.PenPos.X>fClientWidth then Break; until I>=L; if ((fBlinkOn=0) or fBlinkFont) and (Canvas.PenPos.X<fClientWidth) then Canvas.TextOut(Canvas.PenPos.X,R.Top,Copy(S,P,Length(S))); R.Left:=Canvas.PenPos.X; R.Right:=fClientWidth; if fBlinkOn=0 then Canvas.FillRect(R); end; end; procedure TChatView.Paint; begin fBlinkOn:=0; DoPaint; end; procedure TChatView.DoBlink(BlinkOn: Boolean); begin if BlinkOn then fBlinkOn:=1 else fBlinkOn:=2; DoPaint; fBlinkOn:=0; end; procedure TChatView.DoPaint; var I, Start, Stop: Integer; begin if fUpdateLock>0 then Exit; if fNeedScrollUpdate then UpdateScrollBars; Start:=Canvas.ClipRect.Top div fCharHeight; Stop:=(Canvas.ClipRect.Bottom div fCharHeight)+1; for I:=Start to Stop do PaintLine(I+fTopLine,I); end; procedure TChatView.SetTopLine(Value: Integer); //var // Delta: Integer; begin if Value>=fLines.Count then Value:=fLines.Count-1; if Value<0 then Value:=0; if Value <> fTopLine then begin // Delta := fTopLine - Value; fTopLine := Value; // if Abs(Delta) < fLineCount then // ScrollWindow(Handle, 0, fCharHeight * Delta, nil, nil) // else Invalidate; fNeedScrollUpdate:=True; end; end; procedure TChatView.SetLeftChar(Value: Integer); begin if Value>MaxLineLen then Value:=MaxLineLen; if Value<0 then Value:=0; if Value <> fLeftChar then begin fLeftChar := Value; Invalidate; fNeedScrollUpdate:=True; end; end; procedure TChatView.ScrollPageUp; begin TopLine:=TopLine-(fLineCount div 2); end; procedure TChatView.ScrollPageDown; begin TopLine:=TopLine+(fLineCount div 2); end; procedure TChatView.WMHScroll(var Message: TWMScroll); begin case Message.ScrollCode of // Scrolls to start / end of the line SB_TOP: LeftChar := 1; SB_BOTTOM: LeftChar := MaxLineLen-fWidthCount; // Scrolls one char left / right SB_LINEDOWN: LeftChar := LeftChar + 1; SB_LINEUP: LeftChar := LeftChar - 1; // Scrolls one page of chars left / right SB_PAGEDOWN: LeftChar := LeftChar + (fWidthCount div 2); SB_PAGEUP: LeftChar := LeftChar - (fWidthCount div 2); // Scrolls to the current scroll bar position SB_THUMBPOSITION, SB_THUMBTRACK: LeftChar := Message.Pos; // Ends scroll = do nothing end; Update; UserActivity; end; procedure TChatView.WMVScroll(var Message: TWMScroll); begin UserActivity; case Message.ScrollCode of // Scrolls to start / end of the text SB_TOP: TopLine := 0; SB_BOTTOM: TopLine := fLines.Count-1; // Scrolls one line up / down SB_LINEDOWN: TopLine := TopLine + 1; SB_LINEUP: TopLine := TopLine - 1; // Scrolls one page of lines up / down SB_PAGEDOWN: TopLine := TopLine + (fLineCount div 2); SB_PAGEUP: TopLine := TopLine - (fLineCount div 2); // Scrolls to the current scroll bar position SB_THUMBPOSITION, SB_THUMBTRACK: TopLine := Message.Pos; // Ends scrolling SB_ENDSCROLL: end; Update; UserActivity; end; procedure TChatView.WMSize(var Message: TWMSize); begin inherited; SizeOrFontChanged; end; procedure TChatView.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_VSCROLL or WS_HSCROLL or WS_CLIPCHILDREN; if NewStyleControls and Ctl3D then begin Style := Style and not WS_BORDER; ExStyle := ExStyle or WS_EX_CLIENTEDGE; end; end; end; procedure TChatView.WMEraseBkgnd(var Message: TMessage); begin Message.Result:=1; end; procedure TChatView.ChangeFont(AFont: TFont); begin Font.Assign(AFont); SizeOrFontChanged; end; procedure TChatView.FontChange(Sender: TObject); begin SizeOrFontChanged; end; procedure TChatView.WMMouseWheel(var Msg: TMessage); var nDelta: integer; nWheelClicks: integer; begin if GetKeyState(VK_CONTROL) >= 0 then nDelta := Mouse.WheelScrollLines else nDelta := fLineCount div 2; Inc(fMouseWheelAccumulator, SmallInt(Msg.wParamHi)); nWheelClicks := fMouseWheelAccumulator div WHEEL_DELTA; fMouseWheelAccumulator := fMouseWheelAccumulator mod WHEEL_DELTA; if (nDelta = integer(WHEEL_PAGESCROLL)) or (nDelta > fLineCount) then nDelta := fLineCount; TopLine := TopLine - (nDelta * nWheelClicks); // Update; end;
unit VisibleDSA.MazeData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils.UString; type TArr2D_int = array of array of integer; TArr2D_chr = array of array of UChar; TArr2D_bool = array of array of boolean; TMazeData = class(TObject) const ROAD: UChar = ' '; WALL: UChar = '#'; FILE_NAME: UString = '..\..\..\..\..\Resources\maze_01.txt'; private _n: integer; _m: integer; _entranceX: integer; _entranceY: integer; _exitX: integer; _exitY: integer; _maze: TArr2D_chr; public Path: TArr2D_bool; Visited: TArr2D_bool; constructor Create(fileName: UString); destructor Destroy; override; function GetMaze(i, j: integer): UChar; function InArea(x, y: integer): boolean; procedure PrintMaze; property N: integer read _N; property M: integer read _M; property EntranceX: integer read _entranceX; property EntranceY: integer read _entranceY; property ExitX: integer read _exitX; property ExitY: integer read _exitY; end; implementation { TMazeData } constructor TMazeData.Create(fileName: UString); var strList: TStringList; line: UString; i, j: integer; begin strList := TStringList.Create; try strList.LoadFromFile(string(fileName)); _n := strList.Count; _m := UString(strList[0]).Length; SetLength(_maze, N, M); SetLength(Path, N, M); SetLength(Visited, N, M); for i := 0 to N - 1 do begin line := UString(strList[i]); for j := 0 to line.Length - 1 do _maze[i, j] := line.Chars[j]; end; _entranceX := 1; _entranceY := 0; _exitX := N - 2; _exitY := M - 1; finally FreeAndNil(strList); end; end; destructor TMazeData.Destroy; begin inherited Destroy; end; function TMazeData.GetMaze(i, j: integer): UChar; begin if not InArea(i, j) then raise Exception.Create('i or j is out of index in getMaze!'); Result := _maze[i, j]; end; function TMazeData.InArea(x, y: integer): boolean; begin Result := (x >= 0) and (x < N) and (y >= 0) and (y < M); end; procedure TMazeData.PrintMaze; var i, j: integer; begin for i := 0 to High(_maze) do begin for j := 0 to High(_maze[i]) do begin Write(_maze[i, j]); end; WriteLn; end; end; end.
unit vga256; interface uses Crt,Dos; type ColorValue = record Rvalue,Gvalue,Bvalue: byte; end; vgaPaletteType = array [0..255] of ColorValue; procedure InitVGA256; procedure CloseVGA256; procedure vgaPutPixel(x,y: integer; c: byte); function vgaGetPixel(x,y: integer): byte; procedure vgaSetAllPalette(var p: vgaPaletteType); implementation procedure InitVGA256; begin { procedure InitVGA256 } Inline($B8/$13/0/$CD/$10); end; { procedure InitVGA256 } procedure CloseVGA256; begin { procedure CloseVGA256 } TextMode(LastMode); end; { procedure CloseVGA256 } procedure vgaPutPixel(x,y: integer; c: byte); begin { procedure vgaPutPixel } Mem[$A000:word(320*y+x)]:=c; end; { procedure vgaPutPixel } function vgaGetPixel(x,y: integer): byte; begin { function vgaGetPixel } vgaGetPixel:=Mem[$A000:word(320*y+x)]; end; { function vgaGetPixel } procedure vgaSetAllPalette(var p: vgaPaletteType); var regs: Registers; begin { procedure vgaSetAllPalette } with regs do begin AX:=$1012; BX:=0; CX:=256; ES:=Seg(p); DX:=Ofs(p); end; Intr($10,regs); end; { procedure vgaSetAllPalette } end.
unit XLSStream; { ******************************************************************************** ******* XLSReadWriteII V1.15 ******* ******* ******* ******* Copyright(C) 1999,2004 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} interface uses SysUtils, Classes, BIFFRecsII, Windows, ComObj, ActiveX, Math, XLSRWIIResourceStrings, XLSUtils; type PExtraData = ^TExtraData; TExtraData = record Name: PWideChar; LockBytes: ILockBytes; Storage: IStorage; end; type PExtraStreamData = ^TExtraStreamData; TExtraStreamData = record Name: PWideChar; Size: integer; Data: PByteArray; end; type TExtraObjects = class(TList) private FStreams: TList; function GetItems(Index: integer): PExtraData; public constructor Create; destructor Destroy; override; procedure Add(Name: PWideChar; LockBytes: ILockBytes; Storage: IStorage); procedure AddStream(Name: PWideChar; Size: integer); procedure ReadStreams(Storage: IStorage); procedure WriteStreams(Storage: IStorage); procedure Clear; override; property Items[Index: integer]: PExtraData read GetItems; default; end; type TXLSStream = class(TObject) private OleStorage: IStorage; OleStream: IStream; FStream: TStream; FTargetStream: TStream; FLockBytes: ILockBytes; FStreamSize: integer; FWrittenBytes: integer; FWriteCONTINUEPos: integer; FReadCONTINUEPos: integer; FReadCONTINUEActive: boolean; FMaxBytesWrite: integer; FExtraObjects: TExtraObjects; FSaveVBA: boolean; FISAPIRead: boolean; function OpenOleStreamRead(Filename: PWideChar): TExcelVersion; function OpenFileStreamRead(const Filename: string): TExcelVersion; function IntWrite(const Buffer; Count: Longint): longint; procedure WriteStorageToDestStream; procedure ReadVBA(Name: PWideChar); public constructor Create; destructor Destroy; override; function OpenRead(const Filename: string): TExcelVersion; procedure OpenWrite(const Filename: string; Version: TExcelVersion); function Read(var Buffer; Count: Longint): longint; function ReadHeader(var Header: TBIFFHeader): integer; function Write(const Buffer; Count: Longint): longint; procedure WriteHeader(RecId: word; Length: word); procedure WriteBufHeader(const Buffer; RecId: word; Length: word); procedure WriteWord(RecId: word; Value: word); procedure WWord(Value: word); procedure WByte(Value: byte); procedure WStr2ByteLen(Value: string); procedure WriteUnicodeStr16(Value: string); procedure WriteUnicodeStr8(Value: string); procedure WriteWideString(Value: WideString); function ReadWideString(Length: integer; var Str: WideString): integer; function Seek(Offset: Longint; Origin: Word): longint; function Pos: longint; procedure BeginCONTINUEWrite(MaxRecSize: integer); procedure CheckCONTINUEWrite(const Buffer; Count: Longint); procedure EndCONTINUEWrite; procedure BeginCONTINUERead; procedure EndCONTINUERead; procedure WriteVBA; procedure Close; // For debugging procedure WriteFile(RecId,Length: word; Filename: string); property Size: integer read FStreamSize; property WrittenBytes: integer read FWrittenBytes write FWrittenBytes; property TargetStream: TStream read FTargetStream write FTargetStream; property SaveVBA: boolean read FSaveVBA write FSaveVBA; property ISAPIRead: boolean read FISAPIRead write FISAPIRead; property ExtraObjects: TExtraObjects read FExtraObjects write FExtraObjects; end; implementation const EncryptReKeyBlockSz = $0400; { TExtraObjects } procedure TExtraObjects.Add(Name: PWideChar; LockBytes: ILockBytes; Storage: IStorage); var P: PExtraData; begin New(P); GetMem(P.Name,Length(Name) * 2 + 1); System.Move(Name^,P.Name^,Length(Name) * 2 + 1); P.LockBytes := LockBytes; P.Storage := Storage; inherited Add(P); end; procedure TExtraObjects.AddStream(Name: PWideChar; Size: integer); var L: integer; P: PExtraStreamData; begin L := Length(Name) * 2 + 2; New(P); GetMem(P.Name,L); System.Move(Name^,P.Name^,L); P.Name[Length(Name)] := #0; P.Size := Size; P.Data := Nil; FStreams.Add(P); end; procedure TExtraObjects.Clear; var i: integer; begin for i := 0 to FStreams.Count - 1 do begin FreeMem(PExtraStreamData(FStreams[i]).Name); FreeMem(PExtraStreamData(FStreams[i]).Data); end; FStreams.Clear; for i := 0 to Count - 1 do begin FreeMem(PExtraData(inherited Items[i]).Name); PExtraData(inherited Items[i]).LockBytes := Nil; PExtraData(inherited Items[i]).Storage := Nil; FreeMem(inherited Items[i]); end; inherited Clear; end; constructor TExtraObjects.Create; begin inherited Create; FStreams := TList.Create; end; destructor TExtraObjects.Destroy; begin // Clear is called by destroy; inherited; FStreams.Free; FStreams := Nil; end; function TExtraObjects.GetItems(Index: integer): PExtraData; begin Result := inherited Items[Index]; end; procedure TExtraObjects.ReadStreams(Storage: IStorage); var i,p: integer; OleStream: IStream; begin for i := 0 to FStreams.Count - 1 do begin GetMem(PExtraStreamData(FStreams[i]).Data,PExtraStreamData(FStreams[i]).Size); OleCheck(Storage.OpenStream(PExtraStreamData(FStreams[i]).Name,Nil,STGM_DIRECT or FileMode or STGM_SHARE_EXCLUSIVE,0,OleStream)); OleCheck(OleStream.Read(PExtraStreamData(FStreams[i]).Data,PExtraStreamData(FStreams[i]).Size,@p)); end; end; procedure TExtraObjects.WriteStreams(Storage: IStorage); var i,p: integer; OleStream: IStream; begin for i := 0 to FStreams.Count - 1 do begin OleCheck(Storage.CreateStream(PExtraStreamData(FStreams[i]).Name,STGM_DIRECT or STGM_WRITE or STGM_CREATE or STGM_SHARE_EXCLUSIVE,0,0,OleStream)); OleCheck(OleStream.Write(PExtraStreamData(FStreams[i]).Data,PExtraStreamData(FStreams[i]).Size,@p)); end; end; { TXLSStream } { TXLSStream } constructor TXLSStream.Create; begin FWriteCONTINUEPos := -1; FSaveVBA := True; end; destructor TXLSStream.Destroy; begin Close; inherited Destroy; end; procedure TXLSStream.Close; begin if FStream <> Nil then FStream.Free; FStream := Nil; if OleStream <> Nil then begin try if Assigned(FTargetStream) and (FLockBytes <> nil) then begin OleCheck(FLockBytes.Flush); OleCheck(OleStorage.Commit(STGC_DEFAULT)); WriteStorageToDestStream; end; finally OleStorage := nil; OleStream := nil; end; end; end; procedure TXLSStream.ReadVBA(Name: PWideChar); var StorageIn,StorageOut: IStorage; LockBytes: ILockBytes; Enum: IEnumStatStg; Stat: TSTATSTG; begin OleCheck(OleStorage.OpenStorage(Name,Nil,STGM_READ + STGM_SHARE_EXCLUSIVE,Nil,0,StorageIn)); OleCheck(CreateILockBytesOnHGlobal(0, True, LockBytes)); OleCheck(StgCreateDocfileOnILockBytes(LockBytes, STGM_READWRITE or STGM_SHARE_EXCLUSIVE or STGM_CREATE, 0, StorageOut)); OleCheck(StorageIn.CopyTo(0,Nil,Nil,StorageOut)); FExtraObjects.Add(Name,LockBytes,StorageOut); OleCheck(StorageOut.EnumElements(0,Nil,0,Enum)); OleCheck(Enum.Reset); repeat OleCheck(Enum.Next(1,Stat,Nil)); until (Stat.pwcsName = Nil); StorageIn := Nil; end; procedure TXLSStream.WriteVBA; var i: integer; StorageOut: IStorage; begin for i := 0 to FExtraObjects.Count - 1 do begin OleCheck(OleStorage.CreateStorage(FExtraObjects[i].Name,STGM_READWRITE or STGM_SHARE_EXCLUSIVE or STGM_CREATE,0,0,StorageOut)); OleCheck(FExtraObjects[i].Storage.CopyTo(0,Nil,Nil,StorageOut)); end; StorageOut := Nil; end; function TXLSStream.OpenOleStreamRead(Filename: PWideChar): TExcelVersion; var Enum: IEnumStatStg; Stat: TSTATSTG; FoundBOOK,FoundWORKBOOK: boolean; FBOOKStreamSize,FWORKBOOKStreamSize: integer; FileMode: integer; begin Close; FoundBOOK := False; FoundWORKBOOK := False; // FileMode := STGM_READ; if FISAPIRead then FileMode := STGM_READ or STGM_SHARE_DENY_WRITE else FileMode := STGM_READ or STGM_TRANSACTED or STGM_SHARE_DENY_NONE; FWORKBOOKStreamSize := 0; FBOOKStreamSize := 0; // OleCheck(StgOpenStorage(Filename,Nil,FileMode or STGM_SHARE_DENY_WRITE,Nil,0,OleStorage)); OleCheck(StgOpenStorage(Filename,Nil,FileMode ,Nil,0,OleStorage)); OleCheck(OleStorage.EnumElements(0,Nil,0,Enum)); OleCheck(Enum.Reset); repeat OleCheck(Enum.Next(1,Stat,Nil)); if Lowercase(Stat.pwcsName) = 'book' then begin FoundBOOK := True; FBOOKStreamSize := Stat.cbSize; end else if Lowercase(Stat.pwcsName) = 'workbook' then begin FoundWORKBOOK := True; FWORKBOOKStreamSize := Stat.cbSize; end else if FSaveVBA and (Stat.dwType = 2) and not FoundBOOK and not FoundWORKBOOK then FExtraObjects.AddStream(Stat.pwcsName,Stat.cbSize) else if (Stat.dwType = 1) and FSaveVBA then ReadVBA(Stat.pwcsName); until (Stat.pwcsName = Nil); if not FoundBOOK and not FoundWORKBOOK then raise Exception.Create(ersFileIsNotAnExcelWorkbook); FileMode := STGM_READ; if FoundWORKBOOK then begin Result := xvExcel97; FStreamSize := FWORKBOOKStreamSize; end else begin Result := xvExcel50; FStreamSize := FBOOKStreamSize; end; try if FExtraObjects <> Nil then FExtraObjects.ReadStreams(OleStorage); if FoundWORKBOOK then OleCheck(OleStorage.OpenStream('Workbook',Nil,STGM_DIRECT or FileMode or STGM_SHARE_EXCLUSIVE,0,OleStream)) else OleCheck(OleStorage.OpenStream('Book',Nil,STGM_DIRECT or FileMode or STGM_SHARE_EXCLUSIVE,0,OleStream)); except Result := xvNone; end; end; function TXLSStream.OpenFileStreamRead(const Filename: string): TExcelVersion; var Header: TBIFFHeader; begin Result := xvNone; Close; FStream := TFileStream.Create(Filename,fmOpenRead); FStream.Read(Header,SizeOf(TBIFFHeader)); if (Header.RecID and $FF) = BIFFRECID_BOF then begin case (Header.RecID and $FF00) of $0000: Result := xvExcel21; $0200: Result := xvExcel30; $0400: Result := xvExcel40; end; end; FStream.Seek(0,soFromBeginning); end; function TXLSStream.Read(var Buffer; Count: Longint): integer; var R,T: integer; P: Pointer; Header: TBIFFHeader; begin if FStream = Nil then begin if FReadCONTINUEActive then begin if (FReadCONTINUEPos + Count) > MAXRECSZ_97 then begin Result := 0; P := @Buffer; repeat OleCheck(OleStream.Read(P,Min(MAXRECSZ_97 - FReadCONTINUEPos,Count),@R)); Inc(Result,R); Dec(Count,R); FReadCONTINUEPos := 0; P := Pointer(Integer(P) + R); if Count > 0 then begin OleCheck(OleStream.Read(@Header,SizeOf(TBIFFHeader),@T)); // Bug in Excel. MSODRAWINGGROUP may be continued with MSODRAWINGGROUP instead of CONTINUE. if not (Header.RecID in [BIFFRECID_CONTINUE,BIFFRECID_MSODRAWINGGROUP]) then raise Exception.Create('CONTINUE record is missing'); end; until ((Count <= 0) or (R <= 0)); FReadCONTINUEPos := R; end else begin OleCheck(OleStream.Read(@Buffer,Count,@Result)); Inc(FReadCONTINUEPos,Count); end; end else begin OleCheck(OleStream.Read(@Buffer,Count,@Result)) end; end else Result := FStream.Read(Buffer,Count); { if FIsEncrypted then RC4(@Buffer,Count,FRC4Key); } end; function TXLSStream.ReadHeader(var Header: TBIFFHeader): integer; begin Result := Read(Header,SizeOf(TBIFFHeader)); end; procedure TXLSStream.WriteHeader(RecId: word; Length: word); var Header: TBIFFHeader; begin Header.RecId := RecId; Header.Length := Length; IntWrite(Header,SizeOf(TBIFFHeader)); end; procedure TXLSStream.WriteBufHeader(const Buffer; RecId: word; Length: word); var Header: TBIFFHeader; begin Header.RecId := RecId; Header.Length := Length; IntWrite(Header,SizeOf(TBIFFHeader)); IntWrite(Buffer,Length); end; procedure TXLSStream.WriteWord(RecId, Value: word); begin WriteHeader(RecId,2); IntWrite(Value,2); end; function TXLSStream.IntWrite(const Buffer; Count: Integer): longint; begin if FStream = Nil then OleCheck(OleStream.Write(@Buffer,Count,@Result)) else Result := FStream.Write(Buffer,Count); end; function TXLSStream.Write(const Buffer; Count: Longint): longint; begin Result := 0; if FMaxBytesWrite > 0 then CheckCONTINUEWrite(Buffer,Count) else begin Result := IntWrite(Buffer,Count); Inc(FWrittenBytes,Result); end; end; procedure TXLSStream.CheckCONTINUEWrite(const Buffer; Count: Longint); var WBytes: integer; P: Pointer; begin P := @Buffer; if (Count + FWrittenBytes) > FMaxBytesWrite then begin WBytes := FMaxBytesWrite - FWrittenBytes; Seek(FWriteCONTINUEPos + 2,soFromBeginning); IntWrite(FMaxBytesWrite,SizeOf(word)); Seek(0,soFromEnd); IntWrite(P^,WBytes); FWriteCONTINUEPos := Pos; WriteHeader(BIFFRECID_CONTINUE,0); FWrittenBytes := 0; Dec(Count,WBytes); P := Pointer(Integer(P) + WBytes); CheckCONTINUEWrite(P^,Count); end else begin IntWrite(Buffer,Count); Inc(FWrittenBytes,Count); end; end; function TXLSStream.Seek(Offset: Longint; Origin: Word): integer; var Pos: largeint; begin if FStream = Nil then begin case Origin of soFromBeginning: OleCheck(OleStream.Seek(Offset,STREAM_SEEK_SET,Pos)); soFromCurrent: OleCheck(OleStream.Seek(Offset,STREAM_SEEK_CUR,Pos)); soFromEnd: OleCheck(OleStream.Seek(Offset,STREAM_SEEK_END,Pos)); end; Result := Pos; end else Result := FStream.Seek(Offset,Origin); end; function TXLSStream.Pos: longint; begin Result := Seek(0,1); end; function TXLSStream.OpenRead(const Filename: string): TExcelVersion; var WC: PWideChar; begin GetMem(WC,512); try StringToWideChar(FileName,WC,512); if StgIsStorageFile(WC) = S_OK then Result := OpenOLEStreamRead(WC) else Result := OpenFileStreamRead(Filename); finally FreeMem(WC); end; end; procedure TXLSStream.OpenWrite(const Filename: string; Version: TExcelVersion); var WC: PWideChar; begin Close; if Version >= xvExcel50 then begin if Assigned(FTargetStream) then begin OleCheck(CreateILockBytesOnHGlobal(0, True, FLockBytes)); OleCheck(StgCreateDocfileOnILockBytes(FLockBytes, STGM_READWRITE or STGM_SHARE_EXCLUSIVE or STGM_CREATE, 0, OleStorage)); end else begin WC := StringToOleStr(FileName); try OleCheck(StgCreateDocfile(WC, STGM_DIRECT or STGM_READWRITE or STGM_CREATE or STGM_SHARE_EXCLUSIVE, 0, OleStorage)); finally SysFreeString(WC); end; end; if FExtraObjects <> Nil then FExtraObjects.WriteStreams(OleStorage); if Version = xvExcel50 then OleStorage.CreateStream('Book',STGM_DIRECT or STGM_WRITE or STGM_CREATE or STGM_SHARE_EXCLUSIVE,0,0,OleStream) // OleCheck(OleStorage.CreateStream('Book',STGM_DIRECT or STGM_WRITE or STGM_CREATE or STGM_SHARE_EXCLUSIVE,0,0,OleStream)) else OleCheck(OleStorage.CreateStream('Workbook',STGM_DIRECT or STGM_WRITE or STGM_CREATE or STGM_SHARE_EXCLUSIVE,0,0,OleStream)); end else begin if Assigned(FTargetStream) then FStream := FTargetStream else FStream := TFileStream.Create(Filename,fmCreate); end; end; procedure TXLSStream.WriteStorageToDestStream; var DataHandle: HGLOBAL; Buffer: Pointer; begin OleCheck(FLockBytes.Flush); OleCheck(GetHGlobalFromILockBytes(FLockBytes, DataHandle)); Buffer := GlobalLock(DataHandle); try FTargetStream.WriteBuffer(Buffer^, GlobalSize(DataHandle)); finally GlobalUnlock(DataHandle); end; end; procedure TXLSStream.BeginCONTINUEWrite(MaxRecSize: integer); begin FMaxBytesWrite := MaxRecSize; FWrittenBytes := 0; FWriteCONTINUEPos := Pos; end; procedure TXLSStream.EndCONTINUEWrite; var V: word; begin if FWrittenBytes > 0 then begin Seek(FWriteCONTINUEPos + 2,soFromBeginning); V := FWrittenBytes; IntWrite(V,SizeOf(word)); Seek(0,soFromEnd); end; FMaxBytesWrite := -1; end; procedure TXLSStream.WStr2ByteLen(Value: string); begin Value := ToMultibyte1bHeader(Value); if Value <> '' then begin WWord(Length(Value) - 1); IntWrite(Pointer(Value)^,Length(Value)); end; end; procedure TXLSStream.WWord(Value: word); begin IntWrite(Value,SizeOf(word)); end; procedure TXLSStream.WByte(Value: byte); begin IntWrite(Value,SizeOf(byte)); end; procedure TXLSStream.WriteUnicodeStr16(Value: string); var L: word; begin if Length(Value) <= 0 then WWord(0) else begin if Value[1] = #1 then L := (Length(Value) - 1) div 2 else L := Length(Value) - 1; WWord(L); Write(Pointer(Value)^,Length(Value)); end; end; procedure TXLSStream.WriteUnicodeStr8(Value: string); var L: byte; begin if Length(Value) <= 0 then WByte(0) else begin if Value[1] = #1 then L := (Length(Value) - 1) div 2 else L := Length(Value) - 1; WByte(L); Write(Pointer(Value)^,Length(Value)); end; end; procedure TXLSStream.WriteWideString(Value: WideString); begin WWord(Length(Value)); if Value <> '' then begin WByte(1); Write(Pointer(Value)^,Length(Value) * 2); end; end; function TXLSStream.ReadWideString(Length: integer; var Str: WideString): integer; var B: byte; S: string; begin Read(B,1); if B = 1 then begin SetLength(Str,Length); Read(Pointer(Str)^,Length * 2); Result := Length * 2 + 1; end else begin SetLength(S,Length); Read(Pointer(S)^,Length); Str := S; Result := Length+ 1; end; end; procedure TXLSStream.BeginCONTINUERead; begin FReadCONTINUEActive := True; FReadCONTINUEPos := 0; end; procedure TXLSStream.EndCONTINUERead; begin FReadCONTINUEActive := False; FReadCONTINUEPos := 0; end; procedure TXLSStream.WriteFile(RecId, Length: word; Filename: string); var S: string; B: byte; Stream: TFileStream; begin Stream := TFileStream.Create(Filename,fmOpenRead); try WriteHeader(RecId,Length); SetLength(S,3); while (Length > 0) and (Stream.Read(Pointer(S)^,3) = 3) do begin B := 0; if S[1] in ['0'..'9'] then B := (Byte(S[1]) - Byte('0')) shl 4 else if S[1] in ['A'..'F'] then B := (Byte(S[1]) - Byte('A') + 10) shl 4; if S[2] in ['0'..'9'] then B := B + (Byte(S[2]) - Byte('0')) else if S[2] in ['A'..'F'] then B := B + (Byte(S[2]) - Byte('A') + 10); WByte(B); Dec(Length); end; finally Stream.Free; end; end; end.
unit uClientContext; interface uses Classes, Contnrs; type TClientContext = class(TPersistent) protected fClientId: String; fDocuments: TObjectList; public constructor Create; destructor Destroy; override; published property ClientId: String read fClientId write fClientId; property Documents: TObjectList read fDocuments; end; implementation { TClientContext } constructor TClientContext.Create; begin fDocuments := TObjectList.Create(True); end; destructor TClientContext.Destroy; begin fDocuments.Free; inherited; end; end.
unit CommonfrmCDBDump_Base; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.FreeOTFE.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, PasswordRichEdit, Spin64, OTFEFreeOTFEBase_U, Buttons, SDUForms, SDUFrames, SDUSpin64Units, SDUFilenameEdit_U, SDUDialogs, OTFEFreeOTFE_VolumeSelect; type TfrmCDBDump_Base = class(TSDUForm) pbOK: TButton; pbCancel: TButton; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; GroupBox2: TGroupBox; Label3: TLabel; feDumpFilename: TSDUFilenameEdit; OTFEFreeOTFEVolumeSelect1: TOTFEFreeOTFEVolumeSelect; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure ControlChanged(Sender: TObject); procedure pbOKClick(Sender: TObject); procedure OTFEFreeOTFEVolumeSelect1Change(Sender: TObject); private function GetVolumeFilename(): string; function GetDumpFilename(): string; protected procedure EnableDisableControls(); virtual; abstract; function DumpLUKSDataToFile(): boolean; virtual; abstract; public OTFEFreeOTFE: TOTFEFreeOTFEBase; property VolumeFilename: string read GetVolumeFilename; property DumpFilename: string read GetDumpFilename; end; implementation {$R *.DFM} uses SDUi18n, SDUGeneral, CommonSettings; function TfrmCDBDump_Base.GetVolumeFilename(): string; begin Result := OTFEFreeOTFEVolumeSelect1.Filename; end; procedure TfrmCDBDump_Base.OTFEFreeOTFEVolumeSelect1Change(Sender: TObject); begin { if not(fmeVolumeSelect.IsPartitionSelected) then begin edDumpFilename.text := VolumeFilename + '.txt'; end; } ControlChanged(Sender); end; function TfrmCDBDump_Base.GetDumpFilename(): string; begin Result := feDumpFilename.Filename; end; procedure TfrmCDBDump_Base.FormCreate(Sender: TObject); begin // se64UnitOffset set in OnShow event (otherwise units not shown correctly) OTFEFreeOTFEVolumeSelect1.Filename := ''; OTFEFreeOTFEVolumeSelect1.AllowPartitionSelect := TRUE; OTFEFreeOTFEVolumeSelect1.FileSelectFilter := FILE_FILTER_FLT_VOLUMESANDKEYFILES; OTFEFreeOTFEVolumeSelect1.FileSelectDefaultExt := FILE_FILTER_DFLT_VOLUMESANDKEYFILES; OTFEFreeOTFEVolumeSelect1.SelectFor := fndOpen; feDumpFilename.Filename := ''; end; procedure TfrmCDBDump_Base.FormShow(Sender: TObject); begin OTFEFreeOTFEVolumeSelect1.OTFEFreeOTFE := OTFEFreeOTFE; FreeOTFEGUISetupOpenSaveDialog(feDumpFilename); feDumpFilename.Filter := FILE_FILTER_FLT_TEXTFILES; feDumpFilename.DefaultExt := FILE_FILTER_DFLT_TEXTFILES; EnableDisableControls(); end; procedure TfrmCDBDump_Base.ControlChanged(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmCDBDump_Base.pbOKClick(Sender: TObject); var {$IFDEF FREEOTFE_TIME_CDB_DUMP} startTime: TDateTime; stopTime: TDateTime; diffTime: TDateTime; Hour, Min, Sec, MSec: Word; {$ENDIF} dumpOK: boolean; notepadCommandLine: string; begin {$IFDEF FREEOTFE_TIME_CDB_DUMP} startTime := Now(); {$ENDIF} dumpOK := DumpLUKSDataToFile(); if dumpOK then begin {$IFDEF FREEOTFE_TIME_CDB_DUMP} stopTime := Now(); diffTime := (stopTime - startTime); DecodeTime(diffTime, Hour, Min, Sec, MSec); showmessage('Time taken to dump CDB: '+inttostr(Hour)+' hours, '+inttostr(Min)+' mins, '+inttostr(Sec)+'.'+inttostr(MSec)+' secs'); {$ENDIF} if (SDUMessageDlg( _('A human readable copy of your critical data block has been written to:')+SDUCRLF+ SDUCRLF+ DumpFilename+SDUCRLF+ SDUCRLF+ _('Do you wish to open this file in Windows Notepad?'), mtInformation, [mbYes,mbNo], 0) = mrYes) then begin notepadCommandLine := 'notepad '+DumpFilename; if (WinExec(PChar(notepadCommandLine), SW_RESTORE))<31 then begin SDUMessageDlg(_('Error running Notepad'), mtError, [], 0); end; end; ModalResult := mrOK; end else begin {$IFDEF FREEOTFE_TIME_CDB_DUMP} stopTime := Now(); diffTime := (stopTime - startTime); DecodeTime(diffTime, Hour, Min, Sec, MSec); showmessage('Time taken to FAIL to dump CDB: '+inttostr(Hour)+' hours, '+inttostr(Min)+' mins, '+inttostr(Sec)+'.'+inttostr(MSec)+' secs'); {$ENDIF} SDUMessageDlg( _('Unable to dump out critical data block.')+SDUCRLF+ SDUCRLF+ _('Please ensure that your password and details are entered correctly, and that this file is not currently in use (e.g. mounted)'), mtError, [mbOK], 0); end; end; END.
//------------------------------------------------------------------------------ // // Voxelizer // Copyright (C) 2021 by Jim Valavanis // // 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; if not, write to the Free Software // Foundation, inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // // DESCRIPTION: // WAD File Definitions // //------------------------------------------------------------------------------ // Site : https://sourceforge.net/projects/voxelizer/ //------------------------------------------------------------------------------ unit vxl_wad; interface type char8_t = array[0..7] of char; Pchar8_t = ^char8_t; wadinfo_t = packed record // Should be "IWAD" or "PWAD". identification: integer; numlumps: integer; infotableofs: integer; end; Pwadinfo_t = ^wadinfo_t; filelump_t = packed record filepos: integer; size: integer; name: char8_t; end; Pfilelump_t = ^filelump_t; Tfilelump_tArray = packed array[0..$FFFF] of filelump_t; Pfilelump_tArray = ^Tfilelump_tArray; const IWAD = integer(Ord('I') or (Ord('W') shl 8) or (Ord('A') shl 16) or (Ord('D') shl 24)); PWAD = integer(Ord('P') or (Ord('W') shl 8) or (Ord('A') shl 16) or (Ord('D') shl 24)); function char8tostring(src: char8_t): string; function stringtochar8(src: string): char8_t; implementation function char8tostring(src: char8_t): string; var i: integer; begin Result := ''; i := 0; while (i < 8) and (src[i] <> #0) do begin Result := Result + src[i]; inc(i); end; end; function stringtochar8(src: string): char8_t; var i: integer; len: integer; begin len := length(src); if len > 8 then len := 8; i := 1; while (i <= len) do begin Result[i - 1] := src[i]; inc(i); end; for i := len to 7 do Result[i] := #0; end; end.
unit MessageHandler; interface uses Classes, Types, SysUtils, GenesisConsts, GenesisUnit, SiAuto, SmartInspect; type TCompileMessageHandler = class public procedure DoMessage(AUnit:TGenesisUnit; AMessage: string; Alevel: TMessageLevel); end; implementation { TCompileMessageHandler } procedure TCompileMessageHandler.DoMessage(AUnit: TGenesisUnit; AMessage: string; Alevel: TMessageLevel); var LMessage: string; begin SiMain.EnterMethod(Self, 'DoMessage'); LMessage := ''; if Assigned(AUnit) then begin LMessage := AUnit.GenesisUnitName+':'+IntToStr(AUnit.GetCurrentLine)+':'+ IntToStr(AUnit.GetCurrentPosInLine()) + ':'; end else begin LMessage := 'compiler.system:0:0: '; end; if Alevel = mlError then begin Writeln(ErrOutput,LMessage + ' ' + AMessage); end; if Alevel = mlWarning then begin Writeln(LMessage + ' warning: ' + AMessage); end; // else // begin Writeln(AMessage); // end; SiMain.LogWarning(AMessage); SiMain.LeaveMethod(Self, 'DoMessage'); end; end.
unit UNetworkFileCompare; interface uses classes, SyncObjs, UFileBaseInfo, UMyUtil; type {$Region ' ' } // 备份目录 网络比较 TBackupFolderCompare = class private PcID : string; BackupFolderPath : string; private TempBackupFolder : TTempBackupFolderInfo; public constructor Create( _PcID : string ); procedure SetBackupFolderPath( _BackupFolderPath : string ); procedure Update; destructor Destroy; override; private procedure FindTempBackupFolder; procedure CheckFiles; procedure CheckFolders; private procedure FindFile( TempFileInfo : TTempBackupFileInfo ); function CheckNextCompare : Boolean; end; TBackupFileCompareThread = class( TThread ) public constructor Create; destructor Destroy; override; protected procedure Execute; override; end; // 需要比较的 备份文件 TMyBackupFileCompareInfo = class public Lock : TCriticalSection; PcIDList : TStringList; public constructor Create; destructor Destroy; override; end; // 需要比较的 云文件 TMyCloudFileCompareInfo = class public PcIDList : TStringList; public constructor Create; destructor Destroy; override; end; implementation uses UMyBackupInfo; { TMyBackupFileCompareInfo } constructor TMyBackupFileCompareInfo.Create; begin Lock := TCriticalSection.Create; PcIDList := TStringList.Create; end; destructor TMyBackupFileCompareInfo.Destroy; begin PcIDList.Free; Lock.Free; inherited; end; { TMyCloudFileCompareInfo } constructor TMyCloudFileCompareInfo.Create; begin PcIDList := TStringList.Create; end; destructor TMyCloudFileCompareInfo.Destroy; begin PcIDList.Free; inherited; end; { TBackupFileCompareThread } constructor TBackupFileCompareThread.Create; begin inherited Create( True ); end; destructor TBackupFileCompareThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TBackupFileCompareThread.Execute; begin inherited; end; { TBackupFolderCompare } procedure TBackupFolderCompare.CheckFiles; var FileHash : TTempBackupFileHash; p : TTempBackupFilePair; begin FileHash := TempBackupFolder.TempBackupFileHash; for p in FileHash do begin if not CheckNextCompare then Break; // copy // if p.Value.CheckCopyHash.ContainsKey( PcID ) and // p.Value.CheckCopyHash[ PcID ]. FindFile( p.Value ); end; end; procedure TBackupFolderCompare.CheckFolders; var FolderHash : TTempBackupFolderHash; p : TTempBackupFolderPair; ChildFolderPath : string; BackupFolderCompare : TBackupFolderCompare; begin FolderHash := TempBackupFolder.TempBackupFolderHash; for p in FolderHash do begin if not CheckNextCompare then Break; ChildFolderPath := BackupFolderPath + p.Value.FileName; BackupFolderCompare := TBackupFolderCompare.Create( PcID ); BackupFolderCompare.SetBackupFolderPath( ChildFolderPath ); BackupFolderCompare.Update; BackupFolderCompare.Free; end; end; function TBackupFolderCompare.CheckNextCompare: Boolean; begin end; constructor TBackupFolderCompare.Create(_PcID: string); begin PcID := _PcID; TempBackupFolder := TTempBackupFolderInfo.Create; end; destructor TBackupFolderCompare.Destroy; begin TempBackupFolder.Free; inherited; end; procedure TBackupFolderCompare.FindFile(TempFileInfo : TTempBackupFileInfo); begin end; procedure TBackupFolderCompare.FindTempBackupFolder; var FindTempBackupFolderInfo : TFindTempBackupFolderInfo; begin FindTempBackupFolderInfo := TFindTempBackupFolderInfo.Create; FindTempBackupFolderInfo.SetFolderPath( BackupFolderPath ); FindTempBackupFolderInfo.SetTempBackupFolderInfo( TempBackupFolder ); TempBackupFolder := FindTempBackupFolderInfo.get; FindTempBackupFolderInfo.Free; end; procedure TBackupFolderCompare.SetBackupFolderPath(_BackupFolderPath: string); begin BackupFolderPath := _BackupFolderPath; end; procedure TBackupFolderCompare.Update; begin FindTempBackupFolder; BackupFolderPath := MyFilePath.getPath( BackupFolderPath ); CheckFiles; CheckFolders; end; end.
{$include kode.inc} unit modular; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses //kode_library, kode_timeline, //kode_controls, kode_editor, kode_module, kode_object, kode_plugin, kode_rect, //kode_types, kode_widget, kode_widget_graph, kode_widget_menu, kode_widget_menuitem, kode_widget_panel, kode_widget_textedit, kode_widget_timeline;//, //kode_window; type myPlugin = class(KPlugin) private FGraph : KGraph; FTimeline : KTimeline; //m1,m2,m3,m4,m5,m6 : KModule; public property graph : KGraph read FGraph; property timeline : KTimeline read FTimeline; public procedure on_create; override; procedure on_destroy; override; function on_openEditor(AParent:Pointer) : Pointer; override; procedure on_closeEditor; override; procedure on_idleEditor; override; end; KPluginClass = myPlugin; //---------- myEditor = class(KEditor) private wdg_Panel : KWidget_Panel; wdg_Graph : KWidget_Graph; wdg_Menu : KWidget_Menu; wdg_Menu_add : KWidget_Menu; wdg_Timeline : KWidget_Timeline; protected property panel : KWidget_Panel read wdg_Panel; property graph : KWidget_Graph read wdg_Graph; property menu : KWidget_Menu read wdg_Menu; public constructor create(APlugin:KObject; ARect:KRect; AParent:Pointer=nil); procedure on_mouseDown(AXpos,AYpos,AButton,AState : LongInt); override; procedure do_update(AWidget:KWidget); override; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses Windows, kode_array, kode_basepath, kode_color, {%H-}kode_const, {%H-}kode_debug, kode_flags, kode_module_base, kode_string, kode_utils; //---------- //uses Windows; function codegen(arg:integer; size:longint=32768) : integer; type TFuncInt = function(param:Integer) : Integer; // EAX -> EAX var buffer : PByte; begin result := 0; buffer := VirtualAlloc(nil,size,$3000,$40); if buffer <> nil then begin buffer[0] := $40; // inc EAX buffer[1] := $C3; // ret result := TFuncInt(buffer)(arg); // 78 VirtualFree(buffer,0,$8000); end; end; //---------------------------------------------------------------------- // plugin //---------------------------------------------------------------------- procedure myPlugin.on_create; var info : KPModuleInfo; m1,m2,m3,m4,m5,m6 : KModule; track : KTimeline_Track; segment : KTimeline_Segment; //path : array[0..255] of char; //buffer : array[0..65535] of char; //files : KPCharArray; //i : longint; begin KTrace(['codegen: ',codegen(77),KODE_CR]); (* path := KGetBasePath(path); //KStrcat(path,'modules\'); KTrace(['module path: "',path,'"',KODE_CR]); files := KFindAllFiles(path,'*.dll',false,buffer); if files._size > 0 then begin for i := 0 to files._size - 1 do begin KTrace([i,' : ',files[i],KODE_CR]); end; end; files.destroy; *) FName := 'modular'; FAuthor := 'skei.audio'; FProduct := FName; FVersion := 0; FUniqueId := KODE_MAGIC_USER + $ffff; FNumInputs := 2; FNumOutputs := 2; KSetFlag(FFlags, kpf_perSample //+ kpf_sendMidi + kpf_receiveMidi + kpf_isSynth //+ kpf_autoUpdateSync //+ kpf_reaper ); KSetFlag(FFlags,kpf_hasEditor); FEditor := nil; FEditorRect.setup(700,500); //appendParameter( KParamFloat.create( 'param1', 0 )); FGraph := KGraph.create; { audio in } info := KFindModule('audio_in'); if Assigned(info) then begin m1 := KModule.create(info); FGraph.addModule(m1,100,100); end; { parameter } info := KFindModule('parameter'); if Assigned(info) then begin m2 := KModule.create(info); FGraph.addModule(m2,200,100); end; { add } info := KFindModule('add'); if Assigned(info) then begin m3 := KModule.create(info); FGraph.addModule(m3,100,180); end; { add 2 } info := KFindModule('add'); if Assigned(info) then begin m4 := KModule.create(info); FGraph.addModule(m4,200,180); end; { audio out } info := KFindModule('audio_out'); if Assigned(info) then begin m5 := KModule.create(info); FGraph.addModule(m5,150,250); end; { variable } info := KFindModule('variable'); if Assigned(info) then begin m6 := KModule.create(info); FGraph.addModule(m6,250,300); end; { connect } FGraph.addWire( KWire.create( m3,0, m1,0 ) ); FGraph.addWire( KWire.create( m3,1, m2,0 ) ); FGraph.addWire( KWire.create( m4,0, m1,1 ) ); FGraph.addWire( KWire.create( m4,1, m2,0 ) ); FGraph.addWire( KWire.create( m5,0, m3,0 ) ); FGraph.addWire( KWire.create( m5,1, m4,0 ) ); FTimeline := KTimeline.create; FTimeline.cursor := 5; track := KTimeline_Track.create('track1'); track.addSegment( KTimeline_Segment.create('intro',0,3) ); track.addSegment( KTimeline_Segment.create('pattern1',4,7) ); track.addSegment( KTimeline_Segment.create('outro',7,10) ); FTimeline.addTrack( track ); track := KTimeline_Track.create('track2'); track.addSegment( KTimeline_Segment.create('p1',0.5,1.5) ); track.addSegment( KTimeline_Segment.create('p2',3.5,12) ); FTimeline.addTrack( track ); track := KTimeline_Track.create('track3 123'); track.addSegment( KTimeline_Segment.create('shader',2,4) ); track.addSegment( KTimeline_Segment.create('mesh',4,7) ); FTimeline.addTrack( track ); track := KTimeline_Track.create('track4 abc'); FTimeline.addTrack( track ); end; //---------- procedure myPlugin.on_destroy; begin FTimeline.destroyTracks; FTimeline.destroy; FGraph.destroyModules; FGraph.destroyWires; FGraph.destroy; end; //---------- function myPlugin.on_openEditor(AParent:Pointer) : Pointer; var editor : myEditor; begin editor := myEditor.create(self,FEditorRect,AParent); result := editor; end; //---------- procedure myPlugin.on_closeEditor; begin FEditor.hide; FEditor.destroy; FEditor := nil; end; //---------- procedure myPlugin.on_idleEditor; begin end; //---------------------------------------------------------------------- // editor //---------------------------------------------------------------------- constructor myEditor.create(APlugin:KObject; ARect:KRect; AParent:Pointer=nil); var gr : KGraph; tl : KTimeline; i,num : longint; name : pchar; begin inherited; wdg_Panel := KWidget_Panel.create( rect0, KGrey, kwa_fillClient ); appendWidget( wdg_Panel ); { text edit } wdg_Panel.appendWidget( KWidget_TextEdit.create(kode_rect.rect(16),'Hello World! (edit me)',kwa_fillTop) ); { timeline } tl := (FPlugin as myPlugin).timeline; wdg_Timeline := KWidget_Timeline.create( kode_rect.rect(80), tl, kwa_fillBottom ); wdg_Timeline.zoom := 3; wdg_Panel.appendWidget( wdg_Timeline ); { graph } gr := (FPlugin as myPlugin).graph; wdg_Graph := KWidget_Graph.create( kode_rect.rect(10), gr, kwa_fillClient ); wdg_Panel.appendWidget( wdg_Graph ); //KTrace(['gr ',gr.name,KODE_CR]); { menu } wdg_Menu := KWidget_Menu.create( kode_rect.rect(20,20,80,(16*7)) ); wdg_Menu.appendWidget(KWidget_MenuItem.create( kode_rect.rect(16),'add module', kwa_fillTop )); wdg_Menu.appendWidget(KWidget_MenuItem.create( kode_rect.rect(16),'delete modules', kwa_fillTop )); wdg_Menu.appendWidget(KWidget_MenuItem.create( kode_rect.rect(16),'menu 2', kwa_fillTop )); wdg_Menu.appendWidget(KWidget_MenuItem.create( kode_rect.rect(16),'menu 3', kwa_fillTop )); wdg_Menu.appendWidget(KWidget_MenuItem.create( kode_rect.rect(16),'menu 4', kwa_fillTop )); wdg_Menu.appendWidget(KWidget_MenuItem.create( kode_rect.rect(16),'menu 5', kwa_fillTop )); wdg_Menu.appendWidget(KWidget_MenuItem.create( kode_rect.rect(16),'menu 6', kwa_fillTop )); wdg_Menu.setFlag(kwf_clip); wdg_Panel.appendWidget(wdg_Menu); num := KGetNumModules; wdg_Menu_add := KWidget_Menu.create( kode_rect.rect(20,20,80,(16*num)) ); if KGetNumModules > 0 then begin for i := 0 to KGetNumModules-1 do begin name := KGetModuleName(i); KTrace([i,' ', name,KODE_CR ]); wdg_Menu_add.appendWidget( KWidget_MenuItem.create(kode_rect.rect(16),name, kwa_fillTop) ); end; end; wdg_Panel.appendWidget(wdg_Menu_add); end; //-------------------------------------------------- // on_ //-------------------------------------------------- procedure myEditor.on_mouseDown(AXpos, AYpos, AButton, AState : LongInt); var index : longint; menuitem : KWidget_MenuItem; begin inherited; if (AButton = kmb_right) then begin if wdg_Menu_add.isopen then begin wdg_Menu_add.close; wdg_Menu.deselect; end else if wdg_Menu.isopen then wdg_Menu.close else wdg_Menu.open(AXpos,AYpos); end; end; //-------------------------------------------------- // do_ //-------------------------------------------------- procedure myEditor.do_update(AWidget:KWidget); var index : LongInt; subindex : LongInt; x,y : longint; info : KPModuleInfo; changed : boolean; begin changed := false; if AWidget = wdg_Menu then begin index := wdg_Menu.selected; //KTrace(['menu:', index,KODE_CR]); case index of 0: begin x := wdg_Menu._rect.x + 50; y := wdg_Menu._rect.y + 20; wdg_Menu_add.open(x,y); end; 1: begin (FPlugin as myPlugin).graph.removeSelectedModules; do_redraw(self,FRect); changed := true; wdg_Menu.close; end; else begin wdg_Menu.close; end; end; end else if AWidget = wdg_Menu_add then begin index := wdg_Menu.selected; subindex := wdg_Menu_add.selected; //KTrace(['menu:', index,' submenu:',subindex,KODE_CR]); if (subindex >= 0) and (subindex < KGetNumModules) then begin info := KGetModule(subindex); if Assigned(info) then begin x := wdg_Menu._rect.x; y := wdg_Menu._rect.y; (FPlugin as myPlugin).graph.addModule(KModule.create(info),x,y); changed := true;//do_redraw(self,FRect); end; end; wdg_Menu_add.close; wdg_Menu.close; end; if changed then do_redraw(self,FRect); inherited; end; //---------------------------------------------------------------------- end.
unit Integral; {$mode objfpc}{$H+} interface type TIntegral=Class private Ifuncion:String; Ia:Real; Ib:Real; Ino:Real; public Expresion:String; function Primitiva():Real; function TrapecioEvaluateIntegral():Real; function TrapecioEvaluateArea():Real; function Simpson13Evaluate():Real; function SimpsonEvaluateArea():Real; function Simpson38Evaluate():Real; function Simpson38EvaluateArea():Real; function Simpson38CompuestoEvaluate():Real; function Simpson38CompuestoEvaluateArea():Real; constructor create(fun:String;a,b,n:Real); destructor destroy; end; implementation uses Classes, SysUtils, ParseMath,math,Dialogs; constructor TIntegral.create(fun:String;a,b,n:Real); begin Ifuncion:=fun; Ia:=a; Ib:=b; Ino:=n; end; destructor TIntegral.destroy; begin end; function TIntegral.Primitiva():Real; var m_function:TParseMath; fa,fb:Real; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=m_function.Evaluate(); m_function.NewValue('x',Ib); fb:=m_function.Evaluate(); Result:=fb-fa; end; function TIntegral.TrapecioEvaluateIntegral():Real; var fa,fb,h,sum,i:Real; m_function:TParseMath; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=m_function.Evaluate(); m_function.NewValue('x',Ib); fb:=m_function.Evaluate(); h:=(Ib-Ia)/(Ino);///AQUI falata dividir sum:=0; i:=Ia+h; //ShowMessage('xn:'+FloatToStr(i)); repeat ShowMessage('xn:'+FloatToStr(i)); m_function.NewValue('x',i); //ShowMessage('yn'+FloatToStr(m_function.Evaluate())); sum:=sum+m_function.Evaluate(); //ShowMessage('sumatoria'+FloatToStr(sum)); i:=i+h; until i>=Ib; ShowMessage('sumatoria:'+FloatToStr(sum)); ShowMessage('fa'+FloatToStr(fa)+'fb():'+FloatToStr(fb)); //m_function.destroy; TrapecioEvaluateIntegral:=RoundTo(0.5*h*(fa+fb)+h*sum,-6); { h:=(lb-la)/n; MiParse.NewValue('x',la); fa:=MiParse.Evaluate(); MiParse.NewValue('x',lb); fb:=MiParse.Evaluate(); sum:=0; i:=la+h; repeat MiParse.NewValue('x',i); sum:=sum+MiParse.Evaluate(); i:=i+h; until i>=lb; resp:=RoundTo(0.5*h*(fa+fb)+h*sum,-6); Result.resFloat := resp; } end; function TIntegral.TrapecioEvaluateArea():Real; var fa,fb,h,sum,i:Real; m_function:TParseMath; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=m_function.Evaluate(); m_function.NewValue('x',Ib); fb:=m_function.Evaluate(); h:=(Ib-Ia)/(Ino*100000); sum:=0; i:=Ia+h; repeat m_function.NewValue('x',i); sum:=sum+abs(m_function.Evaluate()); i:=i+h; until i>=Ib; TrapecioEvaluateArea:=RoundTo(h*( (abs(fa)+abs(fb))/2 +sum ),-6); end; function TIntegral.Simpson13Evaluate():Real; var fa,fb,h,sum,sum2,i:Real; m_function:TParseMath; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=m_function.Evaluate(); m_function.NewValue('x',Ib); fb:=m_function.Evaluate(); h:=(Ib-Ia)/(2*Ino); ShowMessage('h:='+FloatToStr(h)); sum:=0;//impares sum2:=0; ShowMessage('fa:'+FloatToStr(fa)+ 'fb:'+FloatToStr(fb)); i:=Ia+h; repeat ShowMessage('xn:'+FloatToStr(i)); m_function.NewValue('x',i); sum:=sum+m_function.Evaluate(); i:=i+2*h; until i>=Ib; ShowMessage('impares'+FloatToStr(sum)); i:=Ia+2*h; repeat ShowMessage('xn:'+FloatToStr(i)); m_function.NewValue('x',i); sum2:=sum2+m_function.Evaluate(); i:=i+2*h; until i>=Ib-h; ShowMessage('pares'+FloatToStr(sum2)); // Pares// Impares Simpson13Evaluate:=RoundTo( (h/3) * ((fa+fb) + 2*sum2 + 4 * sum),-6); end; function TIntegral.SimpsonEvaluateArea():Real; var fa,fb,h,sum,sum2,i:Real; m_function:TParseMath; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=abs(m_function.Evaluate()); m_function.NewValue('x',Ib); fb:=abs(m_function.Evaluate()); h:=(Ib-Ia)/(2*Ino); sum:=0; sum2:=0; i:=Ia+h; repeat m_function.NewValue('x',i); sum:=sum+abs(m_function.Evaluate()); i:=i+2*h; until i>=Ib; i:=Ia+2*h; repeat m_function.NewValue('x',i); sum2:=sum2+abs(m_function.Evaluate()); i:=i+2*h; until i>=Ib-h; // Pares// Impares SimpsonEvaluateArea:=RoundTo( (h/3) * ((abs(fa)+abs(fb)) + 2*sum2 + 4 * sum),-6); end; function TIntegral.Simpson38Evaluate():Real; var fa,fb,h,M,M2,i:Real; m_function:TParseMath; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=m_function.Evaluate(); m_function.NewValue('x',Ib); fb:=m_function.Evaluate(); m_function.NewValue('x',(2*Ia+Ib)/3); M:=m_function.Evaluate(); m_function.NewValue('x',(Ia+2*Ib)/3); M2:=m_function.Evaluate(); h:=(Ib-Ia)/3; Simpson38Evaluate:=RoundTo( (3*h/8) * ((fa+fb) + 3*M + 3*M2),-6); end; function TIntegral.Simpson38EvaluateArea():Real; var fa,fb,h,M,M2,i:Real; m_function:TParseMath; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=abs(m_function.Evaluate()); m_function.NewValue('x',Ib); fb:=abs(m_function.Evaluate()); m_function.NewValue('x',(2*Ia+Ib)/3); M:=abs(m_function.Evaluate()); m_function.NewValue('x',(Ia+2*Ib)/3); M2:=abs(m_function.Evaluate()); h:=(Ib-Ia)/3; Simpson38EvaluateArea:=RoundTo( (3*h/8) * ((abs(fa)+abs(fb)) + 3*M + 3*M2),-6); end; function TIntegral.Simpson38CompuestoEvaluate():Real; var fa,fb,h,sum,sum2,sum3,i,Rpt:Real; m_function:TParseMath; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=m_function.Evaluate(); m_function.NewValue('x',Ib); fb:=m_function.Evaluate(); h:=(Ib-Ia)/(3*Ino); sum:=0; sum2:=0; sum3:=0; i:=Ia+h; while i<Ib do begin m_function.NewValue('x',i); sum:=sum+m_function.Evaluate(); i:=i+(3*h); end; i:=Ia+(2*h); while i<Ib do begin m_function.NewValue('x',i); sum2:=sum2+m_function.Evaluate(); i:=i+(3*h); end; // Pares// Impares i:=Ia+(3*h); while i<Ib do begin; m_function.NewValue('x',i); sum3:=sum3+m_function.Evaluate(); i:=i+(3*h); end; Rpt:=fa+fb+(3*sum)+(3*sum2)+(2*sum3); Rpt:=(3*h/8)*Rpt; Simpson38CompuestoEvaluate:=RoundTo(Rpt,-4); end; function TIntegral.Simpson38CompuestoEvaluateArea():Real; var fa,fb,h,sum,sum2,sum3,i:Real; m_function:TParseMath; begin m_function:=TParseMath.create(); m_function.AddVariable('x',0); m_function.Expression:=Ifuncion; m_function.NewValue('x',Ia); fa:=abs(m_function.Evaluate()); m_function.NewValue('x',Ib); fb:=abs(m_function.Evaluate()); h:=(Ib-Ia)/Ino; sum:=0; sum2:=0; sum3:=0; i:=Ia+h; repeat m_function.NewValue('x',i); sum:=sum+abs(m_function.Evaluate()); i:=i+3*h; until i>Ib-2*h; i:=Ia+2*h; repeat m_function.NewValue('x',i); sum2:=sum2+abs(m_function.Evaluate()); i:=i+3*h; until i>Ib-h; // Pares// Impares i:=Ia+3*h; repeat m_function.NewValue('x',i); sum3:=sum3+abs(m_function.Evaluate()); i:=i+3*h; until i>Ib-3*h; Simpson38CompuestoEvaluateArea:=RoundTo( (3*h/8) * ((abs(fa)+abs(fb)) + 3*sum + 3*sum2 + 2*sum3),-6); end; end.
unit UDownThread; interface uses Classes, Windows, SysUtils, IdHTTP, IdComponent, Math, Messages; const WM_DownProgres = WM_USER + 1001; type TDownThread = class(TThread) private FIDHttp: TIdHTTP; FMaxProgres: Int64; FMs: TMemoryStream; FURL: string; FSavePath: string; FHandle: THandle; FileSize, FilePosition: Int64; { Private declarations } procedure DoExecute; procedure DoWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); procedure DoWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); protected procedure Execute; override; public ID: string; constructor Create(AURL, ASavePath: string; AHandle: THandle); destructor Destroy; override; end; implementation { uDownThread } constructor TDownThread.Create(AURL, ASavePath: string; AHandle: THandle); begin FURL := AURL; FSavePath := ASavePath; FHandle := AHandle; FIDHttp := TIdHTTP.Create(nil); FIDHttp.HandleRedirects:=True; FIDHttp.Request.Accept := 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*'; FIDHttp.Request.AcceptLanguage := 'zh-cn'; FIDHttp.Request.ContentType := 'application/x-www-form-urlencoded'; FIDHttp.Request.UserAgent := 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)'; FIDHttp.ReadTimeout:= 60000; FIDHttp.OnWorkBegin := DoWorkBegin; FIDHttp.OnWork := DoWork; inherited Create(False); // ²ÎÊýΪFalseÖ¸Ï̴߳´½¨ºó×Ô¶¯ÔËÐÐ,ΪTrueÔò²»×Ô¶¯ÔËÐÐ FreeOnTerminate := True; // Ö´ÐÐÍê±Ïºó×Ô¶¯ÊÍ·Å end; destructor TDownThread.Destroy; begin PostMessage(FHandle, WM_DownProgres, Integer(ID), 100); FIDHttp.Free; FMs.Free; inherited; end; procedure TDownThread.DoExecute; const RECV_BUFFER_SIZE = 512000;//102400; var DownCount: Integer; begin FMs := TMemoryStream.Create; FIDHttp.Head(FURL); FileSize := FIDHttp.Response.ContentLength; FilePosition:=0; DownCount := 0; while FilePosition < FileSize do begin Inc(DownCount); FIDHttp.Request.Range := IntToStr(FilePosition) + '-' ; if FilePosition + RECV_BUFFER_SIZE < FileSize then FIDHttp.Request.Range := FIDHttp.Request.Range + IntToStr(FilePosition + (RECV_BUFFER_SIZE-1)); FIDHttp.Get(FIDHttp.URL.URI, FMs); // wait until it is done FMs.SaveToFile(FSavePath); FilePosition := FMs.Size; if (DownCount=1) and (FilePosition>RECV_BUFFER_SIZE) then Break; end; // // FIDHttp.Get(FURL, FMs); // FMs.SaveToFile(FSavePath); end; procedure TDownThread.DoWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); var ANowProgres: Integer; begin if FMaxProgres <> 0 then begin // ANowProgres := Ceil(AWorkCount / FMaxProgres * 100); // PostMessage(FHandle, WM_DownProgres, 0, ANowProgres); ANowProgres := Ceil(FMs.Size / FileSize * 100); if ANowProgres<100 then PostMessage(FHandle, WM_DownProgres, Integer(ID), ANowProgres); end; end; procedure TDownThread.DoWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin FMaxProgres := AWorkCountMax; end; procedure TDownThread.Execute; begin DoExecute; end; end.
{ ************************************* Created by Danilo Lucas Github - https://github.com/dliocode ************************************* } unit SendEmail; interface uses System.SysUtils, System.StrUtils, System.Classes, System.TypInfo, System.Threading, System.SyncObjs, IdSMTP, IdSSL, IdSSLOpenSSL, IdSSLOpenSSLHeaders, IdExplicitTLSClientServerBase, IdIOHandler, IdMessage, IdMessageBuilder, idGlobal, IdComponent, IdAttachmentFile; type TPriority = IdMessage.TIdMessagePriority; TAttachmentDisposition = (adAttachment, adInline); TLogMode = (lmComponent, lmLib, lmAll, lmNone); TSendEmail = class private FIdSMTP: TIdSMTP; FIdSSLOpenSSL: TIdSSLIOHandlerSocketOpenSSL; FIdMessage: TIdMessage; FIdMessageBuilderHTML: TIdMessageBuilderHtml; FSSL: Boolean; FTLS: Boolean; FLogExecute: TProc<string>; FLogMode: TLogMode; FWorkBegin: TProc<Int64>; FWork: TProc<Int64>; FWorkEnd: TProc; FMessageStream: TMemoryStream; FConnectMaxReconnection: Integer; FConnectCountReconnect: Integer; FSendMaxReconnection: Integer; FSendCountReconnect: Integer; class var RW: TMultiReadExclusiveWriteSynchronizer; class var FInstance: TSendEmail; procedure Reconnect(AResend: Boolean = False); procedure LogSMTPStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); procedure LogSSLStatus(const AMsg: string); procedure Log(const ALog: string; const AForced: Boolean = False); procedure WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); procedure Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); procedure WorkEnd(ASender: TObject; AWorkMode: TWorkMode); public function From(const AEmail: string; const AName: string = ''): TSendEmail; function AddTo(const AEmail: string; const AName: string = ''): TSendEmail; function AddReceiptRecipient(const AEmail: string; const AName: string = ''): TSendEmail; function AddReplyTo(const AEmail: string; const AName: string = ''): TSendEmail; function AddCC(const AEmail: string; const AName: string = ''): TSendEmail; function AddBCC(const AEmail: string; const AName: string = ''): TSendEmail; function Priority(const APriority: TPriority): TSendEmail; function Subject(const ASubject: string): TSendEmail; function Message(const AMessage: string; const IsBodyHTML: Boolean = True): TSendEmail; function AddAttachment(const AFileName: string; const ADisposition: TAttachmentDisposition = adAttachment): TSendEmail; overload; function AddAttachment(const AData: TStream; const AFileName: string; const ADisposition: TAttachmentDisposition = adAttachment): TSendEmail; overload; function Host(const AHost: string): TSendEmail; function Port(const APort: Integer): TSendEmail; function Auth(const AValue: Boolean): TSendEmail; function UserName(const AUserName: string): TSendEmail; function Password(const APassword: string): TSendEmail; function SSL(const AValue: Boolean): TSendEmail; function TLS(const AValue: Boolean): TSendEmail; function Clear: TSendEmail; function ClearRecipient: TSendEmail; function Connect: TSendEmail; function Send(const ADisconnectAfterSending: Boolean = True): TSendEmail; function SendAsync(const ACallBack: TProc<Boolean, string> = nil; const ADisconnectAfterSending: Boolean = True): TSendEmail; function Disconnect: TSendEmail; function IsConnected: Boolean; function OnLog(const AExecute: TProc<string>; const ALogMode: TLogMode = lmComponent): TSendEmail; function OnWorkBegin(const AExecute: TProc<Int64>): TSendEmail; function OnWork(const AExecute: TProc<Int64>): TSendEmail; function OnWorkEnd(const AExecute: TProc): TSendEmail; constructor Create; destructor Destroy; override; class function New: TSendEmail; class destructor UnInitialize; end; implementation { TSendEmail } class function TSendEmail.New: TSendEmail; begin if not Assigned(FInstance) then FInstance := TSendEmail.Create; Result := FInstance; end; class destructor TSendEmail.UnInitialize; begin if Assigned(FInstance) then try FInstance.OnLog(nil); FInstance.Disconnect; finally FreeAndNil(FInstance); end; end; constructor TSendEmail.Create; begin FIdSMTP := TIdSMTP.Create; FIdSSLOpenSSL := TIdSSLIOHandlerSocketOpenSSL.Create; FIdMessageBuilderHTML := TIdMessageBuilderHtml.Create; FIdMessage := TIdMessage.Create; FMessageStream := TMemoryStream.Create; FLogExecute := nil; FLogMode := lmNone; FWorkBegin := nil; FWork := nil; FWorkEnd := nil; FConnectMaxReconnection := 5; FConnectCountReconnect := 0; FSendMaxReconnection := 5; FSendCountReconnect := 0; Auth(True); SSL(False); TLS(False); Priority(mpNormal); Port(587); with FIdSMTP do begin MailAgent := 'SendEmail'; ConnectTimeout := 60000; ReadTimeout := 60000; UseEhlo := True; OnStatus := LogSMTPStatus; OnWorkBegin := WorkBegin; OnWork := Work; OnWorkEnd := WorkEnd; ManagedIOHandler := True; PipeLine := False; end; with FIdSSLOpenSSL do begin ConnectTimeout := 100000; ReadTimeout := 100000; PassThrough := True; SSLOptions.SSLVersions := [SslvSSLv2, SslvSSLv23, SslvSSLv3, SslvTLSv1, SslvTLSv1_1, SslvTLSv1_2]; SSLOptions.Mode := SslmBoth; SSLOptions.VerifyMode := []; SSLOptions.VerifyDepth := 0; OnStatus := LogSMTPStatus; OnStatusInfo := LogSSLStatus; end; with FIdMessage do begin IsEncoded := True; UseNowForDate := True; end; end; destructor TSendEmail.Destroy; begin FWorkBegin := nil; FWork := nil; FWorkEnd := nil; FLogExecute := nil; FreeAndNil(FMessageStream); FreeAndNil(FIdMessageBuilderHTML); FreeAndNil(FIdMessage); FreeAndNil(FIdSSLOpenSSL); FreeAndNil(FIdSMTP); inherited; end; function TSendEmail.From(const AEmail, AName: string): TSendEmail; begin Result := Self; if AEmail.Trim.IsEmpty then Exit; if IsConnected then if not FIdMessage.From.Address.Contains(AEmail) then Disconnect else Exit; FIdMessage.From.Name := AName; FIdMessage.From.Address := AEmail; Log(Format('From: %s', [AEmail])); end; function TSendEmail.AddTo(const AEmail, AName: string): TSendEmail; begin Result := Self; if AEmail.Trim.IsEmpty then Exit; with FIdMessage.Recipients.Add do begin name := AName; Address := AEmail; end; Log(Format('To(%d): %s', [FIdMessage.Recipients.Count, AEmail])); end; function TSendEmail.AddReceiptRecipient(const AEmail, AName: string): TSendEmail; begin Result := Self; if AEmail.Trim.IsEmpty then Exit; FIdMessage.ReceiptRecipient.Name := AName; FIdMessage.ReceiptRecipient.Address := AEmail; Log(Format('ReceiptRecipient: %s', [AEmail])); end; function TSendEmail.AddReplyTo(const AEmail, AName: string): TSendEmail; begin Result := Self; if AEmail.Trim.IsEmpty then Exit; with FIdMessage.ReplyTo.Add do begin name := AName; Address := AEmail; end; Log(Format('ReplyTo(%d): %s', [FIdMessage.ReplyTo.Count, AEmail])); end; function TSendEmail.AddCC(const AEmail, AName: string): TSendEmail; begin Result := Self; if AEmail.Trim.IsEmpty then Exit; with FIdMessage.CCList.Add do begin name := AName; Address := AEmail; end; Log(Format('CC(%d): %s', [FIdMessage.CCList.Count, AEmail])); end; function TSendEmail.AddBCC(const AEmail, AName: string): TSendEmail; begin Result := Self; if AEmail.Trim.IsEmpty then Exit; with FIdMessage.BCCList.Add do begin name := AName; Address := AEmail; end; Log(Format('BCC(%d): %s', [FIdMessage.BCCList.Count, AEmail])); end; function TSendEmail.Priority(const APriority: TPriority): TSendEmail; begin Result := Self; if FIdMessage.Priority = APriority then Exit; FIdMessage.Priority := APriority; Log(Format('Priority: %s', [GetEnumName(TypeInfo(TPriority), Integer(APriority))])); end; function TSendEmail.Subject(const ASubject: string): TSendEmail; begin Result := Self; if not FIdMessage.Subject.Contains(ASubject) then FIdMessage.Subject := ASubject else Exit; Log(Format('Subject: %s', [ASubject])); end; function TSendEmail.Message(const AMessage: string; const IsBodyHTML: Boolean = True): TSendEmail; begin Result := Self; if IsBodyHTML then begin FIdMessageBuilderHTML.Html.Text := AMessage; FIdMessageBuilderHTML.HtmlCharSet := 'utf-8'; FIdMessageBuilderHTML.HtmlContentTransfer := 'base64'; // quoted-printable end else begin FIdMessageBuilderHTML.PlainText.Text := AMessage; FIdMessageBuilderHTML.PlainTextCharSet := 'utf-8'; FIdMessageBuilderHTML.PlainTextContentTransfer := 'base64'; // quoted-printable end; Log(Format('Message: %s', [IfThen(IsBodyHTML, 'HTML', 'PlainText')])); end; function TSendEmail.AddAttachment(const AFileName: string; const ADisposition: TAttachmentDisposition = adAttachment): TSendEmail; begin Result := Self; if AFileName.Trim.IsEmpty then Exit; if not FileExists(AFileName) then begin Log('Attachment: Not found - ' + ExtractFileName(AFileName)); Exit; end; case ADisposition of adAttachment: begin FIdMessageBuilderHTML.Attachments.Add(AFileName); Log(Format('Attachment(adAttachment)(%d): %s', [FIdMessageBuilderHTML.Attachments.Count, ExtractFileName(AFileName)])); end; adInline: begin FIdMessageBuilderHTML.HtmlFiles.Add(AFileName); Log(Format('Attachment(adInline)(%d): %s', [FIdMessageBuilderHTML.HtmlFiles.Count, ExtractFileName(AFileName)])); end; end; end; function TSendEmail.AddAttachment(const AData: TStream; const AFileName: string; const ADisposition: TAttachmentDisposition = adAttachment): TSendEmail; var LAdd: TIdMessageBuilderAttachment; begin Result := Self; if not Assigned(AData) then Exit; if AFileName.Trim.IsEmpty then Exit; AData.Position := 0; LAdd := nil; case ADisposition of adAttachment: begin LAdd := FIdMessageBuilderHTML.Attachments.Add(AData, '', AFileName); Log(Format('Attachment(adAttachment)(%d): %s', [FIdMessageBuilderHTML.Attachments.Count, ExtractFileName(AFileName)])); end; adInline: begin LAdd := FIdMessageBuilderHTML.HtmlFiles.Add(AData, '', AFileName); Log(Format('Attachment(adInline)(%d): %s', [FIdMessageBuilderHTML.HtmlFiles.Count, ExtractFileName(AFileName)])); end; end; if not Assigned(LAdd) then Exit; LAdd.FileName := AFileName; LAdd.Name := ExtractFileName(AFileName); LAdd.WantedFileName := ExtractFileName(AFileName); end; function TSendEmail.Host(const AHost: string): TSendEmail; begin Result := Self; if IsConnected then if not FIdSMTP.Host.Contains(AHost) then Disconnect else Exit; FIdSMTP.Host := AHost; Log(Format('Host: %s', [AHost])); end; function TSendEmail.Port(const APort: Integer): TSendEmail; begin Result := Self; if IsConnected then if not FIdSMTP.Port = APort then Disconnect else Exit; FIdSMTP.Port := APort; Log(Format('Port: %d', [APort])); end; function TSendEmail.Auth(const AValue: Boolean): TSendEmail; begin Result := Self; if AValue then FIdSMTP.AuthType := satDefault else FIdSMTP.AuthType := satNone; Log(Format('Auth: %s', [IfThen(AValue, 'True', 'False')])); end; function TSendEmail.UserName(const AUserName: string): TSendEmail; begin Result := Self; if IsConnected then if not FIdSMTP.UserName.Contains(AUserName) then Disconnect else Exit; FIdSMTP.UserName := AUserName; Log(Format('UserName: %s', [AUserName])); end; function TSendEmail.Password(const APassword: string): TSendEmail; begin Result := Self; if IsConnected then if not FIdSMTP.Password.Contains(APassword) then Disconnect else Exit; FIdSMTP.Password := APassword; Log(Format('Password: %s', ['********'])); end; function TSendEmail.SSL(const AValue: Boolean): TSendEmail; begin Result := Self; FSSL := AValue; end; function TSendEmail.TLS(const AValue: Boolean): TSendEmail; begin Result := Self; FTLS := AValue; end; function TSendEmail.Clear: TSendEmail; begin Result := Self; Priority(mpNormal); FIdMessage.ClearHeader; FIdMessage.Body.Clear; FIdMessage.MessageParts.Clear; FIdMessageBuilderHTML.Clear; end; function TSendEmail.ClearRecipient: TSendEmail; begin Result := Self; Priority(mpNormal); FIdMessage.Recipients.Clear; FIdMessage.ReceiptRecipient.Text := ''; FIdMessage.ReplyTo.Clear; FIdMessage.CCList.Clear; FIdMessage.BCCList.Clear; FIdMessage.Subject := ''; FIdMessage.MessageParts.Clear; FIdMessageBuilderHTML.Clear; end; function TSendEmail.Connect: TSendEmail; var LLastResult: string; begin Result := Self; if IsConnected then Exit; if FSSL or FTLS then begin if FSSL and FTLS then Log('Defining encryption: SSL/TLS') else if FSSL then Log('Defining encryption: SSL') else Log('Defining encryption: TLS'); Log('Loading DLL'); if not LoadOpenSSLLibrary then begin Log(WhichFailedToLoad); raise Exception.Create(Self.ClassName + ' > ' + WhichFailedToLoad); end; Log('Loaded DLL'); if FSSL then FIdSSLOpenSSL.SSLOptions.Method := SslvSSLv23; if FTLS then FIdSSLOpenSSL.SSLOptions.Method := SslvTLSv1_2; FIdSSLOpenSSL.Destination := FIdSMTP.Host + ':' + FIdSMTP.Port.ToString; FIdSSLOpenSSL.Host := FIdSMTP.Host; FIdSSLOpenSSL.Port := FIdSMTP.Port; FIdSMTP.IOHandler := FIdSSLOpenSSL; if MatchText(FIdSMTP.Port.ToString, ['25', '587', '2587']) then FIdSMTP.UseTLS := utUseExplicitTLS else FIdSMTP.UseTLS := utUseImplicitTLS; end else begin Log('Defining encryption: None'); FIdSMTP.IOHandler := nil; FIdSMTP.UseTLS := UtNoTLSSupport; end; try Log('Connecting'); FIdSMTP.Connect; Log('Connected'); if FIdSMTP.AuthType <> satNone then begin Log('Authenticating'); FIdSMTP.Authenticate; Log('Authenticated'); end; FConnectCountReconnect := 0; except on E: Exception do begin if FIdSMTP.LastCmdResult.ReplyExists then begin LLastResult := Format('Last Result: %s', [FIdSMTP.LastCmdResult.FormattedReply.Text]); if LLastResult.ToUpper.Contains('AUTHENTICATION SUCCEEDED') or LLastResult.Contains('250 OK') then begin Log(LLastResult, True); if FConnectCountReconnect < FConnectMaxReconnection then begin Sleep(100); Inc(FConnectCountReconnect); Reconnect(False); Exit; end else begin FConnectCountReconnect := 0; raise Exception.Create(E.Message); end; end; end; try if E.Message.ToUpper.Contains('INCORRECT AUTHENTICATION DATA') then raise Exception.Create('Incorrect authentication!'); if E.Message.ToUpper.Contains('SOCKET ERROR # 10013') then raise Exception.Create('Firewall is blocking access to the internet!'); if E.Message.ToUpper.Contains('SOCKET ERROR # 10054') then raise Exception.Create('Connection terminated!'); if E.Message.ToUpper.Contains('SOCKET ERROR # 11001') then raise Exception.Create('Host not found!'); if LLastResult.Contains(E.Message) and not LLastResult.Trim.IsEmpty then raise Exception.Create(LLastResult + sLineBreak + 'Message: ' + E.Message) else raise Exception.Create(E.Message); except on E: Exception do begin Log('Except: ' + E.Message, True); Log('Email not connected!'); raise; end; end; end; end; end; function TSendEmail.Send(const ADisconnectAfterSending: Boolean = True): TSendEmail; begin Result := Self; if not IsConnected then Connect; try try Log('Sending email'); FIdMessageBuilderHTML.FillMessage(FIdMessage); FIdMessage.SaveToStream(FMessageStream); FIdSMTP.Send(FIdMessage); Log('Email sent'); FSendCountReconnect := 0; except on E: Exception do begin Log('Except: ' + E.Message, True); if E.Message.ToUpper.Contains('CLOSING CONNECTION') or E.Message.ToUpper.Contains('TOO MANY MESSAGES') or E.Message.ToUpper.Contains('CONNECTION CLOSED') then begin if FSendCountReconnect < FSendMaxReconnection then begin Sleep(100); Inc(FSendCountReconnect); Reconnect(True); Exit; end else begin FSendCountReconnect := 0; raise Exception.Create(E.Message); end; end; if E.Message.ToUpper.Contains('NOT CONNECTED') then raise Exception.Create('Not connected to internet!'); if E.Message.ToUpper.Contains('NO SUCH USER HERE') or E.Message.ToUpper.Contains('USER UNKNOWN') or E.Message.ToUpper.Contains('MAILBOX UNAVAILABLE') then raise Exception.Create('The recipient''s mailbox does not exist in the destination domain. It was probably typed incorrectly!'); if E.Message.ToUpper.Contains('MAILBOX IS FULL') or E.Message.ToUpper.Contains('MAIL QUOTA EXCEEDED') or E.Message.ToUpper.Contains('MAILBOX FULL') or E.Message.ToUpper.Contains('DISK QUOTA EXCEEDED') or E.Message.ToUpper.Contains('USER IS OVER THE QUOTA') then raise Exception.Create('It means that the recipient''s inbox is full and cannot receive any more messages!'); raise Exception.Create(E.Message); end; end; finally if ADisconnectAfterSending then Disconnect; end; end; function TSendEmail.SendAsync(const ACallBack: TProc<Boolean, string> = nil; const ADisconnectAfterSending: Boolean = True): TSendEmail; begin Result := Self; TThread.CreateAnonymousThread( procedure var LMessage: string; begin RW.BeginWrite; try try Send(ADisconnectAfterSending); except on E: Exception do LMessage := E.Message; end; finally RW.EndWrite; end; TThread.Synchronize(TThread.CurrentThread, procedure begin if Assigned(ACallBack) then ACallBack(not LMessage.Trim.IsEmpty, LMessage) else raise Exception.Create(LMessage); end); end).Start; end; function TSendEmail.Disconnect: TSendEmail; begin Result := Self; if IsConnected then try Log('Disconnecting'); FIdSMTP.Disconnect(False); Log('Disconnected'); except Log('Except: Disconnected with error'); end; end; function TSendEmail.IsConnected: Boolean; begin Result := False; try Result := FIdSMTP.Connected; except on E: Exception do begin if E.Message.ToUpper.Contains('CLOSING CONNECTION') or E.Message.ToUpper.Contains('SSL3_GET_RECORD') then try Reconnect(False); Result := True; except Exit; end; end; end; end; function TSendEmail.OnLog(const AExecute: TProc<string>; const ALogMode: TLogMode = lmComponent): TSendEmail; begin Result := Self; FLogExecute := AExecute; FLogMode := ALogMode; end; function TSendEmail.OnWorkBegin(const AExecute: TProc<Int64>): TSendEmail; begin Result := Self; FWorkBegin := AExecute; end; function TSendEmail.OnWork(const AExecute: TProc<Int64>): TSendEmail; begin Result := Self; FWork := AExecute; end; function TSendEmail.OnWorkEnd(const AExecute: TProc): TSendEmail; begin Result := Self; FWorkEnd := AExecute; end; procedure TSendEmail.Reconnect(AResend: Boolean = False); begin if AResend then Log('Reconnecting: ' + FSendCountReconnect.ToString, True) else Log('Reconnecting: ' + FConnectCountReconnect.ToString, True); Disconnect; Connect; if AResend then Send; end; procedure TSendEmail.LogSMTPStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin if Assigned(FLogExecute) and (FLogMode in [lmComponent, lmAll]) then FLogExecute('SMTP: ' + AStatusText); end; procedure TSendEmail.LogSSLStatus(const AMsg: string); begin if Assigned(FLogExecute) and (FLogMode in [lmComponent, lmAll]) then FLogExecute('SSL: ' + AMsg.ToUpper.Replace('SSL STATUS: ', '')); end; procedure TSendEmail.Log(const ALog: string; const AForced: Boolean = False); begin if Assigned(FLogExecute) and ((FLogMode in [lmLib, lmAll]) or AForced) and not(FLogMode = lmNone) then FLogExecute('LIB: ' + ALog); end; procedure TSendEmail.WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin Log('Starting transmission'); if Assigned(FWorkBegin) and (AWorkMode = wmWrite) then begin FMessageStream.Position := 0; FWorkBegin(FMessageStream.Size); end; end; procedure TSendEmail.Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin if Assigned(FWork) and (AWorkMode = wmWrite) then FWork(AWorkCount); end; procedure TSendEmail.WorkEnd(ASender: TObject; AWorkMode: TWorkMode); begin Log('Transmission completed'); FMessageStream.Clear; if Assigned(FWorkEnd) then FWorkEnd; end; initialization TSendEmail.RW := TMultiReadExclusiveWriteSynchronizer.Create; finalization FreeAndNil(TSendEmail.RW); end.
unit rcIssuePriority; {$mode objfpc}{$H+} interface uses Classes, SysUtils, rcObject,rcArrayManager; type { TIssuePriority } TIssuePriority = class(TRCObject) protected isDefault1: boolean; public property isDefault: boolean read isDefault1 write isDefault1; constructor Create(AName: string; AID: Integer); override; end; { TPrioritys } TPrioritys = class(TRCArrayManager) private function GetItem(index: Integer): TIssuePriority; public property Item[index: Integer]: TIssuePriority read GetItem; function Add(AObject: TIssuePriority): TIssuePriority; function GetItemBy(AID: Integer): TIssuePriority; overload; end; implementation { TIssuePriority } constructor TIssuePriority.Create(AName: string; AID: Integer); begin inherited Create(AName, AID); isDefault1 := False; end; { TPrioritys } function TPrioritys.GetItem(index: Integer): TIssuePriority; begin Result := inherited GetItem(index) as TIssuePriority; end; function TPrioritys.Add(AObject: TIssuePriority): TIssuePriority; begin Result := inherited Add(AObject) as TIssuePriority; end; function TPrioritys.GetItemBy(AID: Integer): TIssuePriority; begin Result := inherited GetItemBy(AID) as TIssuePriority; end; end.
unit U_Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,System.JSON, IdContext, IdCustomHTTPServer, IdBaseComponent, IdComponent, IdCustomTCPServer, IdHTTPServer, U_Clientes; type TF_Principal = class(TForm) lblNome: TLabel; lblinfo: TStaticText; memLogReq: TMemo; Label1: TLabel; memLogRes: TMemo; Label2: TLabel; IdHTTPServer1: TIdHTTPServer; btnAtivar: TButton; btnParar: TButton; procedure btnAtivarClick(Sender: TObject); procedure btnPararClick(Sender: TObject); procedure IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure IdHTTPServer1CommandOther(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } cli: TCliente; procedure LogLastRequest(req: TIdHTTPRequestInfo); procedure LogLastResponse(res: TIdHTTPResponseInfo); function CheckAuthentication(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo): Boolean; procedure GetClientes(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo); procedure InsertCliente(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo); procedure UpdateCliente(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo); procedure DeleteCliente(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo); public { Public declarations } end; var F_Principal: TF_Principal; implementation {$R *.dfm} uses U_Utilitarios; { TF_Principal } procedure TF_Principal.btnAtivarClick(Sender: TObject); begin IdHTTPServer1.Active := True; lblinfo.Caption := 'Aguardando requisições...'; btnAtivar.Enabled := False; btnParar.Enabled := True; end; procedure TF_Principal.btnPararClick(Sender: TObject); begin IdHTTPServer1.Active := False; lblinfo.Caption := 'WebService parado.'; btnAtivar.Enabled := True; btnParar.Enabled := False; end; function TF_Principal.CheckAuthentication(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo): Boolean; const user = 'user'; pass = 'pass'; begin Result := (req.AuthUsername = user) and (req.AuthPassword = pass); if not Result then begin res.ResponseNo := 401; LogLastRequest(req); LogLastResponse(res); res.AuthRealm := res.ResponseText; end; end; procedure TF_Principal.FormCreate(Sender: TObject); begin cli := TCliente.Create(Self); end; procedure TF_Principal.FormDestroy(Sender: TObject); begin cli.Free; end; procedure TF_Principal.IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); begin if CheckAuthentication(ARequestInfo, AResponseInfo) then if ARequestInfo.CommandType in [hcGET, hcPOST] then begin LogLastRequest(ARequestInfo); case ARequestInfo.CommandType of hcGET: GetClientes(ARequestInfo, AResponseInfo); hcPOST: InsertCliente(ARequestInfo, AResponseInfo); end; LogLastResponse(AResponseInfo); AResponseInfo.WriteContent; end; end; procedure TF_Principal.IdHTTPServer1CommandOther(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); begin if CheckAuthentication(ARequestInfo, AResponseInfo) then if ARequestInfo.CommandType in [hcPUT, hcDELETE] then begin LogLastRequest(ARequestInfo); case ARequestInfo.CommandType of hcPUT: UpdateCliente(ARequestInfo, AResponseInfo); hcDELETE: DeleteCliente(ARequestInfo, AResponseInfo); end; LogLastResponse(AResponseInfo); AResponseInfo.WriteContent; end; end; procedure TF_Principal.GetClientes(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo); var i, id: Integer; st: TStrings; ret, erro: String; begin st := TStringList.Create; try if req.Params.Count > 0 then begin for i := 0 to req.Params.Count -1 do begin if i = 0 then st.Add(Format('where %s = %s', [GetValueBefore(req.Params[i], '='), QuotedStr(GetValueAfter(req.Params[i], '='))])) else st.Add(Format('and %s = %s', [GetValueBefore(req.Params[i], '='), QuotedStr(GetValueAfter(req.Params[i], '='))])) end; end else if req.URI <> '/' then begin if TryStrToInt(GetValueAfter(req.URI, '/'), id) then st.Add(Format('where id = %d', [id])); end; ret := cli.Buscar(st, erro); if erro = EmptyStr then begin res.ContentText := ret; res.ResponseNo := 200; end else begin res.ContentText := erro; res.ResponseNo := 500; end; finally st.Free; end; end; procedure TF_Principal.InsertCliente(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo); var st: TStringStream; jsObj: TJSONObject; erro: String; begin st := TStringStream.Create(EmptyStr, TEncoding.UTF8); st.CopyFrom(req.PostStream, req.PostStream.Size); jsObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(st.DataString),0) as TJSONObject; cli.nome := GetJsonValue(jsObj, 'nome'); cli.endereco := GetJsonValue(jsObj, 'endereco'); cli.telefone := GetJsonValue(jsObj, 'telefone'); cli.celular := GetJsonValue(jsObj, 'celular'); cli.cidade := GetJsonValue(jsObj, 'cidade'); cli.estado := GetJsonValue(jsObj, 'estado'); cli.ativo := Boolean(StrToIntDef(GetJsonValue(jsObj, 'ativo'), 0)); cli.saldo := StrToFloatDef(GetJsonValue(jsObj, 'saldo'), 0); if cli.Incluir(erro) then begin jsObj.AddPair('id', TJSONNumber.Create(cli.id)); res.ContentText := jsObj.ToJSON; res.ResponseNo := 201; end else begin res.ContentText := erro; res.ResponseNo := 500; end; st.Free; jsObj.Free; end; procedure TF_Principal.UpdateCliente(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo); var st: TStringStream; jsObj: TJSONObject; erro: String; id: Integer; begin if req.URI <> '/' then begin if TryStrToInt(GetValueAfter(req.URI, '/'), id) then begin cli.id := id; st := TStringStream.Create(EmptyStr, TEncoding.UTF8); st.CopyFrom(req.PostStream, req.PostStream.Size); jsObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(st.DataString),0) as TJSONObject; cli.id := id; cli.nome := GetJsonValue(jsObj, 'nome'); cli.endereco := GetJsonValue(jsObj, 'endereco'); cli.telefone := GetJsonValue(jsObj, 'telefone'); cli.celular := GetJsonValue(jsObj, 'celular'); cli.cidade := GetJsonValue(jsObj, 'cidade'); cli.estado := GetJsonValue(jsObj, 'estado'); cli.ativo := Boolean(StrToIntDef(GetJsonValue(jsObj, 'ativo'), 0)); cli.saldo := StrToFloatDef(GetJsonValue(jsObj, 'saldo'), 0); if cli.Alterar(erro) then begin jsObj.AddPair('id', TJSONNumber.Create(cli.id)); res.ContentText := jsObj.ToJSON; res.ResponseNo := 200; end else begin res.ContentText := erro; res.ResponseNo := 500; end; st.Free; jsObj.Free; end else begin res.ResponseNo := 403; res.ContentText := res.ResponseText; end; end else begin res.ResponseNo := 403; res.ContentText := res.ResponseText; end; end; procedure TF_Principal.DeleteCliente(req: TIdHTTPRequestInfo; res: TIdHTTPResponseInfo); var id: Integer; erro: String; begin if req.URI <> '/' then begin if TryStrToInt(GetValueAfter(req.URI, '/'), id) then begin cli.id := id; if cli.Excluir(erro) then res.ResponseNo := 204 else begin res.ContentText := erro; res.ResponseNo := 500; end; end else begin res.ResponseNo := 403; res.ContentText := res.ResponseText; end; end else begin res.ResponseNo := 403; res.ContentText := res.ResponseText; end; end; procedure TF_Principal.LogLastRequest(req: TIdHTTPRequestInfo); begin memLogReq.Lines.Add(Trim(req.UserAgent + sLineBreak + req.RawHTTPCommand)); end; procedure TF_Principal.LogLastResponse(res: TIdHTTPResponseInfo); begin memLogRes.Lines.Add(Trim('status: '+ res.ResponseNo.ToString +' ('+ res.ResponseText +')' + sLineBreak + res.ContentText)); end; end.
Program finitel; Uses crt, graph; Const g = 10; { 10 m/s } zeilen = 5; spalten = 5; epsilon: Real = 0.1; Type teilchen = Record c: Real; { Federkonstante } m: Real; { Masse in kg } xp, yp: Real; { Position } fax: Real; { Belastungskraft} fay: Real; { -"- } fx : Real; { Innere F } fy : Real; { -"- } frx, fry: Real; frei: Boolean; {Beweglich ? } End; Var l0_x, l0_y: Real; schritt_y, schritt_x: Real; verbund : Array [1..zeilen, 1..spalten] Of teilchen; Procedure initgr; Var grDriver: Integer; grMode: Integer; ErrCode: Integer; Begin grDriver := VGA; grMode := VGAhi; InitGraph (grDriver, grMode, 'z:\tp70\bgi'); ErrCode := GraphResult; If ErrCode <> grOk Then Begin WriteLn ('Graphics error:', GraphErrorMsg (ErrCode) ); Halt (1); End; End; Procedure init; Var i, j, k: Integer; Begin For i := 1 To zeilen Do For j := 1 To spalten Do Begin With verbund [i, j] Do Begin c := 50; { [ci]= N/m = 1000 N/mm } xp := j; yp := i; m := 1; { masse [m]=kg } fx := 0; fy := 0; fax := 0; fay := 0; frx := 0; fry := 0; frei := True; If (j = 1) Or (j = spalten) Then frei := False; If (i = 1) Or (i = zeilen) Then frei := False; End; End; With verbund [2, 2] Do Begin fax := 0; { Belastung } fay := 0; End; l0_x := 1; l0_y := 1; schritt_x := l0_x / 1000; schritt_y := l0_y / 1000; End; Function abstand (z1, s1, z2, s2: Integer): Real; Begin abstand := Sqrt (Sqr (verbund [z1, s1].xp - verbund [z2, s2].xp) + Sqr (verbund [z1, s1].yp - verbund [z2, s2].yp) ); End; Procedure approx; Var z, s: Integer; DL: Real; alt_x, alt_y, alt_fr: Real; Begin For z := 1 To zeilen Do Begin For s := 1 To spalten Do Begin If verbund [z, s].frei Then Begin With verbund [z, s] Do Begin fx := fax; fy := - m * g + fay; frx := fx + c * (abstand (z, s, z, s - 1) - abstand (z, s, z, s + 1) ); fry := fy + c * (abstand (z, s, z - 1, s) - abstand (z, s, z + 1, s) ); If Abs (frx) > epsilon Then Begin alt_fr := frx; alt_x := xp; xp := xp + schritt_x; frx := fx + c * (abstand (z, s, z - 1, s) - abstand (z, s, z + 1, s) ); If Abs (alt_fr) < Abs (frx) Then Begin xp := xp - schritt_x; frx := fx + c * (abstand (z, s, z - 1, s) - abstand (z, s, z + 1, s) ); End; End; If Abs (fry) > epsilon Then Begin alt_fr := fry; alt_y := yp; yp := yp + schritt_y; fry := fy + c * (abstand (z, s, z - 1, s) - abstand (z, s, z + 1, s) ); If Abs (alt_fr) < Abs (fry) Then Begin yp := yp - schritt_y; fry := fy + c * (abstand (z, s, z - 1, s) - abstand (z, s, z + 1, s) ); End; End; End; End; End; End; End; Procedure writepos (X, Y, z, s: Integer); Begin GotoXY (X, Y); ClrEol; WriteLn ('Pos(', z, ',', s, ')=(', verbund [z, s].xp: 3: 3, ' | ', verbund [z, s].yp: 3: 3, ')'); End; Procedure writefr (X, Y, z, s: Integer); Begin GotoXY (X, Y); ClrEol; WriteLn ('Fr(', z, ',', s, ')=(', verbund [z, s].frx: 3: 3, ' | ', verbund [z, s].fry: 3: 3, ')'); End; Procedure zeichne; Var z, s: Integer; Begin ClearDevice; For z := 1 To zeilen Do Begin For s := 1 To spalten Do Begin With verbund [z, s] Do Begin Circle (50 + Round (25 * xp), 400 - Round (25 * yp), 5); If s < spalten Then Line (50 + Round (25 * xp) + 6, 400 - Round (25 * yp), 50 + Round (25 * verbund [z, s + 1].xp - 6), 400 - Round (25 * verbund [z, s + 1].yp) ); If z < zeilen Then Line (50 + Round (25 * xp), 400 - Round (25 * yp + 6), 50 + Round (25 * verbund [z + 1, s].xp), 400 - Round (25 * verbund [z + 1, s].yp - 6) ); End; End; End; End; Var i, j: Integer; oldexit: pointer; Procedure myexit; Far; Begin ExitProc := oldexit; CloseGraph; End; Begin oldexit := ExitProc; ExitProc := @myexit; ClrScr; initgr; init; Repeat approx; zeichne; Until KeyPressed; CloseGraph; End. 
{ C_GRAPHICSMEDIA_LAB_DMOROZ_C #/******************************************************************************* # * (C) Copyright 2003/2004 by Vladimir Vezhnevets <vvp@graphics.cs.msu.su> * # *******************************************************************************/ } unit Processing; interface uses graphics, sysutils; procedure WNoise(out_Image :TBitmap; Might:Integer); procedure INoise(out_Image :TBitmap; Might:Integer); procedure Razmytiye(in_Image: TBitmap; out_Image :TBitmap); procedure PovysheniyeChetkosti(in_Image: TBitmap; out_Image :TBitmap); procedure NahozhdeniyeGranic(in_Image: TBitmap; out_Image :TBitmap); procedure GaussovskoyeRazmytiyeDvumernoye(in_Image: TBitmap; out_Image :TBitmap; Might:Single); procedure GaussovskoyeRazmytiyeOdnomernoye(in_Image: TBitmap; out_Image :TBitmap; Might:Single); procedure MediannayaFiltraciya(in_Image: TBitmap; out_Image :TBitmap; R: Integer); procedure MediannayaFiltraciyaVectornaya(in_Image: TBitmap; out_Image :TBitmap; R: Integer); procedure KNearestNeighborsFiltraciya(in_Image: TBitmap; out_Image :TBitmap; R: Integer; Might: Single); procedure BoxFilter(in_Image: TBitmap; out_Image :TBitmap); procedure Colorize(out_Image: TBitmap); implementation {---------------------------------------------------------------------------} { Простейший пример одномерной размывающей фильтрации изображения - усреднение трех соседних пикселей в строке} procedure BoxFilter(in_Image: TBitmap; out_Image :TBitmap); var iY, iX :Integer; pSrcLine, pDstLine : PByteArray; begin {Одномерное усреднение по строкам } for iY := 0 to in_Image.Height - 1 do begin { Быстрый способ обработки пикселей - прямой доступ к памяти } pSrcLine := in_Image.ScanLine[iY]; pDstLine := out_Image.ScanLine[iY]; for iX := 1 to (in_Image.Width - 2) do begin { blue } pDstLine[iX * 3] := round((pSrcLine[iX * 3 - 3] + pSrcLine[iX * 3] + pSrcLine[iX * 3 + 3]) / 3); { green } pDstLine[iX * 3 + 1] := round((pSrcLine[iX * 3 - 3 + 1] + pSrcLine[iX * 3 + 1] + pSrcLine[iX * 3 + 3 + 1]) / 3); { red } pDstLine[iX * 3 + 2] := round((pSrcLine[iX * 3 - 3 + 2] + pSrcLine[iX * 3 + 2] + pSrcLine[iX * 3 + 3 + 2]) / 3); end; end; end; {---------------------------------------------------------------------------} { Простейший пример раскраски изображения } procedure Colorize(out_Image :TBitmap); var iY, iX :Integer; pDstLine : PByteArray; begin for iY := 0 to out_Image.Height - 1 do begin { Быстрый способ обработки пикселей - прямой доступ к памяти } pDstLine := out_Image.ScanLine[iY]; for iX := 0 to (out_Image.Width - 1) do begin /// Делаем плавно изменяющийся вдоль строк градиент // blue pDstLine[iX * 3] := iX mod 256; // green pDstLine[iX * 3 + 1] := (255 - iX) mod 256; // red pDstLine[iX * 3 + 2] := round(Abs(iX - out_Image.Width / 2)) mod 256; end; end; end; procedure WNoise(out_Image :TBitmap; Might:Integer); var iY, iX :Integer; new: Integer; pDstLine : PByteArray; begin for iY := 0 to out_Image.Height - 1 do begin pDstLine := out_Image.ScanLine[iY]; for iX := 0 to (out_Image.Width - 1) do begin new := pDstLine[iX * 3] + Random(Might) - Random(Might); if (new < 0) then new := 0; if (new > 255) then new := 255; pDstLine[iX * 3] := new; new := pDstLine[iX * 3 + 1] + Random(Might) - Random(Might); if (new < 0) then new := 0; if (new > 255) then new := 255; pDstLine[iX * 3 + 1] := new; new := pDstLine[iX * 3 + 2] + Random(Might) - Random(Might); if (new < 0) then new := 0; if (new > 255) then new := 255; pDstLine[iX * 3 + 2] := new; end; end; end; procedure INoise(out_Image :TBitmap; Might:Integer); var iY, iX :Integer; new: Integer; pDstLine : PByteArray; begin for iY := 0 to out_Image.Height - 1 do begin pDstLine := out_Image.ScanLine[iY]; for iX := 0 to (out_Image.Width - 1) do if Random(100) < Might then begin new := pDstLine[iX * 3] + Random(256) - Random(256); if (new < 0) then new := 0; if (new > 255) then new := 255; pDstLine[iX * 3] := new; new := pDstLine[iX * 3 + 1] + Random(256) - Random(256); if (new < 0) then new := 0; if (new > 255) then new := 255; pDstLine[iX * 3 + 1] := new; new := pDstLine[iX * 3 + 2] + Random(256) - Random(256); if (new < 0) then new := 0; if (new > 255) then new := 255; pDstLine[iX * 3 + 2] := new; end; end; end; procedure Razmytiye(in_Image: TBitmap; out_Image :TBitmap); var iY, iX, Znam:Integer; new: array[0..2] of Integer; pSrcLine, pDstLine : array[-1..1] of PByteArray; begin for iY := 0 to out_Image.Height - 1 do begin if iY - 1 >= 0 then begin pSrcLine[-1] := in_Image.ScanLine[iY-1]; pDstLine[-1] := out_Image.ScanLine[iY-1]; end; pSrcLine[0] := in_Image.ScanLine[iY]; pDstLine[0] := out_Image.ScanLine[iY]; if iY + 1 <= out_Image.Height - 1 then begin pSrcLine[1] := in_Image.ScanLine[iY+1]; pDstLine[1] := out_Image.ScanLine[iY+1]; end; for iX := 0 to (out_Image.Width - 1) do begin new[0] := 0; new[1] := 0; new[2] := 0; Znam := 2; if iX - 1 >= 0 then begin new[0] := new[0] + pSrcLine[0][(iX - 1) * 3]; new[1] := new[1] + pSrcLine[0][(iX - 1) * 3 + 1]; new[2] := new[2] + pSrcLine[0][(iX - 1) * 3 + 2]; Znam := Znam + 1; end; if iX + 1 <= out_Image.Width - 1 then begin new[0] := new[0] + pSrcLine[0][(iX + 1) * 3]; new[1] := new[1] + pSrcLine[0][(iX + 1) * 3 + 1]; new[2] := new[2] + pSrcLine[0][(iX + 1) * 3 + 2]; Znam := Znam + 1; end; if iY - 1 >= 0 then begin new[0] := new[0] + pSrcLine[-1][iX * 3]; new[1] := new[1] + pSrcLine[-1][iX * 3 + 1]; new[2] := new[2] + pSrcLine[-1][iX * 3 + 2]; Znam := Znam + 1; end; if iY + 1 <= out_Image.Height - 1 then begin new[0] := new[0] + pSrcLine[1][iX * 3]; new[1] := new[1] + pSrcLine[1][iX * 3 + 1]; new[2] := new[2] + pSrcLine[1][iX * 3 + 2]; Znam := Znam + 1; end; new[0] := new[0] + 2 * pSrcLine[0][iX * 3]; new[1] := new[1] + 2 * pSrcLine[0][iX * 3 + 1]; new[2] := new[2] + 2 * pSrcLine[0][iX * 3 + 2]; new[0] := new[0] div Znam; new[1] := new[1] div Znam; new[2] := new[2] div Znam; pDstLine[0][iX * 3] := new[0]; pDstLine[0][iX * 3 + 1] := new[1]; pDstLine[0][iX * 3 + 2] := new[2]; end; end; end; procedure PovysheniyeChetkosti(in_Image: TBitmap; out_Image :TBitmap); var iY, iX, Znam:Integer; new: array[0..2] of Integer; pSrcLine, pDstLine : array[-1..1] of PByteArray; begin for iY := 0 to out_Image.Height - 1 do begin if iY - 1 >= 0 then begin pSrcLine[-1] := in_Image.ScanLine[iY-1]; pDstLine[-1] := out_Image.ScanLine[iY-1]; end; pSrcLine[0] := in_Image.ScanLine[iY]; pDstLine[0] := out_Image.ScanLine[iY]; if iY + 1 <= out_Image.Height - 1 then begin pSrcLine[1] := in_Image.ScanLine[iY+1]; pDstLine[1] := out_Image.ScanLine[iY+1]; end; for iX := 0 to (out_Image.Width - 1) do begin new[0] := 0; new[1] := 0; new[2] := 0; Znam := 22; if iX - 1 >= 0 then begin new[0] := new[0] - 2 * pSrcLine[0][(iX - 1) * 3]; new[1] := new[1] - 2 * pSrcLine[0][(iX - 1) * 3 + 1]; new[2] := new[2] - 2 * pSrcLine[0][(iX - 1) * 3 + 2]; Znam := Znam - 2; end; if iX + 1 <= out_Image.Width - 1 then begin new[0] := new[0] - 2 * pSrcLine[0][(iX + 1) * 3]; new[1] := new[1] - 2 * pSrcLine[0][(iX + 1) * 3 + 1]; new[2] := new[2] - 2 * pSrcLine[0][(iX + 1) * 3 + 2]; Znam := Znam - 2; end; if iY - 1 >= 0 then begin new[0] := new[0] - 2 * pSrcLine[-1][iX * 3]; new[1] := new[1] - 2 * pSrcLine[-1][iX * 3 + 1]; new[2] := new[2] - 2 * pSrcLine[-1][iX * 3 + 2]; Znam := Znam - 2; end; if iY + 1 <= out_Image.Height - 1 then begin new[0] := new[0] - 2 * pSrcLine[1][iX * 3]; new[1] := new[1] - 2 * pSrcLine[1][iX * 3 + 1]; new[2] := new[2] - 2 * pSrcLine[1][iX * 3 + 2]; Znam := Znam - 2; end; if (iX - 1 >= 0) and (iY - 1 >= 0) then begin new[0] := new[0] - 1 * pSrcLine[-1][(iX - 1) * 3]; new[1] := new[1] - 1 * pSrcLine[-1][(iX - 1) * 3 + 1]; new[2] := new[2] - 1 * pSrcLine[-1][(iX - 1) * 3 + 2]; Znam := Znam - 1; end; if (iX - 1 >= 0) and (iY + 1 <= out_Image.Height - 1) then begin new[0] := new[0] - 1 * pSrcLine[1][(iX - 1) * 3]; new[1] := new[1] - 1 * pSrcLine[1][(iX - 1) * 3 + 1]; new[2] := new[2] - 1 * pSrcLine[1][(iX - 1) * 3 + 2]; Znam := Znam - 1; end; if (iX + 1 <= out_Image.Width - 1) and (iY - 1 >= 0) then begin new[0] := new[0] - 1 * pSrcLine[-1][(iX + 1) * 3]; new[1] := new[1] - 1 * pSrcLine[-1][(iX + 1) * 3 + 1]; new[2] := new[2] - 1 * pSrcLine[-1][(iX + 1) * 3 + 2]; Znam := Znam - 1; end; if (iX + 1 <= out_Image.Width - 1) and (iY + 1 <= out_Image.Height - 1) then begin new[0] := new[0] - 1 * pSrcLine[1][(iX + 1) * 3]; new[1] := new[1] - 1 * pSrcLine[1][(iX + 1) * 3 + 1]; new[2] := new[2] - 1 * pSrcLine[1][(iX + 1) * 3 + 2]; Znam := Znam - 1; end; new[0] := new[0] + 22 * pSrcLine[0][iX * 3]; new[1] := new[1] + 22 * pSrcLine[0][iX * 3 + 1]; new[2] := new[2] + 22 * pSrcLine[0][iX * 3 + 2]; new[0] := new[0] div Znam; new[1] := new[1] div Znam; new[2] := new[2] div Znam; if (new[0] < 0) then new[0] := 0; if (new[0] > 255) then new[0] := 255; if (new[1] < 0) then new[1] := 0; if (new[1] > 255) then new[1] := 255; if (new[2] < 0) then new[2] := 0; if (new[2] > 255) then new[2] := 255; pDstLine[0][iX * 3] := new[0]; pDstLine[0][iX * 3 + 1] := new[1]; pDstLine[0][iX * 3 + 2] := new[2]; end; end; end; procedure NahozhdeniyeGranic(in_Image: TBitmap; out_Image :TBitmap); var iY, iX, Mnozh:Integer; new: array[0..2] of Integer; pSrcLine, pDstLine : array[-1..1] of PByteArray; begin for iY := 0 to out_Image.Height - 1 do begin if iY - 1 >= 0 then begin pSrcLine[-1] := in_Image.ScanLine[iY-1]; pDstLine[-1] := out_Image.ScanLine[iY-1]; end; pSrcLine[0] := in_Image.ScanLine[iY]; pDstLine[0] := out_Image.ScanLine[iY]; if iY + 1 <= out_Image.Height - 1 then begin pSrcLine[1] := in_Image.ScanLine[iY+1]; pDstLine[1] := out_Image.ScanLine[iY+1]; end; for iX := 0 to (out_Image.Width - 1) do begin new[0] := 0; new[1] := 0; new[2] := 0; Mnozh := 0; if iX - 1 >= 0 then begin new[0] := new[0] - pSrcLine[0][(iX - 1) * 3]; new[1] := new[1] - pSrcLine[0][(iX - 1) * 3 + 1]; new[2] := new[2] - pSrcLine[0][(iX - 1) * 3 + 2]; Mnozh := Mnozh + 1; end; if iX + 1 <= out_Image.Width - 1 then begin new[0] := new[0] - pSrcLine[0][(iX + 1) * 3]; new[1] := new[1] - pSrcLine[0][(iX + 1) * 3 + 1]; new[2] := new[2] - pSrcLine[0][(iX + 1) * 3 + 2]; Mnozh := Mnozh + 1; end; if iY - 1 >= 0 then begin new[0] := new[0] - pSrcLine[-1][iX * 3]; new[1] := new[1] - pSrcLine[-1][iX * 3 + 1]; new[2] := new[2] - pSrcLine[-1][iX * 3 + 2]; Mnozh := Mnozh + 1; end; if iY + 1 <= out_Image.Height - 1 then begin new[0] := new[0] - pSrcLine[1][iX * 3]; new[1] := new[1] - pSrcLine[1][iX * 3 + 1]; new[2] := new[2] - pSrcLine[1][iX * 3 + 2]; Mnozh := Mnozh + 1; end; new[0] := new[0] + Mnozh * pSrcLine[0][iX * 3]; new[1] := new[1] + Mnozh * pSrcLine[0][iX * 3 + 1]; new[2] := new[2] + Mnozh * pSrcLine[0][iX * 3 + 2]; if (new[0] < 0) then new[0] := 0; if (new[0] > 255) then new[0] := 255; if (new[1] < 0) then new[1] := 0; if (new[1] > 255) then new[1] := 255; if (new[2] < 0) then new[2] := 0; if (new[2] > 255) then new[2] := 255; pDstLine[0][iX * 3] := new[0]; pDstLine[0][iX * 3 + 1] := new[1]; pDstLine[0][iX * 3 + 2] := new[2]; end; end; end; procedure GaussovskoyeRazmytiyeDvumernoye(in_Image: TBitmap; out_Image :TBitmap; Might:Single); var Koefs : array[-100..100,-100..100] of Single; Sum : Single; iY, iX, dX, dY, R:Integer; new: array[0..2] of Single; pSrc, pDst : PByteArray; iBytesPerLine : Integer; begin if Might = 0 then Exit; for iX := -100 to 100 do for iY := -100 to 100 do Koefs[iX][iY] := exp(-(iX * iX + iY * iY) / (2 * Might * Might)); for R := 1 to 100 do if Koefs[R][0] < 0.01 then Break; Sum := 0; for iX := -R to R do for iY := -R to R do Sum := Sum + Koefs[iX][iY]; for iX := -R to R do for iY := -R to R do Koefs[iX][iY] := Koefs[iX][iY] / Sum; iBytesPerLine := (out_Image.Width * 3 + 3) and -4; pSrc := in_Image.ScanLine[in_Image.Height - 1]; pDst := out_Image.ScanLine[out_Image.Height - 1]; for iY := 0 to out_Image.Height - 1 do begin for iX := 0 to (out_Image.Width - 1) do begin new[0] := 0; new[1] := 0; new[2] := 0; Sum := 0; for dX := -R to R do for dY := -R to R do begin if (iX + dX >= 0) and (iX + dX <= out_Image.Width - 1) and (iY + dY >= 0) and (iY + dY <= out_Image.Height - 1) then begin Sum := Sum + Koefs[dX][dY]; new[0] := new[0] + Koefs[dX][dY] * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3]; new[1] := new[1] + Koefs[dX][dY] * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 1]; new[2] := new[2] + Koefs[dX][dY] * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 2]; end; end; new[0] := new[0] / Sum; new[1] := new[1] / Sum; new[2] := new[2] / Sum; pDst[iY * iBytesPerLine + iX * 3] := Round(new[0]); pDst[iY * iBytesPerLine + iX * 3 + 1] := Round(new[1]); pDst[iY * iBytesPerLine + iX * 3 + 2] := Round(new[2]); end; end; end; procedure GaussovskoyeRazmytiyeOdnomernoye(in_Image: TBitmap; out_Image :TBitmap; Might:Single); var Koefs : array[-100..100] of Single; Sum : Single; iY, iX, dX, dY, R:Integer; new: array[0..2] of Single; pSrc, pDst : PByteArray; iBytesPerLine : Integer; begin if Might = 0 then Exit; for iX := -100 to 100 do Koefs[iX] := exp(-(iX * iX) / (2 * Might * Might)); for R := 1 to 100 do if Koefs[R] < 0.01 then Break; Sum := 0; for iX := -R to R do Sum := Sum + Koefs[iX]; for iX := -R to R do Koefs[iX] := Koefs[iX] / Sum; iBytesPerLine := (out_Image.Width * 3 + 3) and -4; pSrc := in_Image.ScanLine[in_Image.Height - 1]; pDst := out_Image.ScanLine[out_Image.Height - 1]; for iY := 0 to out_Image.Height - 1 do begin for iX := 0 to (out_Image.Width - 1) do begin new[0] := 0; new[1] := 0; new[2] := 0; Sum := 0; for dX := -R to R do begin if (iX + dX >= 0) and (iX + dX <= out_Image.Width - 1) then begin Sum := Sum + Koefs[dX]; new[0] := new[0] + Koefs[dX] * pDst[iY * iBytesPerLine + (iX + dX) * 3]; new[1] := new[1] + Koefs[dX] * pDst[iY * iBytesPerLine + (iX + dX) * 3 + 1]; new[2] := new[2] + Koefs[dX] * pDst[iY * iBytesPerLine + (iX + dX) * 3 + 2]; end; end; new[0] := new[0] / Sum; new[1] := new[1] / Sum; new[2] := new[2] / Sum; pSrc[iY * iBytesPerLine + iX * 3] := Round(new[0]); pSrc[iY * iBytesPerLine + iX * 3 + 1] := Round(new[1]); pSrc[iY * iBytesPerLine + iX * 3 + 2] := Round(new[2]); end; end; for iY := 0 to out_Image.Height - 1 do begin for iX := 0 to (out_Image.Width - 1) do begin new[0] := 0; new[1] := 0; new[2] := 0; Sum := 0; for dY := -R to R do begin if (iY + dY >= 0) and (iY + dY <= out_Image.Height - 1) then begin Sum := Sum + Koefs[dY]; new[0] := new[0] + Koefs[dY] * pSrc[(iY + dY) * iBytesPerLine + iX * 3]; new[1] := new[1] + Koefs[dY] * pSrc[(iY + dY) * iBytesPerLine + iX * 3 + 1]; new[2] := new[2] + Koefs[dY] * pSrc[(iY + dY) * iBytesPerLine + iX * 3 + 2]; end; end; new[0] := new[0] / Sum; new[1] := new[1] / Sum; new[2] := new[2] / Sum; pDst[iY * iBytesPerLine + iX * 3] := Round(new[0]); pDst[iY * iBytesPerLine + iX * 3 + 1] := Round(new[1]); pDst[iY * iBytesPerLine + iX * 3 + 2] := Round(new[2]); end; end; end; var Gray : array[0..40000] of Byte; Color : array[0..40000,0..2] of Byte; Count : Integer; procedure sort(l, r: Integer); var i, j: integer; x, y: Byte; begin i := l; j := r; x := Gray[(l + r) div 2]; repeat while Gray[i] < x do i := i + 1; while x < Gray[j] do j := j - 1; if i <= j then begin y := Gray[i]; Gray[i] := Gray[j]; Gray[j] := y; y := Color[i][0]; Color[i][0] := Color[j][0]; Color[j][0] := y; y := Color[i][1]; Color[i][1] := Color[j][1]; Color[j][1] := y; y := Color[i][2]; Color[i][2] := Color[j][2]; Color[j][2] := y; i := i + 1; j := j - 1; end; until i > j; if l < j then sort(l, j); if i < r then sort(i, r); end; procedure MediannayaFiltraciya(in_Image: TBitmap; out_Image :TBitmap; R: Integer); var iY, iX, dX, dY:Integer; pSrc, pDst : PByteArray; iBytesPerLine : Integer; begin if R = 0 then Exit; if R > 99 then R := 99; iBytesPerLine := (out_Image.Width * 3 + 3) and -4; pSrc := in_Image.ScanLine[in_Image.Height - 1]; pDst := out_Image.ScanLine[out_Image.Height - 1]; for iY := 0 to out_Image.Height - 1 do begin for iX := 0 to (out_Image.Width - 1) do begin Count := 0; for dX := -R to R do for dY := -R to R do begin if (iX + dX >= 0) and (iX + dX <= out_Image.Width - 1) and (iY + dY >= 0) and (iY + dY <= out_Image.Height - 1) then begin Gray[Count] := Round( 0.114 * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3] + 0.587 * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 1] + 0.299 * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 2] ); Color[Count][0] := pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3]; Color[Count][1] := pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 1]; Color[Count][2] := pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 2]; Inc(Count); end; end; sort(0, Count-1); pDst[iY * iBytesPerLine + iX * 3] := Color[Count div 2][0]; pDst[iY * iBytesPerLine + iX * 3 + 1] := Color[Count div 2][1]; pDst[iY * iBytesPerLine + iX * 3 + 2] := Color[Count div 2][2]; end; end; end; procedure MediannayaFiltraciyaVectornaya(in_Image: TBitmap; out_Image :TBitmap; R: Integer); var Distance, BestDistance, Besti, i, j, iY, iX, dX, dY:Integer; pSrc, pDst : PByteArray; iBytesPerLine : Integer; begin if R = 0 then Exit; if R > 99 then R := 99; iBytesPerLine := (out_Image.Width * 3 + 3) and -4; pSrc := in_Image.ScanLine[in_Image.Height - 1]; pDst := out_Image.ScanLine[out_Image.Height - 1]; for iY := 0 to out_Image.Height - 1 do begin for iX := 0 to (out_Image.Width - 1) do begin Count := 0; for dX := -R to R do for dY := -R to R do begin if (iX + dX >= 0) and (iX + dX <= out_Image.Width - 1) and (iY + dY >= 0) and (iY + dY <= out_Image.Height - 1) then begin Color[Count][0] := pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3]; Color[Count][1] := pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 1]; Color[Count][2] := pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 2]; Inc(Count); end; end; BestDistance := 2000000000; for i := 0 to Count - 1 do begin Distance := 0; for j := 0 to Count - 1 do Distance := Distance + abs(Color[i][0] - Color[j][0]) + abs(Color[i][1] - Color[j][1]) + abs(Color[i][2] - Color[j][2]); if Distance < BestDistance then begin BestDistance := Distance; Besti := i; end; end; pDst[iY * iBytesPerLine + iX * 3] := Color[Besti][0]; pDst[iY * iBytesPerLine + iX * 3 + 1] := Color[Besti][1]; pDst[iY * iBytesPerLine + iX * 3 + 2] := Color[Besti][2]; end; end; end; procedure KNearestNeighborsFiltraciya(in_Image: TBitmap; out_Image :TBitmap; R: Integer; Might: Single); var iY, iX, dX, dY: Integer; pSrc, pDst : PByteArray; iBytesPerLine : Integer; new : array[0..2] of Single; Sum : Single; Distance: Single; K: Single; begin if (R = 0) or (Might = 0) then Exit; iBytesPerLine := (out_Image.Width * 3 + 3) and -4; pSrc := in_Image.ScanLine[in_Image.Height - 1]; pDst := out_Image.ScanLine[out_Image.Height - 1]; for iY := 0 to out_Image.Height - 1 do begin for iX := 0 to (out_Image.Width - 1) do begin new[0] := 0; new[1] := 0; new[2] := 0; Sum := 0; for dX := -R to R do for dY := -R to R do begin if (iX + dX >= 0) and (iX + dX <= out_Image.Width - 1) and (iY + dY >= 0) and (iY + dY <= out_Image.Height - 1) then begin Distance := sqr(pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3] - pSrc[iY * iBytesPerLine + iX * 3]) + sqr(pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 1] - pSrc[iY * iBytesPerLine + iX * 3 + 1]) + sqr(pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 2] - pSrc[iY * iBytesPerLine + iX * 3 + 2]); K := exp(-Distance / (2 * Might * Might)); Sum := Sum + K; new[0] := new[0] + K * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3]; new[1] := new[1] + K * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 1]; new[2] := new[2] + K * pSrc[(iY + dY) * iBytesPerLine + (iX + dX) * 3 + 2]; end; end; new[0] := new[0] / Sum; new[1] := new[1] / Sum; new[2] := new[2] / Sum; pDst[iY * iBytesPerLine + iX * 3] := Round(new[0]); pDst[iY * iBytesPerLine + iX * 3 + 1] := Round(new[1]); pDst[iY * iBytesPerLine + iX * 3 + 2] := Round(new[2]); end; end; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors 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 acknowledgement 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. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.PooledObject; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} {$if defined(Windows)} {$undef UseHashMaps} {$else} {$define UseHashMaps} {$ifend} interface uses {$if defined(Windows)} Windows, {$elseif defined(fpc) and not defined(UseHashMaps)} dl, BaseUnix, Unix, UnixType, {$ifend} SysUtils, Classes, PasMP, PasVulkan.Types; const PooledObjectPoolBucketSize=1024; PooledObjectPoolAlignment=16; type EpvPooledObjectException=class(Exception); TpvPooledObjectPool=class; TpvPooledObjectPoolBucket=class; PpvPooledObjectPoolBucketItem=^TpvPooledObjectPoolBucketItem; TpvPooledObjectPoolBucketItem=record // must be 16-byte aligned for the combined Parent and Color storage PoolBucket:TpvPooledObjectPoolBucket; Next:PpvPooledObjectPoolBucketItem; end; PpvPooledObjectPoolBucketItems=^TpvPooledObjectPoolBucketItems; TpvPooledObjectPoolBucketItems=array[0..65535] of TpvPooledObjectPoolBucketItem; TpvPooledObjectPoolBucket=class(TObject) private fPool:TpvPooledObjectPool; fPoolBucketMemoryUnaligned:pointer; fPoolBucketPrevious:TpvPooledObjectPoolBucket; fPoolBucketNext:TpvPooledObjectPoolBucket; fPoolBucketFreePrevious:TpvPooledObjectPoolBucket; fPoolBucketFreeNext:TpvPooledObjectPoolBucket; fPoolBucketItems:PpvPooledObjectPoolBucketItems; fPoolBucketMemory:pointer; fPoolCountAllocatedItems:TpvSizeInt; fPoolBucketItemFreeRoot:PpvPooledObjectPoolBucketItem; fIsOnFreeList:longbool; protected procedure AddToFreeList; procedure RemoveFromFreeList; procedure AddFreeBucketItem(const ABucketItem:PpvPooledObjectPoolBucketItem); function GetFreeBucketItem:PpvPooledObjectPoolBucketItem; public constructor Create(const APool:TpvPooledObjectPool); destructor Destroy; override; property Memory:pointer read fPoolBucketMemory; published property Pool:TpvPooledObjectPool read fPool; end; TpvPooledObjectPool=class(TObject) private fPoolLock:TPasMPSlimReaderWriterLock; fPoolClassType:TClass; fPoolClassInstanceSize:TpvSizeInt; fPoolBucketSize:TpvSizeInt; fPoolAlignment:TpvSizeInt; fPoolAlignmentMask:TpvSizeInt; fPoolAlignedClassInstanceSize:TpvSizeInt; fPoolBucketFirst:TpvPooledObjectPoolBucket; fPoolBucketLast:TpvPooledObjectPoolBucket; fPoolBucketFreeFirst:TpvPooledObjectPoolBucket; fPoolBucketFreeLast:TpvPooledObjectPoolBucket; public constructor Create(const aPoolClassType:TClass;const aPoolBucketSize:TpvSizeInt=PooledObjectPoolBucketSize;const aPoolAlignment:TpvSizeInt=PooledObjectPoolAlignment); destructor Destroy; override; function AllocateObject:pointer; procedure FreeObject(const aInstance:pointer); published property PoolClassType:TClass read fPoolClassType; property PoolClassInstanceSize:TpvSizeInt read fPoolClassInstanceSize; property PoolBucketSize:TpvSizeInt read fPoolBucketSize; property PoolAlignment:TpvSizeInt read fPoolAlignment; property PoolAlignmentMask:TpvSizeInt read fPoolAlignmentMask; property PoolAlignedClassInstanceSize:TpvSizeInt read fPoolAlignedClassInstanceSize; end; PPpvPooledObjectClassMetaInfo=^PpvPooledObjectClassMetaInfo; PpvPooledObjectClassMetaInfo=^TpvPooledObjectClassMetaInfo; TpvPooledObjectClassMetaInfo=record Pool:TpvPooledObjectPool; ID:TpvPtrInt; end; TpvPooledObjectPoolManager=class(TObject) private fMultipleReaderSingleWriterLock:TPasMPMultipleReaderSingleWriterLock; fObjectPoolList:TList; fObjectClassMetaInfoList:TList; public constructor Create; destructor Destroy; override; procedure AllocateObjectClassMetaInfo(const AClassType:TClass); function AllocateObject(const AClassType:TClass):pointer; procedure FreeObject(const aInstance:TObject); end; TpvPooledObject=class(TpvObject) public class function GetClassMetaInfo:pointer; //inline; class procedure InitializeObjectClassMetaInfo; class function NewInstance:TObject; override; procedure FreeInstance; override; end; TpvPooledObjectClass=class of TpvPooledObject; implementation {$ifdef UseHashMaps} const PooledObjectClassMetaInfoHashBits=16; PooledObjectClassMetaInfoHashSize=1 shl PooledObjectClassMetaInfoHashBits; PooledObjectClassMetaInfoHashMask=PooledObjectClassMetaInfoHashSize-1; type PpvPooledObjectClassMetaInfoHashItem=^TpvPooledObjectClassMetaInfoHashItem; TpvPooledObjectClassMetaInfoHashItem=record HashItemNext:PpvPooledObjectClassMetaInfoHashItem; AllocatedNext:PpvPooledObjectClassMetaInfoHashItem; PooledObjectClass:TpvPooledObjectClass; PooledObjectClassMetaInfo:TpvPooledObjectClassMetaInfo; end; PPpvPooledObjectClassMetaInfoHashItems=^TPpvPooledObjectClassMetaInfoHashItems; TPpvPooledObjectClassMetaInfoHashItems=array[0..PooledObjectClassMetaInfoHashSize-1] of PpvPooledObjectClassMetaInfoHashItem; var PooledObjectClassMetaInfoHashItems:TPpvPooledObjectClassMetaInfoHashItems; AllocatedPooledObjectClassMetaInfoHashItems:PpvPooledObjectClassMetaInfoHashItem=nil; function HashPointer(const Key:pointer):TpvUInt32; {$ifdef cpu64} var p:TpvUInt64; {$endif} begin {$ifdef cpu64} // 64-bit big => use 64-bit integer-rehashing p:=TpvUInt64(pointer(@Key)^); p:=(not p)+(p shl 18); // p:=((p shl 18)-p-)1; p:=p xor (p shr 31); p:=p*21; // p:=(p+(p shl 2))+(p shl 4); p:=p xor (p shr 11); p:=p+(p shl 6); result:=TpvUInt32(TpvPtrUInt(p xor (p shr 22))); {$else} // 32-bit big => use 32-bit integer-rehashing result:=TpvUInt32(pointer(@Key)^); dec(result,result shl 6); result:=result xor (result shr 17); dec(result,result shl 9); result:=result xor (result shl 4); dec(result,result shl 3); result:=result xor (result shl 10); result:=result xor (result shr 15); {$endif} end; {$endif} var PooledObjectPoolManager:TpvPooledObjectPoolManager=nil; {$ifndef UseHashMaps} {$ifdef unix} fpmprotect:function(__addr:pointer;__len:cardinal;__prot:TpvInt32):TpvInt32; cdecl;// external 'c' name 'mprotect'; {$endif} {$endif} function RoundUpToPowerOfTwo(Value:TpvPtrUInt):TpvPtrUInt; begin dec(Value); Value:=Value or (Value shr 1); Value:=Value or (Value shr 2); Value:=Value or (Value shr 4); Value:=Value or (Value shr 8); Value:=Value or (Value shr 16); {$ifdef CPU64} Value:=Value or (Value shr 32); {$endif} result:=Value+1; end; constructor TpvPooledObjectPoolBucket.Create(const APool:TpvPooledObjectPool); var Index:TpvSizeInt; PoolBucketItem:PpvPooledObjectPoolBucketItem; ItemsSize,MemorySize,Size:TpvPtrUInt; begin inherited Create; fPool:=APool; ItemsSize:=(fPool.fPoolBucketSize*SizeOf(TpvPooledObjectPoolBucketItem))+32; MemorySize:=(fPool.fPoolAlignedClassInstanceSize*fPool.fPoolBucketSize)+(fPool.fPoolAlignment*2); Size:=ItemsSize+MemorySize; GetMem(fPoolBucketMemoryUnaligned,Size); FillChar(fPoolBucketMemoryUnaligned^,Size,#0); fPoolBucketItems:=pointer(TpvPtrUInt(TpvPtrUInt(TpvPtrUInt(TpvPtrUInt(TpvPtrUInt(fPoolBucketMemoryUnaligned)))+TpvPtrUInt(15)) and not TpvPtrUInt(15))); fPoolBucketMemory:=pointer(TpvPtrUInt(TpvPtrUInt(TpvPtrUInt(TpvPtrUInt(TpvPtrUInt(fPoolBucketMemoryUnaligned)+ItemsSize))+TpvPtrUInt(fPool.fPoolAlignmentMask)) and not TpvPtrUInt(fPool.fPoolAlignmentMask))); fPoolCountAllocatedItems:=0; fIsOnFreeList:=false; fPoolBucketItemFreeRoot:=nil; for Index:=fPool.fPoolBucketSize-1 downto 0 do begin PoolBucketItem:=@fPoolBucketItems^[Index]; PoolBucketItem^.PoolBucket:=self; AddFreeBucketItem(PoolBucketItem); end; if assigned(fPool.fPoolBucketLast) then begin fPool.fPoolBucketLast.fPoolBucketNext:=self; fPoolBucketPrevious:=self; end else begin fPool.fPoolBucketFirst:=self; fPoolBucketPrevious:=nil; end; fPool.fPoolBucketLast:=self; fPoolBucketNext:=nil; AddToFreeList; end; destructor TpvPooledObjectPoolBucket.Destroy; begin RemoveFromFreeList; FreeMem(fPoolBucketMemoryUnaligned); if assigned(fPoolBucketPrevious) then begin fPoolBucketPrevious.fPoolBucketNext:=fPoolBucketNext; end else if fPool.fPoolBucketFirst=self then begin fPool.fPoolBucketFirst:=fPoolBucketNext; end; if assigned(fPoolBucketNext) then begin fPoolBucketNext.fPoolBucketPrevious:=fPoolBucketPrevious; end else if fPool.fPoolBucketLast=self then begin fPool.fPoolBucketLast:=fPoolBucketPrevious; end; inherited Destroy; end; procedure TpvPooledObjectPoolBucket.AddToFreeList; begin if not fIsOnFreeList then begin fIsOnFreeList:=true; if assigned(fPool.fPoolBucketFreeLast) then begin fPool.fPoolBucketFreeLast.fPoolBucketFreeNext:=self; fPoolBucketFreePrevious:=self; end else begin fPool.fPoolBucketFreeFirst:=self; fPoolBucketFreePrevious:=nil; end; fPool.fPoolBucketFreeLast:=self; fPoolBucketFreeNext:=nil; end; end; procedure TpvPooledObjectPoolBucket.RemoveFromFreeList; begin if fIsOnFreeList then begin fIsOnFreeList:=false; if assigned(fPoolBucketFreePrevious) then begin fPoolBucketFreePrevious.fPoolBucketFreeNext:=fPoolBucketFreeNext; end else if fPool.fPoolBucketFreeFirst=self then begin fPool.fPoolBucketFreeFirst:=fPoolBucketFreeNext; end; if assigned(fPoolBucketFreeNext) then begin fPoolBucketFreeNext.fPoolBucketFreePrevious:=fPoolBucketFreePrevious; end else if fPool.fPoolBucketFreeLast=self then begin fPool.fPoolBucketFreeLast:=fPoolBucketFreePrevious; end; end; end; procedure TpvPooledObjectPoolBucket.AddFreeBucketItem(const ABucketItem:PpvPooledObjectPoolBucketItem); begin ABucketItem^.Next:=fPoolBucketItemFreeRoot; fPoolBucketItemFreeRoot:=ABucketItem; if not fIsOnFreeList then begin AddToFreeList; end; end; function TpvPooledObjectPoolBucket.GetFreeBucketItem:PpvPooledObjectPoolBucketItem; begin result:=fPoolBucketItemFreeRoot; if assigned(result) then begin fPoolBucketItemFreeRoot:=result^.Next; end; if fIsOnFreeList and not assigned(fPoolBucketItemFreeRoot) then begin RemoveFromFreeList; end; end; constructor TpvPooledObjectPool.Create(const aPoolClassType:TClass;const aPoolBucketSize:TpvSizeInt=PooledObjectPoolBucketSize;const aPoolAlignment:TpvSizeInt=PooledObjectPoolAlignment); begin inherited Create; fPoolLock:=TPasMPSlimReaderWriterLock.Create; fPoolClassType:=aPoolClassType; fPoolClassInstanceSize:=fPoolClassType.InstanceSize; fPoolBucketSize:=aPoolBucketSize; fPoolAlignment:=RoundUpToPowerOfTwo(aPoolAlignment); fPoolAlignmentMask:=fPoolAlignment-1; fPoolAlignedClassInstanceSize:=TpvPtrInt(TpvPtrInt(fPoolClassInstanceSize)+SizeOf(PpvPooledObjectPoolBucketItem)+TpvPtrInt(fPoolAlignmentMask)) and not TpvPtrInt(fPoolAlignmentMask); fPoolBucketFirst:=nil; fPoolBucketLast:=nil; fPoolBucketFreeFirst:=nil; fPoolBucketFreeLast:=nil; end; destructor TpvPooledObjectPool.Destroy; //var Index:TpvSizeInt; begin while assigned(fPoolBucketLast) do begin fPoolBucketLast.Free; end; fPoolLock.Free; inherited Destroy; end; function TpvPooledObjectPool.AllocateObject:pointer; var PoolBucketItem:PpvPooledObjectPoolBucketItem; PoolBucket:TpvPooledObjectPoolBucket; PoolBucketItemIndex:TpvPtrUInt; begin fPoolLock.Acquire; try if not assigned(fPoolBucketFreeLast) then begin TpvPooledObjectPoolBucket.Create(self); Assert(assigned(fPoolBucketFreeLast)); end; PoolBucket:=fPoolBucketFreeLast; PoolBucketItem:=PoolBucket.GetFreeBucketItem; Assert(assigned(PoolBucketItem)); PoolBucketItemIndex:=TpvPtrUInt(TpvPtrUInt(PoolBucketItem)-TpvPtrUInt(PoolBucket.fPoolBucketItems)) div TpvPtrUInt(SizeOf(TpvPooledObjectPoolBucketItem)); result:=pointer(TpvPtrUInt(TpvPtrUInt(PoolBucket.fPoolBucketMemory)+(PoolBucketItemIndex*TpvPtrUInt(fPoolAlignedClassInstanceSize)))); PpvPooledObjectPoolBucketItem(pointer(TpvPtrUInt(TpvPtrUInt(result)-TpvPtrUInt(SizeOf(PpvPooledObjectPoolBucketItem))))^):=PoolBucketItem; inc(PoolBucket.fPoolCountAllocatedItems); finally fPoolLock.Release; end; end; procedure TpvPooledObjectPool.FreeObject(const aInstance:pointer); var PoolBucketItem:PpvPooledObjectPoolBucketItem; PoolBucket:TpvPooledObjectPoolBucket; begin PoolBucketItem:=PpvPooledObjectPoolBucketItem(pointer(TpvPtrUInt(TpvPtrUInt(aInstance)-TpvPtrUInt(SizeOf(PpvPooledObjectPoolBucketItem))))^); fPoolLock.Acquire; try PoolBucket:=PoolBucketItem^.PoolBucket; dec(PoolBucket.fPoolCountAllocatedItems); if PoolBucket.fPoolCountAllocatedItems=0 then begin PoolBucket.Free; end else begin PoolBucket.AddFreeBucketItem(PoolBucketItem); end; finally fPoolLock.Release; end; end; constructor TpvPooledObjectPoolManager.Create; begin inherited Create; fMultipleReaderSingleWriterLock:=TPasMPMultipleReaderSingleWriterLock.Create; fObjectPoolList:=TList.Create; fObjectClassMetaInfoList:=TList.Create; end; destructor TpvPooledObjectPoolManager.Destroy; var Index:TpvSizeInt; begin for Index:=0 to fObjectPoolList.Count-1 do begin TObject(fObjectPoolList.Items[Index]).Free; end; fObjectPoolList.Free; for Index:=0 to fObjectClassMetaInfoList.Count-1 do begin FreeMem(fObjectClassMetaInfoList.Items[Index]); end; fObjectClassMetaInfoList.Free; fMultipleReaderSingleWriterLock.Free; inherited Destroy; end; procedure TpvPooledObjectPoolManager.AllocateObjectClassMetaInfo(const AClassType:TClass); {$ifdef UseHashMaps} var PooledObjectClass:TpvPooledObjectClass; PooledObjectClassMetaInfoHashItem:PpvPooledObjectClassMetaInfoHashItem; HashBucket:TpvUInt32; begin fMultipleReaderSingleWriterLock.AcquireRead; try PooledObjectClass:=TpvPooledObjectClass(pointer(AClassType)); HashBucket:=HashPointer(PooledObjectClass) and PooledObjectClassMetaInfoHashMask; PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItems[HashBucket]; while assigned(PooledObjectClassMetaInfoHashItem) and (PooledObjectClassMetaInfoHashItem^.PooledObjectClass<>PooledObjectClass) do begin PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItem^.HashItemNext; end; if not assigned(PooledObjectClassMetaInfoHashItem) then begin fMultipleReaderSingleWriterLock.ReadToWrite; try GetMem(PooledObjectClassMetaInfoHashItem,SizeOf(TpvPooledObjectClassMetaInfoHashItem)); FillChar(PooledObjectClassMetaInfoHashItem^,SizeOf(TpvPooledObjectClassMetaInfoHashItem),#0); PooledObjectClassMetaInfoHashItem^.HashItemNext:=PooledObjectClassMetaInfoHashItems[HashBucket]; PooledObjectClassMetaInfoHashItems[HashBucket]:=PooledObjectClassMetaInfoHashItem; PooledObjectClassMetaInfoHashItem^.AllocatedNext:=AllocatedPooledObjectClassMetaInfoHashItems; AllocatedPooledObjectClassMetaInfoHashItems:=PooledObjectClassMetaInfoHashItem; PooledObjectClassMetaInfoHashItem^.PooledObjectClass:=PooledObjectClass; PooledObjectClassMetaInfoHashItem^.PooledObjectClassMetaInfo.Pool:=TpvPooledObjectPool.Create(AClassType); finally fMultipleReaderSingleWriterLock.WriteToRead; end; end; finally fMultipleReaderSingleWriterLock.ReleaseRead; end; end; {$else} var ObjectClassMetaInfo:PpvPooledObjectClassMetaInfo; {$ifdef Windows} OldProtect:TpvUInt32; {$endif} begin fMultipleReaderSingleWriterLock.AcquireRead; try ObjectClassMetaInfo:={%H-}pointer(pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable)))^); if not assigned(ObjectClassMetaInfo) then begin fMultipleReaderSingleWriterLock.ReadToWrite; try ObjectClassMetaInfo:={%H-}pointer(pointer(TpvPtrUInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable)))^); if not assigned(ObjectClassMetaInfo) then begin GetMem(ObjectClassMetaInfo,SizeOf(TpvPooledObjectClassMetaInfo)); FillChar(ObjectClassMetaInfo^,SizeOf(TpvPooledObjectClassMetaInfo),#0); fObjectClassMetaInfoList.Add(ObjectClassMetaInfo); ObjectClassMetaInfo^.Pool:=TpvPooledObjectPool.Create(AClassType); {$ifdef Windows} OldProtect:=0; if VirtualProtect({%H-}pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable))),SizeOf(pointer),PAGE_EXECUTE_READWRITE,OldProtect) then begin {%H-}pointer(pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable)))^):=ObjectClassMetaInfo; FlushInstructionCache(GetCurrentProcess,{%H-}pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable))),SizeOf(pointer)); VirtualProtect({%H-}pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable))),SizeOf(pointer),OldProtect,@OldProtect); end else begin raise EpvPooledObjectException.Create('Object pool fatal error'); end; {$else} {$ifdef Unix} if fpmprotect({%H-}pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable))),SizeOf(pointer),PROT_READ or PROT_WRITE or PROT_EXEC)=0 then begin {%H-}pointer(pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable)))^):=ObjectClassMetaInfo; fpmprotect({%H-}pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable))),SizeOf(pointer),PROT_READ or PROT_EXEC); end else begin raise EpvPooledObjectException.Create('Object pool fatal error'); end; {$else} {$error Unsupported system} {$endif} {$endif} end; finally fMultipleReaderSingleWriterLock.WriteToRead; end; end; finally fMultipleReaderSingleWriterLock.ReleaseRead; end; end; {$endif} function TpvPooledObjectPoolManager.AllocateObject(const AClassType:TClass):pointer; {$ifdef UseHashMaps} var PooledObjectClass:TpvPooledObjectClass; PooledObjectClassMetaInfoHashItem:PpvPooledObjectClassMetaInfoHashItem; HashBucket:TpvUInt32; begin fMultipleReaderSingleWriterLock.AcquireRead; try PooledObjectClass:=TpvPooledObjectClass(pointer(AClassType)); HashBucket:=HashPointer(PooledObjectClass) and PooledObjectClassMetaInfoHashMask; PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItems[HashBucket]; while assigned(PooledObjectClassMetaInfoHashItem) and (PooledObjectClassMetaInfoHashItem^.PooledObjectClass<>PooledObjectClass) do begin PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItem^.HashItemNext; end; if not assigned(PooledObjectClassMetaInfoHashItem) then begin fMultipleReaderSingleWriterLock.ReleaseRead; try AllocateObjectClassMetaInfo(AClassType); finally fMultipleReaderSingleWriterLock.AcquireRead; end; PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItems[HashBucket]; while assigned(PooledObjectClassMetaInfoHashItem) and (PooledObjectClassMetaInfoHashItem^.PooledObjectClass<>PooledObjectClass) do begin PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItem^.HashItemNext; end; end; result:=PooledObjectClassMetaInfoHashItem^.PooledObjectClassMetaInfo.Pool.AllocateObject; finally fMultipleReaderSingleWriterLock.ReleaseRead; end; end; {$else} var ObjectClassMetaInfo:PpvPooledObjectClassMetaInfo; begin fMultipleReaderSingleWriterLock.AcquireRead; try ObjectClassMetaInfo:={%H-}pointer(pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable)))^); if not assigned(ObjectClassMetaInfo) then begin fMultipleReaderSingleWriterLock.ReleaseRead; try AllocateObjectClassMetaInfo(AClassType); finally fMultipleReaderSingleWriterLock.AcquireRead; end; ObjectClassMetaInfo:={%H-}pointer(pointer(TpvPtrInt(TpvPtrInt(pointer(AClassType))+TpvPtrInt(vmtAutoTable)))^); end; result:=ObjectClassMetaInfo^.Pool.AllocateObject; finally fMultipleReaderSingleWriterLock.ReleaseRead; end; end; {$endif} procedure TpvPooledObjectPoolManager.FreeObject(const aInstance:TObject); {$ifdef UseHashMaps} var PooledObjectClass:TpvPooledObjectClass; PooledObjectClassMetaInfoHashItem:PpvPooledObjectClassMetaInfoHashItem; HashBucket:TpvUInt32; begin fMultipleReaderSingleWriterLock.AcquireRead; try PooledObjectClass:=TpvPooledObjectClass(pointer(aInstance.ClassType)); HashBucket:=HashPointer(PooledObjectClass) and PooledObjectClassMetaInfoHashMask; PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItems[HashBucket]; while assigned(PooledObjectClassMetaInfoHashItem) and (PooledObjectClassMetaInfoHashItem^.PooledObjectClass<>PooledObjectClass) do begin PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItem^.HashItemNext; end; if assigned(PooledObjectClassMetaInfoHashItem) then begin PooledObjectClassMetaInfoHashItem^.PooledObjectClassMetaInfo.Pool.FreeObject(aInstance); end; finally fMultipleReaderSingleWriterLock.ReleaseRead; end; end; {$else} var ObjectClassMetaInfo:PpvPooledObjectClassMetaInfo; begin fMultipleReaderSingleWriterLock.AcquireRead; try ObjectClassMetaInfo:={%H-}pointer(pointer(TpvPtrInt(TpvPtrInt(pointer(aInstance.ClassType))+TpvPtrInt(vmtAutoTable)))^); ObjectClassMetaInfo^.Pool.FreeObject(aInstance); finally fMultipleReaderSingleWriterLock.ReleaseRead; end; end; {$endif} class function TpvPooledObject.GetClassMetaInfo:pointer; {$ifdef UseHashMaps} var PooledObjectClass:TpvPooledObjectClass; PooledObjectClassMetaInfoHashItem:PpvPooledObjectClassMetaInfoHashItem; HashBucket:TpvUInt32; begin PooledObjectPoolManager.fMultipleReaderSingleWriterLock.AcquireRead; try PooledObjectClass:=TpvPooledObjectClass(pointer(self)); HashBucket:=HashPointer(PooledObjectClass) and PooledObjectClassMetaInfoHashMask; PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItems[HashBucket]; while assigned(PooledObjectClassMetaInfoHashItem) and (PooledObjectClassMetaInfoHashItem^.PooledObjectClass<>PooledObjectClass) do begin PooledObjectClassMetaInfoHashItem:=PooledObjectClassMetaInfoHashItem^.HashItemNext; end; if assigned(PooledObjectClassMetaInfoHashItem) then begin result:=@PooledObjectClassMetaInfoHashItem^.PooledObjectClassMetaInfo; end else begin result:=nil; end; finally PooledObjectPoolManager.fMultipleReaderSingleWriterLock.ReleaseRead; end; end; {$else} begin result:={%H-}pointer(pointer(TpvPtrInt(TpvPtrInt(pointer(self))+TpvPtrInt(vmtAutoTable)))^); end; {$endif} class procedure TpvPooledObject.InitializeObjectClassMetaInfo; begin PooledObjectPoolManager.AllocateObjectClassMetaInfo(pointer(self)); end; class function TpvPooledObject.NewInstance:TObject; begin result:=InitInstance(pointer(PooledObjectPoolManager.AllocateObject(pointer(self)))); end; procedure TpvPooledObject.FreeInstance; begin CleanupInstance; PooledObjectPoolManager.FreeObject(self); end; initialization {$ifdef UseHashMaps} FillChar(PooledObjectClassMetaInfoHashItems,SizeOf(TPpvPooledObjectClassMetaInfoHashItems),#0); {$else} {$ifdef unix} {$ifdef darwin} fpmprotect:=dlsym(dlopen('libc.dylib',RTLD_NOW),'mprotect'); {$else} fpmprotect:=dlsym(dlopen('libc.so',RTLD_NOW),'mprotect'); {$endif} if not assigned(fpmprotect) then begin raise Exception.Create('Importing of mprotect from libc.so failed!'); end; {$endif} {$endif} PooledObjectPoolManager:=TpvPooledObjectPoolManager.Create; finalization FreeAndNil(PooledObjectPoolManager); end.
unit Delta.Methods; interface uses System.SysUtils, System.Classes, System.rtti, System.TypInfo; function executeClassMethod(const AQualifiedName, AName: string; const Args: array of TValue): TValue; function executeClassMethodReturnIntArgsNone(const AQualifiedName, AName: PAnsiChar): Integer; stdcall; function executeClassMethodReturnReferenceArgsNone(const AQualifiedName, AName: PAnsiChar): Integer; stdcall; procedure executeClassMethodReturnNoneArgsString(const AQualifiedName, AName: PAnsiChar; const value: WideString); stdcall; procedure executeClassMethodReturnNoneArgsStringStringString_Out_String (const AQualifiedName, AName: PAnsiChar; const v1, v2, v3: WideString; out value: WideString); stdcall; procedure executeInstanceMethodReturnEnumArgsNone(const Reference: Integer; const AName: PAnsiChar; out value: WideString); stdcall; function executeClassMethodReturnReferenceArgsReference(const AQualifiedName, AName: PAnsiChar; const Reference: Integer): Integer; stdcall; function executeClassMethodReturnReferenceArgsReferenceInt(const AQualifiedName, AName: PAnsiChar; const Reference, I: Integer): Integer; stdcall; function executeInstanceMethod(const Reference: Integer; const AName: string; const Args: array of TValue): TValue; procedure executeInstanceMethodReturnNoneArgsNone(const Reference: Integer; const AName: PAnsiChar); stdcall; procedure executeInstanceMethodReturnNoneArgsReference(const Reference: Integer; const AName: PAnsiChar; Reference2: Integer); stdcall; function executeInstanceMethodReturnReferenceArgsNone(const Reference: Integer; const AName: PAnsiChar): Integer; stdcall; function executeInstanceMethodReturnReferenceArgsString(const Reference : Integer; const AName, AValue: PAnsiChar): Integer; stdcall; function executeInstanceMethodReturnReferenceArgsInt(const Reference: Integer; const AName: PAnsiChar; const R: Integer): Integer; stdcall; function executeInstanceMethodReturnIntArgsString(const Reference: Integer; const AName, AValue: PAnsiChar): Integer; stdcall; function executeInstanceMethodReturnIntArgsStringReference(const Reference : Integer; const AName, AValue: PAnsiChar; const R: Integer) : Integer; stdcall; exports executeInstanceMethodReturnNoneArgsNone, executeInstanceMethodReturnReferenceArgsNone, executeInstanceMethodReturnIntArgsString, executeInstanceMethodReturnIntArgsStringReference, executeClassMethodReturnReferenceArgsNone, executeClassMethodReturnNoneArgsStringStringString_Out_String, executeInstanceMethodReturnReferenceArgsString, executeClassMethodReturnReferenceArgsReference, executeClassMethodReturnReferenceArgsReferenceInt, executeInstanceMethodReturnNoneArgsReference, executeClassMethodReturnNoneArgsString, executeInstanceMethodReturnEnumArgsNone, executeInstanceMethodReturnReferenceArgsInt; implementation function executeClassMethod(const AQualifiedName, AName: string; const Args: array of TValue): TValue; var context: TRttiContext; instType: TRttiInstanceType; begin context := TRttiContext.Create; try try instType := (context.FindType(AQualifiedName) as TRttiInstanceType); result := instType.GetMethod(AName).Invoke(instType.MetaclassType, Args); except on E: Exception do writeln(E.ClassName + ' error raised, with message : ' + E.Message); end; finally context.Free; end; end; function executeClassMethodReturnIntArgsNone(const AQualifiedName, AName: PAnsiChar): Integer; stdcall; var value: TValue; begin value := executeClassMethod(string(AQualifiedName), string(AName), []); result := value.AsInteger; end; procedure executeClassMethodReturnNoneArgsString(const AQualifiedName, AName: PAnsiChar; const value: WideString); stdcall; begin executeClassMethod(string(AQualifiedName), string(AName), [string(value)]); end; function executeClassMethodReturnReferenceArgsNone(const AQualifiedName, AName: PAnsiChar): Integer; stdcall; var value: TValue; begin value := executeClassMethod(string(AQualifiedName), string(AName), []); result := Integer(value.AsObject); end; function executeClassMethodReturnReferenceArgsReference(const AQualifiedName, AName: PAnsiChar; const Reference: Integer): Integer; stdcall; var value: TValue; obj: TObject; begin if Reference = -1 then obj := nil else obj := TObject(Reference); value := executeClassMethod(string(AQualifiedName), string(AName), [obj]); result := Integer(value.AsObject); end; function executeClassMethodReturnReferenceArgsReferenceInt(const AQualifiedName, AName: PAnsiChar; const Reference, I: Integer): Integer; stdcall; var value: TValue; obj: TObject; begin if Reference = -1 then obj := nil else obj := TObject(Reference); value := executeClassMethod(string(AQualifiedName), string(AName), [obj, I]); result := Integer(value.AsObject); end; function executeInstanceMethod(const Reference: Integer; const AName: string; const Args: array of TValue): TValue; var context: TRttiContext; instType: TRttiInstanceType; obj: TObject; begin context := TRttiContext.Create; try try obj := TObject(Reference); instType := (context.GetType(obj.ClassType) as TRttiInstanceType); result := instType.GetMethod(AName).Invoke(obj, Args); except on E: Exception do writeln(E.ClassName + ' error raised, with message : ' + E.Message); end; finally context.Free; end; end; procedure executeInstanceMethodReturnNoneArgsNone(const Reference: Integer; const AName: PAnsiChar); stdcall; begin executeInstanceMethod(Reference, string(AName), []); end; function executeInstanceMethodReturnReferenceArgsNone(const Reference: Integer; const AName: PAnsiChar): Integer; stdcall; var value: TValue; begin value := executeInstanceMethod(Reference, string(AName), []); result := Integer(value.AsObject); end; procedure executeInstanceMethodReturnNoneArgsReference(const Reference: Integer; const AName: PAnsiChar; Reference2: Integer); stdcall; var obj: TObject; begin if Reference2 = -1 then obj := nil else obj := TObject(Reference2); executeInstanceMethod(Reference, string(AName), [obj]); end; function executeInstanceMethodReturnReferenceArgsInt(const Reference: Integer; const AName: PAnsiChar; const R: Integer): Integer; stdcall; var value: TValue; begin value := executeInstanceMethod(Reference, string(AName), [R]); result := Integer(value.AsObject); end; function executeInstanceMethodReturnReferenceArgsString(const Reference : Integer; const AName, AValue: PAnsiChar): Integer; stdcall; var value: TValue; begin value := executeInstanceMethod(Reference, string(AName), [string(AValue)]); result := Integer(value.AsObject); end; function executeInstanceMethodReturnIntArgsString(const Reference: Integer; const AName, AValue: PAnsiChar): Integer; stdcall; var value: TValue; begin value := executeInstanceMethod(Reference, string(AName), [string(AValue)]); result := value.AsInteger; end; function executeInstanceMethodReturnIntArgsStringReference(const Reference : Integer; const AName, AValue: PAnsiChar; const R: Integer) : Integer; stdcall; var value: TValue; begin value := executeInstanceMethod(Reference, string(AName), [string(AValue), TObject(R)]); result := value.AsInteger; end; procedure executeInstanceMethodReturnEnumArgsNone(const Reference: Integer; const AName: PAnsiChar; out value: WideString); stdcall; var s: String; methodResultValue: TValue; begin methodResultValue := executeInstanceMethod(Reference, string(AName), []); s := methodResultValue.AsString; value := s; end; procedure executeClassMethodReturnNoneArgsStringStringString_Out_String (const AQualifiedName, AName: PAnsiChar; const v1, v2, v3: WideString; out value: WideString); stdcall; var methodResultValue: TValue; begin methodResultValue := executeClassMethod(string(AQualifiedName), string(AName), [string(v1), string(v2), string(v3)]); value := methodResultValue.AsString; end; end.
unit serverwinshoeqotd; interface //////////////////////////////////////////////////////////////////////////////// // Author: Ozz Nixon (RFC 865) [less than 512 characters total, multiple lines OK!] // .. // 5.13.99 Final Version // 13-JAN-2000 MTL: Moved to new Palette Scheme (Winshoes Servers) //////////////////////////////////////////////////////////////////////////////// uses Classes, ServerWinshoe; Type TGetEvent = procedure(Thread: TWinshoeServerThread) of object; TWinshoeQOTDListener = class(TWinshoeListener) private fOnCommandQOTD:TGetEvent; protected function DoExecute(Thread: TWinshoeServerThread): boolean; override; public constructor Create(AOwner: TComponent); override; published property OnCommandQOTD: TGetEvent read fOnCommandQOTD write fOnCommandQOTD; end; procedure Register; implementation uses GlobalWinshoe, SysUtils, Winshoes; procedure Register; begin RegisterComponents('Winshoes Servers', [TWinshoeQOTDListener]); end; constructor TWinshoeQOTDListener.Create(AOwner: TComponent); begin inherited Create(AOwner); Port := WSPORT_QOTD; end; function TWinshoeQOTDListener.DoExecute(Thread: TWinshoeServerThread): boolean; begin result := inherited DoExecute(Thread); if result then exit; with Thread.Connection do begin If Connected then begin if assigned(OnCommandQOTD) then OnCommandQOTD(Thread); End; Disconnect; end; {with} end; {doExecute} end.
PROGRAM Prime(INPUT, OUTPUT); CONST MaxNumber = 200; MinNumber = 2; TYPE IntSet = SET OF MinNumber..MaxNumber; VAR Int: INTEGER; Sieve: SET OF MinNumber..MaxNumber; PrimeNumbers: SET OF MinNumber..MaxNumber; IntFile: FILE OF INTEGER; BEGIN Sieve := [MinNumber..MaxNumber]; PrimeNumbers := []; REWRITE(IntFile); Int := 1; WHILE Int < MaxNumber DO BEGIN Int := Int + 1; WRITE(IntFile, Int) END; WHILE Sieve <> [] DO BEGIN RESET(IntFile); Int := IntFile^; PrimeNumbers := PrimeNumbers + [Int]; WHILE NOT EOF(IntFile) DO BEGIN IF IntFile^ Mod Int = 0 THEN Sieve := Sieve - [IntFile^]; GET(IntFile) END; REWRITE(IntFile); WHILE Int <> MaxNumber DO BEGIN Int := Int + 1; IF Int IN Sieve THEN WRITE(IntFile, Int); END END; Int := MinNumber; WHILE Int <> MaxNumber DO BEGIN IF Int IN PrimeNumbers THEN WRITE(OUTPUT, Int, ' '); Int := Int + 1 END END.
unit expressraider_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6502,m6809,main_engine,controls_engine,ym_2203,ym_3812,gfx_engine, rom_engine,pal_engine,sound_engine; procedure Cargar_expraid; procedure principal_expraid; function iniciar_expraid:boolean; procedure cerrar_expraid; procedure reset_expraid; //Main CPU function getbyte_expraid(direccion:word):byte; procedure putbyte_expraid(direccion:word;valor:byte); function get_io_expraid:byte; //Sound CPU function getbyte_snd_expraid(direccion:word):byte; procedure putbyte_snd_expraid(direccion:word;valor:byte); procedure expraid_sound_update; procedure snd_irq(irqstate:byte); implementation const expraid_rom:array[0..2] of tipo_roms=( (n:'cz01';l:$4000;p:$4000;crc:$dc8f9fba),(n:'cz00';l:$8000;p:$8000;crc:$a81290bc),()); expraid_char:tipo_roms=(n:'cz07';l:$4000;p:$0000;crc:$686bac23); expraid_tiles:array[0..3] of tipo_roms=( (n:'cz04';l:$8000;p:$0000;crc:$643a1bd3),(n:'cz05';l:$8000;p:$10000;crc:$c44570bf), (n:'cz06';l:$8000;p:$18000;crc:$b9bb448b),()); expraid_snd:tipo_roms=(n:'cz02';l:$8000;p:$8000;crc:$552e6112); expraid_tiles_mem:tipo_roms=(n:'cz03';l:$8000;p:$0000;crc:$6ce11971); expraid_sprites:array[0..6] of tipo_roms=( (n:'cz09';l:$8000;p:$0000;crc:$1ed250d1),(n:'cz08';l:$8000;p:$8000;crc:$2293fc61), (n:'cz13';l:$8000;p:$10000;crc:$7c3bfd00),(n:'cz12';l:$8000;p:$18000;crc:$ea2294c8), (n:'cz11';l:$8000;p:$20000;crc:$b7418335),(n:'cz10';l:$8000;p:$28000;crc:$2f611978),()); expraid_proms:array[0..4] of tipo_roms=( (n:'cz17.prm';l:$100;p:$000;crc:$da31dfbc),(n:'cz16.prm';l:$100;p:$100;crc:$51f25b4c), (n:'cz15.prm';l:$100;p:$200;crc:$a6168d7f),(n:'cz14.prm';l:$100;p:$300;crc:$52aad300),()); var vb,prot_val,sound_latch,scroll_x,scroll_y,scroll_x2:byte; mem_tiles:array[0..$7fff] of byte; bg_tiles:array[0..3] of byte; bg_tiles_cam:array[0..3] of boolean; old_val,old_val2:boolean; procedure Cargar_expraid; begin llamadas_maquina.iniciar:=iniciar_expraid; llamadas_maquina.bucle_general:=principal_expraid; llamadas_maquina.cerrar:=cerrar_expraid; llamadas_maquina.reset:=reset_expraid; llamadas_maquina.fps_max:=59.637405; end; function iniciar_expraid:boolean; const pc_x:array[0..7] of dword=(0+($2000*8),1+($2000*8), 2+($2000*8), 3+($2000*8), 0, 1, 2, 3); pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); ps_x:array[0..15] of dword=(128+0, 128+1, 128+2, 128+3, 128+4, 128+5, 128+6, 128+7, 0, 1, 2, 3, 4, 5, 6, 7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8); pt_x:array[0..15] of dword=(0, 1, 2, 3, 1024*32*2,1024*32*2+1,1024*32*2+2,1024*32*2+3, 128+0,128+1,128+2,128+3,128+1024*32*2,128+1024*32*2+1,128+1024*32*2+2,128+1024*32*2+3); pt_y:array[0..15] of dword=(0*8,1*8,2*8,3*8,4*8,5*8,6*8,7*8, 64+0*8,64+1*8,64+2*8,64+3*8,64+4*8,64+5*8,64+6*8,64+7*8); var colores:tpaleta; f:word; i,offs:integer; memoria_temp:array[0..$2ffff] of byte; begin iniciar_expraid:=false; iniciar_audio(false); screen_init(1,256,256,false,true); screen_mod_sprites(1,512,0,$1ff,0); screen_init(2,512,512); screen_init(3,512,512,true); screen_init(4,512,512,true); screen_init(6,256,256,true); iniciar_video(240,240); //Main CPU main_m6502:=cpu_m6502.create(1500000,262,TCPU_DECO16); main_m6502.change_ram_calls(getbyte_expraid,putbyte_expraid); main_m6502.change_io_calls(nil,get_io_expraid); //Sound CPU snd_m6809:=cpu_m6809.Create(1500000,262); snd_m6809.change_ram_calls(getbyte_snd_expraid,putbyte_snd_expraid); snd_m6809.init_sound(expraid_sound_update); //Sound Chip ym2203_0:=ym2203_chip.create(0,1500000,2); ym3812_init(0,3000000,snd_irq); //cargar roms if not(cargar_roms(@memoria,@expraid_rom,'exprraid.zip',0)) then exit; //cargar roms audio if not(cargar_roms(@mem_snd,@expraid_snd,'exprraid.zip')) then exit; //Cargar chars if not(cargar_roms(@memoria_temp,@expraid_char,'exprraid.zip')) then exit; init_gfx(0,8,8,1024); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,8*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //sprites if not(cargar_roms(@memoria_temp,@expraid_sprites,'exprraid.zip',0)) then exit; init_gfx(1,16,16,2048); gfx[1].trans[0]:=true; gfx_set_desc_data(3,0,32*8,2*2048*32*8,2048*32*8,0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //Cargar tiles if not(cargar_roms(@memoria_temp,@expraid_tiles,'exprraid.zip',0)) then exit; //Mover los datos de los tiles para poder usar las rutinas de siempre... i:=$8000-$1000; offs:=$10000-$1000; repeat copymemory(@memoria_temp[offs],@memoria_temp[i],$1000); offs:=offs-$1000; copymemory(@memoria_temp[offs],@memoria_temp[i],$1000); offs:=offs-$1000; i:=i-$1000; until (i<0); init_gfx(2,16,16,1024); gfx[2].trans[0]:=true; for f:=0 to 3 do begin gfx_set_desc_data(3,8,32*8,4+(f*$4000)*8,($10000+f*$4000)*8+0,($10000+f*$4000)*8+4); convert_gfx(2,f*$100*16*16,@memoria_temp,@pt_x,@pt_y,false,false); gfx_set_desc_data(3,8,32*8,0+(f*$4000)*8,($11000+f*$4000)*8+0,($11000+f*$4000)*8+4); convert_gfx(2,(f*$100*16*16)+($80*16*16),@memoria_temp,@pt_x,@pt_y,false,false); end; if not(cargar_roms(@mem_tiles,@expraid_tiles_mem,'exprraid.zip')) then exit; //Paleta if not(cargar_roms(@memoria_temp,@expraid_proms,'exprraid.zip',0)) then exit; for f:=0 to 255 do begin colores[f].r:=((memoria_temp[f] and $f) shl 4) or (memoria_temp[f] and $f); colores[f].g:=((memoria_temp[f+$100] and $f) shl 4) or (memoria_temp[f+$100] and $f); colores[f].b:=((memoria_temp[f+$200] and $f) shl 4) or (memoria_temp[f+$200] and $f); end; set_pal(colores,256); //final reset_expraid; iniciar_expraid:=true; end; procedure cerrar_expraid; begin main_m6502.free; snd_m6809.Free; YM2203_0.Free; YM3812_close(0); close_audio; close_video; end; procedure reset_expraid; begin main_m6502.reset; snd_m6809.reset; YM2203_0.Reset; YM3812_reset(0); marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; vb:=0; prot_val:=0; sound_latch:=0; old_val:=false; old_val2:=false; scroll_x:=0; scroll_y:=0; scroll_x2:=0; end; procedure update_video_expraid;inline; var f,i,nchar,color,atrib:word; x,y,pos_ini:word; rest_scroll:word; begin //Background for i:=0 to 3 do begin if bg_tiles_cam[i] then begin pos_ini:=bg_tiles[i]*$100; for f:=0 to $ff do begin x:=(f mod 16)*16; y:=(f div 16)*16; if i>1 then y:=y+256; x:=x+(256*(i and 1)); atrib:=mem_tiles[$4000+pos_ini+f]; nchar:=mem_tiles[pos_ini+f]+((atrib and $03) shl 8); color:=atrib and $18; put_gfx_flip(x,y,nchar,color,2,2,(atrib and 4)<>0,false); if (atrib and $80)<>0 then put_gfx_trans_flip(x,y,nchar,color,4,2,(atrib and 4)<>0,false) else put_gfx_block_trans(x,y,4,16,16); end; bg_tiles_cam[i]:=false; end; end; //Para acelerar las cosas (creo) rest_scroll:=256-scroll_y; //Express Rider divide en dos la pantalla vertical, con dos scrolls //diferentes, en total 512x256 y otra de 512x256 actualiza_trozo(scroll_x,scroll_y,256,rest_scroll,2,0,0,256,rest_scroll,1); actualiza_trozo(scroll_x2,256,256,scroll_y,2,0,rest_scroll,256,scroll_y,1); //Sprites for f:=0 to $7f do begin x:=((248-memoria[$602+(f*4)]) and $ff)-8; y:=memoria[$600+(f*4)]; nchar:=memoria[$603+(f*4)]+((memoria[$601+(f*4)] and $e0) shl 3); color:=((memoria[$601+(f*4)] and $03) + ((memoria[$601+(f*4)] and $08) shr 1)) shl 3; put_gfx_sprite(nchar,64+color,(memoria[$601+(f*4)] and 4)<>0,false,1); actualiza_gfx_sprite(x,y,1,1); if (memoria[$601+(f*4)] and $10)<>0 then begin put_gfx_sprite(nchar+1,64+color,(memoria[$601+(f*4)] and 4)<>0,false,1); actualiza_gfx_sprite(x,y+16,1,1); end; end; //Prioridad del fondo actualiza_trozo(scroll_x,scroll_y,256,rest_scroll,4,0,0,256,rest_scroll,1); actualiza_trozo(scroll_x2,256,256,scroll_y,4,0,rest_scroll,256,scroll_y,1); //Foreground for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=f mod 32; y:=f div 32; nchar:=memoria[$800+f]+((memoria[$c00+f] and $07) shl 8); color:=(memoria[$c00+f] and $10) shr 2; put_gfx_trans(x*8,y*8,nchar,128+color,6,0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,6,0,0,256,256,1); actualiza_trozo_final(8,8,240,240,1); end; procedure eventos_expraid; begin if event.arcade then begin if arcade_input.right[0] then marcade.in0:=marcade.in0 and $fe else marcade.in0:=marcade.in0 or 1; if arcade_input.left[0] then marcade.in0:=marcade.in0 and $fd else marcade.in0:=marcade.in0 or 2; if arcade_input.up[0] then marcade.in0:=marcade.in0 and $fb else marcade.in0:=marcade.in0 or 4; if arcade_input.down[0] then marcade.in0:=marcade.in0 and $f7 else marcade.in0:=marcade.in0 or 8; if arcade_input.but0[0] then marcade.in0:=marcade.in0 and $ef else marcade.in0:=marcade.in0 or $10; if arcade_input.but1[0] then marcade.in0:=marcade.in0 and $df else marcade.in0:=marcade.in0 or $20; if (arcade_input.coin[0] and not(old_val)) then begin marcade.in2:=(marcade.in2 and $bf); main_m6502.pedir_nmi:=ASSERT_LINE;; end else begin marcade.in2:=(marcade.in2 or $40); end; if (arcade_input.coin[1] and not(old_val2)) then begin marcade.in2:=(marcade.in2 and $7f); main_m6502.pedir_nmi:=ASSERT_LINE; end else begin marcade.in2:=(marcade.in2 or $80); end; old_val:=arcade_input.coin[0]; old_val2:=arcade_input.coin[1]; if arcade_input.start[0] then marcade.in0:=marcade.in0 and $bf else marcade.in0:=marcade.in0 or $40; if arcade_input.start[1] then marcade.in0:=marcade.in0 and $7f else marcade.in0:=marcade.in0 or $80; end; end; procedure principal_expraid; var frame_m,frame_s:single; f:word; begin init_controls(false,false,false,true); frame_m:=main_m6502.tframes; frame_s:=snd_m6809.tframes; while EmuStatus=EsRuning do begin for f:=0 to 261 do begin main_m6502.run(frame_m); frame_m:=frame_m+main_m6502.tframes-main_m6502.contador; //Sound snd_m6809.run(frame_s); frame_s:=frame_s+snd_m6809.tframes-snd_m6809.contador; case f of 7:vb:=0; 247:begin update_video_expraid; vb:=$2; end; end; end; eventos_expraid; video_sync; end; end; function getbyte_expraid(direccion:word):byte; begin case direccion of 0..$fff,$4000..$ffff:getbyte_expraid:=memoria[direccion]; $1800:getbyte_expraid:=$bf; $1801:getbyte_expraid:=marcade.in0; $1802:getbyte_expraid:=marcade.in2; $1803:getbyte_expraid:=$ff; $2800:getbyte_expraid:=prot_val; $2801:getbyte_expraid:=$2; end; end; procedure putbyte_expraid(direccion:word;valor:byte); begin if direccion>$3fff then exit; case direccion of 0..$7ff:memoria[direccion]:=valor; $800..$fff:begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $2000:main_m6502.clear_nmi; $2001:begin sound_latch:=valor; snd_m6809.pedir_nmi:=ASSERT_LINE; end; $2800..$2803:if bg_tiles[direccion and $3]<>(valor and $3f) then begin bg_tiles[direccion and $3]:=valor and $3f; bg_tiles_cam[direccion and $3]:=true; end; $2804:scroll_y:=valor; $2805:scroll_x:=valor; $2806:scroll_x2:=valor; $2807:case valor of $20,$60:; $80:prot_val:=prot_val+1; $90:prot_val:=0; end; end; end; function get_io_expraid:byte; begin get_io_expraid:=vb; end; function getbyte_snd_expraid(direccion:word):byte; begin case direccion of 0..$1fff,$8000..$ffff:getbyte_snd_expraid:=mem_snd[direccion]; $2000:getbyte_snd_expraid:=ym2203_0.read_status; $2001:getbyte_snd_expraid:=ym2203_0.Read_Reg; $4000:getbyte_snd_expraid:=ym3812_status_port(0); $6000:begin getbyte_snd_expraid:=sound_latch; snd_m6809.clear_nmi; end; end; end; procedure putbyte_snd_expraid(direccion:word;valor:byte); begin if direccion>$7fff then exit; case direccion of 0..$1fff:mem_snd[direccion]:=valor; $2000:ym2203_0.control(valor); $2001:ym2203_0.write_reg(valor); $4000:ym3812_control_port(0,valor); $4001:ym3812_write_port(0,valor); end; end; procedure expraid_sound_update; begin ym2203_0.Update; ym3812_Update(0); end; procedure snd_irq(irqstate:byte); begin if (irqstate<>0) then snd_m6809.pedir_irq:=ASSERT_LINE else snd_m6809.pedir_irq:=CLEAR_LINE; end; end.
unit ButtonComps; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TEncartaButton = class(TCustomControl) private Cap : string; Col : TColor; Border: TColor; OverFColor: TColor; OverColor: TColor; DownColor: TColor; MDown: TMouseEvent; MUp: TMouseEvent; MEnter : TNotifyEvent; MLeave : TNotifyEvent; Enab: Boolean; Bmp: TBitmap; SCap: Boolean; BtnClick: TNotifyEvent; procedure SetCol(Value: TColor); procedure SetBorder(Value: TColor); procedure SetCap(Value: string); procedure SetBmp(Value: TBitmap); procedure SetSCap(Value: Boolean); protected procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure MouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure Click; override; procedure SetParent(Value: TWinControl); override; public constructor Create(AOwner: TComponent); override; Destructor Destroy; override; published property Caption : string read Cap write SetCap; property Color : TColor read Col write SetCol; property ColorBorder : TColor read Border write SetBorder; property Enabled : Boolean read Enab write Enab; property OnMouseDown: TMouseEvent read MDown write MDown; property OnMouseUp: TMouseEvent read MUp write MUp; property OnMouseEnter: TNotifyEvent read MEnter write MEnter; property OnMouseLeave: TNotifyEvent read MLeave write MLeave; property OnClick: TNotifyEvent read BtnClick write BtnClick; property Glyph: TBitmap read Bmp write SetBmp; property ColorOverCaption: TColor read OverFColor write OverFColor; property ColorOver: TColor read OverColor write OverColor; property ColorDown: TColor read DownColor write DownColor; property ShowCaption: Boolean read SCap write SetSCap; property ShowHint; property ParentShowHint; property OnMouseMove; property Font; end; TAOLButton = class(TCustomControl) private Cap : string; Col : TColor; RaiseCol: TColor; MDown: TMouseEvent; MUp: TMouseEvent; MLeave : TNotifyEvent; Enab: Boolean; BtnClick: TNotifyEvent; procedure SetCol(Value: TColor); procedure SetCap(Value: string); procedure SetRaiseCol(Value: TColor); protected procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure Click; override; procedure SetParent(Value: TWinControl); override; public constructor Create(AOwner: TComponent); override; published property Caption : string read Cap write SetCap; property Color : TColor read Col write SetCol; property RaiseColor : TColor read RaiseCol write SetRaiseCol; property Enabled : Boolean read Enab write Enab; property OnMouseDown: TMouseEvent read MDown write MDown; property OnMouseUp: TMouseEvent read MUp write MUp; property OnMouseLeave: TNotifyEvent read MLeave write MLeave; property OnClick: TNotifyEvent read BtnClick write BtnClick; property ShowHint; property ParentShowHint; property OnMouseMove; property Font; end; TImageButton = class(TCustomControl) private MOver: TBitmap; MDown: TBitmap; MUp: TBitmap; Bmp: TBitmap; ActualBmp: TBitmap; BmpDAble: TBitmap; BtnClick: TNotifyEvent; OnMDown: TMouseEvent; OnMUp: TMouseEvent; OnMEnter: TNotifyEvent; OnMLeave: TNotifyEvent; procedure SetMOver(Value: TBitmap); procedure SetMDown(Value: TBitmap); procedure SetMUp(Value: TBitmap); procedure SetBmp(Value: TBitmap); procedure SetBmpDAble(Value: TBitmap); protected procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure MouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure Click; override; public constructor Create(AOwner: TComponent); override; Destructor Destroy; override; published property BitmapOver: TBitmap read MOver write SetMOver; property BitmapDown: TBitmap read MDown write SetMDown; property BitmapUp: TBitmap read MUp write SetMUp; property BitmapDisabled: TBitmap read BmpDAble write SetBmpDAble; property Bitmap: TBitmap read Bmp write SetBmp; property OnClick: TNotifyEvent read BtnClick write BtnClick; property OnMouseDown: TMouseEvent read OnMDown write OnMDown; property OnMouseUp: TMouseEvent read OnMUp write OnMUp; property OnMouseEnter: TNotifyEvent read OnMEnter write OnMEnter; property OnMouseLeave: TNotifyEvent read OnMLeave write OnMLeave; property Enabled; property ShowHint; property ParentShowHint; end; TSelButton = class(TCustomControl) private Cap : string; Col : TColor; Border: TColor; OverFColor: TColor; OverColor: TColor; DownColor: TColor; MDown: TMouseEvent; MUp: TMouseEvent; MEnter : TNotifyEvent; MLeave : TNotifyEvent; Enab: Boolean; BtnClick: TNotifyEvent; Alment: TAlignment; BWidth: Longint; procedure SetCol(Value: TColor); procedure SetBorder(Value: TColor); procedure SetCap(Value: string); procedure SetAlment(Value: TAlignment); procedure SetBWidth(Value: Longint); protected procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure MouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure Click; override; procedure SetParent(Value: TWinControl); override; public constructor Create(AOwner: TComponent); override; published property Caption : string read Cap write SetCap; property Color : TColor read Col write SetCol; property ColorBorder : TColor read Border write SetBorder; property Enabled : Boolean read Enab write Enab; property OnMouseDown: TMouseEvent read MDown write MDown; property OnMouseUp: TMouseEvent read MUp write MUp; property OnMouseEnter: TNotifyEvent read MEnter write MEnter; property OnMouseLeave: TNotifyEvent read MLeave write MLeave; property OnClick: TNotifyEvent read BtnClick write BtnClick; property ColorOverCaption: TColor read OverFColor write OverFColor; property ColorOver: TColor read OverColor write OverColor; property ColorDown: TColor read DownColor write DownColor; property Alignment: TAlignment read Alment write SetAlment; property BorderWidth: Longint read BWidth write SetBWidth; property ShowHint; property ParentShowHint; property OnMouseMove; property Font; end; TSquareButton = class(TCustomControl) private Cap : string; Col : TColor; Border: TColor; OverFColor: TColor; OverBorderCol: TColor; DownBorderCol: TColor; MDown: TMouseEvent; MUp: TMouseEvent; MEnter : TNotifyEvent; MLeave : TNotifyEvent; Enab: Boolean; BtnClick: TNotifyEvent; Alment: TAlignment; BWidth: Longint; procedure SetCol(Value: TColor); procedure SetBorder(Value: TColor); procedure SetCap(Value: string); procedure SetAlment(Value: TAlignment); procedure SetBWidth(Value: Longint); protected procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure MouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure Click; override; procedure SetParent(Value: TWinControl); override; public constructor Create(AOwner: TComponent); override; published property Caption : string read Cap write SetCap; property Color : TColor read Col write SetCol; property ColorBorder : TColor read Border write SetBorder; property Enabled : Boolean read Enab write Enab; property OnMouseDown: TMouseEvent read MDown write MDown; property OnMouseUp: TMouseEvent read MUp write MUp; property OnMouseEnter: TNotifyEvent read MEnter write MEnter; property OnMouseLeave: TNotifyEvent read MLeave write MLeave; property OnClick: TNotifyEvent read BtnClick write BtnClick; property ColorOverCaption: TColor read OverFColor write OverFColor; property Alignment: TAlignment read Alment write SetAlment; property ColorOverBorder: TColor read OverBorderCol write OverBorderCol; property BorderWidth: Longint read BWidth write SetBWidth; property DownBorderColor: TColor read DownBorderCol write DownBorderCol; property ShowHint; property ParentShowHint; property OnMouseMove; property Font; end; procedure Register; implementation procedure Register; begin RegisterComponents('Buttons', [TEncartaButton, TAOLButton, TImageButton, TSelButton, TSquareButton]); end; constructor TEncartaButton.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 86; Height := 22; Col := clBtnFace; OverFColor := clBlack; OverColor := $000ABED8; DownColor := $000ABED8; Canvas.Brush.Color := clBlack; Border := $00828F99; Font.Name := 'Arial'; Font.Color := clBlack; Enab := true; Bmp := TBitmap.Create; ShowHint := true; SCap := true; end; Destructor TEncartaButton.Destroy; begin Bmp.Free; inherited; end; procedure TEncartaButton.SetParent(Value: TWinControl); begin inherited; if Value <> nil then Cap := Name; end; procedure TEncartaButton.Paint; var TextWidth, TextHeight : Longint; begin inherited Paint; Canvas.Font := Font; Canvas.Brush.Color := Col; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); Canvas.Font.Color := $00D6E0E0; if Bmp.Empty = false then begin if SCap = true then begin Canvas.BrushCopy(Rect(Width div 2 - (Bmp.Width+TextWidth) div 2-1,Height div 2 - Bmp.Height div 2, bmp.width+Width div 2 - (Bmp.Width+TextWidth) div 2,bmp.height+Height div 2 - Bmp.Height div 2), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); Canvas.Font.Color := Font.Color; Canvas.TextOut(Width div 2 + (Bmp.Width-TextWidth) div 2+5-1,Height div 2-TextHeight div 2,Cap); end else Canvas.BrushCopy(Rect(Width div 2-Bmp.Width div 2,Height div 2-Bmp.Height div 2, bmp.width+Width div 2-Bmp.Width div 2,bmp.height+Height div 2-Bmp.Height div 2), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); end else begin Canvas.Font.Color := Font.Color; if SCap = true then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); end; Canvas.Brush.Color := Border; Canvas.FrameRect(Rect(0,0,Width,Height)); end; procedure TEncartaButton.Click; begin inherited Click; Paint; if Enab then if Assigned(BtnClick) then BtnClick(Self); end; procedure TEncartaButton.SetCol(Value: TColor); begin Col := Value; Paint; end; procedure TEncartaButton.SetBorder(Value: TColor); begin Border := Value; Paint; end; procedure TEncartaButton.SetCap(Value: string); begin Cap := value; Paint; end; procedure TEncartaButton.SetBmp(Value: TBitmap); begin Bmp.Assign(value); invalidate; end; procedure TEncartaButton.SetSCap(value: Boolean); begin SCap := Value; Paint; end; procedure TEncartaButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var TextWidth, TextHeight : Longint; begin inherited MouseDown(Button, Shift, X, Y); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if (Button = mbLeft) and Enab then begin if Assigned (MDown) then MDown(Self, Button, Shift, X, Y); Canvas.Brush.Color := DownColor; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); if Bmp.Empty = false then begin if SCap = true then begin Canvas.BrushCopy(Rect(Width div 2 - (Bmp.Width+TextWidth) div 2-1+1,Height div 2 - Bmp.Height div 2+1, bmp.width+Width div 2 - (Bmp.Width+TextWidth) div 2+1,bmp.height+Height div 2 - Bmp.Height div 2+1), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); Canvas.TextOut(Width div 2 + (Bmp.Width-TextWidth) div 2+5-1+1,Height div 2-TextHeight div 2+1,Cap); end else Canvas.BrushCopy(Rect(Width div 2-Bmp.Width div 2+1,Height div 2-Bmp.Height div 2+1, bmp.width+Width div 2-Bmp.Width div 2+1,bmp.height+Height div 2-Bmp.Height div 2+1), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); end else if SCap = true then Canvas.TextOut(Width div 2 - TextWidth div 2+1,Height div 2-TextHeight div 2+1,Cap); Canvas.Brush.Color := Border; Canvas.FrameRect(Rect(0,0,Width,Height)); Canvas.Pen.Color := $00EDF4F8; Canvas.Polyline([Point(Width-1,0),Point(Width-1,Height)]); Canvas.Polyline([Point(Width,Height-1),Point(-1,Height-1)]); Canvas.Pen.Color := $004F4F4F; Canvas.Polyline([Point(0,Height-2),Point(0,0)]); Canvas.Polyline([Point(0,0),Point(Width-1,0)]); end; end; procedure TEncartaButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var TextWidth, TextHeight : Longint; MouseOverButton: Boolean; P: TPoint; begin inherited MouseUp(Button, Shift, X, Y); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if (Button = mbLeft) and Enab then begin if Assigned (MUp) then MUp(Self, Button, Shift, X, Y); GetCursorPos(P); MouseOverButton := (FindDragTarget(P, True) = Self); if MouseOverButton then begin Canvas.Brush.Color := OverColor; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); Canvas.Font.Color := OverFColor; if Bmp.Empty = false then begin if SCap = true then begin Canvas.BrushCopy(Rect(Width div 2 - (Bmp.Width+TextWidth) div 2-1,Height div 2 - Bmp.Height div 2, bmp.width+Width div 2 - (Bmp.Width+TextWidth) div 2,bmp.height+Height div 2 - Bmp.Height div 2), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); Canvas.TextOut(Width div 2 + (Bmp.Width-TextWidth) div 2+5-1,Height div 2-TextHeight div 2,Cap); end else Canvas.BrushCopy(Rect(Width div 2-Bmp.Width div 2,Height div 2-Bmp.Height div 2, bmp.width+Width div 2-Bmp.Width div 2,bmp.height+Height div 2-Bmp.Height div 2), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); end else if SCap = true then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); Canvas.Brush.Color := Border; Canvas.FrameRect(Rect(0,0,Width,Height)); Canvas.Pen.Color := $00EDF4F8; Canvas.Polyline([Point(0,Height-2),Point(0,0)]); Canvas.Polyline([Point(0,0),Point(Width-1,0)]); Canvas.Pen.Color := $004F4F4F; Canvas.Polyline([Point(Width-1,0),Point(Width-1,Height)]); Canvas.Polyline([Point(Width,Height-1),Point(-1,Height-1)]); end; end; end; procedure TEncartaButton.MouseEnter(var Message: TMessage); var TextWidth, TextHeight : Integer; begin TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if Enab then begin Canvas.Brush.Color := OverColor; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); Canvas.Font.Color := OverFColor; if Bmp.Empty = false then begin if SCap = true then begin Canvas.BrushCopy(Rect(Width div 2 - (Bmp.Width+TextWidth) div 2-1,Height div 2 - Bmp.Height div 2, bmp.width+Width div 2 - (Bmp.Width+TextWidth) div 2,bmp.height+Height div 2 - Bmp.Height div 2), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); Canvas.TextOut(Width div 2 + (Bmp.Width-TextWidth) div 2+5-1,Height div 2-TextHeight div 2,Cap); end else Canvas.BrushCopy(Rect(Width div 2-Bmp.Width div 2,Height div 2-Bmp.Height div 2, bmp.width+Width div 2-Bmp.Width div 2,bmp.height+Height div 2-Bmp.Height div 2), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); end else if SCap = true then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); Canvas.Brush.Color := Border; Canvas.FrameRect(Rect(0,0,Width,Height)); Canvas.Pen.Color := $00EDF4F8; Canvas.Polyline([Point(0,Height-2),Point(0,0)]); Canvas.Polyline([Point(0,0),Point(Width-1,0)]); Canvas.Pen.Color := $004F4F4F; Canvas.Polyline([Point(Width-1,0),Point(Width-1,Height)]); Canvas.Polyline([Point(Width,Height-1),Point(-1,Height-1)]); end; end; procedure TEncartaButton.MouseLeave(var Message: TMessage); var TextWidth, TextHeight : Integer; begin TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); Canvas.Brush.Color := Col; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); Canvas.Font.Color := $00D6E0E0; Canvas.Brush.Color := Col; Canvas.Font.Color := Font.Color; if Bmp.Empty = false then begin if SCap = true then begin Canvas.BrushCopy(Rect(Width div 2 - (Bmp.Width+TextWidth) div 2-1,Height div 2 - Bmp.Height div 2, bmp.width+Width div 2 - (Bmp.Width+TextWidth) div 2,bmp.height+Height div 2 - Bmp.Height div 2), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); Canvas.Font.Color := Font.Color; Canvas.TextOut(Width div 2 + (Bmp.Width-TextWidth) div 2+5-1,Height div 2-TextHeight div 2,Cap); end else Canvas.BrushCopy(Rect(Width div 2-Bmp.Width div 2,Height div 2-Bmp.Height div 2, bmp.width+Width div 2-Bmp.Width div 2,bmp.height+Height div 2-Bmp.Height div 2), bmp,Rect(0,0,bmp.width,bmp.height),bmp.Canvas.pixels[0,0]); end else if SCap = true then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); Canvas.Brush.Color := Border; Canvas.FrameRect(Rect(0,0,Width,Height)); end; constructor TAOLButton.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 89; Height := 23; Col := $00A56934; Canvas.Brush.Color := clBlack; Font.Name := 'Arial'; Font.Color := clWhite; Font.Size := 8; Font.Style :=[fsBold]; Enab := true; ShowHint := true; RaiseCol := $00D7A28A; end; procedure TAOLButton.SetParent(Value: TWinControl); begin inherited; if Value <> nil then Cap := Name; end; procedure TAOLButton.Paint; var TextWidth, TextHeight : Longint; begin inherited Paint; Canvas.Font := Font; Canvas.Brush.Color := Col; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); Canvas.Brush.Color := RaiseCol; Canvas.FillRect(Rect(1,1,3,Height-1)); Canvas.FillRect(Rect(1,1,Width-1,3)); Canvas.Brush.Color := clBlack; Canvas.FillRect(Rect(Width-1,1,Width-3,Height-1)); Canvas.FillRect(Rect(Width-1,Height-1,1,Height-3)); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); Canvas.Font.Color := $00D6E0E0; Canvas.Brush.Color := Col; Canvas.Font.Color := Font.Color; Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); Canvas.Brush.Color := clBlack; Canvas.FrameRect(Rect(0,0,Width,Height)); end; procedure TAOLButton.Click; begin inherited Click; Paint; if Enab then if Assigned(BtnClick) then BtnClick(Self); end; procedure TAOLButton.SetCol(Value: TColor); begin Col := Value; Paint; end; procedure TAOLButton.SetCap(Value: string); begin Cap := value; Paint; end; procedure TAOLButton.SetRaiseCol(Value: TColor); begin RaiseCol := value; Paint; end; procedure TAOLButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var TextWidth, TextHeight : Longint; begin inherited MouseDown(Button, Shift, X, Y); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if (Button = mbLeft) and Enab then begin if Assigned (MDown) then MDown(Self, Button, Shift, X, Y); Canvas.Brush.Color := Color; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); Canvas.Brush.Color := clBlack; Canvas.FillRect(Rect(1,1,Width-1,2)); Canvas.Brush.Color := Col; Canvas.TextOut(Width div 2 - TextWidth div 2+2,Height div 2-TextHeight div 2+2,Cap); Canvas.Brush.Color := clBlack; Canvas.FrameRect(Rect(0,0,Width,Height)); end; end; procedure TAOLButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); if (Button = mbLeft) and Enab then begin if Assigned (MUp) then MUp(Self, Button, Shift, X, Y); if (X>0) and (Y>0) and (X<=Width) and (Y<=Height) then Paint; end; end; procedure TAOLButton.MouseLeave(var Message: TMessage); begin Paint; end; constructor TImageButton.Create(AOwner: TComponent); begin inherited Create(AOwner); MOver := TBitmap.Create; MDown := TBitmap.Create; MUp := TBitmap.Create; Bmp := TBitmap.Create; BmpDAble := TBitmap.Create; ActualBmp := TBitmap.Create; Width := 50; Height := 50; Canvas.Brush.Color := clBtnFace; ShowHint := true; end; Destructor TImageButton.Destroy; begin MOver.Free; MDown.Free; MUp.Free; Bmp.Free; BmpDAble.Free; ActualBmp.Free; inherited; end; procedure TImageButton.Paint; begin inherited Paint; if ActualBmp.Width = 0 then ActualBmp.Assign(Bmp); Canvas.FillRect(Rect(0,0,Width,Height)); if Enabled or (BmpDAble.Width = 0) then Canvas.Draw(0,0,ActualBmp) else begin Width := BmpDAble.Width; Height := BmpDAble.Height; Canvas.Draw(0,0,BmpDAble); end; end; procedure TImageButton.Click; begin inherited Click; Paint; if Enabled then if Assigned(BtnClick) then BtnClick(Self); end; procedure TImageButton.SetMOver(Value: TBitmap); begin MOver.Assign(Value); Paint; end; procedure TImageButton.SetMDown(Value: TBitmap); begin MDown.Assign(Value); Paint; end; procedure TImageButton.SetMUp(Value: TBitmap); begin MUp.Assign(Value); Paint; end; procedure TImageButton.SetBmp(Value: TBitmap); begin Bmp.Assign(Value); ActualBmp.Assign(Value); Width := Bmp.Width; Height := Bmp.Height; Paint; end; procedure TImageButton.SetBmpDAble(Value: TBitmap); begin BmpDAble.Assign(Value); paint; end; procedure TImageButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if (Button = mbLeft) and Enabled then begin if Assigned (OnMDown) then OnMDown(Self, Button, Shift, X, Y); if MDown.Width > 0 then begin ActualBmp.Assign(MDown); Width := MDown.Width; Height := MDown.Height; Paint; end; end; end; procedure TImageButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var MouseOverButton: Boolean; P: TPoint; begin inherited MouseUp(Button, Shift, X, Y); MouseOverButton:=False; if (Button = mbLeft) and Enabled then begin if Assigned (OnMUp) then OnMUp(Self, Button, Shift, X, Y); if MUp.Width > 0 then begin GetCursorPos(P); MouseOverButton := (FindDragTarget(P, True) = Self); if MouseOverButton then begin Width := MUp.Width; Height := MUp.Height; Canvas.FillRect(Rect(0,0,Width,Height)); Canvas.Draw(0,0,MUp); end else begin Width := bmp.Width; Height := Bmp.Height; Canvas.FillRect(Rect(0,0,Width,Height)); Canvas.Draw(0,0,Bmp); end; end else begin if MouseOverButton = false then begin Width := MOver.Width; Height := MOver.Height; Canvas.FillRect(Rect(0,0,Width,Height)); Canvas.Draw(0,0,MOver); end else begin Width := bmp.Width; Height := Bmp.Height; Canvas.FillRect(Rect(0,0,Width,Height)); Canvas.Draw(0,0,Bmp); end; end; end; end; procedure TImageButton.MouseEnter(var Message: TMessage); begin if Enabled then begin if MOver.Width > 0 then begin ActualBmp.Assign(MOver); Width := MOver.Width; Height := MOver.Height; Paint; end; end; end; procedure TImageButton.MouseLeave(var Message: TMessage); begin if Enabled then begin if Bmp.Width > 0 then begin ActualBmp.Assign(Bmp); Width := Bmp.Width; Height := Bmp.Height; Paint; end; end; end; constructor TSelButton.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 105; Height := 20; Col := clBtnFace; OverFColor := clBlack; OverColor := $00A4B984; DownColor := $00A4B984; Canvas.Brush.Color := clBlack; Border := clGray; Font.Name := 'Arial'; Font.Color := clGray; Font.Size := 8; Enab := true; ShowHint := true; Alment := taLeftJustify; BWidth := 1; end; procedure TSelButton.SetParent(Value: TWinControl); begin inherited; if Value <> nil then Cap := Name; end; procedure TSelButton.Paint; var TextWidth, TextHeight : Longint; i: Longint; begin inherited Paint; Canvas.Font := Font; Canvas.Brush.Color := Col; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); Canvas.Font.Color := $00D6E0E0; Canvas.Font.Color := Font.Color; if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); if Alment = taLeftJustify then Canvas.TextOut(5,Height div 2-TextHeight div 2,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 6,Height div 2-TextHeight div 2,Cap); Canvas.Brush.Color := Border; for i := 0 to BWidth-1 do Canvas.FrameRect(Rect(i,i,Width-i,Height-i)); end; procedure TSelButton.Click; begin inherited Click; Paint; if Enab then if Assigned(BtnClick) then BtnClick(Self); end; procedure TSelButton.SetCol(Value: TColor); begin Col := Value; Paint; end; procedure TSelButton.SetBorder(Value: TColor); begin Border := Value; Paint; end; procedure TSelButton.SetCap(Value: string); begin Cap := value; Paint; end; procedure TSelButton.SetAlment(Value: TAlignment); begin Alment := Value; Paint; end; procedure TSelButton.SetBWidth(Value: Longint); begin BWidth := value; Paint; end; procedure TSelButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var TextWidth, TextHeight : Longint; i: Longint; begin inherited MouseDown(Button, Shift, X, Y); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if (Button = mbLeft) and Enab then begin if Assigned (MDown) then MDown(Self, Button, Shift, X, Y); Canvas.Brush.Color := DownColor; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2+1,Height div 2-TextHeight div 2+1,Cap); if Alment = taLeftJustify then Canvas.TextOut(5+1,Height div 2-TextHeight div 2+1,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 6-1,Height div 2-TextHeight div 2+1,Cap); Canvas.Brush.Color := Border; for i := 0 to BWidth-1 do Canvas.FrameRect(Rect(i,i,Width-i,Height-i)); end; end; procedure TSelButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var TextWidth, TextHeight : Longint; i: Longint; MouseOverButton: Boolean; P: TPoint; begin inherited MouseUp(Button, Shift, X, Y); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if (Button = mbLeft) and Enab then begin if Assigned (MUp) then MUp(Self, Button, Shift, X, Y); GetCursorPos(P); MouseOverButton := (FindDragTarget(P, True) = Self); if MouseOverButton then begin Canvas.Brush.Color := OverColor; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); Canvas.Font.Color := OverFColor; if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); if Alment = taLeftJustify then Canvas.TextOut(5,Height div 2-TextHeight div 2,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 6,Height div 2-TextHeight div 2,Cap); Canvas.Brush.Color := Border; for i := 0 to BWidth-1 do Canvas.FrameRect(Rect(i,i,Width-i,Height-i)); end; end; end; procedure TSelButton.MouseEnter(var Message: TMessage); var TextWidth, TextHeight : Integer; i: Longint; begin TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if Enab then begin Canvas.Brush.Color := OverColor; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); Canvas.Font.Color := OverFColor; if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); if Alment = taLeftJustify then Canvas.TextOut(5,Height div 2-TextHeight div 2,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 6,Height div 2-TextHeight div 2,Cap); Canvas.Brush.Color := Border; for i := 0 to BWidth-1 do Canvas.FrameRect(Rect(i,i,Width-i,Height-i)); end; end; procedure TSelButton.MouseLeave(var Message: TMessage); var TextWidth, TextHeight : Integer; i: integer; begin TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); Canvas.Brush.Color := Col; Canvas.FillRect(Rect(1,1,Width-1,Height-1)); Canvas.Font.Color := $00D6E0E0; Canvas.Brush.Color := Col; Canvas.Font.Color := Font.Color; if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2,Cap); if Alment = taLeftJustify then Canvas.TextOut(5,Height div 2-TextHeight div 2,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 6,Height div 2-TextHeight div 2,Cap); Canvas.Brush.Color := Border; for i := 0 to BWidth-1 do Canvas.FrameRect(Rect(i,i,Width-i,Height-i)); end; constructor TSquareButton.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 113; Height := 17; Col := clBtnFace; OverFColor := clWhite; Canvas.Brush.Color := clBlack; Border := clBlack; Font.Name := 'Arial'; Font.Color := clBlack; Font.Size := 8; Enab := true; ShowHint := true; Alment := taLeftJustify; OverBorderCol := clBlack; BWidth := 2; DownBorderCol := clWhite; end; procedure TSquareButton.SetParent(Value: TWinControl); begin inherited; if Value <> nil then Cap := Name; end; procedure TSquareButton.Paint; var TextWidth, TextHeight : Longint; begin inherited Paint; Canvas.Font := Font; Canvas.Brush.Color := Col; Canvas.FillRect(Rect(0,0,Width,Height)); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); Canvas.Font.Color := $00D6E0E0; Canvas.Font.Color := Font.Color; if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2-1,Cap); if Alment = taLeftJustify then Canvas.TextOut(6,Height div 2-TextHeight div 2-1,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 7,Height div 2-TextHeight div 2-1,Cap); Canvas.Brush.Color := Border; Canvas.FillRect(Rect(0,Height,Width,Height-BWidth)); Canvas.FillRect(Rect(0,0,BWidth,Height)); end; procedure TSquareButton.Click; begin inherited Click; Paint; if Enab then if Assigned(BtnClick) then BtnClick(Self); end; procedure TSquareButton.SetCol(Value: TColor); begin Col := Value; Paint; end; procedure TSquareButton.SetBorder(Value: TColor); begin Border := Value; Paint; end; procedure TSquareButton.SetCap(Value: string); begin Cap := value; Paint; end; procedure TSquareButton.SetAlment(Value: TAlignment); begin Alment := Value; Paint; end; procedure TSquareButton.SetBWidth(Value: Longint); begin BWidth := Value; Paint; end; procedure TSquareButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var TextWidth, TextHeight : Longint; begin inherited MouseDown(Button, Shift, X, Y); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if (Button = mbLeft) and Enab then begin if Assigned (MDown) then MDown(Self, Button, Shift, X, Y); Canvas.Brush.Color := Col; Canvas.FillRect(Rect(0,0,Width,Height)); if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2-1,Cap); if Alment = taLeftJustify then Canvas.TextOut(6,Height div 2-TextHeight div 2-1,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 7,Height div 2-TextHeight div 2-1,Cap); Canvas.Brush.Color := DownBorderCol; Canvas.FillRect(Rect(0,Height,Width,Height-BWidth)); Canvas.FillRect(Rect(0,0,BWidth,Height)); end; end; procedure TSquareButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var TextWidth, TextHeight : Longint; P: TPoint; MouseOverButton: Boolean; begin inherited MouseUp(Button, Shift, X, Y); TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); if (Button = mbLeft) and Enab then begin if Assigned (MUp) then MUp(Self, Button, Shift, X, Y); GetCursorPos(P); MouseOverButton := (FindDragTarget(P, True) = Self); if MouseOverButton then begin Canvas.Brush.Color := Col; Canvas.FillRect(Rect(0,0,Width,Height)); Canvas.Font.Color := OverFColor; if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2-1,Cap); if Alment = taLeftJustify then Canvas.TextOut(6,Height div 2-TextHeight div 2-1,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 7,Height div 2-TextHeight div 2-1,Cap); Canvas.Brush.Color := OverBorderCol; Canvas.FillRect(Rect(0,Height,Width,Height-BWidth)); Canvas.FillRect(Rect(0,0,BWidth,Height)); end; end; end; procedure TSquareButton.MouseEnter(var Message: TMessage); var TextWidth, TextHeight : Longint; begin if Enab then begin TextWidth := Canvas.TextWidth(Cap); TextHeight := Canvas.TextHeight(Cap); Canvas.Brush.Color := Col; Canvas.FillRect(Rect(0,0,Width,Height)); Canvas.Font.Color := OverFColor; if Alment = taCenter then Canvas.TextOut(Width div 2 - TextWidth div 2,Height div 2-TextHeight div 2-1,Cap); if Alment = taLeftJustify then Canvas.TextOut(6,Height div 2-TextHeight div 2-1,Cap); if Alment = taRightJustify then Canvas.TextOut(Width - TextWidth - 7,Height div 2-TextHeight div 2-1,Cap); Canvas.Brush.Color := OverBorderCol; Canvas.FillRect(Rect(0,Height,Width,Height-BWidth)); Canvas.FillRect(Rect(0,0,BWidth,Height)); end; end; procedure TSquareButton.MouseLeave(var Message: TMessage); begin Paint; end; end.
// ---------------------------------------------------------------------------- // Unit : PxNeuralNetwork.pas - a part of PxLib // Author : Matthias Hryniszak (based on NeuralNetwork.pas by // Maciej Lubiński) // Date : 2003-xx-xx // Version : 1.0 // Description : Neural network implementation // Changes log : 2003-xx-xx - initial version // 2005-06-15 - imported to PxLib // ToDo : Testing. // ---------------------------------------------------------------------------- unit PxNeuralNetwork; {$I PxDefines.inc} interface uses Classes, SysUtils, Math; const NET_FILE_ID: Integer = $0987ABCD; // ID pliku sieci type TPxNeuralNetwork = class; TPxNNLayer = class; TPxNNBaseObject = class (TObject) protected Network: TPxNeuralNetwork; public constructor Create(ANetwork: TPxNeuralNetwork); virtual; end; { klasa wagi wejscia do komórki } TPxNNWeight = class (TPxNNBaseObject) Weight : Double; constructor Create(ANetwork: TPxNeuralNetwork); override; procedure Init; end; { komorka sieci } TPxNNCell = class (TPxNNBaseObject) protected { aktywacja komórki } Activity: Double; { wyjscie komorki } Output: Double; public constructor Create(ANetwork: TPxNeuralNetwork); override; { wyliczenie aktywacji i wyjscia komorki } procedure Evaluate; virtual; abstract; { odczyt danych komorki ze strumienia } procedure LoadFromStream(S: TStream); virtual; abstract; { zapis danych komorki do strumienia } procedure SaveToStream(S: TStream); virtual; abstract; end; { komorka warstwy wejsciowej } TPxNNInputCell = class (TPxNNCell) protected MinInput: Double; Scale: Double; { normalizacja wejscia } function Normalize(Value: Double): Double; public constructor Create(ANetwork: TPxNeuralNetwork); override; { wyliczenie aktywacji i wyjscia komorki } procedure Evaluate; override; { ustawienie wejscia } procedure SetInput(Input: Double); { ustawienie wartosci minimalnej i maksymalnej wejsc } procedure SetMinMaxInput(Min, Max: Double); { odczyt danych komorki ze strumienia } procedure LoadFromStream(S: TStream); override; { zapis danych komorki do strumienia } procedure SaveToStream(S: TStream); override; end; { komorka sieci (do propagacji wstecznej bledu) } TPxNNBackPCell = class (TPxNNCell) private { poprzednia warstwa komorek } FPreviousLayer : TPxNNLayer; protected { blad komorki } Delta: Double; { wagi dochodzące do komórki } Weights: TList; OldWeights: TList; { funkcja aktywacji komorki } function ActivityFunction(AActivity: Double): Double; { wyliczenie bledu komorki } procedure EvaluateDelta; virtual; abstract; public constructor Create(ANetwork: TPxNeuralNetwork; WeightCount: Integer); reintroduce; destructor Destroy; override; { propagacja bledu } procedure BackPropagate; { wyliczenie aktywacji i wyjscia komorki } procedure Evaluate; override; { ustawienie poprzedniej warstwy } procedure SetPreviousLayer(PreviousLayer: TPxNNLayer); { odczyt danych komorki ze strumienia } procedure LoadFromStream(S: TStream); override; { zapis danych komorki do strumienia } procedure SaveToStream(S: TStream); override; end; { komorka warstwy ukrytej } TPxNNHideCell = class (TPxNNBackPCell) private { nastepna warstwa sieci } FNextLayer: TPxNNLayer; { indeks komorki w warstwie } FMyIndex: Integer; public constructor Create(ANetwork: TPxNeuralNetwork; WeightCount, Index: Integer); reintroduce; { wyliczenie bledu komorki } procedure EvaluateDelta; override; { ustawienie nastepnej warstwy } procedure SetNextLayer(NextLayer: TPxNNLayer); { odczyt danych komorki ze strumienia } procedure LoadFromStream(S: TStream); override; { zapis danych komorki do strumienia } procedure SaveToStream(S: TStream); override; end; { komorka warstwy wyjsciowej } TPxNNOutputCell = class (TPxNNBackPCell) protected MinOutput: Double; Scale: Double; { oczekiwana wartosc wyjscia i wyjscie po skalowaniu } ExpectOutput: Double; { wyliczenie bledu komorki } procedure EvaluateDelta; override; public constructor Create(ANetwork: TPxNeuralNetwork; WeightCount: Integer); reintroduce; { blad kwadratowy komorki } function GetDeviation: Double; { Wyjscie Skalowane } function GetOutput: Double; { ustawienie wartosci oczekiwanego wyjscia } procedure SetExpectOutput(Output: Double); { ustawienie min i max wartosci wyjscia } procedure SetMinMaxOutput(Min, Max: Double); { odczyt danych komorki ze strumienia } procedure LoadFromStream(S: TStream); override; { zapis danych komorki do strumienia } procedure SaveToStream(S: TStream); override; end; { warstwa komorek } TPxNNLayer = class (TPxNNBaseObject) protected function CreateEmptyCell: TPxNNCell; virtual; abstract; public { komorki w warstwie } Cells: TList; constructor Create(ANetwork: TPxNeuralNetwork); override; destructor Destroy; override; { wyliczenie aktywacji i wyjscia komorek w warstwie } procedure Evaluate; { odczyt danych warstwy ze strumienia } procedure LoadFromStream(S: TStream); virtual; { zapis danych warstwy do strumienia } procedure SaveToStream(S: TStream); virtual; end; { warstwa wejsciowa } TPxNNInputLayer = class (TPxNNLayer) protected function CreateEmptyCell: TPxNNCell; override; public constructor Create(ANetwork: TPxNeuralNetwork; CellsCount: Integer); reintroduce; { ustawienie wejscia o indeksie } procedure SetInputs(Inputs: array of Double); { ustawienie min i max wartosci wejscia komorce index } procedure SetMinMaxInputAt(Index: Integer; Min, Max: Double); end; { warstwa sieci (do propagacji wstecznej bledu) } TPxNNBackPLayer = class (TPxNNLayer) { wsteczna propagacja bledu } procedure BackPropagate; { ustawienie poprzedniej warstwy } procedure SetPreviousLayer(APreviousLayer: TPxNNLayer); end; { warstwa komorek ukrytych } TPxNNHideLayer = class (TPxNNBackPLayer) protected function CreateEmptyCell: TPxNNCell; override; public constructor Create(ANetwork: TPxNeuralNetwork; CellsCount, WeightCount: Integer); reintroduce; { ustawienie nastepnej warstwy } procedure SetNextLayer(ANextLayer: TPxNNLayer); end; { warstwa komorek ukrytych } TPxNNOutputLayer = class (TPxNNBackPLayer) protected function CreateEmptyCell: TPxNNCell; override; public constructor Create(ANetwork: TPxNeuralNetwork; CellsCount, WeightsCount: Integer); reintroduce; { blad kwadratowy wyjscia } function GetDeviation: Double; { wyjscie warstwy } function GetOutput(Index: Integer): Double; { ustawienie wyjsc } procedure SetOutputs(Outputs: array of Double); { ustawienie min i max wartosci wyjscia komorki z warstwy } procedure SetMinMaxOutputAt(Index: Integer; Min, Max: Double); end; { Siec neuronowa } TPxNeuralNetwork = class (TObject) private FLayers: TList; FNi: Double; FAlpha: Double; function GetDeviation: Double; virtual; function GetOutput(Index: Integer): Double; public constructor Create(CountIn: Integer; HiddenLayers: array of Integer; CountOut: Integer); destructor Destroy; override; { wsteczna propagacja bledu } procedure BackPropagate; { obliczenie aktywacji komorek w warstwach } procedure Evaluate; { ustawienie min i max wartosci wejscia komorce index z warstwy wejsciowej } procedure SetMinMaxInputAt(Index: Integer; Min, Max: Double); { ustawienie min i max wartosci wyjscia komorki index z warstwy wyjsciowej } procedure SetMinMaxOutputAt(Index: Integer; Min, Max: Double); { ustawienie wejsc } procedure SetInputs(Inputs: array of Double); { ustawienie wyjsc } procedure SetOutputs(Outputs: array of Double); { obsluga zapisu i odczytu z pliku } procedure LoadFromFile(FileName: String); procedure SaveToFile(FileName: String); { blad sieci } property Deviation: Double read GetDeviation; { wyjscie sieci } property Output[Index: Integer]: Double read GetOutput; { wspolczynniki uczenia sie sieci } property Alpha: Double read FAlpha write FAlpha; property Ni: Double read FNi write FNi; end; implementation const // OUT_MRG = 0.0; // IN_MRG = 0.05; IN_MRG = 0.025; OUT_MRG = 0.05; { TPxNNWeight } constructor TPxNNWeight.Create(ANetwork: TPxNeuralNetwork); begin inherited Create(ANetwork); Weight := 0.0; end; procedure TPxNNWeight.Init; const Gen = 19423; begin Weight := Random(Gen) / Gen - 0.5; Weight := -Weight; end; { TPxNNBaseObject } constructor TPxNNBaseObject.Create(ANetwork: TPxNeuralNetwork); begin inherited Create; Network := ANetwork; end; { TPxNNCell } constructor TPxNNCell.Create(ANetwork: TPxNeuralNetwork); begin inherited Create(ANetwork); Activity := 0.5 - Random; end; { TPxNNInputCell } { Protected declarations } function TPxNNInputCell.Normalize(Value: Double): Double; begin Result := (Value - MinInput) * Scale; end; { Public declarations } constructor TPxNNInputCell.Create(ANetwork: TPxNeuralNetwork); begin inherited Create(ANetwork); MinInput := 0.0; Scale := 1.0; end; procedure TPxNNInputCell.Evaluate; begin Output := Normalize(Activity); end; procedure TPxNNInputCell.SetInput(Input: Double); begin Activity := Input; end; procedure TPxNNInputCell.SetMinMaxInput(Min, Max: Double); begin MinInput := Min - IN_MRG * (Max - Min); Scale := 1.0 / ((1.0 + 2 * IN_MRG) * (Max - Min)); end; procedure TPxNNInputCell.LoadFromStream(S: TStream); begin S.Read(MinInput, SizeOf(MinInput)); S.Read(Scale, SizeOf(Scale)); end; procedure TPxNNInputCell.SaveToStream(S: TStream); begin S.Write(MinInput, SizeOf(MinInput)); S.Write(Scale, SizeOf(Scale)); end; { TPxNNBackPCell } { Protected declarations } function TPxNNBackPCell.ActivityFunction(AActivity: Double): Double; begin Result := 1.0 / (1.0 + Exp(-AActivity)); end; { Public declarations } constructor TPxNNBackPCell.Create(ANetwork: TPxNeuralNetwork; WeightCount: Integer); var I: Integer; AWeight, OldWeight: TPxNNWeight; begin inherited Create(ANetwork); FPreviousLayer := nil; Delta := 0.0; Weights := TList.Create; OldWeights := TList.Create; for I := 0 to WeightCount do begin AWeight := TPxNNWeight.Create(Network); AWeight.Init; OldWeight := TPxNNWeight.Create(Network); OldWeight.Weight := AWeight.Weight; Weights.Add(AWeight); OldWeights.Add(OldWeight); end; end; destructor TPxNNBackPCell.Destroy; var I: Integer; begin for I := 0 to OldWeights.Count - 1 do TObject(OldWeights[I]).Free; OldWeights.Free; for I := 0 to Weights.Count - 1 do TObject(Weights[I]).Free; Weights.Free; inherited Destroy; end; procedure TPxNNBackPCell.BackPropagate; var I: Integer; D, T: Double; begin EvaluateDelta; for I := 0 to FPreviousLayer.Cells.Count - 1 do begin T := Network.Alpha * (TPxNNWeight(Weights[I]).Weight - TPxNNWeight(OldWeights[I]).Weight); TPxNNWeight(OldWeights[i]).Weight := TPxNNWeight(Weights[I]).Weight; D := Network.Ni * Delta * TPxNNCell(FPreviousLayer.Cells[I]).Output; TPxNNWeight(Weights[I]).Weight := TPxNNWeight(Weights[I]).Weight + D + T; end; I := Weights.Count - 1; T := Network.Alpha * (TPxNNWeight(Weights[I]).Weight - TPxNNWeight(OldWeights[I]).Weight); TPxNNWeight(OldWeights[I]).Weight := TPxNNWeight(Weights[I]).Weight; D := Network.Ni * Delta; TPxNNWeight(Weights[I]).Weight := TPxNNWeight(Weights[I]).Weight + D + T; end; procedure TPxNNBackPCell.Evaluate; var I: Integer; begin I := FPreviousLayer.Cells.Count; Activity := TPxNNWeight(Weights[I]).Weight; for I := I - 1 downto 0 do Activity := Activity + TPxNNWeight(Weights[I]).Weight * TPxNNCell(FPreviousLayer.Cells[I]).Output; Output := ActivityFunction(Activity); end; procedure TPxNNBackPCell.SetPreviousLayer(PreviousLayer: TPxNNLayer); begin FPreviousLayer := PreviousLayer; end; procedure TPxNNBackPCell.LoadFromStream(S: TStream); var WeightsCount, I: Integer; AWeight, OldWeight: TPxNNWeight; begin FPreviousLayer := nil; Delta := 0.0; Weights.Clear; OldWeights.Clear; S.Read(WeightsCount, Sizeof(WeightsCount)); for I := 0 to WeightsCount - 1 do begin AWeight := TPxNNWeight.Create(Network); S.Read(AWeight.Weight, SizeOf(AWeight.Weight)); OldWeight := TPxNNWeight.Create(Network); OldWeight.Weight := AWeight.Weight; Weights.Add(AWeight); OldWeights.Add(OldWeight); end; end; procedure TPxNNBackPCell.SaveToStream(S: TStream); var WeightsCount: Integer; I : Integer; begin WeightsCount := Weights.Count; S.Write(WeightsCount, Sizeof(WeightsCount)); for I := 0 to WeightsCount - 1 do S.Write(TPxNNWeight(Weights[I]).Weight, SizeOf(TPxNNWeight(Weights[I]).Weight)); end; { TPxNNHideCell } constructor TPxNNHideCell.Create(ANetwork: TPxNeuralNetwork; WeightCount, Index: Integer); begin inherited Create(ANetwork, WeightCount); FMyIndex := Index; end; procedure TPxNNHideCell.EvaluateDelta; var I: Integer; BackPCell: TPxNNBackPCell; begin Delta := 0; for I := 0 to FNextLayer.Cells.Count - 1 do begin BackPCell := TPxNNBackPCell(FNextLayer.Cells[I]); Delta := Delta + BackPCell.Delta * // TPxNNWeight(BackPCell.Weights[MyIndex]).Weight; TPxNNWeight(BackPCell.OldWeights[FMyIndex]).Weight; end; Delta := Delta * Output * (1 - Output); end; procedure TPxNNHideCell.SetNextLayer(NextLayer: TPxNNLayer); begin FNextLayer := NextLayer; end; procedure TPxNNHideCell.LoadFromStream(S: TStream); begin FNextLayer := nil; S.Read(FMyIndex, SizeOf(FMyIndex)); inherited LoadFromStream(S); end; procedure TPxNNHideCell.SaveToStream(S: TStream); begin S.Write(FMyIndex, SizeOf(FMyIndex)); inherited SaveToStream(S); end; { TPxNNOutputCell } { Protected declarations } procedure TPxNNOutputCell.EvaluateDelta; begin Delta := (ExpectOutput - Output) * (1 - Output) * Output; end; { Public declarations } constructor TPxNNOutputCell.Create(ANetwork: TPxNeuralNetwork; WeightCount: Integer); begin inherited Create(ANetwork, WeightCount); MinOutput := 0; Scale := 1; end; function TPxNNOutputCell.GetDeviation: Double; begin Result := (Output - ExpectOutput) * (Output - ExpectOutput); end; function TPxNNOutputCell.GetOutput: Double; begin // Result := Output / 10 + 1.0;//Ln( Output / (1.0 - Output) ); Result := (Output / Scale) + MinOutput; end; procedure TPxNNOutputCell.SetExpectOutput(Output: Double); begin ExpectOutput := (Output - MinOutput) * Scale; // (Outputa - 1) * 10; //ActivityFunction(Output); end; procedure TPxNNOutputCell.SetMinMaxOutput(Min, Max: Double); begin MinOutput := Min - OUT_MRG * (Max - Min); Scale := 1 / ((1 + 2 * OUT_MRG) * (Max - Min)); end; procedure TPxNNOutputCell.LoadFromStream(S: TStream); begin inherited LoadFromStream(S); S.Read(MinOutput, SizeOf(MinOutput)); S.Read(Scale, SizeOf(Scale)); ExpectOutput := 0; end; procedure TPxNNOutputCell.SaveToStream(S: TStream); begin inherited SaveToStream(S); S.Write(MinOutput, SizeOf(MinOutput)); S.Write(Scale, SizeOf(Scale)); end; { TPxNNLayer } constructor TPxNNLayer.Create(ANetwork: TPxNeuralNetwork); begin inherited Create(ANetwork); Cells := TList.Create; end; destructor TPxNNLayer.Destroy; var I: Integer; begin for I := 0 to Cells.Count - 1 do TObject(Cells[I]).Free; Cells.Free; inherited Destroy end; procedure TPxNNLayer.Evaluate; var I: Integer; begin for I := 0 to Cells.Count - 1 do TPxNNCell(Cells[I]).Evaluate; end; procedure TPxNNLayer.LoadFromStream(S: TStream); var CellsCount, I: Integer; Cell: TPxNNCell; begin Cells.Clear; S.Read(CellsCount, SizeOf(CellsCount)); for I := 0 to CellsCount - 1 do begin Cell := CreateEmptyCell; Cell.LoadFromStream(S); Cells.Add(Cell); end; end; procedure TPxNNLayer.SaveToStream(S: TStream); var CellsCount, I: Integer; begin CellsCount := Cells.Count; S.Write(CellsCount, SizeOf(CellsCount)); for I := 0 to CellsCount - 1 do TPxNNCell(Cells[I]).SaveToStream(S); end; { TPxNNInputLayer } { Protected declarations } function TPxNNInputLayer.CreateEmptyCell: TPxNNCell; begin Result := TPxNNInputCell.Create(Network); end; { Public declarations } constructor TPxNNInputLayer.Create(ANetwork: TPxNeuralNetwork; CellsCount: Integer); var I: Integer; begin inherited Create(ANetwork); for I := 1 to CellsCount do Cells.Add(TPxNNInputCell.Create(Network)); end; procedure TPxNNInputLayer.SetInputs(Inputs: array of Double); var I: Integer; begin for I := 0 to Length(Inputs) - 1 do TPxNNInputCell(Cells[I]).SetInput(Inputs[I]); end; procedure TPxNNInputLayer.SetMinMaxInputAt(Index: Integer; Min, Max: Double); begin TPxNNInputCell(Cells[Index]).SetMinMaxInput(Min, Max); end; { TPxNNBackPLayer } procedure TPxNNBackPLayer.BackPropagate; var I: Integer; begin for I := 0 to Cells.Count - 1 do TPxNNBackPCell(Cells[I]).BackPropagate; end; procedure TPxNNBackPLayer.SetPreviousLayer(APreviousLayer: TPxNNLayer); var I: Integer; begin for I := 0 to Cells.Count - 1 do TPxNNBackPCell(Cells[I]).SetPreviousLayer(APreviousLayer); end; { TPxNNHideLayer } { Protected declarations } function TPxNNHideLayer.CreateEmptyCell: TPxNNCell; begin Result := TPxNNHideCell.Create(Network, 0, 0); end; { Public declarations } constructor TPxNNHideLayer.Create(ANetwork: TPxNeuralNetwork; CellsCount, WeightCount: Integer); var I: Integer; begin inherited Create(ANetwork); for I := 0 to CellsCount - 1 do Cells.Add(TPxNNHideCell.Create(Network, WeightCount, I)); end; procedure TPxNNHideLayer.SetNextLayer(ANextLayer: TPxNNLayer); var I: Integer; begin for I := 0 to Cells.Count - 1 do TPxNNHideCell(Cells[I]).SetNextLayer(ANextLayer); end; { TPxNNOutputLayer } { Protected declarations } function TPxNNOutputLayer.CreateEmptyCell: TPxNNCell; begin Result := TPxNNOutputCell.Create(Network, 0); end; { Public declarations } constructor TPxNNOutputLayer.Create(ANetwork: TPxNeuralNetwork; CellsCount, WeightsCount: Integer); var I: Integer; begin inherited Create(ANetwork); for I := 1 to CellsCount do Cells.Add(TPxNNOutputCell.Create(Network, WeightsCount)); end; function TPxNNOutputLayer.GetDeviation: Double; var I: Integer; begin Result := 0; for I := 0 to Cells.Count - 1 do Result := Result + TPxNNOutputCell(Cells[I]).GetDeviation; end; function TPxNNOutputLayer.GetOutput(Index: Integer): Double; begin Result := TPxNNOutputCell(Cells[Index]).GetOutput; end; procedure TPxNNOutputLayer.SetOutputs(Outputs: array of Double); var I: Integer; begin for I := 0 to Length(Outputs) - 1 do TPxNNOutputCell(Cells[I]).SetExpectOutput(Outputs[I]); end; procedure TPxNNOutputLayer.SetMinMaxOutputAt(Index: Integer; Min, Max: Double); begin TPxNNOutputCell(Cells[Index]).SetMinMaxOutput(Min, Max); end; { TPxNeuralNetwork } { Private declarations } function TPxNeuralNetwork.GetDeviation: Double; begin Result := 0.5 * TPxNNOutputLayer(FLayers[FLayers.Count - 1]).GetDeviation; end; function TPxNeuralNetwork.GetOutput(Index: Integer): Double; begin Result := TPxNNOutputLayer(FLayers[FLayers.Count - 1]).GetOutput(Index); end; { Public declarations } constructor TPxNeuralNetwork.Create(CountIn: Integer; HiddenLayers: array of Integer; CountOut: Integer); var I: Integer; begin inherited Create; { ustalenie domyslnych wspolczynnikow uczenia } FNi := 0.3; FAlpha := 0.7; Randomize; FLayers := TList.Create; { Warstwa wejsciowa } FLayers.Add(TPxNNInputLayer.Create(Self, CountIn)); // { Pierwsza warstwa ukryta } { warstwy ukryte } for I := 0 to Length(HiddenLayers) - 1 do begin if I = 0 then begin FLayers.Add(TPxNNHideLayer.Create(Self, HiddenLayers[I], CountIn)); TPxNNBackPLayer(FLayers[I + 1]).SetPreviousLayer(TPxNNLayer(FLayers[I])); end else begin FLayers.Add(TPxNNHideLayer.Create(Self, HiddenLayers[I], HiddenLayers[I - 1])); TPxNNBackPLayer(FLayers[I + 1]).SetPreviousLayer(TPxNNLayer(FLayers[I])); TPxNNHideLayer(FLayers[I]).SetNextLayer(TPxNNLayer(FLayers[I + 1])); end; end; (* FLayers.Add(TPxNNHideLayer.Create(Self, CountHidden1, CountIn)); TPxNNBackPLayer(FLayers[1]).SetPreviousLayer(TPxNNLayer(FLayers[0])); { Druga warstwa ukryta } FLayers.Add(TPxNNHideLayer.Create(Self, CountHidden2, CountHidden1)); TPxNNBackPLayer(FLayers[2]).SetPreviousLayer(TPxNNLayer(FLayers[1])); TPxNNHideLayer(FLayers[1]).SetNextLayer(TPxNNLayer(FLayers[2])); *) { Warstwa wyjsciowa } FLayers.Add(TPxNNOutputLayer.Create(Self, CountOut, HiddenLayers[Length(HiddenLayers) - 1])); TPxNNBackPLayer(FLayers[FLayers.Count - 1]).SetPreviousLayer(TPxNNLayer(FLayers[FLayers.Count - 2])); TPxNNHideLayer(FLayers[FLayers.Count - 2]).SetNextLayer(TPxNNLayer(FLayers[FLayers.Count - 1])); end; destructor TPxNeuralNetwork.Destroy; var I: Integer; begin for I := 0 to FLayers.Count - 1 do TObject(FLayers[I]).Free; FLayers.Free; inherited Destroy; end; procedure TPxNeuralNetwork.BackPropagate; var I: Integer; begin Evaluate; for I := FLayers.Count - 1 downto 1 do TPxNNBackPLayer(FLayers[I]).BackPropagate; end; procedure TPxNeuralNetwork.Evaluate; var I: Integer; begin for I := 0 to FLayers.Count - 1 do TPxNNLayer(FLayers[I]).Evaluate; end; procedure TPxNeuralNetwork.SetMinMaxInputAt(Index: Integer; Min, Max: Double); begin TPxNNInputLayer(FLayers[0]).SetMinMaxInputAt(Index, Min, Max); end; procedure TPxNeuralNetwork.SetMinMaxOutputAt(Index: Integer; Min, Max: Double); begin TPxNNOutputLayer(FLayers[FLayers.Count - 1]).SetMinMaxOutputAt(Index, Min, Max); end; procedure TPxNeuralNetwork.SetInputs(Inputs: array of Double); begin TPxNNInputLayer(FLayers[0]).SetInputs(Inputs); end; procedure TPxNeuralNetwork.SetOutputs(Outputs: array of Double); begin TPxNNOutputLayer(FLayers[FLayers.Count - 1]).SetOutputs(Outputs); end; procedure TPxNeuralNetwork.LoadFromFile(FileName: String); var NeuronFile: TFileStream; LayersCount, I, ID: Integer; Layer: TPxNNLayer; begin NeuronFile := TFileStream.Create(FileName, fmOpenRead ); NeuronFile.Read(ID, SizeOf(ID)); if ID = NET_FILE_ID then begin FLayers.Clear; NeuronFile.Read(LayersCount, SizeOf(LayersCount)); { warstwa wejsciowa } Layer := TPxNNInputLayer.Create(Self, 0); Layer.LoadFromStream(NeuronFile); FLayers.Add(Layer); { warstwy ukryte } for I := 1 to LayersCount - 2 do begin Layer := TPxNNHideLayer.Create(Self, 0, 0); Layer.LoadFromStream(NeuronFile); FLayers.Add(Layer); end; { warstwa wyjsciowa } Layer := TPxNNOutputLayer.Create(Self, 0, 0); Layer.LoadFromStream(NeuronFile); FLayers.Add(Layer); for I := 1 to LayersCount - 2 do begin TPxNNHideLayer(FLayers[I]).SetPreviousLayer(TPxNNLayer(FLayers[I - 1])); TPxNNHideLayer(FLayers[I]).SetNextLayer(TPxNNLayer(FLayers[I + 1])); end; TPxNNOutputLayer(FLayers[LayersCount - 1]).SetPreviousLayer(TPxNNLayer(FLayers[LayersCount - 2])); end; NeuronFile.Free; end; procedure TPxNeuralNetwork.SaveToFile(FileName: String); var NeuronFile: TFileStream; LayersCount, I: Integer; begin NeuronFile := TFileStream.Create(FileName, fmCreate); NeuronFile.Write(NET_FILE_ID, SizeOf(NET_FILE_ID)); LayersCount := FLayers.Count; NeuronFile.Write(LayersCount, SizeOf(LayersCount)); for I := 0 to LayersCount - 1 do TPxNNLayer(FLayers[I]).SaveToStream(NeuronFile); NeuronFile.Free; end; end.
unit orm.lazyload; interface uses System.SysUtils, System.Variants, System.Generics.Collections, System.Rtti, System.TypInfo; type TLazyLoad<T : Class> = Class private FLoad : Boolean; FKey : Variant; FWhere : String; FOrder : String; FIsNull : Boolean; FValue : T; FValueAll : TObjectList<T>; function GetIsNull : Boolean; procedure SetWhere(Value : String); procedure SetKey(Value : Variant); protected FField : String; public Destructor Destroy; Override; function Value : T; function ValueAll : TObjectList<T>; function GetObject : TObject; property Field : String Read FField; property Key : Variant Read FKey Write SetKey; property Where : String Read FWhere Write SetWhere; property Order : String Read FOrder Write FOrder; property IsNull : Boolean Read GetIsNull Write FIsNull; end; implementation uses orm.Attributes.Objects, orm.Objects.Utils, orm.Session, orm.Where, sql.utils; { TLazyLoad<T> } destructor TLazyLoad<T>.Destroy; begin If Assigned(FValue) Then FreeAndNil(FValue); If Assigned(FValueAll) Then Begin FValueAll.OnNotify := nil; FreeAndNil(FValueAll); End; inherited; end; function TLazyLoad<T>.GetObject: TObject; begin Result := FValue; If not Assigned(Result) Then Result := FValueAll; end; procedure TLazyLoad<T>.SetKey(Value: Variant); begin If (Key <> Value) Then FLoad := False; FKey := Value; end; procedure TLazyLoad<T>.SetWhere(Value: String); begin If (Value <> FWhere) Then FLoad := False; FWhere := Value; end; function TLazyLoad<T>.GetIsNull: Boolean; begin Result := FIsNull; If not FIsNull Then Result := (not Assigned(FValueAll)) And (not Assigned(FValue)); end; function TLazyLoad<T>.Value : T; var V : T; C : TClass; begin If FIsNull Then Exit(nil) Else If FLoad And Assigned(FValue) Then Exit(FValue); C := T; V := nil; Try If not FWhere.IsEmpty Then Begin If (not Field.IsEmpty) And (not ((FKey = Unassigned) Or (FKey = Null))) Then V := Session.Find<T>( orm.where.Where.Add(Field +' = '+ sql.utils.SQLFormat(FKey,-1)).Add(FWhere,wcNone) ) Else V := Session.Find<T>( orm.where.Where.Add(FWhere,wcNone) ); End Else If (not Field.IsEmpty) And (not ((FKey = Unassigned) Or (FKey = Null))) Then V := Session.Find<T>( orm.where.Where.Add(Field +' = '+ sql.utils.SQLFormat(FKey,-1),wcNone) ) Else If (not ((FKey = Unassigned) Or (FKey = Null))) Then V := Session.Find<T>(FKey) Else V := T(orm.Objects.Utils.Factory(C)); Finally If Assigned(V) And not Assigned(FValue) Then FValue := V Else If Assigned(V) Then Begin orm.Objects.Utils.Copy(V,FValue); FreeAndNil(V); End Else If (not Assigned(V)) And (not Assigned(FValue)) Then FValue := T(orm.Objects.Utils.Factory(C)); End; Result := FValue; FLoad := True; FIsNull := False; end; function TLazyLoad<T>.ValueAll: TObjectList<T>; var C : TClass; V : TObjectList<T>; Old : TCollectionNotifyEvent<T>; begin If FIsNull Then Exit(nil) Else If FLoad And Assigned(FValueAll) Then Exit(FValueAll); V := nil; Try If not FWhere.IsEmpty Then Begin If not Field.IsEmpty Then V := Session.FindAll<T>( orm.where.Where.Add(Field +' = '+ sql.utils.SQLFormat(FKey,-1)).Add(FWhere,wcNone),FOrder) Else V := Session.FindAll<T>( FWhere, FOrder ) End Else If not Field.IsEmpty Then V := Session.FindAll<T>( Field +' = '+ sql.utils.SQLFormat(FKey,-1), FOrder ) Else V := TObjectList<T>.Create; Finally If Assigned(V) And not Assigned(FValueAll) Then FValueAll := V Else If Assigned(V) Then Begin Old := FValueAll.OnNotify; FValueAll.OnNotify := nil; Try FValueAll.Clear; While (V.Count > 0) Do FValueAll.Add(V.Extract(V.First)); Finally FValueAll.OnNotify := Old; End; FreeAndNil(V); End Else If (not Assigned(V)) And (not Assigned(FValue)) Then FValue := T(orm.Objects.Utils.Factory(C)); End; Result := FValueAll; FLoad := True; FIsNull := False; end; end.
unit UTDMSSegment; interface uses UTDMSLeadInfo,URawdataDataType, System.SysUtils, System.Generics.Collections,UTDMSChannel,System.Classes,UROWDataInfo; type MetaData = class; RawData = class; TDMSSegment = class private ledInfo:LeadInfo; self_metaData:MetaData; self_rawData:RawData; channelMap:TList<TChannel>; public constructor Create(); procedure adderChannel(Channel:TChannel); function getChannels():TList<TChannel>; function fileSize():LongInt; procedure read(buffer:TFileStream); // function getSameRawDataInfo(channelName:string): RawDataInfo; end; MetaData = class private ObjNum:Integer; public constructor Create(buffer:TFileStream;adder:TDMSSegment); procedure read(buffer:TFileStream;adder:TDMSSegment); end; RawData = class public constructor Create(ledInfo:LeadInfo;self_metaData:MetaData;seg:TDMSSegment;buffer:TFileStream); procedure addInt32ToObject( buffer : TFileStream; o: TChannel); procedure addFloatToObject( buffer : TFileStream; o: TChannel); procedure addDoublesToObject( buffer : TFileStream; o: TChannel); //procedure read(buffer:TFileStream); end; implementation { TDMSSegment } procedure TDMSSegment.adderChannel(Channel: TChannel); begin channelMap.add(Channel); end; constructor TDMSSegment.Create(); begin inherited Create(); channelMap := TList<TChannel>.create; end; function TDMSSegment.fileSize: LongInt; begin end; function TDMSSegment.getChannels: TList<TChannel>; begin Result:= channelMap; end; procedure TDMSSegment.read(buffer: TFileStream); begin self.ledInfo := LeadInfo.create(buffer); if ledInfo.hasMetaData then begin Writeln('############读取元数据###############'); self_metaData := MetaData.create(buffer,Self); self_metaData.read(buffer,self); end; if ledInfo.hasRawData then begin Writeln('###########读取原始数据###############'); self_rawData := RawData.create(ledInfo,self_metaData,self,buffer); // Writeln('第一段------------------'); end; end; //-------------------------------- constructor MetaData.Create(buffer:TFileStream;adder:TDMSSegment); //var // i:Integer; // pin:PInteger; // Channel : TChannel; // bytes:array [0..4] of Byte; // num:Integer; begin inherited create; // buffer.Read(bytes,4); // num:= Pinteger(@bytes)^; // // Self.ObjNum := num; 问题:无法使用成员变量 // for I := 0 to num-1 do // begin // Channel := TChannel.create(); // Channel.read(buffer); // adder.adderChannel(Channel); //问题:无法传递类自身 // end; end; //-------------------------------------------- procedure RawData.addDoublesToObject(buffer: TFileStream; o: TChannel); var nbOfValues:LongInt; i:Integer; val:Double; bytes:array [0..7] of Byte; begin nbOfValues := o.getRawDataInfo().getNumOfValue(); for I := 0 to nbOfValues-1 do begin buffer.read(bytes,8); val := Pdouble(@bytes)^; o.addObj(val); end; end; procedure RawData.addFloatToObject(buffer: TFileStream; o: TChannel); var nbOfValues:LongInt; i:Integer; val:Single; bytes:array [0..3] of Byte; begin nbOfValues := o.getRawDataInfo().getNumOfValue(); for I := 0 to nbOfValues-1 do begin buffer.read(bytes,4); val := PSingle(@bytes)^; o.addObj(val); end; end; procedure RawData.addInt32ToObject(buffer: TFileStream; o: TChannel); var nbOfValues:LongInt; i,val:Integer; bytes:array [0..3] of Byte; begin nbOfValues := o.getRawDataInfo().getNumOfValue(); for I := 0 to nbOfValues-1 do begin buffer.read(bytes,4); val := PInteger(@bytes)^; o.addObj(val); end; end; constructor RawData.Create(ledInfo:LeadInfo;self_metaData:MetaData;seg:TDMSSegment;buffer:TFileStream); var RawDataSize:Integer; checkSize:LongInt; i:Integer; list: TList<TChannel> ; numOfvalue,dimension,dataTypeValue,nChunck:Integer; k: Integer; temp :TChannel; dataType:RawdataDataType; bytes:array [0..7] of Byte; begin inherited create; checkSize :=0; RawDataSize := ledInfo.getRawSize; list := seg.getChannels; for I := 0 to list.count-1 do begin if(list[i].getRawDataInfo = nil)then continue; numOfvalue := list[i].getRawDataInfo.getNumOfValue; dimension := list[i].getRawDataInfo.getDimension; dataTypeValue := list[i].getRawDataInfo.getDataType.typelength; checkSize := checkSize + numOfvalue * dimension *dataTypeValue; end; if checkSize =0 then begin writeln('error,there is no data read!'); exit; end; if RawDataSize = 0 then begin nChunck := 0; end else begin nChunck :=trunc(RawDataSize / checkSize); end; Writeln('ChunkSize: '+IntToStr(checkSize)); Writeln('totalChunks: ' + IntToStr(RawDataSize)); Writeln('nChunks: ' + IntToStr(nChunck)); if ledInfo.hasIterleavedData then begin Writeln('#############数据为交叉存储################ ' ); for i := 0 to nChunck-1 do begin for k := 0 to list.count -1 do begin temp := list[i]; if temp.getRawDataInfo = nil then continue; dataType := temp.getRawDataInfo.getDataType; if dataType.type_name = tdsTypeI32 then begin if temp.isFull then continue; buffer.read(bytes,4); temp.addObj(Pinteger(@bytes)^); end else if dataType.type_name = tdsTypeSingleFloat then begin if temp.isFull then continue; buffer.read(bytes,4); temp.addObj(PSingle(@bytes)^); end else if dataType.type_name = tdsTypeDoubleFloat then begin if temp.isFull then continue; buffer.read(bytes,8); temp.addObj(PDouble(@bytes)^); end else if dataType.type_name = INVALID then begin Writeln('datatype is null'); end else begin Writeln('数据类型暂不支持'); end; end; end; end else begin Writeln('#############数据为顺序存储################ ' ); for i := 0 to nChunck-1 do begin for k := 0 to list.count -1 do begin temp := list[i]; if temp.getRawDataInfo = nil then continue; dataType := temp.getRawDataInfo.getDataType; if dataType.type_name = tdsTypeI32 then begin addInt32ToObject(buffer,temp); end else if dataType.type_name = tdsTypeSingleFloat then begin addFloatToObject(buffer,temp); end else if dataType.type_name = tdsTypeDoubleFloat then begin addDoublesToObject(buffer,temp); end else if dataType.type_name = INVALID then begin Writeln('datatype is null'); end else begin Writeln('数据类型暂不支持'); end; end; end; end; end; procedure MetaData.read(buffer: TFileStream; adder: TDMSSegment); var i:Integer; pin:PInteger; Channel : TChannel; bytes:array [0..4] of Byte; num:Integer; begin inherited create; buffer.Read(bytes,4); num:= Pinteger(@bytes)^; ObjNum:= num; // Self.ObjNum := num; 问题:无法使用成员变量 if ObjNum = 0 then Writeln('Object num is zero ,please continue'); for I := 0 to ObjNum-1 do begin Channel := TChannel.create(); Channel.read(buffer); adder.adderChannel(Channel); //问题:无法传递类自身 end; end; end.
unit UCloudBackupThread; interface uses classes, Sockets, UBackupThread, UModelUtil, SysUtils, Windows, UmyUtil, UMyTcp, math; type {$Region ' 网络备份 被扫描 ' } TNetworkFolderAccessScanHandle = class public TcpSocket : TCustomIpClient; PcID : string; public DesFileHash : TScanFileHash; DesFolderHash : TStringHash; public constructor Create( _TcpSocket : TCustomIpClient ); procedure SetPcID( _PcID : string ); procedure Update; destructor Destroy; override; private procedure ScanFolder( FolderPath : string ); procedure SendScanResult; protected // 是否 停止扫描 function CheckNextScan : Boolean; end; TNetworkFileAccessScanHandle = class public TcpSocket : TCustomIpClient; PcID : string; public constructor Create( _TcpSocket : TCustomIpClient ); procedure SetPcID( _PcID : string ); procedure Update; end; {$EndRegion} {$Region ' 网络备份 被备份 ' } TBackupFileReceiveHandle = class public DesFilePath : string; TcpSocket : TCustomIpClient; SourceFileSize : Int64; public constructor Create( _DesFilePath : string ); procedure SetTcpSocket( _TcpSocket : TCustomIpClient ); procedure Update; private procedure FileReceive; function CheckNextReceive : Boolean; end; TNetworkAccessBackupHandle = class public TcpSocket : TCustomIpClient; PcID : string; public constructor Create( _TcpSocket : TCustomIpClient ); procedure SetPcID( _PcID : string ); procedure Update; private procedure FileAddHandle( DesFilePath : string ); end; {$EndRegion} // 备份算法 TCloudBackupHandle = class public TcpSocket : TCustomIpClient; PcID : string; public constructor Create( _TcpSocket : TCustomIpClient ); procedure Update; private procedure ScanHandle; procedure BackupHandle; end; TCloudBackupThread = class( TThread ) private TcpSocket : TCustomIpClient; public constructor Create; procedure SetTcpSocket( _TcpSocket : TCustomIpClient ); destructor Destroy; override; protected procedure Execute; override; private procedure BackupHandle; end; // 云备份处理 TMyCloudBackupHandler = class public CloudBackupThread : TCloudBackupThread; public constructor Create; procedure StopRun; public procedure ReceiveBackup( TcpSocket : TCustomIpClient ); end; var MyCloudBackupHandler : TMyCloudBackupHandler; implementation uses UMyCloudDataInfo; { TCloudBackupThread } procedure TCloudBackupThread.BackupHandle; var CloudBackupHandle : TCloudBackupHandle; begin CloudBackupHandle := TCloudBackupHandle.Create( TcpSocket ); CloudBackupHandle.Update; CloudBackupHandle.Free; end; constructor TCloudBackupThread.Create; begin inherited Create( True ); end; destructor TCloudBackupThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TCloudBackupThread.Execute; begin while not Terminated do begin // 处理备份扫描 BackupHandle; // 断开连接 TcpSocket.Free; if not Terminated then Suspend; end; inherited; end; procedure TCloudBackupThread.SetTcpSocket(_TcpSocket: TCustomIpClient); begin TcpSocket := _TcpSocket; Resume; end; { TNetworkFolderAccessScanHandle } function TNetworkFolderAccessScanHandle.CheckNextScan: Boolean; begin Result := True; end; constructor TNetworkFolderAccessScanHandle.Create(_TcpSocket: TCustomIpClient); begin TcpSocket := _TcpSocket; DesFileHash := TScanFileHash.Create; DesFolderHash := TStringHash.Create; end; destructor TNetworkFolderAccessScanHandle.Destroy; begin DesFileHash.Free; DesFolderHash.Free; inherited; end; procedure TNetworkFolderAccessScanHandle.ScanFolder(FolderPath: string); var sch : TSearchRec; SearcFullPath, FileName, ChildPath : string; IsFolder, IsFillter : Boolean; FileSize : Int64; FileTime : TDateTime; LastWriteTimeSystem: TSystemTime; DesScanFileInfo : TScanFileInfo; begin DesFileHash.Clear; DesFolderHash.Clear; // 循环寻找 目录文件信息 SearcFullPath := MyCloudInfoReadUtil.ReadCloudFilePath( PcID, FolderPath ); SearcFullPath := MyFilePath.getPath( SearcFullPath ); if FindFirst( SearcFullPath + '*', faAnyfile, sch ) = 0 then begin repeat // 检查是否继续扫描 if not CheckNextScan then Break; FileName := sch.Name; if ( FileName = '.' ) or ( FileName = '..') then Continue; // 检测文件过滤 ChildPath := SearcFullPath + FileName; // 添加到目录结果 if DirectoryExists( ChildPath ) then DesFolderHash.AddString( FileName ) else begin // 获取 文件大小 FileSize := sch.Size; // 获取 修改时间 FileTimeToSystemTime( sch.FindData.ftLastWriteTime, LastWriteTimeSystem ); LastWriteTimeSystem.wMilliseconds := 0; FileTime := SystemTimeToDateTime( LastWriteTimeSystem ); // 添加到文件结果集合中 DesScanFileInfo := TScanFileInfo.Create( FileName ); DesScanFileInfo.SetFileInfo( FileSize, FileTime ); DesFileHash.Add( FileName, DesScanFileInfo ); end; until FindNext(sch) <> 0; end; SysUtils.FindClose(sch); end; procedure TNetworkFolderAccessScanHandle.SendScanResult; var p : TScanFilePair; ps : TStringPart; begin // 发文件信息 for p in DesFileHash do begin MySocketUtil.SendString( TcpSocket, FileReq_File ); MySocketUtil.SendString( TcpSocket, p.Value.FileName ); MySocketUtil.SendString( TcpSocket, IntToStr( p.Value.FileSize ) ); MySocketUtil.SendString( TcpSocket, FloatToStr( p.Value.FileTime ) ); end; // 发目录信息 for ps in DesFolderHash do begin MySocketUtil.SendString( TcpSocket, FileReq_Folder ); MySocketUtil.SendString( TcpSocket, p.Value.FileName ); end; // 发送结束 MySocketUtil.SendString( TcpSocket, FileReq_End ); // 清空历史数据 DesFileHash.Clear; DesFolderHash.Clear; end; procedure TNetworkFolderAccessScanHandle.SetPcID(_PcID: string); begin PcID := _PcID; end; procedure TNetworkFolderAccessScanHandle.Update; var FolderPath : string; begin while True do begin FolderPath := MySocketUtil.RevString( TcpSocket ); if ( FolderPath = FileReq_End ) or ( FolderPath = '' ) then Break; ScanFolder( FolderPath ); SendScanResult; end; end; { TNetworkFileAccessScanHandle } constructor TNetworkFileAccessScanHandle.Create(_TcpSocket: TCustomIpClient); begin TcpSocket := _TcpSocket; end; procedure TNetworkFileAccessScanHandle.SetPcID(_PcID: string); begin PcID := _PcID; end; procedure TNetworkFileAccessScanHandle.Update; var SourceFilePath, DesFilePath : string; IsExistFile : Boolean; FileSize : Int64; FileTime : TDateTime; begin // 接收源文件路径 SourceFilePath := MySocketUtil.RevString( TcpSocket ); // 提取目标文件路径 DesFilePath := MyCloudInfoReadUtil.ReadCloudFilePath( PcID, SourceFilePath ); // 发送文件信息 IsExistFile := FileExists( DesFilePath ); MySocketUtil.SendString( TcpSocket, BoolToStr( IsExistFile ) ); if not IsExistFile then Exit; FileSize := MyFileInfo.getFileSize( SourceFilePath ); FileTime := MyFileInfo.getFileLastWriteTime( SourceFilePath ); MySocketUtil.SendString( TcpSocket, IntToStr( FileSize ) ); MySocketUtil.SendString( TcpSocket, FloatToStr( FileTime ) ); end; { TMyCloudBackupHandler } constructor TMyCloudBackupHandler.Create; begin CloudBackupThread := TCloudBackupThread.Create; end; procedure TMyCloudBackupHandler.ReceiveBackup(TcpSocket: TCustomIpClient); begin CloudBackupThread.SetTcpSocket( TcpSocket ); end; procedure TMyCloudBackupHandler.StopRun; begin CloudBackupThread.Free; end; { TNetworkAccessBackupHandle } constructor TNetworkAccessBackupHandle.Create(_TcpSocket: TCustomIpClient); begin TcpSocket := _TcpSocket; end; procedure TNetworkAccessBackupHandle.FileAddHandle(DesFilePath: string); var BackupFileReceiveHandle : TBackupFileReceiveHandle; begin BackupFileReceiveHandle := TBackupFileReceiveHandle.Create( DesFilePath ); BackupFileReceiveHandle.SetTcpSocket( TcpSocket ); BackupFileReceiveHandle.Update; BackupFileReceiveHandle.Free; end; procedure TNetworkAccessBackupHandle.SetPcID(_PcID: string); begin PcID := _PcID; end; procedure TNetworkAccessBackupHandle.Update; var FileBackupType : string; SourceFilePath, DesFilePath : string; begin while True do begin FileBackupType := MySocketUtil.RevString( TcpSocket ); if ( FileBackupType = FileBackup_End ) or ( FileBackupType = '' ) then Break; SourceFilePath := MySocketUtil.RevString( TcpSocket ); DesFilePath := MyCloudInfoReadUtil.ReadCloudFilePath( PcID, SourceFilePath ); if FileBackupType = FileBackup_AddFile then FileAddHandle( DesFilePath ) else if FileBackupType = FileBackup_AddFolder then ForceDirectories( DesFilePath ) else if FileBackupType = FileBackup_RemoveFile then SysUtils.DeleteFile( DesFilePath ) else if FileBackupType = FileBackup_RemoveFolder then MyFolderDelete.DeleteDir( DesFilePath ); end; end; { TBackupFileReceiveHandle } function TBackupFileReceiveHandle.CheckNextReceive: Boolean; begin Result := True; end; constructor TBackupFileReceiveHandle.Create(_DesFilePath: string); begin DesFilePath := _DesFilePath; end; procedure TBackupFileReceiveHandle.FileReceive; var DesFileStream : TFileStream; Buf : array[0..524287] of Byte; FullBufSize, BufSize, ReceiveSize : Integer; RemainSize : Int64; begin ForceDirectories( ExtractFileDir( DesFilePath ) ); DesFileStream := TFileStream.Create( DesFilePath, fmCreate or fmShareDenyNone ); FullBufSize := SizeOf( Buf ); RemainSize := SourceFileSize; while RemainSize > 0 do begin // 取消复制 或 程序结束 if not CheckNextReceive then Break; BufSize := Min( FullBufSize, RemainSize ); ReceiveSize := TcpSocket.ReceiveBuf( Buf, BufSize ); DesFileStream.Write( Buf, ReceiveSize ); RemainSize := RemainSize - ReceiveSize; end; DesFileStream.Free; end; procedure TBackupFileReceiveHandle.SetTcpSocket(_TcpSocket: TCustomIpClient); begin TcpSocket := _TcpSocket; end; procedure TBackupFileReceiveHandle.Update; var IsEnoughSpace : Boolean; FileTime : TDateTime; begin SourceFileSize := StrToInt64Def( MySocketUtil.RevString( TcpSocket ), 0 ); IsEnoughSpace := MyCloudInfoReadUtil.ReadCloudAvalibleSpace >= SourceFileSize; MySocketUtil.SendString( TcpSocket, BoolToStr( IsEnoughSpace ) ); // 空间不足 if not IsEnoughSpace then Exit; // 文件接收 FileReceive; // 设置文件修改时间 FileTime := StrToFloatDef( MySocketUtil.RevString( TcpSocket ), Now ); MyFileSetTime.SetTime( DesFilePath, FileTime ); end; { TCloudBackupHandle } procedure TCloudBackupHandle.BackupHandle; var NetworkAccessBackupHandle : TNetworkAccessBackupHandle; begin NetworkAccessBackupHandle := TNetworkAccessBackupHandle.Create( TcpSocket ); NetworkAccessBackupHandle.SetPcID( PcID ); NetworkAccessBackupHandle.Update; NetworkAccessBackupHandle.Free; end; constructor TCloudBackupHandle.Create(_TcpSocket: TCustomIpClient); begin TcpSocket := _TcpSocket; end; procedure TCloudBackupHandle.ScanHandle; var IsFile : Boolean; NetworkFolderAccessScanHandle : TNetworkFolderAccessScanHandle; NetworkFileAccessScanHandle : TNetworkFileAccessScanHandle; begin IsFile := StrToBoolDef( MySocketUtil.RevString( TcpSocket ), True ); if IsFile then begin NetworkFileAccessScanHandle := TNetworkFileAccessScanHandle.Create( TcpSocket ); NetworkFileAccessScanHandle.SetPcID( PcID ); NetworkFileAccessScanHandle.Update; NetworkFileAccessScanHandle.Free; end else begin NetworkFolderAccessScanHandle := TNetworkFolderAccessScanHandle.Create( TcpSocket ); NetworkFolderAccessScanHandle.SetPcID( PcID ); NetworkFolderAccessScanHandle.Update; NetworkFolderAccessScanHandle.Free; end; end; procedure TCloudBackupHandle.Update; begin PcID := MySocketUtil.RevString( TcpSocket ); // 分析需要备份的文件 ScanHandle; // 备份文件 BackupHandle; end; end.
unit Supplier_Form; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Grids, DBGrids, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid; type TSupplier = class(TForm) EditButton: TBitBtn; ADDButton: TBitBtn; DelButton: TBitBtn; CloseButton: TBitBtn; eFilter: TEdit; ButtonClear: TBitBtn; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; cxGrid1DBTableView1SUP_ID: TcxGridDBColumn; cxGrid1DBTableView1SUP_NAME: TcxGridDBColumn; cxGrid1DBTableView1SUP_ADRES: TcxGridDBColumn; cxGrid1DBTableView1SUP_STATUS: TcxGridDBColumn; cxGrid1DBTableView1SUP_COUNTRY: TcxGridDBColumn; cxGrid1DBTableView1SUP_TELEPHONE: TcxGridDBColumn; cxGrid1DBTableView1SUP_UNN: TcxGridDBColumn; procedure DelButtonClick(Sender: TObject); procedure ADDButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure cxGrid1DBTableView1KeyPress(Sender: TObject; var Key: Char); procedure cxGrid1DBTableView1CellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure cxGrid1DBTableView1CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); private { Private declarations } public { Public declarations } end; var Supplier: TSupplier; implementation uses DataModuleForm, Supplier_Add_Form, Supplier_Edit_Form; {$R *.dfm} procedure TSupplier.ADDButtonClick(Sender: TObject); begin Application.CreateForm(TSupplier_Add, Supplier_Add); try Supplier_Add := TSupplier_Add.create(self); Supplier_Add.ShowModal; finally Supplier_Add.free; end; end; procedure TSupplier.cxGrid1DBTableView1CellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin ModalResult := mrOk; end; procedure TSupplier.cxGrid1DBTableView1CellDblClick (Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin ModalResult := mrOk; end; procedure TSupplier.cxGrid1DBTableView1KeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then // если нажата клавиша <Enter> ModalResult := mrOk; end; procedure TSupplier.DelButtonClick(Sender: TObject); begin ShowMessage('Удаление запрещено ! (временно)'); // DataModule.ds_Supplier.Delete; end; procedure TSupplier.EditButtonClick(Sender: TObject); begin Application.CreateForm(TSupplier_Edit, Supplier_Edit); try Supplier_Edit := TSupplier_Edit.create(self); Supplier_Edit.ShowModal; finally Supplier_Edit.free; end; end; end.
{ Arquivo criado automaticamente Gerador Multicamadas (Multitiers Generator VERSÃO 0.01) Data e Hora: 11/10/2016 - 23:02:06 } unit Marvin.AulaMulticamada.Bd.TipoCliente; interface uses Classes, { marvin } uMRVClasses, uMRVPersistenciaBase, uMRVClassesServidor, uMRVDAO, Marvin.AulaMulticamada.Classes.TipoCliente, Marvin.AulaMulticamada.Repositorio.TipoCliente; type CoMRVBdTipoCliente = class(TObject) public class function Create(const ADataBase: IMRVDatabase): IMRVRepositorioTipoCliente; end; implementation uses SysUtils, uMRVConsts, Marvin.AulaMulticamada.Excecoes.TipoCliente; type TMRVBdTipoCliente = class(TMRVPersistenciaBase, IMRVRepositorioTipoCliente) private FCommandNextId: string; protected procedure DoAlterar(const AItem: TMRVDadosBase); override; procedure DoExcluir(const AItem: TMRVDadosBase); override; procedure DoInserir(const AItem: TMRVDadosBase); override; function DoProcurarItem(const ACriterio: TMRVDadosBase; const AResultado: TMRVDadosBase = nil): Boolean; override; function DoProcurarItems(const ACriterio: TMRVDadosBase; const AListaResultado: TMRVListaBase; const ASearchOption: TMRVSearchOption): Boolean; override; procedure MontarStringsDeComando; override; procedure RecordsetToObjeto(const RS: IMRVQuery; const Objeto: TMRVDadosBase); override; { id } function GetNextId: Integer; property CommandNextId: string read FCommandNextId write FCommandNextId; end; { CoMRVBdTipoCliente } class function CoMRVBdTipoCliente.Create(const ADataBase: IMRVDatabase): IMRVRepositorioTipoCliente; begin Result := TMRVBdTipoCliente.Create(ADataBase); end; { TMRVBdTipoCliente } procedure TMRVBdTipoCliente.DoAlterar(const AItem: TMRVDadosBase); var LTipoCliente: TMRVTipoCliente; begin Assert(AItem <> nil, 'O parâmetro AItem não pode ser nil.'); { Realiza um único typecast seguro inicial, para ser usado por todo o método } LTipoCliente := AItem as TMRVTipoCliente; { Informa qual o comando SQL a ser usado } Query.SetSQL(CommandUpdate); { Informa os parâmetros } Query.ParamByName('PAR_TipoClienteId').AsInteger := LTipoCliente.TipoClienteId; Query.ParamByName('PAR_Descricao').AsString := LTipoCliente.Descricao; { Executa o comando SQL } Query.ExecSQL; end; procedure TMRVBdTipoCliente.DoExcluir(const AItem: TMRVDadosBase); var LTipoCliente: TMRVTipoCliente; begin Assert(AItem <> nil, 'O parâmetro AItem não pode ser nil.'); { Realiza um único typecast seguro inicial, para ser usado por todo o método } LTipoCliente := AItem as TMRVTipoCliente; { Informa qual o comando SQL a ser usado } Query.SetSQL(CommandDelete); { Informa os parâmetros } Query.ParamByName('PAR_TipoClienteId').AsInteger := LTipoCliente.TipoClienteId; { Executa o comando SQL } Query.ExecSQL; end; procedure TMRVBdTipoCliente.DoInserir(const AItem: TMRVDadosBase); var LTipoCliente: TMRVTipoCliente; begin Assert(AItem <> nil, 'Parâmetro AItem não pode ser nil.'); LTipoCliente := AItem as TMRVTipoCliente; { Informa qual o comando SQL a ser usado } Query.SetSQL(CommandInsert); { Informa os parâmetros } Query.ParamByName('PAR_TipoClienteId').AsInteger := LTipoCliente.TipoClienteId; Query.ParamByName('PAR_Descricao').AsString := LTipoCliente.Descricao; { Executa o comando SQL } Query.ExecSQL; end; function TMRVBdTipoCliente.DoProcurarItem(const ACriterio: TMRVDadosBase; const AResultado: TMRVDadosBase = nil): Boolean; var LTipoCliente: TMRVTipoCliente; begin Assert(ACriterio <> nil, 'O parâmetro ACriterio não pode ser nil.'); { Realiza um único typecast seguro inicial, para ser usado por todo o método } LTipoCliente := ACriterio as TMRVTipoCliente; { Informa qual o comando SQL a ser usado } Query.SetSQL(CommandSelectItem); { Informa os parâmetros } Query.ParamByName('PAR_TipoClienteId').AsInteger := LTipoCliente.TipoClienteId; { Abre a consulta } Query.Open; Result := not Query.IsEmpty; if Result and Assigned(AResultado) then begin Self.RecordsetToObjeto(Query, AResultado); end; end; function TMRVBdTipoCliente.DoProcurarItems(const ACriterio: TMRVDadosBase; const AListaResultado: TMRVListaBase; const ASearchOption: TMRVSearchOption): Boolean; var LTipoCliente: TMRVTipoCliente; LCondicao: string; begin Assert(ACriterio <> nil, 'O parâmetro ACriterio não pode ser nil.'); Assert(AListaResultado <> nil, 'O parâmetro AListaResultado não pode ser nil.'); { Informa qual o comando SQL a ser usado } Assert(ASearchOption <> nil, 'O parâmetro ASearchOption não pode ser nil.'); { realiza o typecast} LTipoCliente := ACriterio as TMRVTipoCliente; { Inicializa a variável de condição } LCondicao := EmptyStr; { Montagem das condições de pesquisa } if (LTipoCliente.Descricao <> EmptyStr) then begin if ASearchOption.ExistPropertyName('Descricao') then begin LCondicao := LCondicao + TMRVSQLDefs.AddCondition('Descricao', 'PAR_Descricao'); end; end; { Informa a SQL a ser executada } Query.SetSQL(TMRVSQLDefs.AddWhere(CommandSelectItems, LCondicao)); { realiza a passagem de parâmetros } if (LTipoCliente.Descricao <> EmptyStr) then begin if ASearchOption.ExistPropertyName('Descricao') then begin Query.ParamByName('PAR_Descricao').AsString := LTipoCliente.Descricao; end; end; { Abre a consulta } Query.Open; { Verifica o resultado } Result := not Query.IsEmpty; { Se existirem registros } if Result then begin { Preenche os atributos do objeto com os valores dos campos do registro } RecordsetToLista(Query, AListaResultado, TMRVTipoCliente); end; end; function TMRVBdTipoCliente.GetNextId: Integer; begin { Informa qual o comando SQL a ser usado } Query.SetSQL(CommandNextId); { informa id inicial } Result := 1; { Abre a consulta } Query.Open; if not Query.IsEmpty then begin Result := Query.FieldByName('TipoClienteId').AsInteger + 1; end; end; procedure TMRVBdTipoCliente.MontarStringsDeComando; begin CommandNextId := 'select top 1 TipoClienteId from TipoCliente order by TipoClienteId desc'; CommandInsert := 'INSERT INTO TipoCliente (TipoClienteId, ' + 'Descricao) VALUES (:PAR_TipoClienteId, ' + ':PAR_Descricao)'; CommandUpdate := 'UPDATE TipoCliente SET Descricao = :PAR_Descricao WHERE TipoClienteId = :PAR_TipoClienteId'; CommandDelete := 'DELETE FROM TipoCliente WHERE TipoClienteId = :PAR_TipoClienteId'; CommandSelectItem := 'SELECT TipoClienteId, ' + 'Descricao FROM TipoCliente WHERE TipoClienteId = :PAR_TipoClienteId'; CommandSelectItems := 'SELECT TipoClienteId, ' + 'Descricao FROM TipoCliente'; end; procedure TMRVBdTipoCliente.RecordsetToObjeto(const RS: IMRVQuery; const Objeto: TMRVDadosBase); var LObjeto: TMRVTipoCliente; begin Assert(RS <> nil, 'O parâmetro RS não pode ser nil.'); Assert(Objeto <> nil, 'O parâmetro Objeto não pode ser nil.'); { recupera os dados da propriedade FADORecordset } LObjeto := Objeto as TMRVTipoCliente; { recupera os dados do banco para o objeto } LObjeto.TipoClienteId := RS.FieldByName('TipoClienteId').AsInteger; LObjeto.Descricao := RS.FieldByName('Descricao').AsString; end; end.
unit UtilsTests; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry; type TUtilsTests = class(TTestCase) protected procedure SetUp; override; procedure TearDown; override; published procedure ExtendedTest; end; implementation uses hxUtils; type TExtendedTestCase = record Bytes: TExtended10; DblValue: Double; end; procedure TUtilsTests.ExtendedTest; const TestCases: array[0..3] of TExtendedTestCase = ( (Bytes: ($00, $00, $00, $00, $00, $00, $00, $80, $FF, $3F); DblValue: 1.0), (Bytes: ($00, $00, $00, $00, $00, $00, $00, $80, $00, $40); DblValue: 2.0), (Bytes: ($00, $00, $00, $00, $00, $00, $00, $80, $FD, $3F); DblValue: 0.25), (Bytes: ($00, $00, $00, $00, $00, $00, $00, $80, $FD, $BF); DblValue: -0.25) ); var i: Integer; dbl: Double; begin for i := Low(TestCases) to High(TestCases) do begin dbl := ExtendedToDouble(TestCases[i].Bytes); CheckEquals(TestCases[i].DblValue, dbl, Format('Test #%d mismatch', [i])); end; end; procedure TUtilsTests.SetUp; begin // end; procedure TUtilsTests.TearDown; begin // end; initialization RegisterTest(TUtilsTests); end.
unit Basic; interface uses StdCtrls, SysUtils; type TCartrige = class private cal: real; charge: integer; shell: string; memo:TMemo; public Constructor Init(acal: real; acharge: integer; ashell: string); Function get_cal(): real; Function get_charge(): integer; Function get_shell(): string; procedure print(memo:TMemo); virtual; procedure ShellChange(); procedure ChargeUp(); procedure ChargeDown(); end; implementation Constructor TCartrige.Init(acal: real; acharge: integer; ashell: string); begin cal := acal; charge := acharge; shell := ashell; end; Function TCartrige.get_cal(): real; begin result := cal; end; Function TCartrige.get_charge(): integer; begin result := charge; end; Function TCartrige.get_shell(): string; begin result := shell; end; procedure TCartrige.print(memo:TMemo); begin memo.lines.add('==============='); memo.lines.add('Cal: ' + floattostr(cal)); memo.lines.add('Charge: ' + inttostr(charge) + '%'); memo.lines.add('Shell: ' + shell); end; procedure TCartrige.ShellChange(); begin if shell = 'Metal' then shell := 'Plastic'; if shell = 'Plastic' then shell := 'Metal'; end; procedure TCartrige.ChargeUp(); begin charge := charge + 10; end; procedure TCartrige.ChargeDown(); begin charge := charge - 10; end; end.
Unit Queue; Interface Uses Declare; type FieldIndex=StaticSize..MaxDict; var qin: FieldIndex ; { right end of LRU queue, where things enter } qout: FieldIndex ; { left end of LRU queue, where things leave } place:FieldIndex ; { used to point into LRU queue } FUNCTION Older( place: FieldIndex): FieldIndex; PROCEDURE Dequeue( trieptr: FieldIndex) ; PROCEDURE Enqueue( trieptr, place: FieldIndex) ; Implementation var { LRU queue data structure } olderfield: ARRAY [FieldIndex] OF FieldIndex ; { left pointer } newerfield: ARRAY [FieldIndex] OF FieldIndex ; { right pointer } FUNCTION Older( place: FieldIndex): FieldIndex; BEGIN Older := olderfield[ place] END ; { Remove arg1 from LRU queue; assumes queue size > 1 and place not right end } PROCEDURE Dequeue( trieptr: FieldIndex) ; BEGIN IF ( trieptr = qout) THEN { delete from left } BEGIN qout := newerfield[ trieptr] ; olderfield[ qout] := nilptr END ELSE { delete from middle } BEGIN newerfield[ olderfield[ trieptr]] := newerfield[ trieptr] ; olderfield[ newerfield[ trieptr]] := olderfield[ trieptr] END END { Dequeue }; { Put arg1 after arg2 in LRU queue; if arg2 = nilptr, insert at left end } PROCEDURE Enqueue( trieptr, place: FieldIndex) ; BEGIN IF ( qin = nilptr) THEN { empty queue} BEGIN olderfield[trieptr]:=nilptr; newerfield[trieptr]:=nilptr; qin:= trieptr ; qout:= trieptr ; END ELSE IF ( place = nilptr) THEN { insert at left} BEGIN olderfield[ trieptr] := nilptr ; newerfield[ trieptr] := qout ; olderfield[ qout] := trieptr ; qout := trieptr END ELSE IF ( place = qin) THEN { append to right} BEGIN olderfield[ trieptr] := qin ; newerfield[ trieptr] := nilptr ; newerfield[ qin] := trieptr ; qin := trieptr ; END ELSE { append within the middle} BEGIN olderfield[ trieptr] := place ; newerfield[ trieptr] := newerfield[ place] ; olderfield[ newerfield[ place]] := trieptr ; newerfield[ place] := trieptr ; END END { Enqueue } ; 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. * * Contributor(s): * Jody Dawkins <jdawkins@delphixtreme.com> *) unit Modifiers; interface uses BaseObjects, dSpecIntf, Variants; type TModifier = class(TFailureReportingObject, IModifier) private FRemoveLastFailure: Boolean; FShouldHelper: IShouldHelper; protected FFailureMessage: string; function CreateModifier(RemoveLastFailure : Boolean; AFailureMessage : string) : IModifier; virtual; function DoNotApplicableFailure : IModifier; function DoEvaluation(Failed: Boolean; const Msg, ModName: string; ModValue : Variant) : IModifier; public constructor Create(SpecHelper : IShouldHelper; RemoveLastFailure : Boolean; AFailureMessage : string; ACallerAddress : Pointer; AContext : IContext); reintroduce; virtual; destructor Destroy; override; function Unless(Condition : Boolean) : IModifier; function WithAToleranceOf(Value : Extended) : IModifier; virtual; function Percent : IModifier; virtual; function IgnoringCase : IModifier; virtual; function And_ : IShouldHelper; end; TFloatModifier = class(TModifier) private FExpected: Extended; FActual: Extended; protected function CreateModifier(RemoveLastFailure : Boolean; AFailureMessage : string) : IModifier; override; public constructor Create(Expected, Actual: Extended; SpecHelper : IShouldHelper; RemoveLastFailure: Boolean; AFailureMessage: string; ACallerAddress: Pointer; AContext: IContext); reintroduce; function WithAToleranceOf(Value : Extended) : IModifier; override; function Percent : IModifier; override; end; TStringModifier = class(TModifier) private FActual: string; FExpected: string; protected function CreateModifier(RemoveLastFailure : Boolean; AFailureMessage : string) : IModifier; override; public constructor Create(Expected, Actual: string; SpecHelper : IShouldHelper; RemoveLastFailure: Boolean; AFailureMessage: string; ACallerAddress: Pointer; AContext: IContext); reintroduce; function IgnoringCase : IModifier; override; end; implementation uses dSpecUtils, SysUtils, FailureMessages, Math; { TModifier } constructor TModifier.Create(SpecHelper : IShouldHelper; RemoveLastFailure : Boolean; AFailureMessage: string; ACallerAddress: Pointer; AContext : IContext); begin inherited Create(ACallerAddress, AContext); FShouldHelper := SpecHelper; FRemoveLastFailure := RemoveLastFailure; FFailureMessage := AFailureMessage; end; function TModifier.CreateModifier(RemoveLastFailure: Boolean; AFailureMessage: string): IModifier; begin Result := TModifier.Create(FShouldHelper, RemoveLastFailure, AFailureMessage, FCallerAddress, FContext); end; destructor TModifier.Destroy; begin FShouldHelper := nil; inherited Destroy; end; function TModifier.DoEvaluation(Failed: Boolean; const Msg, ModName: string; ModValue : Variant): IModifier; begin if FRemoveLastFailure then FContext.RepealLastFailure; if Failed then Fail(Msg); Result := CreateModifier(Failed, Msg); FContext.DocumentSpec(ModValue, ModName); end; function TModifier.DoNotApplicableFailure : IModifier; begin if FRemoveLastFailure then FContext.RepealLastFailure; Fail(ModNotApplicable); Result := CreateModifier(True, ModNotApplicable); end; function TModifier.IgnoringCase: IModifier; begin Result := DoNotApplicableFailure; end; function TModifier.Percent: IModifier; begin Result := DoNotApplicableFailure; end; function TModifier.Unless(Condition: Boolean) : IModifier; var Msg: string; begin if Condition then Msg := FFailureMessage + ' - because "unless" condition was true' else Msg := FFailureMessage; Result := DoEvaluation(Condition = True, Msg, 'Unless', Condition); end; function TModifier.WithAToleranceOf(Value: Extended) : IModifier; begin Result := DoNotApplicableFailure; end; function TModifier.And_: IShouldHelper; begin Result := FShouldHelper.CreateNewShouldHelper(False); FContext.DocumentSpec(null, 'And'); end; { TFloatModifier } constructor TFloatModifier.Create(Expected, Actual: Extended; SpecHelper : IShouldHelper; RemoveLastFailure: Boolean; AFailureMessage: string; ACallerAddress: Pointer; AContext: IContext); begin inherited Create(SpecHelper, RemoveLastFailure, AFailureMessage, ACallerAddress, AContext); FExpected := Expected; FActual := Actual; end; function TFloatModifier.CreateModifier(RemoveLastFailure: Boolean; AFailureMessage: string): IModifier; begin Result := TFloatModifier.Create(FExpected, FActual, FShouldHelper, RemoveLastFailure, AFailureMessage, FCallerAddress, FContext); end; function TFloatModifier.Percent: IModifier; var Percentage: Extended; Msg: string; Mismatch : Boolean; begin Percentage := FActual * 100; MisMatch := not SameValue(FExpected, Percentage); if Mismatch then Msg := Format(ModPercentFailure, [FFailureMessage]) else Msg := FFailureMessage + ' - percentage matched'; Result := DoEvaluation(Mismatch, Msg, 'Percent', null); end; function TFloatModifier.WithAToleranceOf(Value: Extended) : IModifier; var ToleranceFailed: Boolean; Msg: string; begin ToleranceFailed := Abs(FExpected - FActual) > Value; if ToleranceFailed then Msg := Format(ModToleranceExceeded, [FFailureMessage, Value]) else Msg := FFailureMessage + ' - tolerance met'; Result := DoEvaluation(ToleranceFailed, Msg, 'WithAToleranceOf', Value); end; { TStringModifier } constructor TStringModifier.Create(Expected, Actual: string; SpecHelper: IShouldHelper; RemoveLastFailure: Boolean; AFailureMessage: string; ACallerAddress: Pointer; AContext: IContext); begin inherited Create(SpecHelper, RemoveLastFailure, AFailureMessage, ACallerAddress, AContext); FActual := Actual; FExpected := Expected; end; function TStringModifier.CreateModifier(RemoveLastFailure: Boolean; AFailureMessage: string): IModifier; begin Result := TStringModifier.Create(FExpected, FActual, FShouldHelper, FRemoveLastFailure, FFailureMessage, FCallerAddress, FContext); end; function TStringModifier.IgnoringCase: IModifier; var CaseInsenstiveMatch: Boolean; Msg: string; begin CaseInsenstiveMatch := CompareText(FActual, FExpected) = 0; if not CaseInsenstiveMatch then Msg := Format(ModCaseInsenstiveMatch, [FFailureMessage]) else Msg := FFailureMessage + ' - case insenstive match'; Result := DoEvaluation(not CaseInsenstiveMatch, Msg, 'IgnoringCase', null); end; end.
{ p_41_2 - Пиратская делёжка по справедливости } program p_41_2; const cSize = 16; { размер массива слитков } type tGolds = array[1..cSize] of integer; var golds: tGolds; procedure BubbleSort(var arg: tGolds); var i, j, t: integer; begin for i:=1 to cSize-1 do for j:=1 to cSize-i do if arg[j]>arg[j+1] then begin t := arg[j]; arg[j] := arg[j+1]; arg[j+1] := t; end; end; var i: integer; begin Randomize; for i:=1 to cSize do golds[i] := 500+Random(500); BubbleSort(golds); Writeln('По справедливости:'); for i:=1 to (cSize div 2) do begin Write(i:2, golds[i]:5, ' + ', golds[cSize+1-i]:3, ' = '); Writeln(golds[i]+golds[cSize+1-i]:4); end; end.
unit sScrollBar; {$I sDefs.inc} {.$DEFINE LOGGED} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Consts, sPanel, acntUtils, sConst, extctrls, sCommonData, sDefaults, sSkinManager{$IFDEF DELPHI6UP}, Types{$ENDIF}; type TsScrollBar = class(TScrollBar) private {$IFNDEF NOTFORHELP} FBtn1Rect : TRect; FBtn2Rect : TRect; FBar1Rect : TRect; FBar2Rect : TRect; FSliderRect : TRect; Timer : TTimer; FBtn1State: integer; FBar2State: integer; FBtn2State: integer; FBar1State: integer; FSliderState : integer; FCommonData: TsCommonData; FDisabledKind: TsDisabledKind; MustBeRecreated : boolean; FSI : TScrollInfo; FCurrPos : integer; FBeginTrack : boolean; function NotRightToLeft: Boolean; procedure CNHScroll(var Message: TWMHScroll); message CN_HSCROLL; procedure CNVScroll(var Message: TWMVScroll); message CN_VSCROLL; procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE; procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST; procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; procedure SetInteger(Index : integer; Value: integer); procedure SetDisabledKind(const Value: TsDisabledKind); function GetSkinManager: TsSkinManager; procedure SetSkinManager(const Value: TsSkinManager); protected CI : TCacheInfo; AppShowHint : boolean; procedure CreateParams(var Params: TCreateParams); override; procedure WndProc(var Message: TMessage); override; procedure Paint(MsgDC : hdc); procedure PlaceToLinked; procedure InitDontChange; procedure ClearDontChange; procedure DrawBtnTop(b : TBitmap); procedure DrawBtnLeft(b : TBitmap); procedure DrawBtnRight(b : TBitmap); procedure DrawBtnBottom(b : TBitmap); procedure DrawSlider(b : TBitmap); function Bar1Rect : TRect; function Bar2Rect : TRect; function Btn1Rect : TRect; function Btn2Rect : TRect; function Btn1DRect : TRect; function Btn2DRect : TRect; function WorkSize : integer; function SliderRect : TRect; function SliderSize : integer; function Btn1SkinIndex : integer; function Btn2SkinIndex : integer; function CoordToPoint(p : TPoint) : TPoint; function CoordToPosition(p : TPoint) : integer; function PositionToCoord : integer; function FirstPoint : integer; function BarIsHot : boolean; procedure PrepareTimer; procedure PrepareBtnTimer; procedure PrepareBarTimer; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure KeyDown(var Key: word; Shift: TShiftState); override; procedure IncPos(Offset : integer); procedure SetPos(Pos : integer); public ScrollCode : integer; RepaintNeeded : boolean; MouseOffset : integer; DrawingForbidden : boolean; LinkedControl : TWinControl; DontChange : boolean; DoSendChanges : boolean; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AfterConstruction; override; procedure Loaded; override; procedure UpdateBar; procedure OnTimer(Sender : TObject); procedure OnBtnTimer(Sender : TObject); procedure OnBarTimer(Sender : TObject); property Btn1State : integer index 0 read FBtn1State write SetInteger; property Btn2State : integer index 1 read FBtn2State write SetInteger; property Bar1State : integer index 2 read FBar1State write SetInteger; property Bar2State : integer index 3 read FBar2State write SetInteger; property SliderState : integer index 4 read FSliderState write SetInteger; property SkinData : TsCommonData read FCommonData write FCommonData; {$ENDIF} published property DisabledKind : TsDisabledKind read FDisabledKind write SetDisabledKind default DefDisabledKind; property SkinManager : TsSkinManager read GetSkinManager write SetSkinManager; {$IFNDEF NOTFORHELP} property OnMouseDown; property OnMouseMove; property OnMouseUp; {$ENDIF} end; {$IFNDEF NOTFORHELP} function UpdateControlScrollBar(Control : TWinControl; var ScrollBar : TsScrollBar; Kind : TScrollBarKind; Free : boolean = true) : boolean; {$ENDIF} implementation uses sGraphUtils, sBorders, sSkinProps, math{$IFDEF LOGGED}, sDebugMsgs{$ENDIF}, sMessages, commctrl, sMaskData, sStyleSimply, sVclUtils{$IFDEF CHECKXP}, UxTheme, Themes{$ENDIF}, sAlphaGraph; var p : TPoint; SkinnedRecreate : boolean = False; type {$HINTS OFF} TScrollBar_ = class(TWinControl) private FPageSize: Integer; FRTLFactor: Integer; end; {$HINTS ON} function Skinned(sb : TsScrollBar): boolean; begin if not Assigned(sb.SkinData.SkinManager) then sb.SkinData.SkinManager := DefaultManager; if Assigned(sb.SkinData.SkinManager) and sb.SkinData.SkinManager.SkinData.Active then Result := True else Result := False; end; function UpdateControlScrollBar(Control : TWinControl; var ScrollBar : TsScrollBar; Kind : TScrollBarKind; Free : boolean = true) : boolean; const SysConsts: array[TScrollBarKind] of Integer = (SM_CXHSCROLL, SM_CXVSCROLL); Kinds: array[TScrollBarKind] of DWORD = (SB_HORZ, SB_VERT); var SI : TScrollInfo; function HaveScroll(Handle : hwnd; fnBar : integer) : boolean; var Style : Longint; begin Style := GetWindowLong(Handle, GWL_STYLE); case fnBar of SB_VERT : Result := (Style and WS_VSCROLL) <> 0; SB_HORZ : Result := (Style and WS_HSCROLL) <> 0; SB_BOTH : Result := ((Style and WS_VSCROLL) <> 0) and ((Style and WS_HSCROLL) <> 0) else Result := False end; end; function GetScrollInfo(Handle: HWND; Kind: Integer; Mask : Cardinal; var ScrollInfo: TScrollInfo): boolean; begin Result := HaveScroll(Handle, Kind); if Result then begin ScrollInfo.cbSize := SizeOf(TScrollInfo); ScrollInfo.fMask := Mask; Result := Windows.GetScrollInfo(Handle, Kind, ScrollInfo); end; end; begin result := false; if Control.Visible then begin if GetScrollInfo(Control.Handle, Kinds[Kind], SIF_ALL, SI) then begin if ScrollBar = nil then begin ScrollBar := TsScrollBar.Create(Control); ScrollBar.Visible := False; ScrollBar.LinkedControl := Control; ScrollBar.DoSendChanges := true; ScrollBar.DrawingForbidden := True; ScrollBar.TabStop := False; ScrollBar.Kind := Kind; ScrollBar.Parent := Control.Parent; end; result := true; end else begin if Assigned(ScrollBar) and Free then FreeAndNil(ScrollBar); end; end else begin if Assigned(ScrollBar) then FreeAndNil(ScrollBar); end; end; { TsScrollBar } procedure TsScrollBar.AfterConstruction; var OldPos : integer; begin inherited; FCommonData.Loaded; {$IFDEF CHECKXP} if UseThemes and not (SkinData.Skinned and SkinData.SkinManager.SkinData.Active) then begin ControlStyle := ControlStyle - [csParentBackground]; // Patching of bug with TGraphicControls repainting when XPThemes used end; {$ENDIF} if MustBeRecreated then begin // Control must be recreated for the skinned mode using without std blinking MustBeRecreated := False; SkinnedRecreate := True; OldPos := Position; RecreateWnd; Position := OldPos; SkinnedRecreate := False; end; end; function TsScrollBar.Btn1Rect: TRect; begin FBtn1Rect.Left := 0; FBtn1Rect.Top := 0; if Kind = sbHorizontal then begin FBtn1Rect.Right := GetSystemMetrics(SM_CXHSCROLL); FBtn1Rect.Bottom := Height; if WidthOf(FBtn1Rect) > Width div 2 then FBtn1Rect.Right := Width div 2; end else begin FBtn1Rect.Right := Width; FBtn1Rect.Bottom := GetSystemMetrics(SM_CYVSCROLL); if HeightOf(FBtn1Rect) > Height div 2 then FBtn1Rect.Bottom := Height div 2; end; Result := FBtn1Rect; end; function TsScrollBar.Btn1SkinIndex: integer; begin if Kind = sbHorizontal then Result := FCommonData.SkinManager.ConstData.IndexScrollLeft else Result := FCommonData.SkinManager.ConstData.IndexScrollTop; end; function TsScrollBar.Btn2Rect: TRect; begin if Kind = sbHorizontal then begin FBtn2Rect.Left := Width - GetSystemMetrics(SM_CXHSCROLL); FBtn2Rect.Top := 0; FBtn2Rect.Right := Width; FBtn2Rect.Bottom := Height; if WidthOf(FBtn2Rect) > Width div 2 then FBtn2Rect.Left := Width div 2; end else begin FBtn2Rect.Left := 0; FBtn2Rect.Top := Height - GetSystemMetrics(SM_CYVSCROLL); FBtn2Rect.Right := Width; FBtn2Rect.Bottom := Height; if HeightOf(FBtn2Rect) > Height div 2 then FBtn2Rect.Top := Height div 2; end; Result := FBtn2Rect; end; function TsScrollBar.Btn2SkinIndex: integer; begin if Kind = sbHorizontal then Result := FCommonData.SkinManager.ConstData.IndexScrollRight else Result := FCommonData.SkinManager.ConstData.IndexScrollBottom; end; function TsScrollBar.CoordToPoint(p: TPoint): TPoint; begin Result := ScreenToClient(P); end; function TsScrollBar.CoordToPosition(p: TPoint): integer; var ss : integer; r : real; begin if Enabled then begin ss := SliderSize; if Kind = sbHorizontal then begin r := (Width - 2 * GetSystemMetrics(SM_CXHSCROLL) - ss); if r = 0 then Result := 0 else Result := Round((p.x - GetSystemMetrics(SM_CXHSCROLL) - ss / 2) * (FSI.nMax - FSI.nMin - Math.Max(Integer(FSI.nPage) - 1, 0)) / r) end else begin r := (Height - 2 * GetSystemMetrics(SM_CYVSCROLL) - ss); if r = 0 then Result := 0 else Result := Round((p.y - GetSystemMetrics(SM_CYVSCROLL) - ss / 2) * (FSI.nMax - FSI.nMin- Math.Max(Integer(FSI.nPage) -1, 0)) / r); end; end else Result := 0; end; constructor TsScrollBar.Create(AOwner: TComponent); begin inherited Create(AOwner); FCommonData := TsCommonData.Create(TWinControl(Self), True); CI := MakeCacheInfo(FCommonData.FCacheBmp); FCommonData.COC := COC_TsScrollBar; FSI.nMax := FSI.nMin - 1; Btn1State := 0; Btn2State := 0; Bar1State := 0; Bar2State := 0; FBtn1Rect.Right := 0; FBtn2Rect.Right := 0; FDisabledKind := DefDisabledKind; end; procedure TsScrollBar.CreateParams(var Params: TCreateParams); procedure DefCreateParams(var Params: TCreateParams); var FText : string; FLeft, FTop, FWidth, FHeight : integer; begin FillChar(Params, SizeOf(Params), 0); FText := Text; FLeft := Left; FTop := Top; FWidth:= Width; FHeight:= Height; with Params do begin Caption := PChar(FText); Style := WS_CHILD or WS_CLIPSIBLINGS; AddBiDiModeExStyle(ExStyle); if csAcceptsControls in ControlStyle then begin Style := Style or WS_CLIPCHILDREN; ExStyle := ExStyle or WS_EX_CONTROLPARENT; end; if not (csDesigning in ComponentState) and not Enabled then Style := Style or WS_DISABLED; if TabStop then Style := Style or WS_TABSTOP; X := FLeft; Y := FTop; Width := FWidth; Height := FHeight; if Parent <> nil then WndParent := Parent.Handle else WndParent := ParentWindow; WindowClass.style := CS_VREDRAW + CS_HREDRAW + CS_DBLCLKS; WindowClass.lpfnWndProc := @DefWindowProc; WindowClass.hCursor := LoadCursor(0, IDC_ARROW); WindowClass.hbrBackground := 0; WindowClass.hInstance := HInstance; StrPCopy(WinClassName, ClassName); end; end; begin if SkinnedRecreate then begin DefCreateParams(Params); if NotRightToLeft then TScrollBar_(Self).FRTLFactor := 1 else TScrollBar_(Self).FRTLFactor := -1; end else begin inherited CreateParams(Params); if Skinned(Self) then MustBerecreated := True; end; end; destructor TsScrollBar.Destroy; begin if Assigned(Timer) then begin Timer.Enabled := False; FreeAndNil(Timer); end; if Assigned(FCommonData) then FreeAndNil(FCommonData); inherited Destroy; end; procedure TsScrollBar.DrawBtnBottom(b: TBitmap); begin with FCommonData.SkinManager.ConstData do begin Ci.Bmp := b; PaintItemFast(IndexScrollBottom, MaskScrollBottom, IndexBGScrollBottom, IndexBGHotScrollBottom, s_ScrollBtnBottom, Ci, True, Btn2State, Btn2DRect, Point(0, 0), b, SkinData.SkinManager); Ci.Bmp := FCommonData.FCacheBmp; if FCommonData.SkinManager.IsValidImgIndex(MaskArrowBottom) then with FCommonData.SkinManager do begin if ma[MaskArrowBottom].Bmp = nil then begin p.x := FBtn2Rect.Left + (WidthOf(FBtn2Rect) - WidthOfImage(ma[MaskArrowBottom])) div 2; p.y := FBtn2Rect.Top + (HeightOf(FBtn2Rect) - HeightOfImage(ma[MaskArrowBottom])) div 2; end else if (ma[MaskArrowBottom].Bmp.Height div 2 < HeightOf(FBtn2Rect)) then begin p.x := FBtn2Rect.Left + (WidthOf(FBtn2Rect) - ma[MaskArrowBottom].Bmp.Width div 3) div 2; p.y := FBtn2Rect.Top + (HeightOf(FBtn2Rect) - ma[MaskArrowBottom].Bmp.Height div 2) div 2; end; if (p.x < 0) or (p.y < 0) then Exit; DrawSkinGlyph(b, p, Btn2State, 1, ma[MaskArrowBottom], CI); end; end; end; procedure TsScrollBar.DrawBtnLeft(b: TBitmap); begin with FCommonData.SkinManager.ConstData do begin Ci.Bmp := b; PaintItemFast(IndexScrollLeft, MaskScrollLeft, IndexBGScrollLeft, IndexBGHotScrollLeft, s_ScrollBtnLeft, Ci, True, Btn1State, Btn1DRect, Point(0, 0), b, SkinData.SkinManager); Ci.Bmp := FCommonData.FCacheBmp; if Assigned(FCommonData.SkinManager) and FCommonData.SkinManager.IsValidImgIndex(MaskArrowLeft) then with FCommonData.SkinManager do begin if ma[MaskArrowLeft].Bmp = nil then begin p.x := FBtn1Rect.Left + (WidthOf(FBtn1Rect) - WidthOfImage(ma[MaskArrowLeft])) div 2; p.y := FBtn1Rect.Top + (HeightOf(FBtn1Rect) - HeightOfImage(ma[MaskArrowLeft])) div 2; end else if (ma[MaskArrowLeft].Bmp.Width div 3 < WidthOf(FBtn1Rect)) then begin p.x := FBtn1Rect.Left + (WidthOf(FBtn1Rect) - ma[MaskArrowLeft].Bmp.Width div 3) div 2; p.y := FBtn1Rect.Top + (HeightOf(FBtn1Rect) - ma[MaskArrowLeft].Bmp.Height div 2) div 2; end; if (p.x < 0) or (p.y < 0) then Exit; DrawSkinGlyph(b, p, Btn1State, 1, ma[MaskArrowLeft], CI); end; end; end; procedure TsScrollBar.DrawBtnRight(b: TBitmap); begin with FCommonData.SkinManager.ConstData do begin Ci.Bmp := b; PaintItemFast(IndexScrollRight, MaskScrollRight, IndexBGScrollRight, IndexBGHotScrollRight, s_ScrollBtnRight, Ci, True, Btn2State, Btn2DRect, Point(0, 0), b, SkinData.SkinManager); Ci.Bmp := FCommonData.FCacheBmp; if Assigned(FCommonData.SkinManager) and FCommonData.SkinManager.IsValidImgIndex(MaskArrowRight) then with FCommonData.SkinManager do begin if ma[MaskArrowRight].Bmp = nil then begin p.x := FBtn2Rect.Left + (WidthOf(FBtn2Rect) - WidthOfImage(ma[MaskArrowRight])) div 2; p.y := FBtn2Rect.Top + (HeightOf(FBtn2Rect) - HeightOfImage(ma[MaskArrowRight])) div 2; end else if (ma[MaskArrowRight].Bmp.Width div 3 < WidthOf(FBtn1Rect)) then begin p.x := FBtn2Rect.Left + (WidthOf(FBtn2Rect) - ma[MaskArrowRight].Bmp.Width div 3) div 2; p.y := FBtn2Rect.Top + (HeightOf(FBtn2Rect) - ma[MaskArrowRight].Bmp.Height div 2) div 2; end; if (p.x < 0) or (p.y < 0) then Exit; DrawSkinGlyph(b, p, Btn2State, 1, ma[MaskArrowRight], CI); end; end; end; procedure TsScrollBar.DrawBtnTop(b: TBitmap); begin with FCommonData.SkinManager.ConstData do begin Ci.Bmp := b; PaintItemFast(IndexScrollTop, MaskScrollTop, IndexBGScrollTop, IndexBGHotScrollTop, s_ScrollBtnTop, Ci, True, Btn1State, Btn1DRect, Point(0, 0), b, SkinData.SkinManager); Ci.Bmp := FCommonData.FCacheBmp; if Assigned(FCommonData.SkinManager) and FCommonData.SkinManager.IsValidImgIndex(MaskArrowTop) then with FCommonData.SkinManager do begin if ma[MaskArrowTop].Bmp = nil then begin p.x := FBtn1Rect.Left + (WidthOf(FBtn1Rect) - WidthOfImage(ma[MaskArrowTop])) div 2; p.y := FBtn1Rect.Top + (HeightOf(FBtn1Rect) - HeightOfImage(ma[MaskArrowTop])) div 2; end else if (ma[MaskArrowTop].Bmp.Height div 2 < HeightOf(FBtn1Rect)) then begin p.x := FBtn1Rect.Left + (WidthOf(FBtn1Rect) - ma[MaskArrowTop].Bmp.Width div 3) div 2; p.y := FBtn1Rect.Top + (HeightOf(FBtn1Rect) - ma[MaskArrowTop].Bmp.Height div 2) div 2; end; if (p.x < 0) or (p.y < 0) then Exit; DrawSkinGlyph(b, p, Btn1State, 1, ma[MaskArrowTop], CI); end; end; end; function TsScrollBar.FirstPoint: integer; begin if Kind = sbHorizontal then Result := GetSystemMetrics(SM_CXHSCROLL) else Result := GetSystemMetrics(SM_CYVSCROLL); end; procedure TsScrollBar.Loaded; var OldPos : integer; begin inherited; FCommonData.Loaded; {$IFDEF CHECKXP} if UseThemes and not (SkinData.Skinned and SkinData.SkinManager.SkinData.Active) then begin ControlStyle := ControlStyle - [csParentBackground]; // Patching of bug with TGraphicControls repainting when XPThemes used end; {$ENDIF} if MustBeRecreated then begin // Control must be recreated for the skinned mode using without std blinking MustBeRecreated := False; SkinnedRecreate := True; OldPos := Position; RecreateWnd; Position := OldPos; SkinnedRecreate := False; end; if (csDesigning in ComponentState) and (FSI.nMax = FSI.nMin - 1) {If FSI is not initialized} then begin FSI.nMax := Max; FSI.nMin := Min; FSI.nPos := Position; FSI.nTrackPos := Position; end; end; procedure TsScrollBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i : integer; begin if not Skinned(Self) or not Enabled or not (Button = mbLeft) then inherited else begin if not ControlIsReady(Self) then Exit; AppShowHint := Application.ShowHint; Application.ShowHint := False; MouseOffset := 0; if CanFocus then SetFocus; // If Button1 pressed... if PtInRect(Btn1Rect, Point(x,y)) then begin if Btn1State <> 2 then begin if Kind = sbVertical then ScrollCode := SB_LINEUP else ScrollCode := SB_LINELEFT; Btn1State := 2; DrawingForbidden := True; IncPos(-1); PrepareBtnTimer; end; end // If Button2 pressed... else if PtInRect(Btn2Rect, Point(x,y)) then begin if Btn2State <> 2 then begin Btn2State := 2; if Kind = sbVertical then ScrollCode := SB_LINEDOWN else ScrollCode := SB_LINERIGHT; DrawingForbidden := True; IncPos(1); PrepareBtnTimer; end; end // If slider pressed... else if PtInRect(SliderRect, Point(x,y)) then begin ScrollCode := SB_THUMBTRACK; InitDontChange; if SliderState <> 2 then begin i := CoordToPosition(Point(x, y)); MouseOffset := i - FCurrPos; SliderState := 2; FBeginTrack := true; IncPos(0); PrepareTimer; end; end else begin if PtInRect(Bar1Rect, Point(x,y)) then begin if Kind = sbVertical then ScrollCode := SB_PAGEUP else ScrollCode := SB_PAGELEFT; if Bar1State <> 2 then begin Bar1State := 2; Bar2State := integer(BarIsHot); DrawingForbidden := True; IncPos(-Math.Max(Integer(FSI.nPage), 1)); PrepareBarTimer; end; end else begin if Kind = sbVertical then ScrollCode := SB_PAGEDOWN else ScrollCode := SB_PAGERIGHT; if Bar2State <> 2 then begin Bar1State := integer(BarIsHot); Bar2State := 2; DrawingForbidden := True; IncPos(Math.Max(Integer(FSI.nPage), 1)); PrepareBarTimer; end; end; end; UpdateBar; inherited; end; end; procedure TsScrollBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if not Skinned(Self) or not Enabled then inherited else begin if not ControlIsReady(Self) then Exit; if Assigned(Timer) then begin Timer.Enabled := False; if Assigned(Timer) then FreeAndNil(Timer); end; if PtInRect(SliderRect, Point(X, Y)) or (SliderState = 2) then begin ScrollCode := SB_THUMBPOSITION; Bar1State := integer(BarIsHot); Bar2State := Bar1State; if SliderState = 2 then begin DrawingForbidden := True; IncPos(0); if PtInRect(SliderRect, Point(X, Y)) then SliderState := 1 else SliderState := 0; ClearDontChange; end else end else if PtInRect(Btn1Rect, Point(X, Y)) and (Btn1State = 2) then begin Btn1State := 1; end else if PtInRect(Btn2Rect, Point(X, Y)) and (Btn2State = 2) then begin Btn2State := 1; end else if (Bar1State = 2) then begin Bar1State := integer(BarIsHot); end else if (Bar2State = 2) then begin Bar2State := integer(BarIsHot); end; UpdateBar; ReleaseCapture; inherited; ScrollCode := SB_ENDSCROLL; IncPos(0); Application.ShowHint := AppShowHint; end; end; function TsScrollBar.NotRightToLeft: Boolean; begin Result := not IsRightToLeft or (Kind = sbVertical); end; procedure TsScrollBar.OnTimer(Sender: TObject); begin if not Assigned(Timer) or not ControlIsReady(Self) or (csDestroying in Timer.ComponentState) or FCommonData.FMouseAbove then Exit; SetPos(CoordToPosition(ScreenToClient(acMousePos)) - MouseOffset); SetCapture(Handle); end; procedure TsScrollBar.Paint(MsgDC : hdc); var DC, SavedDC : hdc; bmp : TBitmap; lCI : TCacheInfo; LocalState : integer; c : TsColor; PS : TPaintStruct; BG : TacBGInfo; begin bmp := nil; BeginPaint(Handle, PS); if MsgDC = 0 then DC := GetWindowDC(Handle) else DC := MsgDC; SavedDC := SaveDC(DC); try if DrawingForbidden or not ControlIsReady(Self) or RestrictDrawing or (csDestroying in ComponentState) or (csLoading in ComponentState) or FCommonData.Updating then else begin RepaintNeeded := False; InitCacheBmp(SkinData); if not Enabled then bmp := CreateBmpLike(FCommonData.FCacheBmp) else bmp := FCommonData.FCacheBmp; BG.PleaseDraw := False; if (LinkedControl <> nil) and (LinkedControl is TWinControl) then begin GetBGInfo(@BG, LinkedControl); lCI := BGInfoToCI(@BG); if not (LinkedControl is TCustomForm) then begin dec(lCI.X, LinkedControl.Left); dec(lCI.Y, LinkedControl.Top); end; end else begin GetBGInfo(@BG, Parent); lCI := BGInfoToCI(@BG); end; with FCommonData.SkinManager.ConstData do begin Bar1Rect; if (HeightOf(FBar1Rect) > 0) and (WidthOf(FBar1Rect) > 0) then begin LocalState := Bar1State; if LocalState = 0 then LocalState := integer(BarIsHot); LocalState := LocalState * integer(Enabled); if Kind = sbHorizontal then begin if not Assigned(FCommonData.SkinManager) or not FCommonData.SkinManager.IsValidSkinIndex(IndexScrollBar1H) then Exit; PaintItemFast(IndexScrollBar1H, MaskScrollBar1H, BGScrollBar1H, BGHotScrollBar1H, s_ScrollBar1H, lCi, True, LocalState, FBar1Rect, Point(Left, Top), FCommonData.FCacheBmp, SkinData.SkinManager); end else begin if not Assigned(FCommonData.SkinManager) or not FCommonData.SkinManager.IsValidSkinIndex(IndexScrollBar1V) then Exit; PaintItemFast(IndexScrollBar1V, MaskScrollBar1V, BGScrollBar1V, BGHotScrollBar1V, s_ScrollBar1V, lCi, True, LocalState, FBar1Rect, Point(Left, Top), FCommonData.FCacheBmp, SkinData.SkinManager); end; end; Bar2Rect; if (HeightOf(FBar2Rect) > 0) and (WidthOf(FBar2Rect) > 0) then begin LocalState := Bar2State; if LocalState = 0 then LocalState := integer(BarIsHot); LocalState := LocalState * integer(Enabled); if Kind = sbHorizontal then begin PaintItemFast(IndexScrollBar2H, MaskScrollBar2H, BGScrollBar2H, BGHotScrollBar2H, s_ScrollBar2H, lCi, True, LocalState, FBar2Rect, Point(Left + FBar2Rect.Left, Top + FBar2Rect.Top), FCommonData.FCacheBmp, SkinData.SkinManager); end else begin PaintItemFast(IndexScrollBar2V, MaskScrollBar2V, BGScrollBar2V, BGHotScrollBar2V, s_ScrollBar2V, lCi, True, LocalState, FBar2Rect, Point(Left + FBar2Rect.Left, Top + FBar2Rect.Top), FCommonData.FCacheBmp, SkinData.SkinManager); end; end; end; BitBlt(bmp.Canvas.Handle, 0, 0, bmp.Width, bmp.Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY); if Kind = sbHorizontal then begin DrawBtnLeft(bmp); DrawBtnRight(bmp); end else begin DrawBtnTop(bmp); DrawBtnBottom(bmp); end; if (LinkedControl = nil) or Enabled or not LinkedControl.Enabled then DrawSlider(bmp); BG.PleaseDraw := False; if not Enabled then begin if (LinkedControl <> nil) then begin GetBGInfo(@BG, LinkedControl); lCI := BGInfoToCI(@BG); if lCI.Ready then begin BmpDisabledKind(bmp, FDisabledKind, Parent, lCI, Point(Left - LinkedControl.Left, Top - LinkedControl.Top)); end else begin c.C := lCI.FillColor; FadeBmp(bmp, Rect(0, 0, bmp.Width + 1, bmp.Height + 1), 60, c, 0, 0); end; end else begin lCI := GetParentCache(FCommonData); BmpDisabledKind(bmp, FDisabledKind, Parent, lCI, Point(Left, Top)); end; end; BitBlt(DC, 0, 0, bmp.Width, bmp.Height, bmp.Canvas.Handle, 0, 0, SRCCOPY); end; if not Enabled and Assigned(bmp) then FreeAndNil(bmp); finally RestoreDC(DC, SavedDC); if MsgDC = 0 then ReleaseDC(Handle, DC); EndPaint(Handle, PS); end; end; procedure TsScrollBar.Preparetimer; begin if Assigned(Timer) then FreeAndNil(Timer); SetCapture(Handle); Timer := TTimer.Create(Self); Timer.OnTimer := OnTimer; Timer.Interval := 50; Timer.Enabled := True; end; function TsScrollBar.SliderRect: TRect; begin if Kind = sbHorizontal then begin if Max = Min then FSliderRect.Left := Btn1Rect.Right else FSliderRect.Left := PositionToCoord - SliderSize div 2; FSliderRect.Top := 0; FSliderRect.Right := FSliderRect.Left + SliderSize; FSliderRect.Bottom := Height; end else begin if Max = Min then FSliderRect.Top := Btn1Rect.Bottom else FSliderRect.Top := PositionToCoord - SliderSize div 2; FSliderRect.Left := 0; FSliderRect.Right := Width; FSliderRect.Bottom := FSliderRect.Top + SliderSize; end; Result := FSliderRect; end; function TsScrollBar.SliderSize : integer; const MinSize = 14; begin if FSI.nPage = 0 then Result := MinSize // else if FSI.nPage = FSI.nMax - FSI.nMin + 1 then // Result := WorkSize else Result := math.max(MinSize, Round(FSI.nPage * (WorkSize / (FSI.nMax - Math.Max(Integer(FSI.nPage) - 1, 0) + integer(FSI.nPage) - FSI.nMin)))); end; procedure TsScrollBar.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin if not DrawingForbidden and not InAnimationProcess then DefaultHandler(Message); end; procedure TsScrollBar.WndProc(var Message: TMessage); var OldPos : integer; begin {$IFDEF LOGGED} AddToLog(Message); {$ENDIF} if (Message.Msg = SM_ALPHACMD) and not (csDestroying in ComponentState) then case Message.WParamHi of AC_CTRLHANDLED : begin Message.Result := 1; Exit end; AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end; AC_REMOVESKIN : if LongWord(Message.LParam) = LongWord(SkinData.SkinManager) then begin CommonWndProc(Message, FCommonData); if not SkinnedRecreate then begin OldPos := Position; RecreateWnd; Position := OldPos; end; exit end; AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin CommonWndProc(Message, FCommonData); exit end; AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin CommonWndProc(Message, FCommonData); FCommonData.BGChanged := True; if not SkinnedRecreate then begin SkinnedRecreate := True; OldPos := Position; RecreateWnd; Position := OldPos; SkinnedRecreate := False; end; exit end; AC_ENDPARENTUPDATE : begin FCommonData.Updating := False; Repaint; Exit end end; if Assigned(FCommonData) then begin case Message.Msg of WM_PRINT : if (DefaultManager <> nil) and DefaultManager.Active then begin SendMessage(Handle, WM_PAINT, Message.WParam, Message.LParam); Perform(WM_NCPAINT, Message.WParam, Message.LParam); Exit; end; WM_PAINT, WM_NCHITTEST : if MustBeRecreated and not InAnimationProcess then begin // Control must be recreated for the skinned mode using without std blinking MustBeRecreated := False; SkinnedRecreate := True; OldPos := Position; RecreateWnd; Position := OldPos; SkinnedRecreate := False; end; end; CommonWndProc(Message, FCommonData); end; if Assigned(FCommonData) and Skinned(Self) then begin case Message.Msg of CM_ENABLEDCHANGED : begin inherited; FCommonData.Invalidate; Exit; end; SBM_SETSCROLLINFO : begin with PScrollInfo(Message.LParam)^ do begin if Boolean(fMask and SIF_PAGE) and (FSI.nPage <> nPage) then begin FSI.nPage := PScrollInfo(Message.LParam)^.nPage; RepaintNeeded := LongBool(Message.WParam); end; if Boolean(fMask and SIF_POS) and (FSI.nPos <> nPos) then begin FSI.nPos := PScrollInfo(Message.LParam)^.nPos; RepaintNeeded := LongBool(Message.WParam); end; if Boolean(fMask and SIF_RANGE) and ((FSI.nMin <> nMin) or (FSI.nMax <> nMax)) then begin if (nMax - nMin) < 0 then begin FSI.nMin := 0; FSI.nMax := 0; RepaintNeeded := LongBool(Message.WParam); end else begin FSI.nMin := nMin; FSI.nMax := nMax; RepaintNeeded := LongBool(Message.WParam); end; if Boolean(fMask and SIF_POS) then begin if (Min <> FSI.nMin) then Min := FSI.nMin; if (FSI.nMax <> Max) then Max := FSI.nMax; if (Cardinal(PageSize) <> FSI.nPage) and (FSI.nPage < Cardinal(Max)) then PageSize := FSI.nPage; end; end; if integer(FSI.nPage) < 0 then FSI.nPage := 0 else if integer(FSI.nPage) > (FSI.nMax - FSI.nMin + 1) then FSI.nPage := (FSI.nMax - FSI.nMin + 1); if FSI.nPos < FSI.nMin then FSI.nPos := FSI.nMin else if FSI.nPos > (FSI.nMax - Math.Max(Integer(FSI.nPage) - 1, 0)) then FSI.nPos := (FSI.nMax - Math.Max(Integer(FSI.nPage) - 1, 0)); if (ScrollCode <> SB_THUMBTRACK) then FCurrPos := FSI.nPos; end; UpdateBar; end; SBM_GETSCROLLINFO : begin with PScrollInfo(Message.LParam)^ do begin if Boolean(fMask and SIF_PAGE) then nPage := FSI.nPage; if Boolean(fMask and SIF_POS) then nPos := FSI.nPos; if Boolean(fMask and SIF_TRACKPOS) and (cbSize = SizeOf(TScrollInfo)) then nTrackPos := FSI.nTrackPos; if Boolean(fMask and SIF_RANGE) then begin nMin := FSI.nMin; nMax := FSI.nMax; end; end; end; end; end; inherited WndProc(Message); end; procedure TsScrollBar.DrawSlider(b: TBitmap); var R : TRect; i1 : integer; TmpBmp : TBitmap; begin R := SliderRect; if (Kind = sbVertical) then begin if HeightOf(R) > Height - HeightOf(FBtn1Rect) - HeightOf(FBtn2Rect) then Exit end else if WidthOf(R) > Width - WidthOf(FBtn1Rect) - WidthOf(FBtn2Rect) then Exit; TmpBmp := CreateBmp32(WidthOf(R), HeightOf(R)); BitBlt(TmpBmp.Canvas.Handle, 0, 0, TmpBmp.Width, TmpBmp.Height, FCommonData.FCacheBmp.Canvas.Handle, R.Left, R.Top, SRCCOPY); Ci := MakeCacheInfo(FCommonData.FCacheBmp); with FCommonData.SkinManager.ConstData do begin if Kind = sbHorizontal then begin PaintItemFast(IndexSliderHorz, MaskSliderHorz, ScrollSliderBGHorz, ScrollSliderBGHotHorz, s_ScrollSliderH, Ci, True, SliderState, Rect(0, 0, TmpBmp.Width, TmpBmp.Height), R.TopLeft, TmpBmp, SkinData.SkinManager); i1 := MaskSliderGlyphHorz; end else begin PaintItemFast(IndexSliderVert, MaskSliderVert, ScrollSliderBGVert, ScrollSliderBGHotVert, s_ScrollSliderV, Ci, True, SliderState, Rect(0, 0, TmpBmp.Width, TmpBmp.Height), R.TopLeft, TmpBmp, SkinData.SkinManager); i1 := MaskSliderGlyphVert; end; end; BitBlt(b.Canvas.Handle, R.Left, R.Top, TmpBmp.Width, TmpBmp.Height, TmpBmp.Canvas.Handle, 0, 0, SRCCOPY); FreeAndNil(TmpBmp); Ci.Bmp := FCommonData.FCacheBmp; if Assigned(FCommonData.SkinManager) and FCommonData.SkinManager.IsValidImgIndex(i1) then with FCommonData.SkinManager do begin if FCommonData.SkinManager.ma[i1].Bmp = nil then begin p.x := FSliderRect.Left + (WidthOf(FSliderRect) - WidthOf(ma[i1].R) div ma[i1].ImageCount) div 2 + integer(SliderState = 2); p.y := FSliderRect.Top + (HeightOf(FSliderRect) - HeightOf(ma[i1].R) div (1 + ma[i1].MaskType)) div 2 + integer(SliderState = 2); end else if (((Kind = sbVertical) and (ma[i1].Bmp.Height div 2 < HeightOf(FSliderRect))) or ((Kind = sbHorizontal) and (ma[i1].Bmp.Width div 2 < WidthOf(FSliderRect)))) then begin p.x := FSliderRect.Left + (WidthOf(FSliderRect) - ma[i1].Bmp.Width div 3) div 2 + integer(SliderState = 2); p.y := FSliderRect.Top + (HeightOf(FSliderRect) - ma[i1].Bmp.Height div 2) div 2 + integer(SliderState = 2); end; DrawSkinGlyph(b, p, SliderState, 1, ma[i1], CI); end; end; procedure TsScrollBar.WMNCHitTest(var Message: TWMNCHitTest); var i : integer; begin if Skinned(Self) and Enabled and (not (csDesigning in ComponentState)) then begin if not ControlIsReady(Self) then Exit; if PtInRect(SliderRect, CoordToPoint(SmallPointToPoint(Message.Pos))) or (SliderState = 2) then begin if SliderState <> 2 then SliderState := 1 else begin i := CoordToPosition(CoordToPoint(Point(Message.Pos.X, Message.Pos.Y))) - MouseOffset; if FCurrPos <> i then begin DrawingForbidden := True; SetPos(i); end; end; end else if PtInRect(Btn1Rect, CoordToPoint(SmallPointToPoint(Message.Pos))) then begin if Btn1State <> 2 then Btn1State := 1; end else if PtInRect(Btn2Rect, CoordToPoint(SmallPointToPoint(Message.Pos))) then begin if Btn2State <> 2 then Btn2State := 1; end else if (SliderState = 2) then begin i := CoordToPosition(CoordToPoint(SmallPointToPoint(Message.Pos))); if FCurrPos <> i then begin DrawingForbidden := True; SetPos(i); end; end else begin SliderState := 0; Btn1State := 0; Btn2State := 0; end; if Self <> nil then UpdateBar; end; inherited; end; procedure TsScrollBar.OnBtnTimer(Sender: TObject); begin if not Assigned(Timer) or (csDestroying in Timer.ComponentState) then Exit; if Btn1State = 2 then begin IncPos(-1); end else if Btn2State = 2 then begin IncPos(1); end else begin if Assigned(Timer) then FreeAndNil(Timer); end; if Assigned(Timer) and (Timer.Interval > 50) then Timer.Interval := 50; end; procedure TsScrollBar.PrepareBtnTimer; begin if Assigned(Timer) then FreeAndNil(Timer); Timer := TTimer.Create(Self); Timer.OnTimer := OnBtnTimer; Timer.Interval := 500; Timer.Enabled := True; end; function TsScrollBar.PositionToCoord: integer; begin if Enabled and ((FSI.nMax - FSI.nMin - Math.Max(Integer(FSI.nPage) - 1, 0)) <> 0) then begin if Kind = sbHorizontal then begin Result := FirstPoint + SliderSize div 2 + Round((FCurrPos - FSI.nMin) * ((Width - 2 * FirstPoint - SliderSize) / (FSI.nMax - FSI.nMin - Math.Max(Integer(FSI.nPage) - 1,0)))); end else begin Result := FirstPoint + SliderSize div 2 + Round((FCurrPos - FSI.nMin) * ((Height - 2 * FirstPoint - SliderSize) / (FSI.nMax - FSI.nMin - Math.Max(Integer(FSI.nPage) - 1,0)))); end end else if Kind = sbHorizontal then Result := Width div 2 else Result := Height div 2; end; procedure TsScrollBar.KeyDown(var Key: word; Shift: TShiftState); begin inherited; end; procedure TsScrollBar.WMPaint(var Msg: TWMPaint); begin if DrawingForbidden or (not (csCreating in Controlstate) and Assigned(SkinData.SkinManager) and SkinData.SkinManager.SkinData.Active and not (csDestroying in Componentstate)) then begin Self.FCommonData.Updating := Self.FCommonData.Updating; Paint(Msg.DC); end else inherited; end; procedure TsScrollBar.CMMouseLeave(var Msg: TMessage); begin if Skinned(Self) then begin Btn1State := 0; Btn2State := 0; if SliderState <> 2 then begin SliderState := 0; Bar1State := 0; Bar2State := 0; end; UpdateBar; end else inherited; end; procedure TsScrollBar.PrepareBarTimer; begin if Assigned(Timer) then FreeAndNil(Timer); Timer := TTimer.Create(Self); Timer.OnTimer := OnBarTimer; Timer.Interval := 500; Timer.Enabled := True; end; procedure TsScrollBar.OnBarTimer(Sender: TObject); begin if not Assigned(Timer) or (csDestroying in Timer.ComponentState) then Exit; if (Bar1State = 2) and (FCurrPos > CoordToPosition(ScreenToClient(acMousePos))) then begin IncPos(-Math.Max(Integer(FSI.nPage),1)); end else if (Bar2State = 2) and (FCurrPos < CoordToPosition(ScreenToClient(acMousePos))) then begin IncPos(Math.Max(Integer(FSI.nPage),1)); end else begin if Assigned(Timer) then FreeAndNil(Timer); end; if assigned(Timer) and (Timer.Interval > 50) then Timer.Interval := 50; end; function TsScrollBar.Bar1Rect: TRect; begin FBar1Rect.Left := 0; FBar1Rect.Top := 0; if Kind = sbHorizontal then begin FBar1Rect.Right := PositionToCoord; FBar1Rect.Bottom := Height; end else begin FBar1Rect.Right := Width; FBar1Rect.Bottom := PositionToCoord; end; Result := FBar1Rect; end; function TsScrollBar.Bar2Rect: TRect; begin if Kind = sbHorizontal then begin FBar2Rect.Left := PositionToCoord; FBar2Rect.Top := 0; FBar2Rect.Right := Width; FBar2Rect.Bottom := Height; end else begin FBar2Rect.Left := 0; FBar2Rect.Top := PositionToCoord; FBar2Rect.Right := Width; FBar2Rect.Bottom := Height; end; Result := FBar2Rect; end; procedure TsScrollBar.CMMouseEnter(var Msg: TMessage); begin if Skinned(Self) then begin Bar1State := 1; Bar2State := 1; UpdateBar; end else inherited; end; function TsScrollBar.Btn1DRect: TRect; begin Result := Btn1Rect; with FCommonData.SkinManager.ConstData, FCommonData.SkinManager do if Kind = sbHorizontal then begin if (IndexScrollLeft > -1) and gd[IndexScrollLeft].ReservedBoolean and (MaskScrollLeft > -1) then begin if ma[MaskScrollLeft].Bmp = nil then Result.Right := math.max(GetSystemMetrics(SM_CXHSCROLL), WidthOfImage(ma[MaskScrollLeft])) else Result.Right := math.max(GetSystemMetrics(SM_CXHSCROLL), ma[MaskScrollLeft].Bmp.Width div 3); end; end else begin if (IndexScrollTop > -1) and gd[ConstData.IndexScrollTop].ReservedBoolean and (MaskScrollTop > -1) then begin if ma[ConstData.MaskScrollTop].Bmp = nil then Result.Bottom := math.max(GetSystemMetrics(SM_CYVSCROLL), HeightOfImage(ma[MaskScrollTop])) else Result.Bottom := math.max(GetSystemMetrics(SM_CYVSCROLL), ma[MaskScrollTop].Bmp.Height div 2); end; end; end; procedure TsScrollBar.UpdateBar; begin DrawingForbidden := False; if RepaintNeeded then Paint(0); end; procedure TsScrollBar.SetInteger(Index, Value: integer); begin case Index of 0 : if FBtn1State <> Value then begin RepaintNeeded := True; FBtn1State := Value; case Value of 1, 2 : begin FBtn2State := 0; FSliderState := 0; FBar1State := 1; FBar2State := 1; end; end; end; 1 : if FBtn2State <> Value then begin RepaintNeeded := True; FBtn2State := Value; case Value of 1, 2 : begin FBtn1State := 0; FSliderState := 0; FBar1State := 1; FBar2State := 1; end; end; end; 2 : if FBar1State <> Value then begin RepaintNeeded := True; FBar1State := Value; case Value of 1, 2 : begin FBtn1State := 0; FBtn2State := 0; FSliderState := 0; FBar2State := 1; end; end; end; 3 : if FBar2State <> Value then begin RepaintNeeded := True; FBar2State := Value; case Value of 1, 2 : begin FBtn1State := 0; FBtn2State := 0; FSliderState := 0; FBar1State := 1; end; end; end; 4 : if FSliderState <> Value then begin RepaintNeeded := True; FSliderState := Value; case Value of 1, 2 : begin FBtn1State := 0; FBtn2State := 0; FBar1State := 1; FBar2State := 1; end; end; end; end; end; function TsScrollBar.Btn2DRect: TRect; begin Result := Btn2Rect; with FCommonData.SkinManager.ConstData, FCommonData.SkinManager do if Kind = sbHorizontal then begin if (IndexScrollRight > -1) and gd[IndexScrollRight].ReservedBoolean and (MaskScrollRight > -1) then begin Result.Left := width - math.max(GetSystemMetrics(SM_CXHSCROLL), WidthOfImage(ma[MaskScrollRight])) end; end else begin if (IndexScrollBottom > -1) and gd[IndexScrollBottom].ReservedBoolean and (MaskScrollBottom > -1) then begin Result.Top := height - math.max(GetSystemMetrics(SM_CYVSCROLL), HeightOfImage(ma[MaskScrollBottom])) end; end; end; function TsScrollBar.BarIsHot: boolean; begin Result := ControlIsActive(FCommonData); end; function TsScrollBar.WorkSize: integer; begin if Kind = sbHorizontal then Result := Width - 2 * GetSystemMetrics(SM_CXHSCROLL) else Result := Height - 2 * GetSystemMetrics(SM_CYVSCROLL); end; procedure TsScrollBar.ClearDontChange; begin DontChange := False; end; procedure TsScrollBar.InitDontChange; begin DontChange := True; end; procedure TsScrollBar.SetDisabledKind(const Value: TsDisabledKind); begin if FDisabledKind <> Value then begin FDisabledKind := Value; FCommonData.Invalidate; end; end; procedure TsScrollBar.PlaceToLinked; begin end; procedure TsScrollBar.IncPos(Offset: integer); begin SetPos(FCurrPos + Offset); end; procedure TsScrollBar.SetPos(Pos: integer); const Kinds: array[TScrollBarKind] of DWORD = (SB_HORZ, SB_VERT); Styles: array[TScrollBarKind] of DWORD = (WM_HSCROLL, WM_VSCROLL); var m : TWMScroll; begin FCurrPos := Pos; if FCurrPos < FSI.nMin then FCurrPos := FSI.nMin else if FCurrPos > (FSI.nMax - Math.Max(Integer(FSI.nPage) - 1, 0)) then FCurrPos := (FSI.nMax - Math.Max(Integer(FSI.nPage) - 1, 0)); m.Msg := Styles[Kind]; m.ScrollBar := Handle; m.ScrollCode := SmallInt(ScrollCode); if (m.ScrollCode = SB_THUMBTRACK) then begin if (FSI.nTrackPos = FCurrPos) and (not FBeginTrack) then exit; FBeginTrack := false; FSI.nTrackPos := FCurrPos end else m.Pos := FCurrPos; // v6.45 if m.ScrollCode in [SB_THUMBTRACK, SB_THUMBPOSITION] then m.Pos := FCurrPos else m.Pos := 0; SendMessage(Handle, M.Msg, TMessage(M).WParam, TMessage(M).LParam); RepaintNeeded := true; UpdateBar; if DoSendChanges and Assigned(LinkedControl) and LinkedControl.HandleAllocated then SendMessage(LinkedControl.Handle, M.Msg, TMessage(M).WParam, TMessage(M).LParam); end; procedure TsScrollBar.CNHScroll(var Message: TWMHScroll); begin if not (DoSendChanges and Assigned(LinkedControl)) then inherited; end; procedure TsScrollBar.CNVScroll(var Message: TWMVScroll); begin if not (DoSendChanges and Assigned(LinkedControl)) then inherited; end; function TsScrollBar.GetSkinManager: TsSkinManager; begin Result := SkinData.SkinManager end; procedure TsScrollBar.SetSkinManager(const Value: TsSkinManager); begin SkinData.SkinManager := Value; end; end.
unit Server.Models.Cadastros.FoneAreas; interface uses System.Classes, DB, System.SysUtils, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, dbcbr.mapping.register, Server.Models.Base.TabelaBase; type [Entity] [Table('fone_areas','')] [PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')] TFoneAreas = class(TTabelaBase) private fid: String; fDESCRICAO: String; fArea: String; function Getid: String; procedure Setid(const Value: String); procedure GetDESCRICAO(const Value: String); public constructor create; destructor destroy; override; { Public declarations } [Restrictions([Unique])] [Column('CODIGO', ftString, 5)] [Dictionary('CODIGO','','','','',taCenter)] property id: String read Getid write Setid; [Column('DESCRICAO', ftString, 3)] property DESCRICAO: String read fDESCRICAO write GetDESCRICAO; property Area: String read fArea write fArea; end; implementation { TFoneAreas } uses Infotec.Utils; constructor TFoneAreas.create; begin end; destructor TFoneAreas.destroy; begin inherited; end; procedure TFoneAreas.GetDESCRICAO(const Value: String); begin fDESCRICAO := TInfotecUtils.RemoverEspasDuplas(Value); end; function TFoneAreas.Getid: String; begin Result := fid; end; procedure TFoneAreas.Setid(const Value: String); begin fid := Value; fArea := Value; end; initialization TRegisterClass.RegisterEntity(TFoneAreas); end.
//------------------------------------------------------------------------------ // // Voxelizer // Copyright (C) 2021 by Jim Valavanis // // 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; if not, write to the Free Software // Foundation, inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // // DESCRIPTION: // Voxel stuff // //------------------------------------------------------------------------------ // Site : https://sourceforge.net/projects/voxelizer/ //------------------------------------------------------------------------------ unit vxl_voxels; interface uses Windows, Classes, SysUtils; const MAXVOXELSIZE = 256; type voxelview_t = (vv_none, vv_front, vv_back, vv_left, vv_right, vv_top, vv_down); voxelitem_t = LongWord; voxelitem_p = ^voxelitem_t; voxelbuffer_t = array[0..MAXVOXELSIZE - 1, 0..MAXVOXELSIZE - 1, 0..MAXVOXELSIZE - 1] of voxelitem_t; voxelbuffer_p = ^voxelbuffer_t; voxelbuffer2d_t = array[0..MAXVOXELSIZE - 1, 0..MAXVOXELSIZE - 1] of voxelitem_t; voxelbuffer2d_p = ^voxelbuffer2d_t; procedure vox_getviewbuffer(const buf: voxelbuffer_p; const size: integer; const outbuf: voxelbuffer2d_p; const vv: voxelview_t); procedure vox_shrinkyaxis(const buf: voxelbuffer_p; const size: integer; const amin, amax: integer); procedure vox_removenonvisiblecells(const buf: voxelbuffer_p; const size: integer); procedure VXE_ExportVoxelToSlab6VOX(const voxelbuffer: voxelbuffer_p; const voxelsize: Integer; const palarray: PByteArray; const fname: string); procedure VXE_ExportVoxelToDDVOX(const voxelbuffer: voxelbuffer_p; const voxelsize: Integer; const fname: string); implementation uses vxl_utils, vxl_palettes; procedure vox_getviewbuffer(const buf: voxelbuffer_p; const size: integer; const outbuf: voxelbuffer2d_p; const vv: voxelview_t); var x, y, z: integer; c: voxelitem_t; begin for x := 0 to size - 1 do for y := 0 to size - 1 do outbuf[x, y] := 0; if vv = vv_front then begin for x := 0 to size - 1 do for y := 0 to size - 1 do begin c := 0; for z := 0 to size - 1 do if buf[x, y, z] <> 0 then begin c := buf[x, y, z]; Break; end; outbuf[x, y] := c; end; Exit; end; if vv = vv_back then begin for x := 0 to size - 1 do for y := 0 to size - 1 do begin c := 0; for z := size - 1 downto 0 do if buf[x, y, z] <> 0 then begin c := buf[x, y, z]; Break; end; outbuf[x, y] := c; end; Exit; end; if vv = vv_left then begin for z := 0 to size - 1 do for y := 0 to size - 1 do begin c := 0; for x := 0 to size - 1 do if buf[x, y, z] <> 0 then begin c := buf[x, y, z]; Break; end; outbuf[size - 1 - z, y] := c; end; Exit; end; if vv = vv_right then begin for z := 0 to size - 1 do for y := 0 to size - 1 do begin c := 0; for x := size - 1 downto 0 do if buf[x, y, z] <> 0 then begin c := buf[x, y, z]; Break; end; outbuf[z, y] := c; end; Exit; end; if vv = vv_top then begin for x := 0 to size - 1 do for z := 0 to size - 1 do begin c := 0; for y := 0 to size - 1 do if buf[x, y, z] <> 0 then begin c := buf[x, y, z]; Break; end; outbuf[x, size - 1 - z] := c; end; Exit; end; if vv = vv_down then begin for x := 0 to size - 1 do for z := 0 to size - 1 do begin c := 0; for y := size - 1 downto 0 do if buf[x, y, z] <> 0 then begin c := buf[x, y, z]; Break; end; outbuf[x, z] := c; end; Exit; end; end; procedure vox_shrinkyaxis(const buf: voxelbuffer_p; const size: integer; const amin, amax: integer); var bck: voxelbuffer_p; mn, mx, tmp: integer; x, y, y1, z: integer; factor, mne: Extended; begin if amin = 0 then if amax = 255 then Exit; if amax = 0 then if amin = 255 then Exit; GetMem(bck, MAXVOXELSIZE * MAXVOXELSIZE * size * SizeOf(voxelitem_t)); for x := 0 to size - 1 do for y := 0 to size - 1 do for z := 0 to size - 1 do bck[x, y, z] := buf[x, y, z]; mn := amin; mx := amax; if mn < 0 then mn := 0 else if mn > 255 then mn := 255; if mx < 0 then mx := 0 else if mx > 255 then mx := 255; if mn > mx then begin tmp := mn; mn := mx; mx := tmp; end; for x := 0 to size - 1 do for z := 0 to size - 1 do for y := 0 to size - 1 do buf[x, y, z] := 0; factor := (mx - mn) / MAXVOXELSIZE; if size = MAXVOXELSIZE then begin for x := 0 to size - 1 do for z := 0 to size - 1 do for y := 0 to size - 1 do begin y1 := Round(mn + y * factor); if y1 < 0 then y1 := 0 else if y1 >= MAXVOXELSIZE then y1 := MAXVOXELSIZE; if buf[x, y1, z] = 0 then buf[x, y1, z] := bck[x, y, z]; end; end else begin mne := mn * size / MAXVOXELSIZE; for x := 0 to size - 1 do for z := 0 to size - 1 do for y := 0 to size - 1 do begin y1 := Round(mne + y * factor); if y1 < 0 then y1 := 0 else if y1 >= size then y1 := size; if buf[x, y1, z] = 0 then buf[x, y1, z] := bck[x, y, z]; end; end; FreeMem(bck, MAXVOXELSIZE * MAXVOXELSIZE * size * SizeOf(voxelitem_t)); end; procedure vox_removenonvisiblecells(const buf: voxelbuffer_p; const size: integer); type flags_t = array[0..MAXVOXELSIZE - 1, 0..MAXVOXELSIZE - 1, 0..MAXVOXELSIZE - 1] of boolean; flags_p = ^flags_t; var i, j, k: integer; flags: flags_p; begin GetMem(flags, SizeOf(flags_t)); FillChar(flags^, SizeOf(flags_t), Chr(0)); for i := 1 to size - 2 do begin for j := 1 to size - 2 do for k := 1 to size - 2 do if buf[i, j, k] <> 0 then if buf[i - 1, j, k] <> 0 then if buf[i + 1, j, k] <> 0 then if buf[i, j - 1, k] <> 0 then if buf[i, j + 1, k] <> 0 then if buf[i, j, k - 1] <> 0 then if buf[i, j, k + 1] <> 0 then flags^[i, j, k] := true; end; for i := 1 to size - 2 do begin for j := 1 to size - 2 do for k := 1 to size - 2 do if flags^[i, j, k] then buf[i, j, k] := 0; end; FreeMem(flags, SizeOf(flags_t)); end; procedure VXE_ExportVoxelToSlab6VOX(const voxelbuffer: voxelbuffer_p; const voxelsize: Integer; const palarray: PByteArray; const fname: string); var i: integer; fvoxelsize: Integer; x, y, z: integer; x1, x2, y1, y2, z1, z2: integer; voxdata: PByteArray; voxsize: integer; dpal: array[0..767] of byte; vpal: array[0..255] of LongWord; fs: TFileStream; c: LongWord; begin BackupFile(fname); if voxelsize >= 256 then begin x1 := 1; x2 := 255; y1 := 1; y2 := 255; z1 := 1; z2 := 255; fvoxelsize := 255 end else begin x1 := 0; x2 := voxelsize - 1; y1 := 0; y2 := voxelsize - 1; z1 := 0; z2 := voxelsize - 1; fvoxelsize := voxelsize; end; voxsize := fvoxelsize * fvoxelsize * fvoxelsize; GetMem(voxdata, voxsize); for i := 0 to 255 do vpal[i] := 0; for i := 0 to 764 do dpal[i] := palarray[i + 3]; for i := 765 to 767 do dpal[i] := 0; for i := 0 to 254 do vpal[i] := RGB(dpal[3 * i], dpal[3 * i + 1], dpal[3 * i + 2]); fs := TFileStream.Create(fname, fmCreate); try for i := 0 to 2 do fs.Write(fvoxelsize, SizeOf(integer)); i := 0; for x := x1 to x2 do for y := y1 to y2 do for z := z1 to z2 do begin c := voxelbuffer[x, z, fvoxelsize - 1 - y]; if c = 0 then voxdata[i] := 255 else voxdata[i] := DT_FindAproxColorIndex(@vpal, c, 0, 254); inc(i); end; fs.Write(voxdata^, voxsize); for i := 0 to 767 do dpal[i] := dpal[i] div 4; fs.Write(dpal, 768); finally fs.Free; end; FreeMem(voxdata, voxsize); end; procedure VXE_ExportVoxelToDDVOX(const voxelbuffer: voxelbuffer_p; const voxelsize: Integer; const fname: string); var t: TextFile; xx, yy, zz: integer; skip: integer; begin BackupFile(fname); AssignFile(t, fname); Rewrite(t); Writeln(t, voxelsize); for xx := 0 to voxelsize - 1 do for yy := 0 to voxelsize - 1 do begin skip := 0; for zz := 0 to voxelsize - 1 do begin if voxelbuffer[xx, yy, zz] and $FFFFFF = 0 then begin Inc(skip); if zz = voxelsize - 1 then Writeln(t, 'skip ', skip); end else begin if skip > 0 then begin Write(t, 'skip ', skip, ', '); skip := 0; end; if zz = voxelsize - 1 then Writeln(t, voxelbuffer[xx, yy, zz] and $FFFFFF) else Write(t, voxelbuffer[xx, yy, zz] and $FFFFFF, ', '); end; end; end; CloseFile(t); end; end.
//'========================================================================================= //' //' Project Name : ACR120RWIDValue //' //' Company : Advanced Card Systems LTD. //' //' Author : Mary Anne C.A Arana //' //' Date : September 27, 2005 //' //' Description : This Sample Reads and Writes Value to the Value Block. //' Aided With Increment and Decrement Functions, this was Intended for //' ease of use when the data need to be written on a block was a //' numerical value which later to be use in computation. //' //' //'========================================================================================= unit ACR120RWIDValue; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ACR120U, ExtCtrls, StdCtrls, MyRoutines, login, Read, Write; type TMain = class(TForm) Panel1: TPanel; GroupBox1: TGroupBox; Label1: TLabel; cmbPort: TComboBox; BtnConnect: TButton; BtnSelect: TButton; BtnLogin: TButton; GroupBox2: TGroupBox; BtnReadValue: TButton; Memo1: TMemo; BtnWriteValue: TButton; txtblock: TEdit; Label3: TLabel; Label4: TLabel; Text1: TEdit; cmdInc: TButton; cmdDec: TButton; procedure BtnConnectClick(Sender: TObject); procedure BtnSelectClick(Sender: TObject); procedure BtnLoginClick(Sender: TObject); procedure BtnReadValueClick(Sender: TObject); procedure BtnWriteValueClick(Sender: TObject); procedure cmdIncClick(Sender: TObject); procedure cmdDecClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Main: TMain; Lindx: longint; listbox: Trect; implementation {$R *.DFM} procedure TMain.BtnConnectClick(Sender: TObject); var FirmVer: array[0..30] of Byte; infolen: Byte; Firm: String; temp: smallint; FirmVer1: array[0..19] of Byte; RState : tReaderStatus; begin //'open port connection to ACR120 Reader rHandle := ACR120_Open(cmbPort.itemindex); //'Check if Handle is Valid If rHandle < 0 Then memo1.Lines.add(ErrDef(rHandle)) Else begin memo1.Lines.add('Connected to : ' + cmbPort.Text); //DLL version retcode := ACR120_RequestDLLVersion(@infolen, @FirmVer); Firm := ''; for temp := 0 to infolen - 1 do begin Firm := Firm + Chr(FirmVer[temp]); end; memo1.Lines.add('DLL Version : ' + Firm); //Get the firmware version. retcode := ACR120_Status(rHandle, @FirmVer1, @RState); Firm := ''; for temp := 0 to infolen - 1 do begin if (FirmVer1[temp] <> 0) And (FirmVer1[temp] <> 255) Then begin Firm := Firm + chr(FirmVer1[temp]); end; end; memo1.Lines.add ('Firmware Version : ' + Firm); lindx:=lindx + 1; end; BtnSelect.Enabled := true; end; procedure TMain.BtnSelectClick(Sender: TObject); var HaveTag: array[0..49] of Byte; tmpArray: array[0..9] of Byte; tmpbyte: Byte; SN: String; ctr: Integer; begin //'Selects a single card and returns the card ID (Serial Number) retcode := ACR120_Select(rHandle, @HaveTag, @tmpbyte, @tmpArray); //'Check if Retcode is Error If retcode < 0 Then begin //'Call Function to Define Error Code in string form. memo1.Lines.Add(ErrDef(retcode)); end Else begin memo1.Lines.Add('Select Success'); //'Convert Serial Number to Hex Format. //'(You Can Bypass Hex() Conversion if you want to display serial number as decimal) If (HaveTag[0] = 4) Or (HaveTag[0] = 5) Then begin SN := ''; For ctr := 0 To 6 do begin SN := SN + IntToHex(tmpArray[ctr], 2) + ' '; end; end Else begin SN := ''; For ctr := 0 To 3 do begin SN := SN + IntToHex(tmpArray[ctr], 2) + ' '; end; end; SN := ''; For ctr := 0 To tmpbyte - 1 do begin SN := SN + IntToHex(tmpArray[ctr], 2) + ' '; end; //'Display Serial Number memo1.Lines.Add('Card Serial Number: ' + SN + GetTagType1(HaveTag[0])); BtnLogin.Enabled := true; end; end; procedure TMain.BtnLoginClick(Sender: TObject); begin //show FormLogin formlogin.ShowModal; //Check if Button Press in Login Form is OK or Cancel if buttonOK = true then begin //set buttonOK to false buttonOK := False; //'Log in retcode := ACR120_Login(rHandle, PhysicalSector, LogType, sto, @pKey); //'check if retcode is error If retcode < 0 Then begin memo1.Lines.Add(ErrDef(retcode)); end Else begin memo1.Lines.Add('Login Success: ' + inttostr(retcode)); memo1.Lines.Add('Log at Sector: ' + inttostr(Sec)); memo1.Lines.Add('Login at Physical Sector: ' + inttostr(PhysicalSector)); end; end else memo1.Lines.Add('Login Cancelled...'); GroupBox2.Enabled := true; end; procedure TMain.BtnReadValueClick(Sender: TObject); var ctr: smallint; pVal: Longint; begin //Open FormRead formread.ShowModal; //Check if Button press is OK or Cancel if buttonOK = True then begin //'read specified block value retcode := ACR120_ReadValue(rHandle, BLCK, @pVal); //'check if retcode is error If retcode < 0 Then memo1.Lines.Add(ErrDef(retcode)) Else begin memo1.Lines.Add('Read Block Success: ' + inttostr(retcode)); memo1.Lines.Add('Value Readed: ' + inttostr(pVal)); end; end else memo1.Lines.Add('Read Block Cancelled...'); end; procedure TMain.BtnWriteValueClick(Sender: TObject); begin //show formwrite formwrite.ShowModal; if buttonOK = True then begin //'execute ACR120 write value , Write value to Block retcode := ACR120_WriteValue(rHandle, BLCK, Value2Write); //'check if retcode was error If retcode < 0 Then memo1.Lines.Add(ErrDef(retcode)) Else memo1.Lines.Add('Write Value To Block ' + inttostr(BLCK) + ' Success: ' + inttostr(retcode)); end else memo1.Lines.Add('Write Block Cancelled...'); end; procedure TMain.cmdIncClick(Sender: TObject); var NewVal: Longint; val: Longint; begin //'check block range if within the range of 0 to 3 If (strtoint(txtblock.Text) < 0) Or (strtoint(txtblock.Text) > 3) Then begin application.MessageBox('Block Ranges From 0 to 3 only','Block Out of Range', MB_OK); txtblock.SetFocus; Exit; end Else begin //'set block Blck := strtoint(txtblock.Text); end; //'To access the exact block on the card you must Multiply Sector where you Login by 4 //'add the Block in the sector you want to access Blck := Sec * 4 + Blck; //set val variable val := strtoint64(Text1.Text); //'Increment Value using the value given by the user retcode := ACR120_Inc(rHandle, Blck, val, @NewVal); //'check if retcode is error If retcode < 0 Then memo1.lines.add('Increment Error: ' + inttostr(retcode)) Else memo1.lines.add('Increment Success: ' + inttostr(retcode)); //'display incremented Value memo1.lines.add('Incremented Value of Block ' + inttostr(Blck) + ' : ' + inttostr(NewVal)); end; procedure TMain.cmdDecClick(Sender: TObject); var NewVal: Longint; Blck: Byte; val: Longint; begin //'check block range if within the range of 0 to 3 If (strtoint(txtblock.Text) < 0) Or (strtoint(txtblock.Text) > 3) Then begin application.MessageBox('Block Ranges From 0 to 3 only','Block Out of Range', MB_OK); txtblock.SetFocus; Exit; end Else begin //'set block Blck := strtoint(txtblock.Text); end; //'To access the exact block on the card you must Multiply Sector where you Login by 4 //'add the Block in the sector you want to access Blck := Sec * 4 + Blck; //set val variable val := strtoint64(Text1.Text); //'Decrement Value using the value given by the user retcode := ACR120_Dec(rHandle, Blck, val, @NewVal); //'check if retcode is error If retcode < 0 Then memo1.lines.add('Increment Error: ' + inttostr(retcode)) Else memo1.lines.add('Increment Success: ' + inttostr(retcode)); //'display decremented Value memo1.lines.add('Decremented Value of Block ' + inttostr(Blck) + ' : ' + inttostr(NewVal)); end; end.
unit DUP.Model.Conexao.Firedac.Query; interface uses DUP.Model.Conexao.Interfaces, 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.Comp.DataSet, FireDAC.Comp.Client, System.SysUtils; type TModelConexaoFiredacQuery = class(TInterfacedObject, iModelQuery) private FQuery : TFDQuery; FConexao : iModelConexao; public constructor Create(aValue : iModelConexao) ; destructor Destroy ; override; class function New(aValue : iModelConexao): iModelQuery; function Query : TObject; function OpenTable (aTable : String ) : iModelQuery; end; implementation { TModelConexaoFiredacQuery } constructor TModelConexaoFiredacQuery.Create(aValue : iModelConexao) ; begin FConexao := aValue; FQuery := TFDQuery.Create(nil); FQuery.Connection := TFDConnection(FConexao.Connection); end; destructor TModelConexaoFiredacQuery.Destroy; begin Freeandnil(FQuery); inherited; end; class function TModelConexaoFiredacQuery.New(aValue : iModelConexao): iModelQuery; begin Result := Self.Create(aValue); end; function TModelConexaoFiredacQuery.OpenTable(aTable: String): iModelQuery; begin Result := Self; FQuery.Open('SELECT * FROM ' + aTable); end; function TModelConexaoFiredacQuery.Query: TObject; begin Result := FQuery; end; end.
{ June, 2006 Funkcje transformujące bitmapy i inne związane z grafiką } unit JPP.Graphics; interface uses Winapi.Windows, Winapi.ShellAPI, System.SysUtils, System.Classes, Winapi.Messages, Vcl.Graphics, System.Math, Vcl.Imaging.pngimage ; const MaxPixelCount = 32767; type TRGBRec = packed record R, G, B: BYTE; end; PRGBArray = ^TRGBArray; TRGBArray = array[0..MaxPixelCount] of TRGBRec; TBrightInt = -100..100; {$region ' INT - Bitmap Procs '} function FlipBitmap(Bmp: TBitmap): Boolean; function InvertBitmap(Bmp: TBitmap): Boolean; function MirrorBitmap(Bmp: TBitmap): Boolean; function SetBitmapBrightness(Value: TBrightInt; Bmp: TBitmap): Boolean; overload; function SetBitmapBrightness(Value: TBrightInt; Bmp: TBitmap; ColorUnchanged: TColor): Boolean; overload; function SetBitmapContrast(Value: Single; Bmp: TBitmap): Boolean; overload; function SetBitmapContrast(Value: Single; Bmp: TBitmap; ColorUnchanged: TColor): Boolean; overload; function SetBitmapGamma(Value: Single; Bmp: TBitmap): Boolean; function SetBitmapGammaR(Value: Single; Bmp: TBitmap): Boolean; function SetBitmapGammaG(Value: Single; Bmp: TBitmap): Boolean; function SetBitmapGammaB(Value: Single; Bmp: TBitmap): Boolean; function RotateBitmap90(Bmp: TBitmap): Boolean; function RotateBitmap180(Bmp: TBitmap): Boolean; function RotateBitmap270(Bmp: TBitmap): Boolean; {$endregion} {$region ' INT - PNG Procs '} procedure SetPNGAlpha(PNG: TPNGImage; Alpha: Byte); function SetPngGamma(Value: Single; Png: TPngImage): Boolean; function SetPngBrightness(Value: TBrightInt; Png: TPngImage): Boolean; function SetPngContrast(Value: Single; Png: TPngImage): Boolean; {$endregion} {$region ' INT - Functions from VCL.cyGraphics.pas (http://sourceforge.net/projects/tcycomponents/)'} function ColorSetPercentBrightness(Color: TColor; PercentLight: Integer): TColor; function ColorModify(Color: TColor; incR, incG, incB: Integer): TColor; function ColorSetPercentContrast(Color: TColor; IncPercent: Integer): TColor; function ColorSetPercentPale(Color: TColor; IncPercent: integer): TColor; function MediumColor(Color1, Color2: TColor): TColor; {$endregion} function GetSimilarColor(cl: TColor; Percent: integer; Lighter: Boolean = True): TColor; function GetSimilarColor2(Color: TColor; IncPercent: integer): TColor; // ColorSetPercentPale function PointInRect(Point: TPoint; Rect: TRect): Boolean; function InvertColor(Color: TColor): TColor; function FadeToGray(Color: TColor): TColor; function GetIconCount(const FileName: string): Integer; function ColorToDelphiHex(Color: TColor; Prefix: string = '$'): string; function RGB3(bt: Byte): TColor; function RectHeight(R: TRect): integer; function RectWidth(R: TRect): integer; implementation function RectWidth(R: TRect): integer; begin Result := R.Left - R.Right; end; function RectHeight(R: TRect): integer; begin Result := R.Bottom - R.Top; end; function RGB3(bt: Byte): TColor; begin Result := RGB(bt,bt,bt); end; function ColorToDelphiHex(Color: TColor; Prefix: string = '$'): string; var r, g, b: Byte; begin r := GetRValue(Color); g := GetGValue(Color); b := GetBValue(Color); Result := Prefix + '00' + IntToHex(b, 2) + IntToHex(g, 2) + IntToHex(r, 2); end; function GetIconCount(const FileName: string): Integer; begin Result := ExtractIcon(hInstance, PChar(FileName), DWORD(-1)); end; function FadeToGray(Color: TColor): TColor; var LBytGray: byte; begin Color := ColorToRGB(Color); LBytGray := HiByte(GetRValue(Color) * 74 + GetGValue(Color) * 146 + GetBValue(Color) * 36); Result := RGB(LBytGray, LBytGray, LBytGray); end; function InvertColor(Color: TColor): TColor; begin Result := ColorToRGB(Color) xor $00FFFFFF; end; function PointInRect(Point: TPoint; Rect: TRect): Boolean; begin Result := (Point.X >= Rect.Left) and (Point.X <= Rect.Width) and (Point.Y >= Rect.Top) and (Point.Y <= Rect.Bottom); end; function GetSimilarColor2(Color: TColor; IncPercent: integer): TColor; // ColorSetPercentPale from JPP.Graphics var r, g, b: Integer; begin r := GetRValue(Color); g := GetGValue(Color); b := GetBValue(Color); r := r + Round((255 - r) * IncPercent / 100); g := g + Round((255 - g) * IncPercent / 100); b := b + Round((255 - b) * IncPercent / 100); if r < 0 then r := 0; if r > 255 then r := 255; if g < 0 then g := 0; if g > 255 then g := 255; if b < 0 then b := 0; if b > 255 then b := 255; Result := RGB(r,g,b); end; function GetSimilarColor(cl: TColor; Percent: integer; Lighter: Boolean = True): TColor; var r, g, b: integer; x: integer; begin cl := ColorToRgb(cl); r := GetRValue(cl); g := GetGValue(cl); b := GetBValue(cl); x := r * Percent div 100; if Lighter then r := r + x else r := r - x; if r > 255 then r := 255; if r < 0 then r := 0; x := g * Percent div 100; if Lighter then g := g + x else g := g - x; if g > 255 then g := 255; if g < 0 then g := 0; x := b * Percent div 100; if Lighter then b := b + x else b := b - x; if b > 255 then b := 255; if b < 0 then b := 0; Result := RGB(r, g, b); end; {$region ' Functions from VCL.cyGraphics.pas (http://sourceforge.net/projects/tcycomponents/)'} function ColorSetPercentBrightness(Color: TColor; PercentLight: Integer): TColor; var r, g, b, incValue: Integer; begin incValue := MulDiv(255, PercentLight, 100); Color:= ColorToRGB(Color); r := GetRValue(Color); g := GetGValue(Color); b := GetBValue(Color); r := r + incValue; g := g + incValue; b := b + incValue; if r < 0 then r := 0; if r > 255 then r := 255; if g < 0 then g := 0; if g > 255 then g := 255; if b < 0 then b := 0; if b > 255 then b := 255; RESULT := RGB(r,g,b); end; function ColorModify(Color: TColor; incR, incG, incB: Integer): TColor; var r,g,b: Integer; begin Color:= ColorToRGB(Color); r:= GetRValue(Color); g:= GetGValue(Color); b:= GetBValue(Color); r := r + incR; g := g + incG; b := b + incB; if r < 0 then r := 0; if r > 255 then r := 255; if g < 0 then g := 0; if g > 255 then g := 255; if b < 0 then b := 0; if b > 255 then b := 255; Result := RGB(r,g,b); end; function ColorSetPercentContrast(Color: TColor; IncPercent: Integer): TColor; var r, g, b, Media: Integer; begin if IncPercent > 100 then IncPercent := 100; if IncPercent < -100 then IncPercent := -100; Color:= ColorToRGB(Color); r := GetRValue(Color); g := GetGValue(Color); b := GetBValue(Color); Media := (r+g+b) Div 3; r := r + Round( (r - Media) * (IncPercent / 100) ); g := g + Round( (g - Media) * (IncPercent / 100) ); b := b + Round( (b - Media) * (IncPercent / 100) ); if r < 0 then r := 0; if r > 255 then r := 255; if g < 0 then g := 0; if g > 255 then g := 255; if b < 0 then b := 0; if b > 255 then b := 255; RESULT := RGB(r,g,b); end; function ColorSetPercentPale(Color: TColor; IncPercent: integer): TColor; var r, g, b: Integer; begin r := GetRValue(Color); g := GetGValue(Color); b := GetBValue(Color); r := r + Round((255 - r) * IncPercent / 100); g := g + Round((255 - g) * IncPercent / 100); b := b + Round((255 - b) * IncPercent / 100); if r < 0 then r := 0; if r > 255 then r := 255; if g < 0 then g := 0; if g > 255 then g := 255; if b < 0 then b := 0; if b > 255 then b := 255; RESULT := RGB(r,g,b); end; function MediumColor(Color1, Color2: TColor): TColor; var r,g,b: Integer; begin if Color1 <> Color2 then begin Color1 := ColorToRGB(Color1); Color2 := ColorToRGB(Color2); r := ( GetRValue(Color1) + GetRValue(Color2) ) div 2; g := ( GetGValue(Color1) + GetGValue(Color2) ) div 2; b := ( GetBValue(Color1) + GetBValue(Color2) ) div 2; // RESULT := TColor( RGB(r, g, b) ); RESULT := RGB(r, g, b); end else RESULT := Color1; end; {$endregion} {$region ' PNG Procs '} procedure SetPNGAlpha(PNG: TPNGImage; Alpha: Byte); var pScanline: pByteArray; nScanLineCount, nPixelCount : Integer; begin if Alpha = 255 then begin PNG.RemoveTransparency; end else begin PNG.CreateAlpha; for nScanLineCount := 0 to PNG.Height - 1 do begin pScanline := PNG.AlphaScanline[nScanLineCount]; for nPixelCount := 0 to Png.Width - 1 do pScanline[nPixelCount] := Alpha; end; end; PNG.Modified := True; end; function SetPngContrast(Value: Single; Png: TPngImage): Boolean; var LUT: array[0..255] of double; i, j, RValue, GValue, BValue: Integer; R, G, B: array[0..255] of double; Color: TColor; p: PRGBArray; begin Result := False; if Png.Empty then Exit; //Bmp.PixelFormat := pf24Bit; if Value < 0.05 then Value := 0.05; for i := 0 to 255 do if (Value * i) > 255 then LUT[i] := 255 else LUT[i] := Value * i; FillChar(R, SizeOf(R), 0); FillChar(G, SizeOf(G), 0); FillChar(B, SizeOf(B), 0); for i := 0 to Png.Height - 1 do begin p := Png.ScanLine[i]; for j := 0 to Png.Width - 1 do begin RValue := p[j].R; GValue := p[j].G; BValue := p[j].B; Color := Round(LUT[RValue]) + (Round(LUT[GValue]) shl 8) + (Round(LUT[BValue]) shl 16); p[j].R := Color and $000000FF; p[j].G := (Color and $0000FF00) shr 8; p[j].B := (Color and $00FF0000) shr 16; end; end; Result := True; end; function SetPngBrightness(Value: TBrightInt; Png: TPngImage): Boolean; var i, j, Val: integer; Line: PRGBArray; begin Result := False; if Png.Empty then Exit; Val := Value * 255 div 100; if Val > 0 then for i := 0 to Png.Height - 1 do begin Line := Png.ScanLine[i]; for j := 0 to Png.Width - 1 do with Line[j] do begin if B + Val > 255 then B := 255 else B := B + Val; if G + Val > 255 then G := 255 else G := G + Val; if R + Val > 255 then R := 255 else R := R + Val; end; end // for i else // Val < 0 for i := 0 to Png.Height - 1 do begin Line := Png.ScanLine[i]; for j := 0 to Png.Width - 1 do with Line[j] do begin if B + Val < 0 then B := 0 else B := B + Val; if G + Val < 0 then G := 0 else G := G + Val; if R + Val < 0 then R := 0 else R := R + Val; end; end; // for i Result := True; end; function SetPngGamma(Value: Single; Png: TPngImage): Boolean; var i, j, RValue, GValue, BValue: integer; R, G, B: array[0..255] of double; Color: TColor; LUT: array[0..255] of double; p: PRGBArray; begin Result := False; if Png.Empty then Exit; //Png.PixelFormat := pf24Bit; if Value < 0.1 then Value := 0.1; for i := 0 to 255 do if (255 * Power(i / 255, 1 / Value)) > 255 then LUT[i] := 255 else LUT[i] := 255 * Power(i / 255, 1 / Value); FillChar(R, SizeOf(R), 0); FillChar(G, SizeOf(G), 0); FillChar(B, SizeOf(B), 0); for i := 0 to Png.Height - 1 do begin p := Png.ScanLine[i]; for j := 0 to Png.Width - 1 do begin RValue := p[j].R; GValue := p[j].G; BValue := p[j].B; Color := Round(LUT[RValue]) + (Round(LUT[GValue]) shl 8) + (Round(LUT[BValue]) shl 16); p[j].R := Color and $000000FF; p[j].G := (Color and $0000FF00) shr 8; p[j].B := (Color and $00FF0000) shr 16; end; end; Result := True; end; {$endregion PNG Procs} {$region ' Bitmap Procs '} function RotateBitmap180(Bmp: TBitmap): Boolean; begin Result := False; if Bmp.Empty then Exit; MirrorBitmap(Bmp); FlipBitmap(Bmp); Result := True; end; function RotateBitmap270(Bmp: TBitmap): Boolean; var p: PRGBArray; i, j: integer; Bmp2: TBitmap; Color: TColor; k: integer; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; Bmp2 := TBitmap.Create; try Bmp2.Width := Bmp.Height; Bmp2.Height := Bmp.Width; Bmp2.PixelFormat := pf24Bit; for i := 0 to Bmp.Height - 1 do begin p := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do begin Color := p[j].B + (p[j].G shl 8) + (p[j].R shl 16); k := Bmp2.Height - j; Bmp2.Canvas.Pixels[i, k] := Color; end; end; Bmp.Assign(Bmp2); finally Bmp2.Free; end; Result := True; end; function RotateBitmap90(Bmp: TBitmap): Boolean; var p: PRGBArray; i, j: integer; Bmp2: TBitmap; Color: TColor; w, k: integer; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; Bmp2 := TBitmap.Create; try Bmp2.Width := Bmp.Height; Bmp2.Height := Bmp.Width; Bmp2.PixelFormat := pf24Bit; for i := 0 to Bmp.Height - 1 do begin p := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do begin Color := p[j].B + (p[j].G shl 8) + (p[j].R shl 16); k := j; w := Bmp2.Width - i; Bmp2.Canvas.Pixels[w, k] := Color; end; end; Bmp.Assign(Bmp2); finally Bmp2.Free; end; Result := True; end; function SetBitmapGammaB(Value: Single; Bmp: TBitmap): Boolean; var i, j, RValue, GValue, BValue: integer; R, G, B: array[0..255] of double; Color: TColor; LUT: array[0..255] of double; p: PRGBArray; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; if Value < 0.1 then Value := 0.1; for i := 0 to 255 do if (255 * Power(i / 255, 1 / Value)) > 255 then LUT[i] := 255 else LUT[i] := 255 * Power(i / 255, 1 / Value); FillChar(R, SizeOf(R), 0); FillChar(G, SizeOf(G), 0); FillChar(B, SizeOf(B), 0); for i := 0 to Bmp.Height - 1 do begin p := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do begin RValue := p[j].R; GValue := p[j].G; BValue := p[j].B; Color := Round(LUT[RValue]) + (Round(LUT[GValue]) shl 8) + (Round(LUT[BValue]) shl 16); p[j].R := Color and $000000FF; //p[j].G := (Color and $0000FF00) shr 8; //p[j].B := (Color and $00FF0000) shr 16; end; end; Result := True; end; function SetBitmapGammaG(Value: Single; Bmp: TBitmap): Boolean; var i, j, RValue, GValue, BValue: integer; R, G, B: array[0..255] of double; Color: TColor; LUT: array[0..255] of double; p: PRGBArray; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; if Value < 0.1 then Value := 0.1; for i := 0 to 255 do if (255 * Power(i / 255, 1 / Value)) > 255 then LUT[i] := 255 else LUT[i] := 255 * Power(i / 255, 1 / Value); FillChar(R, SizeOf(R), 0); FillChar(G, SizeOf(G), 0); FillChar(B, SizeOf(B), 0); for i := 0 to Bmp.Height - 1 do begin p := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do begin RValue := p[j].R; GValue := p[j].G; BValue := p[j].B; Color := Round(LUT[RValue]) + (Round(LUT[GValue]) shl 8) + (Round(LUT[BValue]) shl 16); //p[j].R := Color and $000000FF; p[j].G := (Color and $0000FF00) shr 8; //p[j].B := (Color and $00FF0000) shr 16; end; end; Result := True; end; function SetBitmapGammaR(Value: Single; Bmp: TBitmap): Boolean; var i, j, RValue, GValue, BValue: integer; R, G, B: array[0..255] of double; Color: TColor; LUT: array[0..255] of double; p: PRGBArray; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; if Value < 0.1 then Value := 0.1; for i := 0 to 255 do if (255 * Power(i / 255, 1 / Value)) > 255 then LUT[i] := 255 else LUT[i] := 255 * Power(i / 255, 1 / Value); FillChar(R, SizeOf(R), 0); FillChar(G, SizeOf(G), 0); FillChar(B, SizeOf(B), 0); for i := 0 to Bmp.Height - 1 do begin p := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do begin RValue := p[j].R; GValue := p[j].G; BValue := p[j].B; Color := Round(LUT[RValue]) + (Round(LUT[GValue]) shl 8) + (Round(LUT[BValue]) shl 16); //p[j].R := Color and $000000FF; //p[j].G := (Color and $0000FF00) shr 8; p[j].B := (Color and $00FF0000) shr 16; end; end; Result := True; end; function SetBitmapGamma(Value: Single; Bmp: TBitmap): Boolean; var i, j, RValue, GValue, BValue: integer; R, G, B: array[0..255] of double; Color: TColor; LUT: array[0..255] of double; p: PRGBArray; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; if Value < 0.1 then Value := 0.1; for i := 0 to 255 do if (255 * Power(i / 255, 1 / Value)) > 255 then LUT[i] := 255 else LUT[i] := 255 * Power(i / 255, 1 / Value); FillChar(R, SizeOf(R), 0); FillChar(G, SizeOf(G), 0); FillChar(B, SizeOf(B), 0); for i := 0 to Bmp.Height - 1 do begin p := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do begin RValue := p[j].R; GValue := p[j].G; BValue := p[j].B; Color := Round(LUT[RValue]) + (Round(LUT[GValue]) shl 8) + (Round(LUT[BValue]) shl 16); p[j].R := Color and $000000FF; p[j].G := (Color and $0000FF00) shr 8; p[j].B := (Color and $00FF0000) shr 16; end; end; Result := True; end; function SetBitmapContrast(Value: Single; Bmp: TBitmap; ColorUnchanged: TColor): Boolean; var LUT: array[0..255] of double; i, j, RValue, GValue, BValue: Integer; R, G, B: array[0..255] of double; Color, cl: TColor; p: PRGBArray; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; if Value < 0.05 then Value := 0.05; for i := 0 to 255 do if (Value * i) > 255 then LUT[i] := 255 else LUT[i] := Value * i; FillChar(R, SizeOf(R), 0); FillChar(G, SizeOf(G), 0); FillChar(B, SizeOf(B), 0); for i := 0 to Bmp.Height - 1 do begin p := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do begin cl := RGB(p[j].R, p[j].G, p[j].B); if cl = ColorUnchanged then Continue; RValue := p[j].R; GValue := p[j].G; BValue := p[j].B; Color := Round(LUT[RValue]) + (Round(LUT[GValue]) shl 8) + (Round(LUT[BValue]) shl 16); p[j].R := Color and $000000FF; p[j].G := (Color and $0000FF00) shr 8; p[j].B := (Color and $00FF0000) shr 16; end; end; Result := True; end; function SetBitmapContrast(Value: Single; Bmp: TBitmap): Boolean; var LUT: array[0..255] of double; i, j, RValue, GValue, BValue: Integer; R, G, B: array[0..255] of double; Color: TColor; p: PRGBArray; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; if Value < 0.05 then Value := 0.05; for i := 0 to 255 do if (Value * i) > 255 then LUT[i] := 255 else LUT[i] := Value * i; FillChar(R, SizeOf(R), 0); FillChar(G, SizeOf(G), 0); FillChar(B, SizeOf(B), 0); for i := 0 to Bmp.Height - 1 do begin p := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do begin RValue := p[j].R; GValue := p[j].G; BValue := p[j].B; Color := Round(LUT[RValue]) + (Round(LUT[GValue]) shl 8) + (Round(LUT[BValue]) shl 16); p[j].R := Color and $000000FF; p[j].G := (Color and $0000FF00) shr 8; p[j].B := (Color and $00FF0000) shr 16; end; end; Result := True; end; function SetBitmapBrightness(Value: TBrightInt; Bmp: TBitmap; ColorUnchanged: TColor): Boolean; var i, j, Val: integer; Line: PRGBArray; Color: TColor; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; Val := Value * 255 div 100; if Val > 0 then for i := 0 to Bmp.Height - 1 do begin Line := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do with Line[j] do begin Color := RGB(R, G, B); if Color = ColorUnchanged then Continue; if B + Val > 255 then B := 255 else B := B + Val; if G + Val > 255 then G := 255 else G := G + Val; if R + Val > 255 then R := 255 else R := R + Val; end; end // for i else // Val < 0 for i := 0 to Bmp.Height - 1 do begin Line := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do with Line[j] do begin if B + Val < 0 then B := 0 else B := B + Val; if G + Val < 0 then G := 0 else G := G + Val; if R + Val < 0 then R := 0 else R := R + Val; end; end; // for i Result := True; end; function SetBitmapBrightness(Value: TBrightInt; Bmp: TBitmap): Boolean; var i, j, Val: integer; Line: PRGBArray; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; Val := Value * 255 div 100; if Val > 0 then for i := 0 to Bmp.Height - 1 do begin Line := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do with Line[j] do begin if B + Val > 255 then B := 255 else B := B + Val; if G + Val > 255 then G := 255 else G := G + Val; if R + Val > 255 then R := 255 else R := R + Val; end; end // for i else // Val < 0 for i := 0 to Bmp.Height - 1 do begin Line := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do with Line[j] do begin if B + Val < 0 then B := 0 else B := B + Val; if G + Val < 0 then G := 0 else G := G + Val; if R + Val < 0 then R := 0 else R := R + Val; end; end; // for i Result := True; end; function MirrorBitmap(Bmp: TBitmap): Boolean; var i, j: Integer; Line: PRGBArray; RGBRec: TRGBRec; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; for i := 0 to Bmp.Height - 1 do begin Line := Bmp.ScanLine[i]; for j := 0 to (Bmp.Width - 1) div 2 do begin RGBRec := Line[j]; Line[j] := Line[Bmp.Width - j - 1]; Line[Bmp.Width - j - 1] := RGBRec; end; end; Result := True; end; function InvertBitmap(Bmp: TBitmap): Boolean; var i, j: Integer; Line: PRGBArray; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; for i := 0 to Bmp.Height - 1 do begin Line := Bmp.ScanLine[i]; for j := 0 to Bmp.Width - 1 do with Line[j] do begin B := not B; G := not G; R := not R; end; end; Result := True; end; function FlipBitmap(Bmp: TBitmap): Boolean; var i, j: Integer; Line, Line2: PRGBArray; RGBRec: TRGBRec; begin Result := False; if Bmp.Empty then Exit; Bmp.PixelFormat := pf24Bit; for i := 0 to (Bmp.Height - 1) div 2 do begin Line := Bmp.ScanLine[i]; Line2 := Bmp.ScanLine[Bmp.Height - i - 1]; for j := 0 to Bmp.Width - 1 do begin RGBRec := Line[j]; Line[j] := Line2[j]; Line2[j] := RGBRec; end; end; Result := True; end; {$endregion Bitmap Procs} end.
unit PrgrBar; interface uses Windows, Messages, SysUtils, Classes, Controls, Graphics, Dialogs; type TPrgrBar = class(TCustomControl) private fColorFirst:TColor; fColorSecond:TColor; fColorThird:TColor; fColorEmpty:TColor; fMin:Integer; fMax:Integer; fPos:Integer; Procedure Set_ColorFirst(Value:TColor); Procedure Set_ColorSecond(Value:TColor); Procedure Set_ColorThird(Value:TColor); Procedure Set_ColorEmpty(Value:TColor); Procedure Set_Min(Value:Integer); Procedure Set_Max(Value:Integer); Procedure Set_Pos(Value:Integer); protected procedure Resize; override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published Property ColorFirst:TColor Read fColorFirst Write Set_ColorFirst; Property ColorSecond:TColor Read fColorSecond Write Set_ColorSecond; Property ColorThird:TColor Read fColorThird Write Set_ColorThird; Property ColorEmpty:TColor Read fColorEmpty Write Set_ColorEmpty; Property Min:Integer Read fMin Write Set_Min; Property Max:Integer Read fMax Write Set_Max; Property Pos:Integer Read fPos Write Set_Pos; Property Tag; Property Enabled; Property OnMouseDown; Property OnMouseMove; Property OnMouseUp; Property OnClick; Property OnDblClick; Property Color; Property OnEnter; Property OnExit; Property OnKeyPress; Property OnKeyDown; Property OnKeyUp; end; procedure Register; implementation procedure Register; begin RegisterComponents('MUSIC_PRO', [TPrgrBar]); end; constructor TPrgrBar.Create(AOwner: TComponent); begin inherited Create(AOwner); DoubleBuffered:=True; Width:=44; fMin:=-12; fMax:=12; fPos:=12; Color:=$00A3B4BE; ColorFirst:=$009CE8F5; ColorSecond:=$001ACBEA; ColorThird:=$0013AECA; ColorEmpty:=$00F7F4F2; end; destructor TPrgrBar.Destroy; begin inherited; end; Procedure TPrgrBar.Set_ColorFirst(Value:TColor); begin fColorFirst:=Value; Invalidate; end; Procedure TPrgrBar.Set_ColorSecond(Value:TColor); begin fColorSecond:=Value; Invalidate; end; Procedure TPrgrBar.Set_ColorThird(Value:TColor); begin fColorThird:=Value; Invalidate; end; Procedure TPrgrBar.Set_ColorEmpty(Value:TColor); begin fColorEmpty:=Value; Invalidate; end; Procedure TPrgrBar.Set_Min(Value:Integer); begin if (Value<=fPos) And (Value<fMax) Then Begin fMin:=Value; Invalidate; End; end; Procedure TPrgrBar.Set_Max(Value:Integer); begin if (Value>=fPos) And (Value>fMin) Then Begin fMax:=Value; Invalidate; End; end; Procedure TPrgrBar.Set_Pos(Value:Integer); begin if (Value>=fMin) And (Value<=fMax) Then Begin fPos:=Value; Invalidate; End; end; procedure TPrgrBar.Resize; Begin InHerited; Width:=(Width Div 2)*2; If Width<50 Then Width:=50; Height:=6*Width; End; procedure TPrgrBar.Paint; Const HeightRect=5; Var UpperCorner,LowerCorner:Array [0..2] Of TPoint; HeightCurrent, IndexRect, NbRect, PosInDiv:Integer; ElemRect:TRect; Begin InHerited; With Canvas Do Begin Pen.Width:=2; UpperCorner[0]:=Point(0,Height); UpperCorner[1]:=Point(0,0); UpperCorner[2]:=Point(Width,0); LowerCorner[0]:=Point(0,Self.Height); LowerCorner[1]:=Point(Width,Height); LowerCorner[2]:=Point(Width,0); Pen.Color:=ClWhite; Polyline(UpperCorner); Pen.Color:=$00657271; Polyline(LowerCorner); Pen.Width:=1; HeightCurrent:=8*Height Div 10; NbRect:=HeightCurrent Div HeightRect; PosInDiv:=(fMax-fPos)*NbRect Div (fMax-fMin); For IndexRect:=0 To (NbRect-1) Do With ElemRect Do Begin Left:=Width Div 3; Right:=2*Width Div 3; Top:=Height Div 10 + IndexRect*HeightRect ; Bottom:=Top+HeightRect; If IndexRect<PosInDiv Then Brush.Color:=fColorEmpty Else Begin Brush.Color:=ColorThird; If IndexRect<(2*NbRect Div 3) Then Brush.Color:=ColorSecond; If IndexRect<(NbRect Div 3) Then Brush.Color:=ColorFirst; End; Pen.Color:=ClBlack; Rectangle(ElemRect); End; End; End; end.
{ ******************************************************************************* Title: T2TiPDV Description: Permite a digitação e importação de um número inteiro. The MIT License Copyright: Copyright (C) 2015 T2Ti.COM 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. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije @version 1.0 ******************************************************************************* } unit UImportaNumero; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, UBase, Dialogs, StdCtrls, JvExStdCtrls, JvEdit, JvValidateEdit, JvExControls, JvLabel, JvButton, JvCtrls, Buttons, JvExButtons, JvBitBtn, pngimage, ExtCtrls, Vcl.Mask, JvExMask, JvToolEdit, JvBaseEdits, Vcl.Imaging.jpeg; type TFImportaNumero = class(TFBase) LabelEntrada: TJvLabel; JvBitBtn1: TJvBitBtn; JvImgBtn1: TJvImgBtn; Image1: TImage; EditEntrada: TJvCalcEdit; Image2: TImage; procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FImportaNumero: TFImportaNumero; implementation {$R *.dfm} procedure TFImportaNumero.FormActivate(Sender: TObject); begin Color := StringToColor(Sessao.Configuracao.CorJanelasInternas); end; end.
unit SException; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ImgList, StdCtrls, Buttons, ComCtrls, ExtCtrls, DBTables, DB; type TTipoMsg = ( tmPadrao, tmErro, tmAviso, tmInformacao, tmPergunta); TFrmSException = class(TForm) PnlMsg: TPanel; RedMsg: TRichEdit; RedMsgDetalhada: TRichEdit; PnlIcone: TPanel; BtnGeraLogTxt: TSpeedButton; Splitter1: TSplitter; PnlControle: TPanel; BtnOK: TBitBtn; BtnDetalhes: TBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnGeraLogTxtClick(Sender: TObject); procedure BtnDetalhesClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Splitter1CanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); private FTipoMsg: TTipoMsg; procedure SetTipoMsg(const Value: TTipoMsg); procedure TrataTodosOsErros(E: Exception; vpsMsgErro: String; vptTipoMsg: TTipoMsg); procedure TrataErroJaCatalogado(E: Exception); procedure MostraDetalhes(vpbMostraDetalhes: Boolean); { Private declarations } protected property TipoMsg: TTipoMsg read FTipoMsg write SetTipoMsg; { Protected declarations } public { Public declarations } end; { TSException } TSException = class(Exception) private FSender: TObject; FTipoMsg: TTipoMsg; { Private declarations } protected { Protected declarations } public constructor Create(const vptSender: TObject; vpsMsg: String); overload; constructor Create(const vptSender: TObject; vpsMsg: String; vptTipoMsg: TTipoMsg); overload; property Sender: TObject read FSender default Nil; property TipoMsg: TTipoMsg read FTipoMsg; { Public declarations } end; { TSExceptionError } TSExceptionError = class(TSException) end; { TSExceptionWarning } TSExceptionWarning = class(TSException) end; { TSExceptionMessage } TSExceptionMessage = class(TSException) end; procedure MsgErro(E: Exception); overload; procedure MsgErro(E: Exception; vpsMsgErro: String; vptTipoMsg: TTipoMsg); overload; var FrmSException: TFrmSException; vliHeightForm: Integer; vliHeightPnlMsg: Integer; implementation {$R *.DFM} uses UConst, UFerramentas; procedure MsgErro(E: Exception); begin MsgErro(E, '', tmPadrao); end; procedure MsgErro(E: Exception; vpsMsgErro: String; vptTipoMsg: TTipoMsg); overload; begin FrmSException := TFrmSException.Create(Application); FrmSException.TrataTodosOsErros(E, vpsMsgErro, vptTipoMsg); FrmSException.Free; end; { TSException } constructor TSException.Create(const vptSender: TObject; vpsMsg: String); begin Create(Sender, vpsMsg, tmPadrao); end; constructor TSException.Create(const vptSender: TObject; vpsMsg: String; vptTipoMsg: TTipoMsg); begin FSender := vptSender; FTipoMsg := vptTipoMsg; inherited Create(vpsMsg); end; procedure TFrmSException.TrataTodosOsErros(E: Exception; vpsMsgErro: String; vptTipoMsg: TTipoMsg); begin RedMsg.Lines.Text := E.Message; RedMsgDetalhada.Lines.Text := E.Message; if (vptTipoMsg = tmPadrao) then Self.TipoMsg := tmErro else Self.TipoMsg := TipoMsg; if (Trim(vpsMsgErro) <> '') then RedMsg.Lines.Text := vpsMsgErro else TrataErroJaCatalogado(E); MostraDetalhes(False); // MostraDetalhes(RedMsg.Lines.Text <> RedMsgDetalhada.Lines.Text); ShowModal; end; procedure TFrmSException.TrataErroJaCatalogado(E: Exception); begin if (Pos('Couldn', E.Message) > 0) and (Pos('t perform the edit because another user changed the record.', E.Message) > 0) then begin RedMsg.Text := 'Não foi possível realizar a edição porque outro usuário alterou o registro.' + #13 + 'Para atualizar as informações, feche a tela e tente novamente!!!'; Exit; end; if (Pos('violation of FOREIGN KEY constraint', E.Message) > 0) and (Pos('present for the record', E.Message) > 0) then begin RedMsg.Lines.Text := 'Este registro já está sendo utilizado.'; Exit; end; if (Pos('violation of FOREIGN KEY constraint', E.Message) > 0) and (Pos('does not exist', E.Message) > 0) then begin RedMsg.Lines.Text := 'Registro pai inexistente.'; Exit; end; if (Pos('Key violation.', E.Message) > 0) and (Pos('violation of PRIMARY or UNIQUE KEY constraint', E.Message) > 0) then begin RedMsg.Lines.Text := 'Registro já existe.'; Exit; end; if (Pos('Record/Key deleted.', E.Message) > 0) then begin RedMsg.Lines.Text := 'Registro já foi eliminado por outro usuário.' + #13 + 'Para atualizar as informações, feche a tela e tente novamente!!!'; Exit; end; end; procedure TFrmSException.SetTipoMsg(const Value: TTipoMsg); begin FTipoMsg := Value; end; procedure TFrmSException.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; FrmSException := nil; end; procedure TFrmSException.BtnGeraLogTxtClick(Sender: TObject); begin AbreArqTxt(LogTxt(RedMsgDetalhada.Text)); end; procedure TFrmSException.BtnDetalhesClick(Sender: TObject); begin MostraDetalhes(Height <> vliHeightForm); end; procedure TFrmSException.MostraDetalhes(vpbMostraDetalhes: Boolean); begin if vpbMostraDetalhes then begin Height := vliHeightForm; RedMsgDetalhada.Visible := True; BtnDetalhes.Caption := '<< Detalhes'; end else begin Height := PnlMsg.Height + 30; RedMsgDetalhada.Visible := False; BtnDetalhes.Caption := 'Detalhes >>'; end; end; procedure TFrmSException.FormCreate(Sender: TObject); begin vliHeightForm := Height; vliHeightPnlMsg := PnlMsg.Height; end; procedure TFrmSException.Splitter1CanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); begin if NewSize < vliHeightPnlMsg then Accept := False; end; end.
uses Crt, Graph, Module; //Ракета const PathToDrivers = '\TP\BGI'; type NodePtr = ^Node; Node = record Item : PointPtr; Next : NodePtr; end; ListPtr = ^List; List = object Nodes : NodePtr; constructor Init; destructor Done; virtual; procedure Add(Item : PointPtr); procedure Drag(DragBy : integer); procedure Show; procedure Hide; end; var GraphDriver : integer; GraphMode : integer; Temp : String; AList : List; PRec:RectanglePtr; PTri : TrianglePtr; PCircle : CirclePtr; RootNode : NodePtr; procedure OutTextLn(TheText : string); begin OutText(TheText); MoveTo(0, GetY+100); end; procedure HeapStatus(StatusMessage : string); begin OutTextLn(StatusMessage+Temp); end; constructor List.Init; begin Nodes := nil; end; destructor List.Done; var N : NodePtr; begin while Nodes <> nil do begin N := Nodes; Nodes := N^.next; Dispose(N^.Item, Done); Dispose(N); end; end; procedure List.Show; var Top : NodePtr; begin Top := Nodes; while Top <> nil do begin Top^.Item^.Show; Top := Top^.next; end; end; procedure List.Hide; var Top : NodePtr; begin Top := Nodes; while Top <> nil do begin Top^.Item^.Hide; Top := Top^.next; end; ClearViewPort; end; procedure List.Add(Item : PointPtr); var N : NodePtr; begin New(N); N^.Item := Item; N^.Next := Nodes; Nodes := N; end; procedure List.Drag(DragBy : integer); var top : NodePtr; DeltaX, DeltaY : integer; FigureX, FigureY : integer; begin Show; while GetDelta(DeltaX, DeltaY) do begin Top := Nodes; Hide; while Top <> nil do begin FigureX := Top^.Item^.GetX; FigureY := Top^.Item^.GetY; FigureX := FigureX + (DeltaX * DragBy); FigureY := FigureY + (DeltaY * DragBy); Top^.Item^.MoveTo(FigureX, FigureY); Top := Top^.Next; end; end; end; begin DetectGraph(GraphDriver, GraphMode); InitGraph(GraphDriver, GraphMode, PathToDrivers); if GraphResult <> GrOK then begin writeln(GraphErrorMsg(GraphDriver)); if GraphDriver = grFileNotFound then begin writeln('in ', PathToDrivers, '. Modify this program''s "PathToDrivers"'); writeln('constant tp specify the actual location of this file.'); writeln; end; writeln('Press Enter...'); readln; Halt(1); end; AList.Init; AList.Add(New(CirclePtr, Init(230, 230, 45, 15))); //Белый круг (окно) AList.Add(New(CirclePtr, Init(230, 230, 50, 4))); //Красный круг (обводка окна) AList.Add(New(TrianglePtr, Init(150, 130, 160, True, 4))); //Красный треугольник(башня) AList.Add(New(TrianglePtr, Init(105, 500, 90, True, 4))); //Красный треугольник(левый двигатель) AList.Add(New(TrianglePtr, Init(265, 500, 90, True, 4))); //Красный треугольник(правый двигатель) AList.Add(New(RectanglePtr, Init(150, 130, 310, 450, 1))); //Синий прямоугольник (корпус) AList.Drag(5); AList.Done; CloseGraph; end.
unit uClasseGrupo; interface uses uConn, Data.SqlExpr, Data.DB,System.classes; Type TGrupo = class private // A varialve Conex�o receber a class da Unit uConn Conexao: TConn; // propriendades do usuario FId : String; FNome : string; FDtOpe : string; FInativo : String; FQry: TSQLQuery; FDs: TDataSource; FDsPesquisa: TDataSource; FQryPesquisa: TSQLQuery; procedure SetDs(const Value: TDataSource); procedure SetDsPesquisa(const Value: TDataSource); procedure SetQry(const Value: TSQLQuery); procedure SetQryPesquisa(const Value: TSQLQuery); procedure SetDtOpe(const Value: String); procedure SetId(const Value: String); procedure SetInativo(const Value: String); procedure SetNome(const Value: String); public constructor Create(Conn : TConn); // Propriedades property Id : String read FId write SetId; property Nome : String read FNome write SetNome; property DtOpe: String read FDtOpe write SetDtOpe; property Inativo: String read FInativo write SetInativo; // Componentes property Qry : TSQLQuery read FQry write SetQry; property QryPesquisa : TSQLQuery read FQryPesquisa write SetQryPesquisa; property Ds : TDataSource read FDs write SetDs; property DsPesquisa : TDataSource read FDsPesquisa write SetDsPesquisa; // Metodos function Inserir : Boolean; function UltimoRegistro : Integer; function Alterar : Boolean; function Status( Id : String ) : String; function ListaGrupo : TStrings; function IdGrupo( Nome : String ) : string; function Deletar( Id : String ): Boolean; function VerificaGrupo : Boolean; end; implementation uses System.SysUtils, uBancoDados, uBancoRelatorio, uClasseRelatorio, uLibrary, uRelatorio, uTrataException, Vcl.Forms, Winapi.Windows; { TGrupo } constructor TGrupo.Create(Conn: TConn); begin Conexao := Conn; Qry := TSQLQuery.Create(nil); Ds := TDataSource.Create(nil); QryPesquisa := TSQLQuery.Create(nil); DsPesquisa := TDataSource.Create(nil); // Conecta a Query no TSQLconnection Qry.SQLConnection := Conexao.ConexaoBanco; QryPesquisa.SQLConnection := Conexao.ConexaoBanco; Ds.DataSet := Qry; DsPesquisa.DataSet := QryPesquisa; end; function TGrupo.Inserir: Boolean; begin with Qry do begin Close; SQL.Text := ' insert into figru (nmgru, dtope) values (:NMGRU, :DTOPE) '; Params.ParamByName('NMGRU').Value := FNome; Params.ParamByName('DTOPE').Value := Date; // Pega a data que esta fazedno o insert try ExecSQL(); DM.cdsGrupo.Refresh; Result := True; // Retorna True se Executa sem erro except Result := False; // Retorna False se Executa com erro end; end; end; // Function para retorno o ultimo registro do banco function TGrupo.UltimoRegistro: Integer; begin with QryPesquisa do begin Close; SQL.Text := ' select max(cdgru) from figru '; try Open; Result := FieldByName('MAX').AsInteger + 1; // Retorna o registro do banco except Result := 0; end; end; end; function TGrupo.Alterar: Boolean; begin if (FInativo = 'S') and ( VerificaGrupo ) then begin Application.MessageBox(' Grupo possui conta, impossivel inativa ','Atenção',MB_OK); end else begin with Qry do begin Close; SQL.Text := ' update FIgru set NMgru = :NMGRU , INATIVO = :INTV ' + ' where CDGRU = :CDGRU '; Params.ParamByName('NMGRU').Value:= FNome; Params.ParamByName('INTV').Value:= FInativo; Params.ParamByName('CDGRU').Value:= FId; try ExecSQL(); DM.cdsGrupo.Refresh; Result := True; // Retorna True se Executa sem erro except Result := False; // Retorna False se Executa com erro end; end; end; end; function TGrupo.Status( Id : String ) : String; begin with QryPesquisa do begin Close; SQL.Text := ' select inativo from figru where cdgru = '+Id; try Open; Result := FieldByName('inativo').AsString; // Retorna o registro do banco except Result := '0'; end; end; end; function TGrupo.ListaGrupo: TStrings; begin Result := TStringList.Create; Result.Clear; Result.BeginUpdate; with QryPesquisa do begin Close; SQL.Text := ' Select NMGRU From figru where inativo = ''N'' '; try Open; finally First; while not Eof do begin Result.Add(FieldByName('NMGRU').AsString); Next; end; end; end; Result.EndUpdate; end; function TGrupo.IdGrupo( Nome : String ) : string; begin with QryPesquisa do begin Close; SQL.Text := ' select cdgru from figru where nmgru = :NMGRU'; Params.ParamByName('NMGRU').Value := Nome; try Open; Result := FieldByName('cdgru').AsString; // Retorna o registro do banco except Result := '0'; end; end; end; function TGrupo.Deletar(Id: String): Boolean; begin with Qry do begin Close; SQL.Text := ' delete from figru where cdgru = '+Id; try ExecSQL(); DM.cdsGrupo.Refresh; Result := True; except Result := False; end; end; end; function TGrupo.VerificaGrupo: Boolean; var count : Integer; begin with QryPesquisa do begin Close; SQL.Text := ' select count(cdgru) from figru where nmgru = :NMGRU'; Params.ParamByName('NMGRU').Value := FNome; try Open; count := FieldByName('count').AsInteger; // Retorna o registro do banco finally if count > 0 then Result := True else Result := False; end; end; end; procedure TGrupo.SetDs(const Value: TDataSource); begin FDs := Value; end; procedure TGrupo.SetDsPesquisa(const Value: TDataSource); begin FDsPesquisa := Value; end; procedure TGrupo.SetDtOpe(const Value: String); begin FDtOpe := Value; end; procedure TGrupo.SetId(const Value: String); begin FId := Value; end; procedure TGrupo.SetInativo(const Value: String); begin FInativo := Value; end; procedure TGrupo.SetNome(const Value: String); begin if Value = EmptyStr then raise Exception.Create('Preenchar o Campo Nome Grupo!') else FNome := Value; end; procedure TGrupo.SetQry(const Value: TSQLQuery); begin FQry := Value; end; procedure TGrupo.SetQryPesquisa(const Value: TSQLQuery); begin FQryPesquisa := Value; end; end.
unit LongEdit; interface uses Classes, StdCtrls, Graphics; type TLongEdit = class(TEdit) private bm: TBitMap; protected procedure Change; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation { TLongEdit } procedure TLongEdit.Change; var nwidth: integer; begin inherited Change; bm.Canvas.Font := Font; if length(Text)=0 then nWidth := bm.Canvas.TextWidth('ww') else nWidth := bm.Canvas.TextWidth(Text+'ww'); if (nwidth>width)and (parent<>nil) and (width+left+5 > parent.ClientWidth) then exit; width := nwidth; end; constructor TLongEdit.Create(AOwner: TComponent); begin inherited; bm := TBitmap.Create; Change; end; destructor TLongEdit.Destroy; begin bm.Free; inherited; end; end.
{***************************************************************************} { } { Command Line Parser } { Copyright (C) 2019-2021 Wuping Xin } { } { Based on VSoft.CommandLine } { Copyright (C) 2014 Vincent Parrett } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit CmdlineParser; interface uses System.Classes, System.TypInfo, Generics.Collections; type {$REGION 'Forward Declaration'} ICommandDefinition = interface; IOptionDefinition = interface; {$ENDREGION} TEnumerateCommandAction = reference to procedure(const ACommand: ICommandDefinition); TEnumerateCommandOptionsAction = reference to procedure(const AOption: IOptionDefinition); TOptionParsedAction<T> = reference to procedure(const AValue: T); TPrintUsageAction = reference to procedure(const AText: String); IOptionDefinition = interface ['{1EAA06BA-8FBF-43F8-86D7-9F5DE26C4E86}'] {$REGION 'Property Gettors and Settors'} function Get_HelpText: String; procedure Set_HelpText(const AValue: String); function Get_IsAnonymous: Boolean; function Get_IsOptionFile: Boolean; procedure Set_IsOptionFile(const AValue: Boolean); function Get_LongName: String; function Get_Name: String; function Get_Required: Boolean; procedure Set_Required(const AValue: Boolean); function Get_RequiresValue: Boolean; procedure Set_RequiresValue(const AValue: Boolean); function Get_ShortName: String; {$ENDREGION} property HelpText: String read Get_HelpText write Set_HelpText; property IsAnonymous: Boolean read Get_IsAnonymous; property IsOptionFile: Boolean read Get_IsOptionFile write Set_IsOptionFile; property LongName: String read Get_LongName; property Name: String read Get_Name; property Required: Boolean read Get_Required write Set_Required; property RequiresValue: Boolean read Get_RequiresValue write Set_RequiresValue; property ShortName: String read Get_ShortName; end; IOptionDefinitionInvoke = interface ['{580B5B40-CD7B-41B8-AE53-2C6890141FF0}'] function GetTypeInfo: PTypeInfo; procedure Invoke(const AValue: String); function WasFound: Boolean; end; ICommandDefinition = interface ['{58199FE2-19DF-4F9B-894F-BD1C5B62E0CB}'] {$REGION 'Property Gettors and Settors'} function Get_Alias: String; function Get_Description: String; function Get_HelpText: String; function Get_IsDefault: Boolean; function Get_Name: String; function Get_RegisteredAnonymousOptions: TList<IOptionDefinition>; function Get_RegisteredNamedOptions: TList<IOptionDefinition>; function Get_Usage: String; function Get_Visible: Boolean; {$ENDREGION} procedure AddOption(const aOption: IOptionDefinition); procedure Clear; procedure EnumerateNamedOptions(const AProc: TEnumerateCommandOptionsAction); overload; procedure GetAllRegisteredOptions(const AResult: TList<IOptionDefinition>); function HasOption(const AName: String): Boolean; function TryGetOption(const AName: String; var aOption: IOptionDefinition): Boolean; { Properties } property Alias: String read Get_Alias; property Description: String read Get_Description; property HelpText: String read Get_HelpText; property IsDefault: Boolean read Get_IsDefault; property Name: String read Get_Name; property RegisteredAnonymousOptions: TList<IOptionDefinition> read Get_RegisteredAnonymousOptions; property RegisteredNamedOptions: TList<IOptionDefinition> read Get_RegisteredNamedOptions; property Usage: String read Get_Usage; property Visible: Boolean read Get_Visible; end; ICmdlineParseResult = interface ['{1715B9FF-8A34-47C9-843E-619C5AEA3F32}'] {$REGION 'Property Gettors and Settors'} function Get_CommandName: String; function Get_ErrorText: String; function Get_HasErrors: Boolean; {$ENDREGION} { Properties } property CommandName: String read Get_CommandName; property ErrorText: String read Get_ErrorText; property HasErrors: Boolean read Get_HasErrors; end; TCommandDefinitionHelper = record strict private FCommand: ICommandDefinition; {$REGION 'Property Gettors and Settors'} function Get_Alias: String; function Get_Description: String; function Get_Name: String; function Get_Usage: String; {$ENDREGION} public constructor Create(const ACommand: ICommandDefinition); function HasOption(const AOptionName: String): Boolean; function RegisterAnonymousOption<T>(const AHelp: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; overload; function RegisterOption<T>(const ALongName, AShortName, AHelp: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; overload; function RegisterOption<T>(const ALongName, AShortName: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; overload; function RegisterOption<T>(const ALongName: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; overload; { Properties } property Alias: String read Get_Alias; property Command: ICommandDefinition read FCommand; property Description: String read Get_Description; property Name: String read Get_Name; property Usage: String read Get_Usage; end; TOptionDefinition<T> = class(TInterfacedObject, IOptionDefinition, IOptionDefinitionInvoke) strict private FDefault: T; FHelpText: String; FIsOptionFile: Boolean; FLongName: String; FProc: TOptionParsedAction<T>; FRequired: Boolean; FRequiresValue: Boolean; FShortName: String; FTypeInfo: PTypeInfo; FWasFound: Boolean; {$REGION 'Property Gettors and Settors'} function Get_HelpText: String; procedure Set_HelpText(const AValue: String); function Get_IsAnonymous: Boolean; function Get_IsOptionFile: Boolean; procedure Set_IsOptionFile(const AValue: Boolean); function Get_LongName: String; function Get_Name: String; function Get_Required: Boolean; procedure Set_Required(const AValue: Boolean); function Get_RequiresValue: Boolean; procedure Set_RequiresValue(const AValue: Boolean); function Get_ShortName: String; {$ENDREGION} strict private function OptionValueStrToTypedValue(const AValueStr: String): T; procedure InitOptionDefaultValue; strict protected function GetTypeInfo: PTypeInfo; procedure Invoke(const AValueStr: String); function WasFound: Boolean; public constructor Create(const ALongName, AShortName, AHelp: String; const AProc: TOptionParsedAction<T>); overload; constructor Create(const ALongName, AShortName: String; const AProc: TOptionParsedAction<T>); overload; { Properties } property HelpText: String read Get_HelpText write Set_HelpText; property IsAnonymous: Boolean read Get_IsAnonymous; property IsOptionFile: Boolean read Get_IsOptionFile write Set_IsOptionFile; property LongName: String read Get_LongName; property Name:string read Get_Name; property Required: Boolean read Get_Required write Set_Required; property RequiresValue: Boolean read Get_RequiresValue write Set_RequiresValue; property ShortName: String read Get_ShortName; end; TOptionsRegistry = class strict private class var FCommands: TDictionary<string, ICommandDefinition>; FConsoleWidth: Integer; FDefaultCommandHelper: TCommandDefinitionHelper; FDescriptionTabSize: Integer; FNameValueSeparator: String; strict private class constructor Create; class destructor Destroy; {$REGION 'Property Gettors and Settors'} class function Get_DefaultCommand: ICommandDefinition; static; {$ENDREGION} public class procedure Clear; class procedure EmumerateCommandOptions(const ACommandName: String; const AProc: TEnumerateCommandOptionsAction); overload; class procedure EnumerateCommands(const AProc: TEnumerateCommandAction); overload; class function GetCommandByName(const AName: String): ICommandDefinition; class function Parse: ICmdLineParseResult; overload; class function Parse(const ACmdLine: TStrings): ICmdLineParseResult; overload; class procedure PrintUsage(const ACommandName: String; const AProc: TPrintUsageAction); overload; class procedure PrintUsage(const ACommand: ICommandDefinition; const AProc: TPrintUsageAction); overload; class procedure PrintUsage(const AProc: TPrintUsageAction); overload; class function RegisterCommand(const AName: String; const AAlias: String; const ADescription: String; const AHelpText: String; const AUsage: String; const AVisible: Boolean = True): TCommandDefinitionHelper; class function RegisterAnonymousOption<T>(const AHelpText: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; class function RegisterOption<T>(const ALongName: String; const AShortName: String; const AHelp: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; overload; class function RegisterOption<T>(const ALongName: String; const AShortName: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; overload; class function RegisterOption<T>(const ALongName: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; overload; { Properties } class property DefaultCommand: ICommandDefinition read Get_DefaultCommand; class property DescriptionTabSize: Integer read FDescriptionTabSize write FDescriptionTabSize; class property NameValueSeparator: String read FNameValueSeparator write FNameValueSeparator; class property RegisteredCommands: TDictionary<string, ICommandDefinition> read FCommands; end; {$REGION 'Utility Functions'} function GetConsoleWidth: Integer; /// <summary> /// Split a given text into array of strings, each string not exceeding a maximum number of characters. /// </summary> /// <param name="AText"> /// The given text. /// </param> /// <param name="AMaxLen"> /// Maximum number of characters of each string. /// </param> function SplitText(const AText: String; const AMaxLen: Integer): TArray<string>; /// <summary> /// Split a given string into array of strings; each string element not exceeding maximum number of /// characters. /// </summary> /// <param name="ALen"> /// Length of the division. /// </param> /// <param name="ASrcStr"> /// Source string to be divided. /// </param> function SplitStringAt(const ALen: Integer; const ASrcStr: String): TArray<string>; /// <summary> /// Convert a Boolean compatible string to Boolean type. /// </summary> /// <param name="AValue"> /// A Boolean compatible string. /// </param> function StringToBoolean(const AValue: String): Boolean; /// <summary> /// Strip quote char from the given string. Quote char include single quote or double quote. /// </summary> /// <param name="AStr"> /// A string to strip quote char at two ends. /// </param> procedure StripQuotes(var AStr: String); {$ENDREGION} const DefaultDescriptionTabSize = 15; ShortNameExtraSpaceSize = 5; const OptionTokens: array [1 .. 4] of string = ('--', '-', '/', '@'); const SErrParsingParamFile = 'Error parsing parameter file [%s]: %s'; SErrSettingOption = 'Error setting option: %s to %s: %s'; SGlobalOptionText = 'global optoins: '; SInvalidEnumValue = 'Invalid enum value: %s.'; SOptionNameDuplicated = 'Option: %s already registered'; SOptions = 'options: '; SParamFileMissing = 'Parameter file [%s] does not exist.'; SRequiredNamedOptionMissing = 'Required option missing: [%s].'; SRequiredAnonymousOptionMissing = 'Required anonymous option missing.'; StrBoolean = 'Boolean'; SUnknownCommand = 'Unknown command: %s.'; SUnknownOption = 'Unknown option: %s.'; SUnknownAnonymousOption = 'Unknown anonymous option: %s.'; SUsage = 'usage: '; SCommandNameMissing = 'Command name required'; SOptionNameMissing = 'Option name required - use RegisterAnonymousOption for unnamed options.'; SInvalidOptionType = 'Invalid option type: only string, integer, float, boolean, enum and set types are supported.'; SOptionValueMissing = 'Option [%s] expects a <value> following %s, but none was found.'; const TrueStrings: array [0 .. 10] of string = ('True', 'T', '+', 'Yes', 'Y', 'On', 'Enable', 'Enabled', '1', '-1', ''); FalseStrings: array [0 .. 8] of string = ('False', 'F', '-', 'No', 'N', 'Off', 'Disable', 'Disabled', '0'); implementation uses {$IFDEF MSWINDOWS} WinApi.Windows, {$ENDIF} Generics.Defaults, System.Rtti, System.StrUtils, System.SysUtils; function SplitStringAt(const ALen: Integer; const ASrcStr: String): TArray<string>; begin SetLength(Result, 0); var LSrcLen := Length(ASrcStr); if LSrcLen < ALen then begin SetLength(Result, 1); Result[0] := ASrcStr; Exit; end; var LIndex := 1; var LCount := 0; while LIndex <= LSrcLen do begin Inc(LCount); SetLength(Result, LCount); Result[LCount - 1] := Copy(ASrcStr, LIndex, ALen); Inc(LIndex, ALen); end; end; function SplitText(const AText: String; const AMaxLen: Integer): TArray<string>; begin SetLength(Result, 0); // Otherwise a CRLF will result in two lines. var LText := StringReplace(AText, sLineBreak, #13, [rfReplaceAll]); // Splits at each CR *and* each LF! Delimiters denotes set of single characters used to // split string. Each character in Delimiters string will be used as one of possible // delimiters. var LLines := SplitString(LText, #13#10); var K := 0; for var I := 0 to Length(LLines) - 1 do begin var LStrs := SplitStringAt(AMaxLen, LLines[I]); Inc(K, Length(LStrs)); SetLength(Result, K); for var J := 0 to Length(LStrs) - 1 do Result[K - Length(LStrs) + J] := LStrs[J]; end; end; {$IFDEF MSWINDOWS} function GetConsoleWidth: Integer; var LStdOutputHandle: THandle; LConcoleScreenInfo: CONSOLE_SCREEN_BUFFER_INFO; begin // Default is unlimited width Result := High(Integer); LStdOutputHandle := GetStdHandle(STD_OUTPUT_HANDLE); if GetConsoleScreenBufferInfo(LStdOutputHandle, LConcoleScreenInfo) then Result := LConcoleScreenInfo.dwSize.X; end; {$ENDIF} {$IFDEF MACOS} function GetConsoleWidth: Integer; const kDefaultWidth = 80; begin Result := kDefaultWidth; end; {$ENDIF} function StringToBoolean(const AValue: String): Boolean; const sInvalidBooleanStr = 'Invalid string, not Boolean compliant.'; begin if MatchText(AValue, TrueStrings) then Result := True else if MatchText(AValue, FalseStrings) then Result := False else raise Exception.Create(sInvalidBooleanStr); end; procedure StripQuotes(var AStr: String); const kMinStrLen = 2; kQuoteCharSet = ['''', '"']; begin var LStrLen := Length(AStr); if LStrLen < kMinStrLen then Exit; if CharInSet(AStr[1], kQuoteCharSet) and CharInSet(AStr[LStrLen], kQuoteCharSet) then begin Delete(AStr, LStrLen, 1); Delete(AStr, 1, 1); end; end; type ICmdlineParser = interface ['{6F970026-D1EE-4A3E-8A99-300AD3EE9C33}'] function Parse: ICmdlineParseResult; overload; function Parse(const AValues: TStrings): ICmdlineParseResult; overload; end; IInternalParseResult = interface ['{9EADABED-511B-4095-9ACA-A5E431AB653D}'] procedure AddError(const AError: String); procedure SetCommand(const ACommand: ICommandDefinition); function Get_Command: ICommandDefinition; { Properties } property Command: ICommandDefinition read Get_Command; end; TCommandDefinitionCreateParams = record Alias: String; Description: String; HelpText: String; IsDefault: Boolean; Name: String; Usage: String; Visible: Boolean; end; TCommandDefinition = class(TInterfacedObject, ICommandDefinition) private FAlias: String; FDescription: String; FHelpText: String; FIsDefault: Boolean; FName: String; FRegisteredAnonymousOptions: TList<IOptionDefinition>; FRegisteredNamedOptions: TList<IOptionDefinition>; FRegisteredNamedOptionsDictionary: TDictionary<string, IOptionDefinition>; FUsage: String; FVisible: Boolean; {$REGION 'Property Gettors and Settors'} function Get_Alias: String; function Get_Description: String; function Get_HelpText: String; function Get_IsDefault: Boolean; function Get_Name: String; function Get_RegisteredAnonymousOptions: TList<IOptionDefinition>; function Get_RegisteredNamedOptions: TList<IOptionDefinition>; function Get_Usage: String; function Get_Visible: Boolean; {$ENDREGION} protected procedure AddOption(const AOption: IOptionDefinition); procedure Clear; procedure EnumerateNamedOptions(const AProc: TEnumerateCommandOptionsAction); procedure GetAllRegisteredOptions(const AResult: TList<IOptionDefinition>); function HasOption(const AName: String): Boolean; function TryGetOption(const AName: String; var AOption: IOptionDefinition): Boolean; public constructor Create(const AParams: TCommandDefinitionCreateParams); constructor CreateDefault; destructor Destroy; override; { Properties } property Alias: String read Get_Alias; property Description: String read Get_Description; property HelpText: String read Get_HelpText; property IsDefault: Boolean read Get_IsDefault; property Name: String read Get_Name; property RegisteredAnonymousOptions: TList<IOptionDefinition> read Get_RegisteredAnonymousOptions; property RegisteredOptions: TList<IOptionDefinition> read Get_RegisteredNamedOptions; property Usage: String read Get_Usage; property Visible: Boolean read Get_Visible; end; TCmdlineParseResult = class(TInterfacedObject, ICmdlineParseResult, IInternalParseResult) private FCommand: ICommandDefinition; FErrors: TStringList; {$REGION 'Property Gettors and Settors'} procedure AddError(const AError: String); procedure SetCommand(const ACommand: ICommandDefinition); function Get_Command: ICommandDefinition; function Get_CommandName: String; function Get_ErrorText: String; function Get_HasErrors: Boolean; {$ENDREGION} public constructor Create; destructor Destroy; override; property Command: ICommandDefinition read Get_Command; property CommandName: String read Get_CommandName; property ErrorText: String read Get_ErrorText; property HasErrors: Boolean read Get_HasErrors; end; TCmdlineParser = class(TInterfacedObject, ICmdLineParser) strict private FAnonymousIndex: Integer; FNameValueSeparator: String; {$REGION 'Private Helper Methods'} function ParseCommand(const ACmdlineItem: String; var AActiveCommand: ICommandDefinition; const AParseResult: IInternalParseResult): Boolean; function ParseOption(const ACmdlineItem: String; const AActiveCommand: ICommandDefinition; out AOption: IOptionDefinition; out AOptionValue: String; const AParseResult: IInternalParseResult): Boolean; procedure ParseOptionFile(const AFileName: String; const AParseResult: IInternalParseResult); function InvokeOption(AOption: IOptionDefinition; const AValue: String; out AErrMsg: String): Boolean; function HasOptionToken(var ACmdlineItem: String): Boolean; function TryGetCommand(const AName: String; out ACommand: ICommandDefinition): Boolean; function TryGetOption(const ACommand, ADefaultCommand: ICommandDefinition; const AOptionName: String; out AOption: IOptionDefinition): Boolean; {$ENDREGIOn} strict protected procedure DoParse(const ACmdlineItems: TStrings; const AParseResult: IInternalParseResult); virtual; procedure ValidateParseResult(const AParseResult: IInternalParseResult); virtual; public constructor Create(const aNameValueSeparator: String); destructor Destroy; override; function Parse: ICmdlineParseResult; overload; function Parse(const ACmdlineItems: TStrings): ICmdlineParseResult; overload; end; class constructor TOptionsRegistry.Create; begin FDefaultCommandHelper := TCommandDefinitionHelper.Create(TCommandDefinition.CreateDefault); FCommands := TDictionary<string, ICommandDefinition>.Create; FNameValueSeparator := ':'; // Default separator. FDescriptionTabSize := DefaultDescriptionTabSize; FConsoleWidth := GetConsoleWidth; // This is a system function. end; class destructor TOptionsRegistry.Destroy; begin FCommands.Free; end; class procedure TOptionsRegistry.Clear; begin FDefaultCommandHelper.Command.Clear; FCommands.Clear; end; class procedure TOptionsRegistry.EmumerateCommandOptions(const ACommandName: String; const AProc: TEnumerateCommandOptionsAction); var LCommand: ICommandDefinition; begin if not FCommands.TryGetValue(ACommandName, LCommand) then raise Exception.Create(Format(SUnknownCommand, [ACommandName])); LCommand.EnumerateNamedOptions(AProc); end; class procedure TOptionsRegistry.EnumerateCommands(const AProc: TEnumerateCommandAction); var LCommand: ICommandDefinition; begin var LCommands := TList<ICommandDefinition>.Create; try for LCommand in FCommands.Values do if LCommand.Visible then LCommands.Add(LCommand); LCommands.Sort(TComparer<ICommandDefinition>.Construct( function(const L, R: ICommandDefinition): Integer begin Result := CompareText(L.Name, R.Name); end) ); for LCommand in LCommands do AProc(LCommand); finally LCommands.Free; end; end; class function TOptionsRegistry.GetCommandByName(const AName: String): ICommandDefinition; begin Result := nil; FCommands.TryGetValue(AName.ToLower, Result); end; class function TOptionsRegistry.Get_DefaultCommand: ICommandDefinition; begin Result := TOptionsRegistry.FDefaultCommandHelper.Command; end; class function TOptionsRegistry.Parse: ICmdLineParseResult; begin var LParser: ICmdlineParser := TCmdlineParser.Create(NameValueSeparator); Result := LParser.Parse; end; class function TOptionsRegistry.Parse(const ACmdLine: TStrings): ICmdLineParseResult; begin var LParser: ICmdlineParser := TCmdlineParser.Create(NameValueSeparator); Result := LParser.Parse(ACmdLine); end; class procedure TOptionsRegistry.PrintUsage(const ACommandName: String; const AProc: TPrintUsageAction); begin if ACommandName = '' then begin PrintUsage(AProc); Exit; end; var LCommand: ICommandDefinition; if not FCommands.TryGetValue(LowerCase(ACommandName), LCommand) then begin AProc(Format(SUnknownCommand, [ACommandName])); Exit; end; PrintUsage(LCommand, AProc); end; class procedure TOptionsRegistry.PrintUsage(const ACommand: ICommandDefinition; const AProc: TPrintUsageAction); begin if not ACommand.IsDefault then begin AProc(SUsage + ACommand.Usage); AProc(''); AProc(ACommand.Description); if ACommand.HelpText <> '' then begin AProc(''); AProc(' ' + ACommand.HelpText); end; AProc(''); AProc(SOptions); AProc(''); end else begin AProc(''); if FCommands.Count > 0 then AProc(SGlobalOptionText) else AProc(SOptions); AProc(''); end; var LMaxDescWidth: Integer; if FConsoleWidth < High(Integer) then LMaxDescWidth := FConsoleWidth else LMaxDescWidth := High(Integer); LMaxDescWidth := LMaxDescWidth - FDescriptionTabSize; ACommand.EnumerateNamedOptions( procedure(const aOption: IOptionDefinition) begin var al := Length(aOption.ShortName); if al <> 0 then Inc(al, ShortNameExtraSpaceSize); // add brackets (- ) and 2 spaces; var s := ' -' + aOption.LongName.PadRight(DescriptionTabSize - 1 - al); if al > 0 then s := s + '(-' + aOption.ShortName + ')' + ' '; var descStrings := SplitText(aOption.HelpText, LMaxDescWidth); s := s + descStrings[0]; AProc(s); var numDescStrings := Length(descStrings); if numDescStrings > 1 then for var I := 1 to numDescStrings - 1 do AProc(''.PadRight(DescriptionTabSize + 1) + descStrings[I]); end ); end; class procedure TOptionsRegistry.PrintUsage(const AProc: TPrintUsageAction); begin AProc(''); if FCommands.Count > 0 then begin var LMaxDescWidth: Integer; if FConsoleWidth < High(Integer) then LMaxDescWidth := FConsoleWidth else LMaxDescWidth := High(Integer); LMaxDescWidth := LMaxDescWidth - FDescriptionTabSize; for var LCommand in FCommands.Values do begin if LCommand.Visible then begin var LDescStrings := SplitText(LCommand.Description, LMaxDescWidth); AProc(' ' + LCommand.Name.PadRight(DescriptionTabSize - 1) + LDescStrings[0]); var LNumDescStrings := Length(LDescStrings); if LNumDescStrings > 1 then for var I := 1 to LNumDescStrings - 1 do AProc(''.PadRight(DescriptionTabSize) + LDescStrings[I]); AProc(''); end; end; end; PrintUsage(FDefaultCommandHelper.Command, AProc); end; class function TOptionsRegistry.RegisterAnonymousOption<T>(const AHelpText: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; begin Result := FDefaultCommandHelper.RegisterAnonymousOption<T>(AHelpText, AAction); end; class function TOptionsRegistry.RegisterCommand(const AName, AAlias, ADescription, AHelpText, AUsage: String; const AVisible: Boolean = True): TCommandDefinitionHelper; begin if Aname.IsEmpty then raise EArgumentException.Create(SCommandNameMissing); var LParams: TCommandDefinitionCreateParams; with LParams do begin Alias := AAlias; Description := ADescription; HelpText := AHelpText; IsDefault := False; // Always false. Only one default command. Name := AName; Usage := AUsage; Visible := AVisible; end; var LCommand: ICommandDefinition := TCommandDefinition.Create(LParams); FCommands.Add(AName.ToLower, LCommand); Result := TCommandDefinitionHelper.Create(LCommand); end; class function TOptionsRegistry.RegisterOption<T>(const ALongName, AShortName, AHelp: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; begin Result := RegisterOption<T>(ALongName, AShortName, AAction); Result.HelpText := AHelp; end; class function TOptionsRegistry.RegisterOption<T>(const ALongName, AShortName: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; begin Result := FDefaultCommandHelper.RegisterOption<T>(ALongName, AShortName, AAction); end; class function TOptionsRegistry.RegisterOption<T>(const ALongName: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; begin Result := RegisterOption<T>(ALongName, '', AAction); end; constructor TCommandDefinitionHelper.Create(const ACommand: ICommandDefinition); begin FCommand := ACommand; end; function TCommandDefinitionHelper.Get_Alias: String; begin Result := FCommand.Alias; end; function TCommandDefinitionHelper.Get_Description: String; begin Result := FCommand.Description; end; function TCommandDefinitionHelper.Get_Name: String; begin Result := FCommand.Name; end; function TCommandDefinitionHelper.Get_Usage: String; begin Result := FCommand.Usage; end; function TCommandDefinitionHelper.HasOption(const AOptionName: String): Boolean; begin Result := FCommand.HasOption(AOptionName); end; function TCommandDefinitionHelper.RegisterAnonymousOption<T>(const AHelp: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; begin Result := TOptionDefinition<T>.Create('', '', AHelp, AAction); Result.RequiresValue := False; FCommand.AddOption(Result); end; function TCommandDefinitionHelper.RegisterOption<T>(const ALongName, AShortName, AHelp: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; begin Result := RegisterOption<T>(ALongName, AShortName, AAction); Result.HelpText := AHelp; end; function TCommandDefinitionHelper.RegisterOption<T>(const ALongName, AShortName: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; begin if ALongName.IsEmpty then raise EArgumentException.Create(SOptionNameMissing); if FCommand.HasOption(LowerCase(ALongName)) then raise EArgumentException.Create(Format(SOptionNameDuplicated, [ALongName])); if FCommand.HasOption(LowerCase(AShortName)) then raise EArgumentException.Create(Format(SOptionNameDuplicated, [AShortName])); Result := TOptionDefinition<T>.Create(ALongName, AShortName, AAction); FCommand.AddOption(Result); end; function TCommandDefinitionHelper.RegisterOption<T>(const ALongName: String; const AAction: TOptionParsedAction<T>): IOptionDefinition; begin Result := RegisterOption<T>(ALongName, '', AAction); end; constructor TCommandDefinition.Create(const AParams: TCommandDefinitionCreateParams); begin inherited Create; with AParams do begin FAlias := Alias; FDescription := Description; FHelpText := HelpText; FIsDefault := IsDefault; FName := Name; FUsage := Usage; FVisible := Visible; end; FRegisteredNamedOptionsDictionary := TDictionary<string, IOptionDefinition>.Create; FRegisteredNamedOptions := TList<IOptionDefinition>.Create; FRegisteredAnonymousOptions := TList<IOptionDefinition>.Create; end; constructor TCommandDefinition.CreateDefault; var LParams: TCommandDefinitionCreateParams; begin with LParams do begin Alias := EmptyStr; // Empty Description := EmptyStr; // Empty HelpText := EmptyStr; // Empty IsDefault := True; // Default is always True. Name := EmptyStr; // Anonymous command, as default. Usage := EmptyStr; // Global default commdn, no usage string. Visible := False; // Always invisible. end; Create(LParams); end; destructor TCommandDefinition.Destroy; begin FRegisteredNamedOptionsDictionary.Free; FRegisteredAnonymousOptions.Free; FRegisteredNamedOptions.Free; inherited; end; // Will be called only after HasOption is checked by TCommandDefintionHelper. // HasOption must return False before proceeding to AddOption. procedure TCommandDefinition.AddOption(const AOption: IOptionDefinition); begin if AOption.IsAnonymous then begin FRegisteredAnonymousOptions.Add(AOption); end else begin FRegisteredNamedOptions.Add(AOption); FRegisteredNamedOptionsDictionary.AddOrSetValue(LowerCase(AOption.LongName), AOption); // Add short name to the dictionary too, if not empty. if not AOption.ShortName.IsEmpty then FRegisteredNamedOptionsDictionary.AddOrSetValue(LowerCase(AOption.ShortName), AOption); end; end; procedure TCommandDefinition.Clear; begin FRegisteredNamedOptionsDictionary.Clear; FRegisteredNamedOptions.Clear; FRegisteredAnonymousOptions.Clear; end; procedure TCommandDefinition.EnumerateNamedOptions(const AProc: TEnumerateCommandOptionsAction); begin var LNamedOptions := TList<IOptionDefinition>.Create(FRegisteredNamedOptions); try LNamedOptions.Sort(TComparer<IOptionDefinition>.Construct( function(const L, R: IOptionDefinition): Integer begin Result := CompareText(L.LongName, R.LongName); // Longname is garantteed to be not empty. end) ); for var o in LNamedOptions do AProc(o); finally LNamedOptions.Free; end; end; procedure TCommandDefinition.GetAllRegisteredOptions(const AResult: TList<IOptionDefinition>); begin AResult.AddRange(FRegisteredAnonymousOptions); AResult.AddRange(FRegisteredNamedOptions); end; function TCommandDefinition.Get_Alias: String; begin Result := FAlias; end; function TCommandDefinition.Get_Description: String; begin Result := FDescription; end; function TCommandDefinition.Get_HelpText: String; begin Result := FHelpText; end; function TCommandDefinition.Get_IsDefault: Boolean; begin Result := FIsDefault; end; function TCommandDefinition.Get_Name: String; begin Result := FName; end; function TCommandDefinition.Get_RegisteredAnonymousOptions: TList<IOptionDefinition>; begin Result := FRegisteredAnonymousOptions; end; function TCommandDefinition.Get_RegisteredNamedOptions: TList<IOptionDefinition>; begin Result := FRegisteredNamedOptions; end; function TCommandDefinition.Get_Usage: String; begin Result := FUsage; end; function TCommandDefinition.Get_Visible: Boolean; begin Result := FVisible; end; function TCommandDefinition.HasOption(const AName: String): Boolean; begin Result := FRegisteredNamedOptionsDictionary.ContainsKey(LowerCase(AName)); end; function TCommandDefinition.TryGetOption(const AName: String; var AOption: IOptionDefinition): Boolean; begin Result := FRegisteredNamedOptionsDictionary.TryGetValue(LowerCase(AName), AOption); end; constructor TOptionDefinition<T>.Create(const ALongName, AShortName, AHelp: String; const AProc: TOptionParsedAction<T>); begin Create(ALongName, AShortName, AProc); FHelpText := AHelp; end; constructor TOptionDefinition<T>.Create(const ALongName, AShortName: String; const AProc: TOptionParsedAction<T>); const kAllowedTypeKinds: set of TTypeKind = [tkInteger, tkEnumeration, tkFloat, tkString, tkSet, tkLString, tkWString, tkInt64, tkUString]; begin FTypeInfo := TypeInfo(T); if not (FTypeInfo.Kind in kAllowedTypeKinds) then raise EArgumentException.Create(SInvalidOptionType); FLongName := ALongName; // If long name is empty, then the option is anonymous. FShortName := AShortName; FProc := AProc; FRequiresValue := True; // Default is True, a value is required. FIsOptionFile := False; // Default is False, not an option file. FRequired := False; // Default is False, not a required option. // Initialize the default value. InitOptionDefaultValue; end; function TOptionDefinition<T>.GetTypeInfo: PTypeInfo; begin Result := FTypeInfo; end; function TOptionDefinition<T>.Get_RequiresValue: Boolean; begin Result := FRequiresValue; end; function TOptionDefinition<T>.Get_HelpText: String; begin Result := FHelpText; end; function TOptionDefinition<T>.Get_IsAnonymous: Boolean; begin Result := FLongName.IsEmpty; end; function TOptionDefinition<T>.Get_IsOptionFile: Boolean; begin Result := FIsOptionFile; end; function TOptionDefinition<T>.Get_LongName: String; begin Result := FLongName; end; function TOptionDefinition<T>.Get_Name: String; const sAnonymousOptionName = 'unnamed'; begin if IsAnonymous then Result := sAnonymousOptionName else Result := Format('%s(%s)', [LongName, ShortName]); end; function TOptionDefinition<T>.Get_Required: Boolean; begin // Anonymous option always required in order to enforce their positions. Result := FRequired or IsAnonymous; end; function TOptionDefinition<T>.Get_ShortName: String; begin Result := FShortName; end; procedure TOptionDefinition<T>.InitOptionDefaultValue; begin FDefault := Default (T); // Note - the default value for Boolean option is True. If the option name (the flag) // appears without a value, by default it will be treated as True. if not FRequiresValue and (FTypeInfo.Name = StrBoolean) then FDefault := TValue.FromVariant(True).AsType<T>; end; procedure TOptionDefinition<T>.Invoke(const AValueStr: String); begin FWasFound := True; if not Assigned(FProc) then Exit; if AValueStr.IsEmpty then begin FProc(FDefault); end else begin var LValue:T := OptionValueStrToTypedValue(AValueStr); FProc(LValue); end; end; function TOptionDefinition<T>.OptionValueStrToTypedValue(const AValueStr: String): T; var LValue: TValue; begin case FTypeInfo.Kind of tkInteger: begin var LIntVal := StrToInt(AValueStr); LValue := TValue.From<Integer>(LIntVal); end; tkInt64: begin var LInt64Val := StrToInt64(AValueStr); LValue := TValue.From<Int64>(LInt64Val); end; tkString, tkLString, tkWString, tkUString: begin LValue := TValue.From<string>(AValueStr); end; tkSet: begin var LIntVal := StringToSet(FTypeInfo, AValueStr); var LPtr := @LIntVal; LValue := TValue.From<T>(T(LPtr^)); end; tkEnumeration: begin if FTypeInfo.Name = StrBoolean then begin LValue := TValue.From<Boolean>(StringToBoolean(AValueStr)); end else begin var LIntVal := GetEnumValue(FTypeInfo, AValueStr); if LIntVal < 0 then raise EArgumentException.Create(Format(SInvalidEnumValue, [AValueStr])); LValue := TValue.FromOrdinal(FTypeInfo, LIntVal); end; end; tkFloat: begin var LFloatVal := StrToFloat(AValueStr); LValue := TValue.From<Double>(LFloatVal); end; else raise EArgumentException.Create(SInvalidOptionType); end; Result := LValue.AsType<T>; end; procedure TOptionDefinition<T>.Set_RequiresValue(const AValue: Boolean); begin FRequiresValue := AValue; InitOptionDefaultValue; end; procedure TOptionDefinition<T>.Set_HelpText(const AValue: String); begin FHelpText := AValue; end; procedure TOptionDefinition<T>.Set_IsOptionFile(const AValue: Boolean); begin FIsOptionFile := AValue; end; procedure TOptionDefinition<T>.Set_Required(const AValue: Boolean); begin FRequired := AValue; end; function TOptionDefinition<T>.WasFound: Boolean; begin Result := FWasFound; end; constructor TCmdlineParser.Create(const aNameValueSeparator: String); begin inherited Create; FAnonymousIndex := 0; FNameValueSeparator := aNameValueSeparator; end; destructor TCmdlineParser.Destroy; begin inherited; end; procedure TCmdlineParser.DoParse(const ACmdlineItems: TStrings; const AParseResult: IInternalParseResult); begin var LActiveCommand := TOptionsRegistry.DefaultCommand; for var I := 0 to ACmdlineItems.Count - 1 do begin var LCmdlineItem := ACmdlineItems.Strings[I]; // LCmdlineItem possibly empty, if inside quotes. if LCmdlineItem.IsEmpty then Continue; // Find if a new command appears, if so, set it as currently active command. Returns true if a new command // is set as currently active command. And if a new command is found, skip the rest. if ParseCommand(LCmdlineItem, LActiveCommand, AParseResult) then Continue; var LOption: IOptionDefinition; var LOptionValue: String; if not ParseOption(LCmdlineItem, LActiveCommand, LOption, LOptionValue, AParseResult) then Continue; if LOption.RequiresValue and LOptionValue.IsEmpty then begin AParseResult.AddError(Format(SOptionValueMissing, [LOption.Name, FNameValueSeparator])); Continue; end; if LOption.IsOptionFile then begin if not FileExists(LOptionValue) then begin AParseResult.AddError(Format(SParamFileMissing, [LOptionValue])); Continue; end else begin ParseOptionFile(LOptionValue, AParseResult); Break; // Option file override all other in-line options. end; end; var LErrStr: String; if not InvokeOption(LOption, LOptionValue, LErrStr) then AParseResult.AddError(LErrStr); end; end; function TCmdlineParser.HasOptionToken(var ACmdlineItem: String): Boolean; begin Result := False; for var token in OptionTokens do begin if StartsStr(token, ACmdlineItem) then begin Delete(ACmdlineItem, 1, Length(token)); Result := True; Break; end; end; end; function TCmdlineParser.InvokeOption(AOption: IOptionDefinition; const AValue: String; out AErrMsg: String): Boolean; begin try (AOption as IOptionDefinitionInvoke).Invoke(AValue); Result := True; except on E: Exception do begin Result := False; AErrMsg := Format(SErrSettingOption, [AOption.Name, AValue, E.Message]); end; end; end; function TCmdlineParser.Parse: ICmdlineParseResult; begin FAnonymousIndex := 0; // Reset anonymous option position to 0. var LCmdlineItems := TStringList.Create; try if ParamCount > 0 then begin for var I := 1 to ParamCount do LCmdlineItems.Add(ParamStr(I)); // Excluding ParamStr(0) end; Result := Parse(LCmdlineItems); finally LCmdlineItems.Free; end; end; function TCmdlineParser.Parse(const ACmdlineItems: TStrings): ICmdlineParseResult; begin Result := TCmdlineParseResult.Create; DoParse(ACmdlineItems, Result as IInternalParseResult); ValidateParseResult(Result as IInternalParseResult); end; function TCmdlineParser.ParseCommand(const ACmdlineItem: String; var AActiveCommand: ICommandDefinition; const AParseResult: IInternalParseResult): Boolean; begin var LCmdlineItem := ACmdlineItem; // Check if there is any option token, and strip off if any. if HasOptionToken(LCmdlineItem) then Exit(False); var LNewCommand: ICommandDefinition; Result := AActiveCommand.IsDefault and TryGetCommand(ACmdlineItem, LNewCommand); if Result then begin AActiveCommand := LNewCommand; FAnonymousIndex := 0; AParseResult.SetCommand(AActiveCommand); end; end; function TCmdlineParser.ParseOption(const ACmdlineItem: String; const AActiveCommand: ICommandDefinition; out AOption: IOptionDefinition; out AOptionValue: String; const AParseResult: IInternalParseResult): Boolean; begin var LCmdlineItem := ACmdlineItem; // Check if there is any option token, and strip off if any. if not HasOptionToken(LCmdlineItem) then begin // The command line item represents an anonymous option of the currently active command. if FAnonymousIndex < AActiveCommand.RegisteredAnonymousOptions.Count then begin AOption := AActiveCommand.RegisteredAnonymousOptions[FAnonymousIndex]; Inc(FAnonymousIndex); AOptionValue := LCmdlineItem; Result := True; end else begin AParseResult.AddError(Format(SUnknownAnonymousOption, [LCmdlineItem])); Result := False; end; end else begin // The command line item represents a named option var LNameValueSeparatorPos := Pos(FNameValueSeparator, LCmdlineItem); var LOptionName: String; if LNameValueSeparatorPos > 0 then begin // The named option has a name, and a value. LOptionName := Copy(LCmdlineItem, 1, LNameValueSeparatorPos - 1).Trim; AOptionValue := Copy(LCmdlineItem, LNameValueSeparatorPos + Length(FNameValueSeparator), MaxInt).Trim; StripQuotes(AOptionValue); end else begin // The named option has a name, without a value. LOptionName := LCmdlineItem; AOptionValue := EmptyStr; end; Result := TryGetOption(AActiveCommand, TOptionsRegistry.DefaultCommand, LOptionName, AOption); if not Result then AParseResult.AddError(Format(SUnknownOption, [LOptionName])); end; end; procedure TCmdlineParser.ParseOptionFile(const AFileName: String; const AParseResult: IInternalParseResult); begin var LCmdline := TStringList.Create; try LCmdline.LoadFromFile(AFileName); DoParse(LCmdline, AParseResult); finally LCmdline.Free; end; end; function TCmdlineParser.TryGetCommand(const AName: String; out ACommand: ICommandDefinition): Boolean; begin Result := TOptionsRegistry.RegisteredCommands.TryGetValue(LowerCase(AName), ACommand); end; function TCmdlineParser.TryGetOption(const ACommand, ADefaultCommand: ICommandDefinition; const AOptionName: String; out AOption: IOptionDefinition): Boolean; begin if not ACommand.TryGetOption(LowerCase(AOptionName), AOption) then begin // Continue to search the option in defaul command. if not ACommand.IsDefault then ADefaultCommand.TryGetOption(LowerCase(AOptionName), AOption); end; Result := Assigned(AOption); end; procedure TCmdlineParser.ValidateParseResult(const AParseResult: IInternalParseResult); begin for var LOption in TOptionsRegistry.DefaultCommand.RegisteredNamedOptions do begin if LOption.Required then begin if not (LOption as IOptionDefinitionInvoke).WasFound then AParseResult.AddError(Format(SRequiredNamedOptionMissing, [LOption.LongName])); end; end; for var LOption in TOptionsRegistry.DefaultCommand.RegisteredAnonymousOptions do begin if LOption.Required then begin if not (LOption as IOptionDefinitionInvoke).WasFound then begin AParseResult.AddError(SRequiredAnonymousOptionMissing); Break; end; end; end; if Assigned(AParseResult.Command) then begin for var LOption in AParseResult.Command.RegisteredNamedOptions do begin if LOption.Required then begin if not (LOption as IOptionDefinitionInvoke).WasFound then AParseResult.AddError(Format(SRequiredNamedOptionMissing, [LOption.LongName])); end; end; end; end; constructor TCmdlineParseResult.Create; begin FErrors := TStringList.Create; FCommand := nil; end; destructor TCmdlineParseResult.Destroy; begin FErrors.Free; inherited; end; procedure TCmdlineParseResult.AddError(const AError: String); begin FErrors.Add(AError) end; function TCmdlineParseResult.Get_Command: ICommandDefinition; begin Result := FCommand; end; function TCmdlineParseResult.Get_CommandName: String; begin if Assigned(FCommand) then Result := FCommand.Name else Result := EmptyStr; end; function TCmdlineParseResult.Get_ErrorText: String; begin Result := FErrors.Text; end; function TCmdlineParseResult.Get_HasErrors: Boolean; begin Result := FErrors.Count > 0; end; procedure TCmdlineParseResult.SetCommand(const ACommand: ICommandDefinition); begin FCommand := ACommand; end; initialization end.
{ ******************************************************************************* Title: T2TiPDV Description: Encerra um movimento aberto. The MIT License Copyright: Copyright (C) 2015 T2Ti.COM 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. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije @version 1.0 ******************************************************************************* } unit UEncerraMovimento; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, UBase, Dialogs, Grids, DBGrids, JvExDBGrids, JvDBGrid, StdCtrls, ExtCtrls, JvExStdCtrls, JvButton, JvCtrls, Buttons, JvExButtons, JvBitBtn, pngimage, FMTBcd, JvEnterTab, Provider, DBClient, DB, SqlExpr, Generics.Collections, JvComponentBase, Mask, JvExMask, JvToolEdit, JvBaseEdits, Biblioteca, Controller, JvDBUltimGrid, Tipos, DateUtils, Vcl.Imaging.jpeg, Printers; type TFEncerraMovimento = class(TFBase) Image1: TImage; GroupBox2: TGroupBox; editSenhaOperador: TLabeledEdit; GroupBox1: TGroupBox; editLoginGerente: TLabeledEdit; editSenhaGerente: TLabeledEdit; botaoConfirma: TJvBitBtn; botaoCancela: TJvImgBtn; JvEnterAsTab1: TJvEnterAsTab; Label1: TLabel; Label2: TLabel; Label3: TLabel; Bevel1: TBevel; Bevel2: TBevel; Bevel3: TBevel; LabelTurno: TLabel; LabelTerminal: TLabel; LabelOperador: TLabel; GroupBox3: TGroupBox; ComboTipoPagamento: TComboBox; Label5: TLabel; Label6: TLabel; Label8: TLabel; edtValor: TJvCalcEdit; btnAdicionar: TBitBtn; btnRemover: TBitBtn; edtTotal: TJvCalcEdit; DSFechamento: TDataSource; GridFechamento: TJvDBUltimGrid; CDSFechamento: TClientDataSet; Image2: TImage; Bevel4: TBevel; Memo1: TMemo; procedure Confirma; procedure FormActivate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure botaoConfirmaClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure TotalizaFechamento; procedure ImprimeFechamento; procedure btnAdicionarClick(Sender: TObject); procedure btnRemoverClick(Sender: TObject); procedure edtValorExit(Sender: TObject); procedure editSenhaGerenteExit(Sender: TObject); procedure botaoCancelaClick(Sender: TObject); private public { Public declarations } end; var FEncerraMovimento: TFEncerraMovimento; FechouMovimento: Boolean; implementation uses NfceFechamentoController, NfceTipoPagamentoVO, NfceOperadorVO, NfceFechamentoVO; {$R *.dfm} {$Region 'Infra'} procedure ImprimirMemo(Memo: TMemo); var I: integer; F: Text; begin { Usa na impressora a mesma fonte do memo } Printer.Canvas.Font.Assign(Memo.Font); AssignPrn(F); Rewrite(F); try for I := 0 to Memo.Lines.Count -1 do WriteLn(F, Memo.Lines[I]); finally CloseFile(F); end; end; procedure TFEncerraMovimento.FormCreate(Sender: TObject); var I: Integer; begin FechouMovimento := False; LabelTurno.Caption := Sessao.Movimento.NfceTurnoVO.Descricao; LabelTerminal.Caption := Sessao.Movimento.NfceCaixaVO.Nome; LabelOperador.Caption := Sessao.Movimento.NfceOperadorVO.Login; try for i := 0 to Sessao.ListaTipoPagamento.Count - 1 do ComboTipoPagamento.Items.Add(TNfceTipoPagamentoVO(Sessao.ListaTipoPagamento.Items[i]).Descricao); ComboTipoPagamento.ItemIndex := 0; finally end; end; procedure TFEncerraMovimento.FormActivate(Sender: TObject); begin Color := StringToColor(Sessao.Configuracao.CorJanelasInternas); ComboTipoPagamento.SetFocus; // Configura a Grid do Fechamento ConfiguraCDSFromVO(CDSFechamento, TNfceFechamentoVO); ConfiguraGridFromVO(GridFechamento, TNfceFechamentoVO); TotalizaFechamento; end; procedure TFEncerraMovimento.editSenhaGerenteExit(Sender: TObject); begin botaoConfirma.SetFocus; end; procedure TFEncerraMovimento.edtValorExit(Sender: TObject); begin if edtValor.Value = 0 then editSenhaOperador.SetFocus; end; procedure TFEncerraMovimento.FormClose(Sender: TObject; var Action: TCloseAction); begin if FechouMovimento then begin ModalResult := mrOK; Sessao.Movimento := Nil; end else ModalResult := mrCancel; Action := caFree; end; procedure TFEncerraMovimento.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F12 then Confirma; if Key = VK_ESCAPE then botaoCancela.Click; end; procedure TFEncerraMovimento.botaoCancelaClick(Sender: TObject); begin Close; end; procedure TFEncerraMovimento.botaoConfirmaClick(Sender: TObject); begin Confirma; end; {$EndRegion 'Infra'} {$Region 'Dados de Fechamento'} procedure TFEncerraMovimento.btnAdicionarClick(Sender: TObject); var Fechamento: TNfceFechamentoVO; begin if trim(ComboTipoPagamento.Text) = '' then begin Application.MessageBox('Informe um tipo de Pagamento Válido!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); ComboTipoPagamento.SetFocus; Exit; end; if edtValor.Value <= 0 then begin Application.MessageBox('Informe um Valor Válido!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); edtValor.SetFocus; Exit; end; try Fechamento := TNfceFechamentoVO.Create; Fechamento.IdNfceMovimento := Sessao.Movimento.Id; Fechamento.TipoPagamento := ComboTipoPagamento.Text; Fechamento.Valor := edtValor.Value; TController.ExecutarMetodo('NfceFechamentoController.TNfceFechamentoController', 'Insere', [Fechamento], 'PUT', 'Lista'); TotalizaFechamento; finally FreeAndNil(Fechamento); end; edtValor.Clear; ComboTipoPagamento.SetFocus; end; procedure TFEncerraMovimento.btnRemoverClick(Sender: TObject); begin if not CDSFechamento.IsEmpty then begin TController.ExecutarMetodo('NfceFechamentoController.TNfceFechamentoController', 'Exclui', [CDSFechamento.FieldByName('ID').AsInteger], 'DELETE', 'Boolean'); TotalizaFechamento; end; ComboTipoPagamento.SetFocus; end; procedure TFEncerraMovimento.TotalizaFechamento; var Total: Extended; Filtro: String; begin // Verifica se já existem dados para o fechamento Filtro := 'ID_NFCE_MOVIMENTO = ' + IntToStr(Sessao.Movimento.Id); TNfceFechamentoController.SetDataSet(CDSFechamento); TController.ExecutarMetodo('NfceFechamentoController.TNfceFechamentoController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista'); Total := 0; if not CDSFechamento.IsEmpty then begin CDSFechamento.DisableControls; CDSFechamento.First; while not CDSFechamento.Eof do begin Total := Total + CDSFechamento.FieldByName('VALOR').AsExtended; CDSFechamento.Next; end; CDSFechamento.EnableControls; end; edtTotal.Value := Total; end; {$EndRegion 'Dados de Fechamento'} {$Region 'Confirmação e Encerramento do Movimento'} procedure TFEncerraMovimento.Confirma; var Operador: TNfceOperadorVO; Gerente: TNfceOperadorVO; begin try try // verifica se senha do operador esta correta Operador := TNfceOperadorVO(TController.BuscarObjeto('NfceOperadorController.TNfceOperadorController', 'Usuario', [LabelOperador.Caption, editSenhaOperador.Text], 'GET')); if Assigned(Operador) then begin // verifica se senha do gerente esta correta Gerente := TNfceOperadorVO(TController.BuscarObjeto('NfceOperadorController.TNfceOperadorController', 'Usuario', [editLoginGerente.Text, editSenhaGerente.Text], 'GET')); if Assigned(Gerente) then begin if (Gerente.NivelAutorizacao = 'G') or (Gerente.NivelAutorizacao = 'S') then begin // encerra movimento Sessao.Movimento.DataFechamento := Date; Sessao.Movimento.HoraFechamento := FormatDateTime('hh:nn:ss', Now); Sessao.Movimento.StatusMovimento := 'F'; TController.ExecutarMetodo('NfceMovimentoController.TNfceMovimentoController', 'Altera', [Sessao.Movimento], 'POST', 'Boolean'); ImprimeFechamento; Application.MessageBox('Movimento encerrado com sucesso.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); FechouMovimento := True; botaoConfirma.ModalResult := mrOK; self.ModalResult := mrOK; Close; end else begin Application.MessageBox('Gerente ou Supervisor: nível de acesso incorreto.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); editLoginGerente.SetFocus; end; // if (Gerente.Nivel = 'G') or (Gerente.Nivel = 'S') then end else begin Application.MessageBox('Gerente ou Supervisor: dados incorretos.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); editLoginGerente.SetFocus; end; // if Gerente.Id <> 0 then end else begin Application.MessageBox('Operador: dados incorretos.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); editSenhaOperador.SetFocus; end; // if Operador.Id <> 0 then except end; finally if Assigned(Operador) then FreeAndNil(Operador); if Assigned(Gerente) then FreeAndNil(Gerente); end; end; {$EndRegion 'Confirmação e Encerramento do Movimento'} {$Region 'Impressão do Fechamento'} procedure TFEncerraMovimento.ImprimeFechamento; var Declarado, Meio: AnsiString; Suprimento, Sangria, NaoFiscal, TotalVenda, Desconto, Acrescimo, Recebido, Troco, Cancelado, TotalFinal: AnsiString; TotDeclarado: Currency; begin // Exercício: implemente o relatório no seu gerenciador preferido try Memo1.Lines.Add(StringOfChar('=', 48)); Memo1.Lines.Add(' FECHAMENTO DE CAIXA '); Memo1.Lines.Add(StringOfChar('=', 48)); Memo1.Lines.Add(''); Memo1.Lines.Add('DATA DE ABERTURA : ' + FormatDateTime('dd/mm/yyyy', Sessao.Movimento.DataAbertura)); Memo1.Lines.Add('HORA DE ABERTURA : ' + Sessao.Movimento.HoraAbertura); Memo1.Lines.Add('DATA DE FECHAMENTO: ' + FormatDateTime('dd/mm/yyyy', Sessao.Movimento.DataFechamento)); Memo1.Lines.Add('HORA DE FECHAMENTO: ' + Sessao.Movimento.HoraFechamento); Memo1.Lines.Add(Sessao.Movimento.NfceCaixaVO.Nome + ' OPERADOR: ' + Sessao.Movimento.NfceOperadorVO.Login); Memo1.Lines.Add('MOVIMENTO: ' + IntToStr(Sessao.Movimento.Id)); Memo1.Lines.Add(StringOfChar('=', 48)); Memo1.Lines.Add(''); Suprimento := FloatToStrF(Sessao.Movimento.TotalSuprimento, ffNumber, 11, 2); Suprimento := StringOfChar(' ', 33 - Length(Suprimento)) + Suprimento; Sangria := FloatToStrF(Sessao.Movimento.TotalSangria, ffNumber, 11, 2); Sangria := StringOfChar(' ', 33 - Length(Sangria)) + Sangria; NaoFiscal := FloatToStrF(Sessao.Movimento.TotalNaoFiscal, ffNumber, 11, 2); NaoFiscal := StringOfChar(' ', 33 - Length(NaoFiscal)) + NaoFiscal; TotalVenda := FloatToStrF(Sessao.Movimento.TotalVenda, ffNumber, 11, 2); TotalVenda := StringOfChar(' ', 33 - Length(TotalVenda)) + TotalVenda; Desconto := FloatToStrF(Sessao.Movimento.TotalDesconto, ffNumber, 11, 2); Desconto := StringOfChar(' ', 33 - Length(Desconto)) + Desconto; Acrescimo := FloatToStrF(Sessao.Movimento.TotalAcrescimo, ffNumber, 11, 2); Acrescimo := StringOfChar(' ', 33 - Length(Acrescimo)) + Acrescimo; Recebido := FloatToStrF(Sessao.Movimento.TotalRecebido, ffNumber, 11, 2); Recebido := StringOfChar(' ', 33 - Length(Recebido)) + Recebido; Troco := FloatToStrF(Sessao.Movimento.TotalTroco, ffNumber, 11, 2); Troco := StringOfChar(' ', 33 - Length(Troco)) + Troco; Cancelado := FloatToStrF(Sessao.Movimento.TotalCancelado, ffNumber, 11, 2); Cancelado := StringOfChar(' ', 33 - Length(Cancelado)) + Cancelado; TotalFinal := FloatToStrF(Sessao.Movimento.TotalFinal, ffNumber, 11, 2); TotalFinal := StringOfChar(' ', 33 - Length(TotalFinal)) + TotalFinal; Memo1.Lines.Add('SUPRIMENTO...: ' + Suprimento); Memo1.Lines.Add('SANGRIA......: ' + Sangria); Memo1.Lines.Add('NAO FISCAL...: ' + NaoFiscal); Memo1.Lines.Add('TOTAL VENDA..: ' + TotalVenda); Memo1.Lines.Add('DESCONTO.....: ' + Desconto); Memo1.Lines.Add('ACRESCIMO....: ' + Acrescimo); Memo1.Lines.Add('RECEBIDO.....: ' + Recebido); Memo1.Lines.Add('TROCO........: ' + Troco); Memo1.Lines.Add('CANCELADO....: ' + Cancelado); Memo1.Lines.Add('TOTAL FINAL..: ' + TotalFinal); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add(StringOfChar('=', 48)); Memo1.Lines.Add(' VALORES DECLARADOS PARA FECHAMENTO'); Memo1.Lines.Add(StringOfChar('=', 48)); Memo1.Lines.Add(''); CDSFechamento.DisableControls; CDSFechamento.First; while not CDSFechamento.Eof do begin Declarado := FloatToStrF(CDSFechamento.FieldByName('VALOR').AsExtended, ffNumber, 9, 2); Declarado := StringOfChar(' ', 28 - Length(Declarado)) + Declarado; Meio := CDSFechamento.FieldByName('TIPO_PAGAMENTO').AsString; Meio := StringOfChar(' ', 20 - Length(Meio)) + Meio; TotDeclarado := TotDeclarado + CDSFechamento.FieldByName('VALOR').AsExtended; Memo1.Lines.Add(Meio + Declarado); CDSFechamento.Next; end; CDSFechamento.First; CDSFechamento.EnableControls; Memo1.Lines.Add(StringOfChar('-', 48)); Declarado := FloatToStrF(TotDeclarado, ffNumber, 9, 2); Declarado := StringOfChar(' ', 33 - Length(Declarado)) + Declarado; Memo1.Lines.Add('TOTAL.........:' + Declarado); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add(' ________________________________________ '); Memo1.Lines.Add(' VISTO DO CAIXA '); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add(''); Memo1.Lines.Add(' ________________________________________ '); Memo1.Lines.Add(' VISTO DO SUPERVISOR '); ImprimirMemo(Memo1); finally end; end; {$EndRegion 'Impressão do Fechamento'} end.
unit Hatch; ///////////////////////////////////////////////////////////////////// // // Hi-Files Version 2 // Copyright (c) 1997-2004 Dmitry Liman [2:461/79] // // http://hi-files.narod.ru // ///////////////////////////////////////////////////////////////////// interface procedure RunHatcher; { =================================================================== } implementation uses {$IFDEF Win32} Windows, {$ENDIF} Objects, MyLib, MyViews, Views, Dialogs, Drivers, Editors, App, _fopen, MsgBox, SysUtils, _LOG, _CFG, _RES, _Fareas, _Tic, _CRC32, Gen, HiFiHelp; const MEMO_BUFFER_SIZE = $FFF0; { --------------------------------------------------------- } { TFileEchoBox } { --------------------------------------------------------- } type PFileEchoBox = ^TFileEchoBox; TFileEchoBox = object (TMyListBox) function GetText( Item, MaxLen: Integer ) : String; virtual; function DataSize: Integer; virtual; procedure SetData( var Data ); virtual; procedure GetData( var Data ); virtual; end; { TFileEchoBox } { GetText ------------------------------------------------- } function TFileEchoBox.GetText( Item, MaxLen: Integer ) : String; begin Result := PFileEcho( List^.At(Item) )^.Name^; end; { GetText } { DataSize ------------------------------------------------ } function TFileEchoBox.DataSize: Word; begin Result := TListBox.DataSize; end; { DataSize } { GetData ------------------------------------------------- } procedure TFileEchoBox.GetData( var Data ); begin TListBox.GetData( Data ); end; { GetData } { SetData ------------------------------------------------- } procedure TFileEchoBox.SetData( var Data ); begin TListBox.SetData( Data ); end; { SetData } { --------------------------------------------------------- } { SelectFileEcho } { --------------------------------------------------------- } function SelectFileEcho( var Echo: PFileEcho ) : Boolean; var R: TRect; D: PDialog; Q: record List: PCollection; Sel : Word; end; begin R.Assign( 0, 0, 0, 0 ); D := PDialog( Res^.Get('SELECT_ECHO') ); D^.HelpCtx := hcSelectEcho; ShoeHorn( D, New( PFileEchoBox, Init( R, 1, nil))); Q.List := FileBase^.EchoList; if Echo <> nil then Q.Sel := FileBase^.EchoList^.IndexOf( Echo ) else Q.Sel := 0; if Application^.ExecuteDialog( D, @Q ) = cmOk then begin if Q.Sel < FileBase^.EchoList^.Count then begin Echo := FileBase^.EchoList^.At( Q.Sel ); Result := True; end; end else begin Echo := nil; Result := False; end; end; { SelectFileEcho } { --------------------------------------------------------- } { PHatchDialog } { --------------------------------------------------------- } const bDelayToss = $0001; bKillFile = $0002; type PMemoData = ^TMemoData; PHatchDialogData = ^THatchDialogData; THatchDialogData = record FileName: LongStr; EchoTag : LongStr; Replaces: LongStr; Magic : LongStr; Opt : Longint; MemoData: PMemoData; end; { THatchDialogData } PHatchDialog = ^THatchDialog; THatchDialog = object (TDialog) FileName: PInputLine; Echotag : PInputLine; Replaces: PInputLine; Magic : PInputLine; Opt : PCheckBoxes; Memo : PMemo; procedure SetupDialog; procedure SetData( var Data ); virtual; procedure GetData( var Data ); virtual; function DataSize: Word; virtual; procedure HandleEvent( var Event: TEvent ); virtual; private procedure BrowseFile; procedure SelectArea; procedure GetDiz; end; { THatchDialog } { DataSize ------------------------------------------------ } function THatchDialog.DataSize: Word; begin Result := SizeOf(THatchDialogData); end; { DataSize } { GetData ------------------------------------------------- } procedure THatchDialog.GetData( var Data ); var Q: THatchDialogData absolute Data; begin if Q.MemoData <> nil then FreeMem( Q.MemoData ); GetMem( Q.MemoData, Memo^.DataSize ); FileName^.GetData( Q.FileName ); EchoTag^.GetData( Q.EchoTag ); Replaces^.GetData( Q.Replaces ); Magic^.GetData( Q.Magic ); Opt^.GetData( Q.Opt ); Memo^.GetData( Q.MemoData^ ); end; { GetData } { SetData ------------------------------------------------- } procedure THatchDialog.SetData( var Data ); var Q: THatchDialogData absolute Data; begin FileName^.SetData( Q.FileName ); EchoTag^.SetData( Q.EchoTag ); Replaces^.SetData( Q.Replaces ); Magic^.SetData( Q.Magic ); Opt^.SetData( Q.Opt ); if Q.MemoData = nil then begin GetMem( Q.MemoData, SizeOf(Word) ); Q.MemoData^.Length := 0; end; Memo^.SetData( Q.MemoData^ ); FreeMem( Q.MemoData ); Q.MemoData := nil; end; { SetData } { SetupDialog --------------------------------------------- } procedure THatchDialog.SetupDialog; const ISize = SizeOf(LongStr) - 1; var R: TRect; begin R.Assign( 0, 0, 0, 0 ); Memo := PMemo( ShoeHorn( @Self, New( PMemo, Init( R, nil, nil, nil, MEMO_BUFFER_SIZE) ))); Opt := PCheckBoxes( ShoeHorn( @Self, New( PCheckBoxes, Init( R, nil )))); Magic := PInputLine( ShoeHorn( @Self, New( PInputLine, Init( R, ISize )))); Replaces := PInputLine( ShoeHorn( @Self, New( PInputLine, Init( R, ISize )))); EchoTag := PInputLine( ShoeHorn( @Self, New( PInputLine, Init( R, ISize )))); FileName := PInputLine( ShoeHorn( @Self, New( PInputLine, Init( R, ISize )))); Memo^.GetBounds( R ); R.A.X := R.B.X; R.B.X := R.A.X + 1; Memo^.VScrollBar := New( PScrollBar, Init(R) ); Insert( Memo^.VScrollBar ); end; { SetupDialog } { HandleEvent --------------------------------------------- } procedure THatchDialog.HandleEvent( var Event: TEvent ); const cmBrowseFile = 200; cmSelectArea = 201; cmGetDiz = 202; begin inherited HandleEvent( Event ); case Event.What of evCommand: begin case Event.Command of cmBrowseFile: BrowseFile; cmSelectArea: SelectArea; cmGetDiz : GetDiz; else Exit; end; ClearEvent( Event ); end; end; end; { HandleEvent } { BrowseFile ---------------------------------------------- } procedure THatchDialog.BrowseFile; var FName: String; begin FName := '*.*'; if not ExecFileOpenDlg(LoadString(_SHatchCaption), FName, FName) then Exit; if FileExists( FName ) then FileName^.SetData( FName ) else ShowError( Format(LoadString(_SFileNotFound), [FName] )); end; { BrowseFile } { SelectArea ---------------------------------------------- } procedure THatchDialog.SelectArea; var EName: String; Echo : PFileEcho; begin OpenFileBase; EchoTag^.GetData( EName ); Echo := FileBase^.GetEcho( EName ); if SelectFileEcho( Echo ) then EchoTag^.SetData( Echo^.Name^ ); end; { SelectArea } { GetDiz -------------------------------------------------- } procedure THatchDialog.GetDiz; var FD: PFileDef; NS: LongStr; MD: PMemoData; N : Word; procedure DoSum( P: PString ); far; begin Inc( N, Length(P^) + 2 ); end; { DoSum } procedure DoCopy( P: PString ); far; begin Move( P^[1], MD^.Buffer[N], Length(P^) ); Inc( N, Length(P^) + 2 ); MD^.Buffer[N-2] := ^M; MD^.Buffer[N-1] := ^J; end; { DoCopy } begin FileName^.GetData( NS ); FD := New( PFileDef, Init(ExtractFileName(NS))); try BuildComment( FD, ExtractFilePath(NS) ); if FD^.NoComment then MessageBox( LoadString(_SGetDizFailed), nil, mfWarning + mfOkButton ) else begin N := 0; FD^.ForEach( @DoSum ); GetMem( MD, N + SizeOf(Word) ); MD^.Length := N; N := 0; FD^.ForEach( @DoCopy ); Memo^.SetData( MD^ ); FreeMem( MD ); end; finally Destroy( FD ); end; end; { GetDiz } { --------------------------------------------------------- } { RunHatcher } { --------------------------------------------------------- } procedure RunHatcher; var R: TRect; D: PDialog; E: PHatchDialog; Q: THatchDialogData; S: String; B: Integer; Tic: PTic; Ok : Boolean; {$IFDEF Win32} var ShortName : String; InboundName: String; {$ENDIF} function GetLine( var S: String ) : Boolean; var j: Word; L: Byte absolute S; begin S := ''; Result := False; if B >= Q.MemoData^.Length then Exit; j := ScanR( Q.MemoData^.Buffer, B, Q.MemoData^.Length, #$0d ); L := j - B; Move( Q.MemoData^.Buffer[B], S[1], L ); B := j + 2; Result := True; end; { GetLine } begin Log^.Write( ll_Service, LoadString(_SLogStartHatcher) ); R.Assign( 0, 0, 0, 0 ); D := PDialog( Res^.Get('HATCH') ); D^.HelpCtx := hcHatch; E := New( PHatchDialog, Init(R, '') ); SwapDlg( D, E ); E^.SetupDialog; FillChar( Q, SizeOf(Q), 0 ); Tic := nil; try if Application^.ExecuteDialog( E, @Q ) = cmOk then begin New( Tic, Init ); {$IFDEF Win32} if VFS_GetShortName( Q.FileName, ShortName ) then begin InboundName := AtPath( ShortName, CFG^.Inbound ); if TestBit( Q.Opt, bKillFile ) then ok := VFS_MoveFile( Q.FileName, InboundName ) = 0 else ok := VFS_CopyFile( Q.FileName, InboundName ); if not ok then raise Exception.Create( Format(LoadString(_SCantCopyToInbound), [Q.FileName] )); MyLib.ReplaceStr( Tic^.FileName, ExtractFileName(InboundName) ); MyLib.ReplaceStr( Tic^.FullName, ExtractFileName(Q.FileName) ); end else begin {$ENDIF} if TestBit( Q.Opt, bKillFile ) then ok := VFS_MoveFile( Q.FileName, AtPath(Q.FileName, CFG^.Inbound) ) = 0 else ok := VFS_CopyFile( Q.FileName, AtPath(Q.FileName, CFG^.Inbound) ); if not ok then raise Exception.Create( Format(LoadString(_SCantCopyToInbound), [Q.FileName] )); MyLib.ReplaceStr( Tic^.FileName, ExtractFileName(Q.FileName) ); {$IFDEF Win32} end; {$ENDIF} with Tic^ do begin CRC := GetFileCrc( Q.FileName ); MyLib.ReplaceStr( AreaTag, Q.EchoTag ); if Q.Magic <> '' then MyLib.ReplaceStr( Magic, Q.Magic ); if Q.Replaces <> '' then MyLib.ReplaceStr( Replaces, Q.Replaces ); B := 0; GetLine( S ); New( LDesc, Init(20, 20) ); MyLib.ReplaceStr( Desc, S ); while GetLine( S ) do LDesc^.Insert( AllocStr(S) ); Origin := CFG^.PrimaryAddr; FromAddr := Origin; ToAddr := Origin; MyLib.ReplaceStr( Created, 'by ' + SHORT_PID ); MyLib.ReplaceStr( Pw, CFG^.HatchPw ); Tic^.SaveTo( BuildTicName(CFG^.PrimaryAddr, CFG^.Inbound), @CFG^.PrimaryAddr ); Log.Write( ll_Service, Format(LoadString(_SFileHatchOk), [Q.FileName, Q.EchoTag] )); if TestBit( Q.Opt, bDelayToss ) then MessageBox( LoadString(_STicBuilt), nil, mfInformation + mfOkButton ) else begin RunTicTosser; MessageBox( LoadString(_SHatchDone), nil, mfInformation + mfOkButton ); end end end; except on E: Exception do ShowError( E.Message ); end; if Q.MemoData <> nil then FreeMem( Q.MemoData ); if Tic <> nil then Destroy( Tic ); end; { RunHatcher } end.
unit OrderedListUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, DBGridEh, DB, IBCustomDataSet, IBQuery, IBUpdateSQL, ComCtrls, DataUnit; type { TOrderedListForm } TOrderedListForm = class(TForm) OKBtn: TButton; CancelBtn: TButton; ListQuery: TIBQuery; ListView: TListView; UpBtn: TButton; DownBtn: TButton; procedure ListViewColumnClick(Sender: TObject; Column: TListColumn); procedure ListViewCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure ListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure UpBtnClick(Sender: TObject); procedure DownBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); private FSorted: Boolean; FIndex: Integer; FAscending: Boolean; FSection: string; procedure ReassignIndices; public procedure FillListView; property Section: string read FSection write FSection; end; var OrderedListForm: TOrderedListForm; procedure OrderedSelectList(const Caption, SQL: string; const Params: array of Integer; const StorageSection: string; const ColumnInfos: array of TListColumnInfo; List: TList); procedure OrderSelectProductAttributes(Kind, ProductID: Integer; List: TList); procedure OrderSelectFillProductAttributes(ProductID: Integer; List: TList); implementation uses StorageUnit; {$R *.dfm} procedure OrderSelectProductAttributes(Kind, ProductID: Integer; List: TList); const ColumnInfos: array [0..2] of TListColumnInfo = ( (Title: 'Номер пп.'; Width: 80), (Title: 'Название'; Width: 120), (Title: 'Описание'; Width: 180) ); begin OrderedSelectList('Порядок следования атрибутов', 'select AL.ATTR_ID, A.NAME, A.DESCR' + ' from ATTR_LIST AL' + ' left join ATTRIBUTES A on (AL.ATTR_ID = A.ID)' + ' where (AL.KIND = :KIND) and (AL.ID = :ID)' + ' order by AL.ORDER_ID', [Kind, ProductID], 'OrderedListForm.ATTR_LIST', ColumnInfos, List); end; // Для налива procedure OrderSelectFillProductAttributes(ProductID: Integer; List: TList); const ColumnInfos: array [0..2] of TListColumnInfo = ( (Title: 'Номер пп.'; Width: 80), (Title: 'Название'; Width: 120), (Title: 'Описание'; Width: 180) ); begin OrderedSelectList('Порядок следования атрибутов', 'select AL.ATTR_ID, A.NAME, A.DESCR' + ' from FILL_ATTR_LIST AL' + ' left join ATTRIBUTES A on (AL.ATTR_ID = A.ID)' + ' where (AL.PRODUCT_ID = :PRODUCT_ID)' + ' order by AL.ORDER_ID', [ProductID], 'OrderedListForm.FILL_ATTR_LIST', ColumnInfos, List); end; type { TListItemProp } TListItemProp = class(TObject) Index: Integer; Id: Integer; end; procedure OrderedSelectList(const Caption, SQL: string; const Params: array of Integer; const StorageSection: string; const ColumnInfos: array of TListColumnInfo; List: TList); var Form: TOrderedListForm; I: Integer; Column: TListColumn; begin Form := TOrderedListForm.Create(Application); try Form.Caption := Caption; Form.ListQuery.SQL.Text := SQL; Form.Section := StorageSection; for I := Low(ColumnInfos) to High(ColumnInfos) do begin Column := Form.ListView.Columns.Add; Column.Caption := ColumnInfos[I].Title; Column.Width := ColumnInfos[I].Width; end; for I := 0 to Form.ListQuery.Params.Count - 1 do begin Form.ListQuery.Params[I].AsInteger := Params[I]; end; Form.FillListView; if Form.ShowModal = mrOK then begin for I := 0 to Form.ListView.Items.Count - 1 do List.Add(Pointer(TListItemProp(Form.ListView.Items[I].Data).ID)); end; finally Form.Free; end; end; { TOrderedListForm } procedure TOrderedListForm.FillListView; var ItemProp: TListItemProp; ListItem: TListItem; Index, I: Integer; begin ListQuery.Open; try Index := 0; while not ListQuery.Eof do begin ListItem := ListView.Items.Add; ItemProp := TListItemProp.Create; ListItem.Data := ItemProp; ItemProp.Index := Index; Inc(Index); ItemProp.Id := ListQuery.Fields[0].AsInteger; ListItem.Caption := IntToStr(Index); for I := 1 to ListQuery.Fields.Count - 1 do begin ListItem.SubItems.Add(ListQuery.Fields[I].AsString); end; ListQuery.Next; end; finally ListQuery.Close; end; ListView.CustomSort(nil, -1); end; procedure TOrderedListForm.ListViewColumnClick(Sender: TObject; Column: TListColumn); begin if not FSorted or (FIndex <> Column.Index) then begin FSorted := True; FIndex := Column.Index; FAscending := True; end else FAscending := not FAscending; ListView.CustomSort(nil, Column.Index); ReassignIndices; end; procedure TOrderedListForm.ReassignIndices; var I: Integer; begin for I := 0 to ListView.Items.Count - 1 do TListItemProp(ListView.Items[I].Data).Index := I; end; function IntegerCompare(I1, I2: Integer): Integer; begin if I1 > I2 then Result := 1 else if I1 = I2 then Result := 0 else Result := -1; end; procedure TOrderedListForm.ListViewCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); begin if Data = -1 then begin Compare := IntegerCompare(TListItemProp(Item1.Data).Index, TListItemProp(Item2.Data).Index); // do not count asc/desc mode !!! Exit; end else if Data = 0 then Compare := IntegerCompare(StrToIntDef(Item1.Caption, 0), StrToIntDef(Item2.Caption, 0)) else Compare := CompareText(Item1.SubItems[Data - 1], Item2.SubItems[Data - 1]); if not FAscending then Compare := - Compare; end; procedure TOrderedListForm.ListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); var SelectionIsNotEmpty: Boolean; begin SelectionIsNotEmpty := ListView.SelCount > 0; UpBtn.Enabled := SelectionIsNotEmpty; DownBtn.Enabled := SelectionIsNotEmpty; end; procedure TOrderedListForm.UpBtnClick(Sender: TObject); var I: Integer; ListItem, ListItem1: TListItem; begin ListItem := ListView.Items[0]; for I := 1 to ListView.Items.Count - 1 do begin ListItem1 := ListView.Items[I]; if not ListItem.Selected and ListItem1.Selected then begin Inc(TListItemProp(ListItem.Data).Index); Dec(TListItemProp(ListItem1.Data).Index); end else begin ListItem := ListItem1; end; end; ListView.CustomSort(nil, -1); end; procedure TOrderedListForm.DownBtnClick(Sender: TObject); var I: Integer; ListItem, ListItem1: TListItem; begin ListItem := ListView.Items[ListView.Items.Count - 1]; for I := ListView.Items.Count - 2 downto 0 do begin ListItem1 := ListView.Items[I]; if not ListItem.Selected and ListItem1.Selected then begin Dec(TListItemProp(ListItem.Data).Index); Inc(TListItemProp(ListItem1.Data).Index); end else begin ListItem := ListItem1; end; end; ListView.CustomSort(nil, -1); end; procedure TOrderedListForm.FormShow(Sender: TObject); begin LoadFormState(Self, Section, ''); end; procedure TOrderedListForm.FormHide(Sender: TObject); begin SaveFormState(Self, Section, ''); end; end.
unit unitVirtualMemory; interface uses Windows, Classes, SysUtils; type TVirtualMemoryStream = class (TCustomMemoryStream) private fReserved : Integer; fChunkSize : Integer; protected procedure SetSize (NewSize : Integer); override; public constructor Create (AReserved, AInitialSize : Integer); destructor Destroy; override; function Write(const Buffer; Count: Longint): Longint; override; property Reserved : Integer read fReserved; property ChunkSize : Integer read fChunkSize write fChunkSize; end; EVirtualMemory = class (Exception); implementation constructor TVirtualMemoryStream.Create (AReserved, AInitialSize : Integer); begin fReserved := AReserved; fChunkSize := 1024; SetPointer (VirtualAlloc (Nil, AReserved, MEM_RESERVE, PAGE_READWRITE), AInitialSize); if AInitialSize > 0 then VirtualAlloc (Memory, AInitialSize, MEM_COMMIT, PAGE_READWRITE); end; destructor TVirtualMemoryStream.Destroy; begin VirtualFree (Memory, 0, MEM_RELEASE); inherited; end; procedure TVirtualMemoryStream.SetSize (NewSize : Integer); var oldSize : Integer; commitSize : Integer; begin oldSize := Size; if NewSize <> oldSize then if NewSize <= Reserved then begin if NewSize > oldSize then // Grow the buffer begin commitSize := NewSize - oldSize; if commitSize < ChunkSize then commitSize := ChunkSize; if commitSize + oldSize > Reserved then commitSize := Reserved - oldSize; NewSize := oldSize + commitSize; VirtualAlloc (PChar (memory) + oldSize, commitSize, MEM_COMMIT, PAGE_READWRITE) end else // Shrink the buffer (lop off the end) VirtualFree (PChar (Memory) + NewSize, oldSize - NewSize, MEM_DECOMMIT); SetPointer (Memory, NewSize); end else raise EVirtualMemory.Create ('Size exceeds capacity'); end; function TVirtualMemoryStream.Write(const Buffer; Count: Longint): Longint; var pos : Integer; begin pos := Seek (0, soFromCurrent); if pos + count > Size then Size := pos + count; Move (buffer, PChar (Integer (memory) + pos)^, count); Seek (count, soFromCurrent); result := Count end; end.
unit TextEditor.Caret.Styles; interface uses System.Classes, TextEditor.Types; type TTextEditorCaretStyles = class(TPersistent) strict private FInsert: TTextEditorCaretStyle; FOnChange: TNotifyEvent; FOverwrite: TTextEditorCaretStyle; procedure DoChange; procedure SetInsert(const AValue: TTextEditorCaretStyle); procedure SetOverwrite(const AValue: TTextEditorCaretStyle); public constructor Create; procedure Assign(ASource: TPersistent); override; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Insert: TTextEditorCaretStyle read FInsert write SetInsert default csThinVerticalLine; property Overwrite: TTextEditorCaretStyle read FOverwrite write SetOverwrite default csThinVerticalLine; end; implementation constructor TTextEditorCaretStyles.Create; begin inherited; FInsert := csThinVerticalLine; FOverwrite := csThinVerticalLine; end; procedure TTextEditorCaretStyles.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCaretStyles) then with ASource as TTextEditorCaretStyles do begin Self.FOverwrite := FOverwrite; Self.FInsert := FInsert; Self.DoChange; end else inherited Assign(ASource); end; procedure TTextEditorCaretStyles.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TTextEditorCaretStyles.SetInsert(const AValue: TTextEditorCaretStyle); begin if FInsert <> AValue then begin FInsert := AValue; DoChange; end; end; procedure TTextEditorCaretStyles.SetOverwrite(const AValue: TTextEditorCaretStyle); begin if FOverwrite <> AValue then begin FOverwrite := AValue; DoChange; end; end; end.
unit BeepSpeaker; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TBeepSpeaker = class(TComponent) private { Private declarations } fInterval: integer; fEnabled: boolean; fTimer: TTimer; protected { Protected declarations } procedure SetInterval(interval: integer); virtual; procedure SetEnabled(enabled: boolean); virtual; procedure BeepSpeaker(sender: TObject); virtual; public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; published { Published declarations } property Interval: integer read fInterval write SetInterval; property Enabled: boolean read fEnabled write SetEnabled; end; implementation constructor TBeepSpeaker.Create(Owner: TComponent); begin inherited Create(Owner); fTimer:=TTimer.Create(self); fTimer.Enabled:=False; SetInterval(fTimer.Interval); fTimer.OnTimer:=BeepSpeaker; end; destructor TBeepSpeaker.Destroy; begin fTimer.Enabled:=False; fTimer.Free; inherited Destroy; end; procedure TBeepSpeaker.SetInterval(interval: integer); begin fInterval:=interval; fTimer.Interval:=interval; end; procedure TBeepSpeaker.SetEnabled(enabled: boolean); begin fEnabled:=enabled; fTimer.Enabled:=enabled; end; procedure TBeepSpeaker.BeepSpeaker(sender: TObject); begin Beep; end; end.