text
stringlengths
14
6.51M
unit DW.OSLog.Android; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // DW DW.OSLog; type /// <remarks> /// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS /// </remarks> TPlatformOSLog = record public class function GetTrace: string; static; class procedure Log(const ALogType: TLogType; const AMsg: string); static; class procedure Trace; static; end; implementation uses // RTL System.SysUtils, // Android Androidapi.JNI.JavaTypes, Androidapi.Log, Androidapi.Helpers, // DW DW.Androidapi.JNI.Log; { TPlatformOSLog } class procedure TPlatformOSLog.Log(const ALogType: TLogType; const AMsg: string); var LMarshaller: TMarshaller; LPointer: Pointer; begin LPointer := LMarshaller.AsUtf8(AMsg).ToPointer; case ALogType of TLogType.Debug: LOGI(LPointer); TLogType.Warning: LOGW(LPointer); TLogType.Error: LOGE(LPointer); end; end; class function TPlatformOSLog.GetTrace: string; begin Result := JStringToString(TJutil_Log.JavaClass.getStackTraceString(TJException.JavaClass.init)); end; class procedure TPlatformOSLog.Trace; begin Log(TLogType.Debug, GetTrace); end; end.
unit Sample5.Contact; interface uses DSharp.Core.PropertyChangedBase; type TContact = class(TPropertyChangedBase) private FLastname: string; FFirstname: string; procedure SetFirstname(const Value: string); procedure SetLastname(const Value: string); public constructor Create(AFirstname: string = ''; ALastname: string = ''); property Firstname: string read FFirstname write SetFirstname; property Lastname: string read FLastname write SetLastname; end; implementation { TContact } constructor TContact.Create(AFirstname, ALastname: string); begin FFirstname := AFirstname; FLastname := ALastname; end; procedure TContact.SetFirstname(const Value: string); begin FFirstname := Value; NotifyOfPropertyChange('Firstname'); end; procedure TContact.SetLastname(const Value: string); begin FLastname := Value; NotifyOfPropertyChange('Lastname'); end; end.
unit GoodsAdditionalEdit; interface uses DataModul, AncestorEditDialog, ParentForm, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, cxPropertiesStore, dsdAddOn, dsdGuides, dsdDB, dsdAction, System.Classes, Vcl.ActnList, cxMaskEdit, cxButtonEdit, cxCurrencyEdit, Vcl.StdCtrls, cxButtons, cxLabel, Vcl.Controls, cxTextEdit, cxCheckBox, dxSkinsCore, dxSkinsDefaultPainters, cxDBEdit, cxCheckListBox, Data.DB, Datasnap.DBClient; type TGoodsAdditionalEditForm = class(TAncestorEditDialogForm) edName: TcxTextEdit; cxLabel1: TcxLabel; cxLabel2: TcxLabel; ceCode: TcxCurrencyEdit; Код: TcxLabel; GoodsMakerNameGuides: TdsdGuides; edMakerName: TcxButtonEdit; edNumberPlates: TcxCurrencyEdit; cxLabel3: TcxLabel; cxLabel7: TcxLabel; ceQtyPackage: TcxCurrencyEdit; cbIsRecipe: TcxCheckBox; edNameUkr: TcxTextEdit; cxLabel12: TcxLabel; edFormDispensing: TcxButtonEdit; cxLabel14: TcxLabel; FormDispensingGuides: TdsdGuides; edMakerNameUkr: TcxTextEdit; cxLabel4: TcxLabel; edDosage: TcxTextEdit; cxLabel5: TcxLabel; edVolume: TcxTextEdit; cxLabel6: TcxLabel; edGoodsMethodAppl: TcxButtonEdit; cxLabel9: TcxLabel; edGoodsSignOrigin: TcxButtonEdit; cxLabel10: TcxLabel; GoodsSignOriginGuides: TdsdGuides; GoodsMethodApplGuides: TdsdGuides; cblGoodsWhoCan: TcxCheckListBox; cxLabel8: TcxLabel; CheckListBoxAddOnWhoCanGuides: TCheckListBoxAddOn; WhoCanGuidesCDS: TClientDataSet; spSelect_GoodsWhoCan: TdsdStoredProc; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} initialization RegisterClass(TGoodsAdditionalEditForm); end.
unit uKeyboardSpecialKeyTest; { ********** * Test d'appui des touches spéciales du clavier ********** Liste des modifications : 04/04/2017, Patrick Prémartin (Olf Software) : version Windows/Mac du programme (utilisable en VCL et Firemonkey) } // (c) Patrick Prémartin / Olf Software 07/2017 interface type tKeyboardSpecialKeyTestPosition = (Left, Right, All, Any); tKeyboardSpecialKeyTest = class class function isAltDown(Position : tKeyboardSpecialKeyTestPosition = Any): Boolean; class function isCtrlDown(Position : tKeyboardSpecialKeyTestPosition = Any): Boolean; class function isShiftDown(Position : tKeyboardSpecialKeyTestPosition = Any): Boolean; class function isWindowsDown(Position : tKeyboardSpecialKeyTestPosition = Any): Boolean; class function isCommandDown(Position : tKeyboardSpecialKeyTestPosition = Any): Boolean; end; implementation {$IF Defined(MSWINDOWS)} uses windows; {$ELSEIF Defined(IOS)} {$ELSEIF Defined(MACOS)} uses macapi.appkit; {$ELSEIF Defined(ANDROID)} {$ELSEIF Defined(LINUX)} {$ENDIF} type tKeyboardSpecialKeyTestKeycode = (Alt, Shift, Ctrl, windows, command); function isKeyDown(key: tKeyboardSpecialKeyTestKeycode; Position: tKeyboardSpecialKeyTestPosition): Boolean; {$IF Defined(MSWINDOWS)} {$ELSEIF Defined(IOS)} {$ELSEIF Defined(MACOS)} {$ELSEIF Defined(ANDROID)} {$ELSEIF Defined(LINUX)} {$ENDIF} begin result := false; {$IF Defined(MSWINDOWS)} case Position of Left: case key of Alt: result := (getKeyState(VK_LMENU) < 0); Shift: result := (getKeyState(VK_LSHIFT) < 0); Ctrl: result := (getKeyState(VK_LCONTROL) < 0); windows: result := (getKeyState(VK_LWIN) < 0); end; Right: case key of Alt: result := (getKeyState(VK_RMENU) < 0); Shift: result := (getKeyState(VK_RSHIFT) < 0); Ctrl: result := (getKeyState(VK_RCONTROL) < 0); windows: result := (getKeyState(VK_RWIN) < 0); end; Any: case key of Alt: result := (getKeyState(VK_MENU) < 0); Shift: result := (getKeyState(VK_SHIFT) < 0); Ctrl: result := (getKeyState(VK_CONTROL) < 0); windows: result := (getKeyState(VK_LWIN) < 0) or (getKeyState(VK_RWIN) < 0); end; All: case key of Alt: result := (getKeyState(VK_LMENU) < 0) and (getKeyState(VK_RMENU) < 0); Shift: result := (getKeyState(VK_LSHIFT) < 0) and (getKeyState(VK_RSHIFT) < 0); Ctrl: result := (getKeyState(VK_LCONTROL) < 0) and (getKeyState(VK_RCONTROL) < 0); windows: result := (getKeyState(VK_LWIN) < 0) and (getKeyState(VK_RWIN) < 0); end; end; {$ELSEIF Defined(IOS)} // non géré {$ELSEIF Defined(MACOS)} // non géré // Event := TNSEvent.Create; // if (Event.modifierFlags <> 0) then // result := true // else // result := false; {$ELSEIF Defined(ANDROID)} // non géré {$ELSEIF Defined(LINUX)} // non géré {$ENDIF} end; { tKeyboardSpecialKeyTest } class function tKeyboardSpecialKeyTest.isAltDown (Position: tKeyboardSpecialKeyTestPosition): Boolean; begin result := isKeyDown(tKeyboardSpecialKeyTestKeycode.Alt, Position); end; class function tKeyboardSpecialKeyTest.isCommandDown (Position: tKeyboardSpecialKeyTestPosition): Boolean; begin {$IF Defined(MSWINDOWS)} result := isWindowsDown(Position); {$ELSEIF Defined(IOS)} {$ELSEIF Defined(MACOS)} result := isKeyDown(tKeyboardSpecialKeyTestKeycode.command, Position); {$ELSEIF Defined(ANDROID)} {$ELSEIF Defined(LINUX)} {$ENDIF} end; class function tKeyboardSpecialKeyTest.isCtrlDown (Position: tKeyboardSpecialKeyTestPosition): Boolean; begin result := isKeyDown(tKeyboardSpecialKeyTestKeycode.Ctrl, Position); end; class function tKeyboardSpecialKeyTest.isShiftDown (Position: tKeyboardSpecialKeyTestPosition): Boolean; begin result := isKeyDown(tKeyboardSpecialKeyTestKeycode.Shift, Position); end; class function tKeyboardSpecialKeyTest.isWindowsDown (Position: tKeyboardSpecialKeyTestPosition): Boolean; begin {$IF Defined(MSWINDOWS)} result := isKeyDown(tKeyboardSpecialKeyTestKeycode.windows, Position); {$ELSEIF Defined(IOS)} {$ELSEIF Defined(MACOS)} result := isCommandDown(Position); {$ELSEIF Defined(ANDROID)} {$ELSEIF Defined(LINUX)} {$ENDIF} end; end.
///* // * android-plugin-client-sdk-for-locale https://github.com/twofortyfouram/android-plugin-client-sdk-for-locale // * Copyright 2014 two forty four a.m. LLC // * // * 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 twofortyfouram.Locale.SDK.Client.UI.Activity.AbstractFragmentPluginActivity; interface //import android.os.Bundle; //import android.support.annotation.NonNull; //import android.support.annotation.Nullable; //import android.support.v4.app.FragmentActivity; // //import com.twofortyfouram.locale.sdk.client.internal.PluginActivityDelegate; // ///** // * <p>NOTE: This class is for backwards compatibility via the support-v4 library. To use this // * class, support-v4 must be on the application's build path. Typically, this would involve adding // * support-v4 to the dependencies section of the application's build.gradle script. For example, // * the dependency might look something like this // * {@code compile group:'com.android.support', name:'support-v4', version:'[21,)'}</p> // * <p> // * Implements the basic behaviors of a "Edit" activity for a // * plug-in, handling the Intent protocol for storing and retrieving the plug-in's data. // * Recall that a plug-in Activity more or less saves a Bundle and a String blurb via the Intent // * extras {@link com.twofortyfouram.locale.api.Intent#EXTRA_BUNDLE EXTRA_BUNDLE} and {@link // * com.twofortyfouram.locale.api.Intent#EXTRA_STRING_BLURB EXTRA_STRING_BLURB}. // * Those extras represent the configured plug-in, so this Activity helps plug-ins store and // * retrieve // * those // * extras while abstracting the actual Intent protocol. // * </p> // * <p> // * The Activity can be started in one of two states: // * <ul> // * <li>New plug-in instance: The Activity's Intent will not contain // * {@link com.twofortyfouram.locale.api.Intent#EXTRA_BUNDLE EXTRA_BUNDLE}.</li> // * <li>Old plug-in instance: The Activity's Intent will contain // * {@link com.twofortyfouram.locale.api.Intent#EXTRA_BUNDLE EXTRA_BUNDLE} and {@link // * com.twofortyfouram.locale.api.Intent#EXTRA_STRING_BLURB EXTRA_STRING_BLURB} from a previously // * saved plug-in instance that the user is editing. The previously saved Bundle // * and blurb can be retrieved at any time via {@link #getPreviousBundle()} and // * {@link #getPreviousBlurb()}. These will also be delivered via // * {@link #onPostCreateWithPreviousResult(Bundle, String)} during the // * Activity's {@link #onPostCreate(Bundle)} phase when the Activity is first // * created.</li> // * </ul> // * <p>During // * the Activity's {@link #finish()} lifecycle callback, this class will call {@link // * #getResultBundle()} and {@link #getResultBlurb(android.os.Bundle)}, which should return the // * Bundle and blurb data the Activity would like to save back to the host. // * </p> // * <p> // * Note that all of these behaviors only apply if the Intent // * starting the Activity is one of the plug-in "edit" Intent actions. // * </p> // * // * @see com.twofortyfouram.locale.api.Intent#ACTION_EDIT_CONDITION ACTION_EDIT_CONDITION // * @see com.twofortyfouram.locale.api.Intent#ACTION_EDIT_SETTING ACTION_EDIT_SETTING // */ //public abstract class AbstractFragmentPluginActivity extends FragmentActivity implements IPluginActivity { // // /** // * Flag boolean that can be set prior to calling {@link #finish()} to control whether the // * Activity // * attempts to save a result back to the host. Typically this is only set to true after an // * explicit user interaction to abort editing the plug-in, such as tapping a "cancel" button. // */ // /* // * There is no need to save/restore this field's state. // */ // protected boolean mIsCancelled = false; // // @NonNull // private final PluginActivityDelegate<AbstractFragmentPluginActivity> mPluginActivityDelegate = new PluginActivityDelegate<>(); // // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // mPluginActivityDelegate.onCreate(this, savedInstanceState); // } // // @Override // public void onPostCreate(@Nullable final Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // // mPluginActivityDelegate.onPostCreate(this, savedInstanceState); // } // // @Override // public void finish() { // mPluginActivityDelegate.finish(this, mIsCancelled); // // /* // * Super call must come after the Activity result is set. If it comes // * first, then the Activity result will be lost. // */ // super.finish(); // } // // /** // * @return The {@link com.twofortyfouram.locale.api.Intent#EXTRA_BUNDLE EXTRA_BUNDLE} that was // * previously saved to the host and subsequently passed back to this Activity for further // * editing. Internally, this method relies on {@link #isBundleValid(android.os.Bundle)}. If // * the bundle exists but is not valid, this method will return null. // */ // @Nullable // public final Bundle getPreviousBundle() { // return mPluginActivityDelegate.getPreviousBundle(this); // } // // /** // * @return The {@link com.twofortyfouram.locale.api.Intent#EXTRA_STRING_BLURB // * EXTRA_STRING_BLURB} that was // * previously saved to the host and subsequently passed back to this Activity for further // * editing. // */ // @Nullable // public final String getPreviousBlurb() { // return mPluginActivityDelegate.getPreviousBlurb(this); // } //} implementation end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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. *) {$endif} unit cwThreading.Internal.Thread.Posix; {$ifdef fpc}{$mode delphiunicode}{$endif} interface {$ifndef MSWINDOWS} uses cwThreading , cwThreading.Internal {$ifdef fpc} , pthreads , unixtype {$endif} {$ifndef fpc} , Posix.SysTypes , posix.pthread {$endif} ; type TThread = class( TInterfacedObject, IThread ) strict private //- IThread -// fHandle: pthread_t; fSleepCS: ISignaledCriticalSection; fTerminateFlag: boolean; fRunning: boolean; fThreadExecuteMethod: TThreadExecuteMethod; strict private //- IThread -// function getSleepCS: ISignaledCriticalSection; function IsRunning: boolean; function getTerminateFlag: boolean; procedure setTerminateFlag( const value: boolean ); procedure Acquire; procedure Release; procedure Sleep; procedure Wake; protected procedure Execute; public constructor Create( const ThreadExecuteMethod: TThreadExecuteMethod; const SleepCS: ISignaledCriticalSection ); reintroduce; destructor Destroy; override; end; {$endif} implementation {$ifndef MSWINDOWS} uses cwStatus , cwTypes {$ifdef fpc} , BaseUnix {$else} , Posix.errno {$endif} ; const cDefaultStackSize = 2097152; // 2MB; function InternalHandler( Thread: pointer ): uint32; stdcall; var ThreadRef: TThread; begin Result := 0; ThreadRef := TThread(Thread); if not assigned(ThreadRef) then exit; ThreadRef.Execute; end; function TThread.getSleepCS: ISignaledCriticalSection; begin Result := fSleepCS; end; function TThread.IsRunning: boolean; begin Result := fRunning; end; function TThread.getTerminateFlag: boolean; begin Result := fTerminateFlag; end; procedure TThread.setTerminateFlag(const value: boolean); begin fTerminateFlag := value; end; procedure TThread.Acquire; begin if assigned(fSleepCS) then begin fSleepCS.Acquire; end; end; procedure TThread.Release; begin if assigned(fSleepCS) then begin fSleepCS.Release; end; end; procedure TThread.Sleep; begin if assigned(fSleepCS) then begin fSleepCS.Sleep; end; end; procedure TThread.Wake; begin if assigned(fSleepCS) then begin fSleepCS.Wake; end; end; procedure TThread.Execute; begin if fTerminateFlag then exit; fRunning := True; try if assigned(fThreadExecuteMethod) then begin fThreadExecuteMethod(Self); end; finally fRunning := False; end; end; constructor TThread.Create( const ThreadExecuteMethod: TThreadExecuteMethod; const SleepCS: ISignaledCriticalSection ); var Attr: pthread_attr_t; begin inherited Create; //- Init fTerminateFlag := False; fRunning := False; fThreadExecuteMethod := ThreadExecuteMethod; fSleepCS := SleepCS; //- Define and create thread. if pthread_attr_init({$ifdef fpc}@{$endif}attr)<>0 then begin TStatus(stThreadAttrInitFailed).Raize([errno.AsString]); end; if pthread_attr_setstacksize({$ifdef fpc}@{$endif}attr,cDefaultStackSize)<>0 then begin TStatus(stThreadStackSetFailed).Raize([errno.AsString]); end; if pthread_create({$ifdef fpc}@{$endif}fHandle,{$ifdef fpc}@{$endif}attr,@InternalHandler,self)<>0 then begin TStatus(stThreadCreateFailed).Raize([errno.AsString]); end; if pthread_attr_destroy({$ifdef fpc}@{$endif}attr)<>0 then begin TStatus(stThreadAttrFnitFailed).Raize([errno.AsString]); end; end; destructor TThread.Destroy; begin if pthread_join(fHandle, nil)<>0 then begin TStatus(stThreadJoinFailed).Raize([errno.AsString]); end; fSleepCS := nil; inherited Destroy; end; {$endif} end.
{*******************************************************} { } { Delphi FireMonkey Platform } { Copyright(c) 2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.KeyMapping; interface uses System.UITypes, FMX.Types; implementation {$IFDEF ANDROID} uses Androidapi.KeyCodes; {$ENDIF} {$IF defined(MACOS) and NOT defined(IOS)} uses Macapi.KeyCodes; {$ENDIF} {$IFDEF IOS} {$ENDIF} {$IFDEF MSWINDOWS} {$ENDIF} procedure AddArray(A: array of Word; Kind: TKeyKind); var I: Integer; begin for I := 0 to (Length(A) - 1) div 2 do RegisterKeyMapping(A[I * 2], A[I * 2 + 1], Kind); end; {$IFDEF ANDROID} {$REGION 'Android key map'} procedure RegisterVirtualKeys; const TrivialKeys: array [0..71] of Word = ( AKEYCODE_F1, vkF1, AKEYCODE_F2, vkF2, AKEYCODE_F3, vkF3, AKEYCODE_F4, vkF4, AKEYCODE_F5, vkF5, AKEYCODE_F6, vkF6, AKEYCODE_F7, vkF7, AKEYCODE_F8, vkF8, AKEYCODE_F9, vkF9, AKEYCODE_F10, vkF10, AKEYCODE_F11, vkF11, AKEYCODE_F12, vkF12, AKEYCODE_TAB, vkTab, AKEYCODE_INSERT, vkInsert, AKEYCODE_FORWARD_DEL, vkDelete, AKEYCODE_MOVE_HOME, vkHome, AKEYCODE_MOVE_END, vkEnd, AKEYCODE_PAGE_UP, vkPrior, AKEYCODE_PAGE_DOWN, vkNext, AKEYCODE_DPAD_UP, vkUp, AKEYCODE_DPAD_DOWN, vkDown, AKEYCODE_DPAD_LEFT, vkLeft, AKEYCODE_DPAD_RIGHT, vkRight, AKEYCODE_NUM_LOCK, vkNumLock, AKEYCODE_ENTER, vkReturn, AKEYCODE_DEL, vkBack, AKEYCODE_ESCAPE, vkEscape, AKEYCODE_SCROLL_LOCK, vkScroll, AKEYCODE_CAPS_LOCK, vkCapital, AKEYCODE_CTRL_LEFT, vkLControl, AKEYCODE_CTRL_RIGHT, vkRControl, AKEYCODE_MENU, vkMenu, AKEYCODE_ALT_LEFT, vkLMenu, AKEYCODE_ALT_RIGHT, vkRMenu, AKEYCODE_SHIFT_LEFT, vkLShift, AKEYCODE_SHIFT_RIGHT, vkRShift); OtherKeys: array [0..29] of Word = ( AKEYCODE_HOME, vkBrowserHome, AKEYCODE_BACK, vkHardwareBack, AKEYCODE_CAMERA, vkCamera, AKEYCODE_CLEAR, vkOemClear, AKEYCODE_VOLUME_UP, vkVolumeUp , AKEYCODE_VOLUME_DOWN, vkVolumeDown, AKEYCODE_MEDIA_PLAY_PAUSE, vkMediaPlayPause, AKEYCODE_MEDIA_STOP, vkMediaStop, AKEYCODE_MEDIA_NEXT, vkMediaNextTrack, AKEYCODE_MEDIA_PREVIOUS, vkMediaPrevTrack, AKEYCODE_CONTACTS, vkLaunchMail, AKEYCODE_CALENDAR, vkLaunchApp1, AKEYCODE_MUSIC, vkLaunchMediaSelect, AKEYCODE_CALCULATOR, vkLaunchApp2, AKEYCODE_POWER, vkSleep); TextKeys: array [0..125] of Word = ( AKEYCODE_0, vk0, AKEYCODE_1, vk1, AKEYCODE_2, vk2, AKEYCODE_3, vk3, AKEYCODE_4, vk4, AKEYCODE_5, vk5, AKEYCODE_6, vk6, AKEYCODE_7, vk7, AKEYCODE_8, vk8, AKEYCODE_9, vk9, AKEYCODE_A, vkA, AKEYCODE_B, vkB, AKEYCODE_C, vkC, AKEYCODE_D, vkD, AKEYCODE_E, vkE, AKEYCODE_F, vkF, AKEYCODE_G, vkG, AKEYCODE_H, vkH, AKEYCODE_I, vkI, AKEYCODE_J, vkJ, AKEYCODE_K, vkK, AKEYCODE_L, vkL, AKEYCODE_M, vkM, AKEYCODE_N, vkN, AKEYCODE_O, vkO, AKEYCODE_P, vkP, AKEYCODE_Q, vkQ, AKEYCODE_R, vkR, AKEYCODE_S, vkS, AKEYCODE_T, vkT, AKEYCODE_U, vkU, AKEYCODE_V, vkV, AKEYCODE_W, vkW, AKEYCODE_X, vkX, AKEYCODE_Y, vkY, AKEYCODE_Z, vkZ, AKEYCODE_APOSTROPHE, vkQuote, AKEYCODE_BACKSLASH, vkBackslash, AKEYCODE_COMMA, vkComma, AKEYCODE_EQUALS, vkEqual, AKEYCODE_GRAVE, vkTilde, AKEYCODE_LEFT_BRACKET, vkLeftBracket, AKEYCODE_PERIOD, vkPeriod, AKEYCODE_MINUS, vkMinus, AKEYCODE_RIGHT_BRACKET, vkRightBracket, AKEYCODE_SEMICOLON, vkSemicolon, AKEYCODE_SLASH, vkSlash, AKEYCODE_NUMPAD_0, vkNumpad0, AKEYCODE_NUMPAD_1, vkNumpad1, AKEYCODE_NUMPAD_2, vkNumpad2, AKEYCODE_NUMPAD_3, vkNumpad3, AKEYCODE_NUMPAD_4, vkNumpad4, AKEYCODE_NUMPAD_5, vkNumpad5, AKEYCODE_NUMPAD_6, vkNumpad6, AKEYCODE_NUMPAD_7, vkNumpad7, AKEYCODE_NUMPAD_8, vkNumpad8, AKEYCODE_NUMPAD_9, vkNumpad9, AKEYCODE_NUMPAD_ADD, vkAdd, AKEYCODE_NUMPAD_DIVIDE, vkDivide, AKEYCODE_NUMPAD_DOT, vkDecimal, AKEYCODE_NUMPAD_MULTIPLY, vkMultiply, AKEYCODE_NUMPAD_SUBTRACT, vkSubtract, AKEYCODE_SPACE, vkSpace); begin AddArray(TrivialKeys, TKeyKind.kkFunctional); AddArray(OtherKeys, TKeyKind.kkUnknown); AddArray(TextKeys, TKeyKind.kkUsual); end; {$ENDREGION} {$ENDIF} {$IF defined(MACOS) and NOT defined(IOS)} {$REGION 'OSX key map'} procedure RegisterVirtualKeys; const TrivialKeys: array [0..71] of Word = ( KEY_F1 , vkF1, KEY_F2 , vkF2, KEY_F3 , vkF3, KEY_F4 , vkF4, KEY_F5 , vkF5, KEY_F6 , vkF6, KEY_F7 , vkF7, KEY_F8 , vkF8, KEY_F9 , vkF9, KEY_F10 , vkF10, KEY_F11 , vkF11, KEY_F12 , vkF12, KEY_F13 , vkF13, KEY_F14 , vkF14, KEY_F15 , vkF15, KEY_F16 , vkF16, KEY_F17 , vkF17, KEY_F18 , vkF18, KEY_F19 , vkF19, KEY_F20 , vkF20, KEY_TAB , vkTab, KEY_INS , vkInsert, KEY_DEL , vkDelete, KEY_HOME , vkHome, KEY_END , vkEnd, KEY_PAGUP , vkPrior, KEY_PAGDN , vkNext, KEY_UP , vkUp, KEY_DOWN , vkDown, KEY_LEFT , vkLeft, KEY_RIGHT , vkRight, KEY_NUMLOCK , vkNumLock, KEY_PADENTER , vkReturn, KEY_BACKSPACE , vkBack, KEY_ENTER , vkReturn, KEY_ESC , vkEscape); TextKeys: array [0..125] of Word = ( KEY_NUMPAD0 , vkNumpad0, KEY_NUMPAD1 , vkNumpad1, KEY_NUMPAD2 , vkNumpad2, KEY_NUMPAD3 , vkNumpad3, KEY_NUMPAD4 , vkNumpad4, KEY_NUMPAD5 , vkNumpad5, KEY_NUMPAD6 , vkNumpad6, KEY_NUMPAD7 , vkNumpad7, KEY_NUMPAD8 , vkNumpad8, KEY_NUMPAD9 , vkNumpad9, KEY_PADDIV , vkDivide, KEY_PADMULT , vkMultiply, KEY_PADSUB , vkSubtract, KEY_PADADD , vkAdd, KEY_PADDEC , vkDecimal, KEY_SEMICOLON , vkSemicolon, KEY_EQUAL , vkEqual, KEY_COMMA , vkComma, KEY_MINUS , vkMinus, KEY_PERIOD , vkPeriod, KEY_SLASH , vkSlash, KEY_TILDE , vkTilde, KEY_LEFTBRACKET , vkLeftBracket, KEY_BACKSLASH , vkBackslash, KEY_RIGHTBRACKET , vkRightBracket, KEY_QUOTE , vkQuote, KEY_PARA , vkPara, KEY_1 , vk1, KEY_2 , vk2, KEY_3 , vk3, KEY_4 , vk4, KEY_5 , vk5, KEY_6 , vk6, KEY_7 , vk7, KEY_8 , vk8, KEY_9 , vk9, KEY_0 , vk0, KEY_Q , vkQ, KEY_W , vkW, KEY_E , vkE, KEY_R , vkR, KEY_T , vkT, KEY_Y , vkY, KEY_U , vkU, KEY_I , vkI, KEY_O , vkO, KEY_P , vkP, KEY_A , vkA, KEY_S , vkS, KEY_D , vkD, KEY_F , vkF, KEY_G , vkG, KEY_H , vkH, KEY_J , vkJ, KEY_K , vkK, KEY_L , vkL, KEY_Z , vkZ, KEY_X , vkX, KEY_C , vkC, KEY_V , vkV, KEY_B , vkB, KEY_N , vkN, KEY_M , vkM); begin AddArray(TrivialKeys, TKeyKind.kkFunctional); AddArray(TextKeys, TKeyKind.kkUsual); end; {$ENDREGION} {$ENDIF} {$IF defined(MACOS) and defined(IOS)} {$REGION 'IOS key map'} procedure RegisterVirtualKeys; begin // Currently not used end; {$ENDREGION} {$ENDIF} {$IFDEF MSWINDOWS} {$REGION 'Windows key map'} procedure RegisterVirtualKeys; begin // Currently not used end; {$ENDREGION} {$ENDIF} initialization RegisterVirtualKeys; end.
unit ExeParams; interface uses SysUtils; type TStartParams = record isStartOpros :Boolean; isWriteLog :Boolean; isResError :Boolean; UserName : string; Pass : string; AutoReset : Boolean; LogOn : Boolean; end; var startParams :TStartParams; implementation procedure InitParams(); var I :Integer; S,n :String; pc : integer; begin startParams.isStartOpros := False; startParams.isWriteLog := False; startParams.isResError := False; startParams.LogOn := False; startParams.AutoReset := False; startParams.UserName := ''; startParams.Pass := ''; for I := 1 to ParamCount do begin S := LowerCase(ParamStr(I)); if S = '-startopros' then begin startParams.isStartOpros := True; //параметр автоматического опроса end else if S = '-writelog' then begin //параметр логирования в файл startParams.isWriteLog := True; end else if S = '-reserror' then begin //параметр перезапуск программы с дозапросом startParams.isResError := True; end else if S = '-username' then begin startParams.UserName := ParamStr(I+1); end else if S = '-pass' then begin startParams.Pass := ParamStr(I+1); end else if S = '-logon' then begin startParams.LogOn := True; // Принудительно включить лог при запуске программы end end; end; initialization InitParams(); finalization end.
unit LeadEditorForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, SizeableOutlines; const WM_CHANGE = WM_USER + $400; type TveLeadOutlineEditor = class(TForm) BodyLengthTEdit: TEdit; BodyWidthTEdit: TEdit; Label1: TLabel; Label2: TLabel; BodyHeightTUpdown: TUpDown; BodyWidthTUpdown: TUpDown; Pin0NameTEdit: TEdit; Pin1NameTEdit: TEdit; Label3: TLabel; Label4: TLabel; Label5: TLabel; ReferenceTCheckBox: TCheckBox; procedure BodyLengthTEditChange(Sender: TObject); private { Private declarations } FOutline : TveLeadedOutline; FOnChanged : TNotifyEvent; procedure SetOutline( value : TveLeadedOutline ) ; procedure WMCHANGE(var Message: TMessage); message WM_CHANGE; public { Public declarations } property Outline : TveLeadedOutline read FOutline write SetOutline; property OnChanged : TNotifyEvent read FOnChanged write FOnChanged; end; var veLeadOutlineEditor : TveLeadOutlineEditor; implementation {$R *.DFM} procedure TveLeadOutlineEditor.WMCHANGE(var Message: TMessage); var PinName : string; begin if FOutline <> nil then begin FOutline.BodyLength := StrToInt( BodyLengthTEdit.Text ); FOutline.BodyWidth := StrToInt( BodyWidthTEdit.Text ); PinName := Trim( Pin0NameTEdit.Text ); if PinName = '' then begin PinName := '1'; end; FOutline.Pins[0].Name := PinName; PinName := Trim( Pin1NameTEdit.Text ); if PinName = '' then begin PinName := '2'; end; FOutline.Pins[1].Name := PinName; FOutline.ShowReference := ReferenceTCheckBox.Checked; if Assigned( FOnChanged ) then begin FOnChanged(self); end; end; end; procedure TveLeadOutlineEditor.SetOutline( value : TveLeadedOutline ) ; begin // display outline settings in TEdits if value <> nil then begin //.. prevent on change firing when TEdits changed and altering an Outline FOutline := nil; BodyLengthTEdit.Text := IntToStr( value.BodyLength ); BodyWidthTEdit.Text := IntToStr( value.BodyWidth ); Pin0NameTEdit.Text := value.Pins[0].Name; Pin1NameTEdit.Text := value.Pins[1].Name; ReferenceTCheckBox.Checked := value.ShowReference; end; // store new outline we are working with FOutline := value; end; procedure TveLeadOutlineEditor.BodyLengthTEditChange(Sender: TObject); begin if (FOutline <> nil) and Assigned(FOnChanged) then begin PostMessage( handle, WM_CHANGE, 0, 0 ); end; end; end.
unit AqDrop.DB.ORM.Reader; interface {$I '..\Core\AqDrop.Core.Defines.Inc'} uses System.Rtti, System.TypInfo, System.SyncObjs, AqDrop.Core.Types, AqDrop.Core.Collections, AqDrop.Core.Collections.Intf, AqDrop.Core.InterfacedObject, AqDrop.DB.SQL, AqDrop.DB.ORM.Attributes, AqDrop.DB.Types; type TAqDBORMColumn = class strict private FAttribute: AqColumn; function GetAlias: string; strict protected function GetName: string; virtual; abstract; procedure SetValue(const pInstance: TObject; const pValue: TValue); virtual; abstract; function GetValue(const pInstance: TObject): TValue; virtual; abstract; function GetTypeInfo: PTypeInfo; virtual; abstract; function GetType: TAqDataType; virtual; abstract; public constructor Create(const pAttribute: AqColumn); procedure SetObjectValue(const pInstance: TObject; pValue: TValue); overload; procedure SetObjectValue(const pInstance: TObject; pValue: IAqDBReadValue); overload; procedure SetDBValue(const pInstance: TObject; pValue: IAqDBValue); property Attribute: AqColumn read FAttribute; property Name: string read GetName; property Alias: string read GetAlias; property &Type: TAqDataType read GetType; end; TAqDBORMColumnField = class(TAqDBORMColumn) strict private FField: TRttiField; function ExtractColumnName(const pRttiObject: TRttiNamedObject): string; strict protected function GetName: string; override; procedure SetValue(const pInstance: TObject; const pValue: TValue); override; function GetValue(const pInstance: TObject): TValue; override; function GetType: TAqDataType; override; function GetTypeInfo: PTypeInfo; override; public constructor Create(const pField: TRttiField; const pAttribute: AqColumn); property Field: TRttiField read FField; end; TAqDBORMColumnProperty = class(TAqDBORMColumn) strict private FProperty: TRttiProperty; strict protected function GetName: string; override; procedure SetValue(const pInstance: TObject; const pValue: TValue); override; function GetValue(const pInstance: TObject): TValue; override; function GetType: TAqDataType; override; function GetTypeInfo: PTypeInfo; override; public constructor Create(const pProperty: TRttiProperty; const pAttribute: AqColumn); property &Property: TRttiProperty read FProperty; end; TAqDBORMTable = class strict private FType: TRttiType; FColumns: TAqList<TAqDBORMColumn>; function GetColumns: TAqReadList<TAqDBORMColumn>; private procedure SetType(const pType: TRttiType); strict protected function GetName: string; virtual; abstract; function ExtractTableName(const pType: TRttiType): string; property &Type: TRttiType read FType; public constructor Create(const pType: TRttiType); destructor Destroy; override; procedure AddColumn(const pField: TRttiField; const pAttribute: AqColumn); overload; procedure AddColumn(const pProperty: TRttiProperty; const pAttribute: AqColumn); overload; function HasAutoIncrementColumn(out pColumn: TAqDBORMColumn): Boolean; property Name: string read GetName; property Columns: TAqReadList<TAqDBORMColumn> read GetColumns; end; TAqDBORMTable<T: AqTable> = class(TAqDBORMTable) strict private FAttribute: T; private procedure SetAttribute(const pAttribute: T; const pType: TRttiType); strict protected function GetName: string; override; public constructor Create(const pAttribute: T; const pType: TRttiType); property Attribute: T read FAttribute; end; TAqDBORM = class strict private FMainTable: TAqDBORMTable<AqTable>; FSpecializations: TAqList<TAqDBORMTable<AqSpecialization>>; function GetInitialized: Boolean; function GetActiveTable: TAqDBORMTable<AqTable>; function GetHasSpecializations: Boolean; function GetSpecializations: TAqReadList<TAqDBORMTable<AqSpecialization>>; class var FTableSeparator: string; private class procedure _Initialize; public constructor Create; destructor Destroy; override; procedure AddTable(const pTableInfo: AqTable; const pType: TRttiType); function GetTable(const pName: string; out pTable: TAqDBORMTable): Boolean; function GetColumn(const pName: string; out pColumn: TAqDBORMColumn): Boolean; function GetPrimaryKeys: IAqResultList<TAqDBORMColumn>; property Initialized: Boolean read GetInitialized; property MainTable: TAqDBORMTable<AqTable> read FMainTable; property HasSpecializations: Boolean read GetHasSpecializations; property Specializations: TAqReadList<TAqDBORMTable<AqSpecialization>> read GetSpecializations; property ActiveTable: TAqDBORMTable<AqTable> read GetActiveTable; // se for necessária mais uma configuração, é melhor isolá-las em uma sub-classe. class property TableSeparator: string read FTableSeparator; end; TAqDBORMReader = class strict private class var FRttiContext: TRttiContext; class var FLocker: TCriticalSection; class var FTypes: TAqDictionary<string, TRttiType>; class var FORMs: TAqDictionary<string, TAqDBORM>; class function GetType(const pClass: TClass): TRttiType; class function CreateNewORM(const pClass: TClass): TAqDBORM; private class procedure _Initialize; class procedure _Finalize; public class function GetORM(const pClass: TClass; const pUsePool: Boolean = True): TAqDBORM; end; implementation uses System.StrUtils, System.SysUtils, AqDrop.Core.Exceptions, AqDrop.Core.Helpers, AqDrop.Core.Helpers.TRttiType, AqDrop.Core.Helpers.TRttiObject; { TAqDBORMReader } class function TAqDBORMReader.CreateNewORM(const pClass: TClass): TAqDBORM; procedure ReadClass(pClasse: TClass); var lClassType: TRttiType; lORMOff: AqORMOff; lTable: AqTable; lField: TRttiField; lActiveTable: TAqDBORMTable<AqTable>; lColumn: AqColumn; lProperty: TRttiProperty; lHasMapping: Boolean; begin if pClasse <> nil then begin ReadClass(pClasse.ClassParent); lClassType := GetType(pClasse); if not lClassType.GetAttribute<AqORMOff>(lORMOff) then begin if lClassType.GetAttribute<AqTable>(lTable) then begin Result.AddTable(lTable, lClassType); end; lActiveTable := Result.ActiveTable; for lField in lClassType.GetDeclaredFields do begin if not lField.GetAttribute<AqORMOff>(lORMOff) then begin lHasMapping := lField.GetAttribute<AqColumn>(lColumn); if not lHasMapping then begin lColumn := nil; end; if lHasMapping or (Result.Initialized and (tmpAutoMapFields in lActiveTable.Attribute.MappingProperties)) then begin lActiveTable.AddColumn(lField, lColumn); end; end; end; for lProperty in lClassType.GetDeclaredProperties do begin if not lProperty.GetAttribute<AqORMOff>(lORMOff) then begin lHasMapping := lProperty.GetAttribute<AqColumn>(lColumn); if not lHasMapping then begin lColumn := nil; end; if lHasMapping or (Result.Initialized and (tmpAutoMapProperties in lActiveTable.Attribute.MappingProperties)) then begin lActiveTable.AddColumn(lProperty, lColumn); end; end; end; end; end; end; begin Result := TAqDBORM.Create; try ReadClass(pClass); except Result.Free; raise; end; end; class function TAqDBORMReader.GetORM(const pClass: TClass; const pUsePool: Boolean): TAqDBORM; begin if pUsePool then begin FLocker.Enter; try if not FORMs.TryGetValue(pClass.QualifiedClassName, Result) then begin Result := CreateNewORM(pClass); try FORMs.Add(pClass.QualifiedClassName, Result); except Result.Free; raise; end; end; finally FLocker.Leave; end; end else begin Result := CreateNewORM(pClass); end; end; class function TAqDBORMReader.GetType(const pClass: TClass): TRttiType; begin FLocker.Enter; try if not FTypes.TryGetValue(pClass.QualifiedClassName, Result) then begin Result := FRttiContext.GetType(pClass); try FTypes.Add(pClass.QualifiedClassName, Result); except Result.Free; raise; end; end; finally FLocker.Leave; end; end; class procedure TAqDBORMReader._Finalize; begin FORMs.Free; FTypes.Free; FLocker.Free; FRttiContext.Free; end; class procedure TAqDBORMReader._Initialize; begin FRttiContext := TRttiContext.Create; FLocker := TCriticalSection.Create; FTypes := TAqDictionary<string, TRttiType>.Create; FORMs := TAqDictionary<string, TAqDBORM>.Create([TAqKeyValueOwnership.kvoValue]); end; { TAqDBORM } procedure TAqDBORM.AddTable(const pTableInfo: AqTable; const pType: TRttiType); begin if not Assigned(FMainTable.Attribute) then begin FMainTable.SetAttribute(pTableInfo, pType); end else begin if not (pTableInfo is AqSpecialization) then begin raise EAqInternal.Create('This ORM already has a main table. All other tables must be specializations.'); end; if not Assigned(FSpecializations) then begin FSpecializations := TAqList<TAqDBORMTable<AqSpecialization>>.Create(True); end; FSpecializations.Add(TAqDBORMTable<AqSpecialization>.Create(AqSpecialization(pTableInfo), pType)); end; end; constructor TAqDBORM.Create; begin FMainTable := TAqDBORMTable<AqTable>.Create(nil, nil); end; destructor TAqDBORM.Destroy; begin FSpecializations.Free; FMainTable.Free; inherited; end; function TAqDBORM.GetColumn(const pName: string; out pColumn: TAqDBORMColumn): Boolean; var lSeparatorPosition: Int32; lTableName: string; lColumnName: string; lITable: Int32; function FindColumn(const pColumns: TAqReadList<TAqDBORMColumn>; out pColumn: TAqDBORMColumn): Boolean; var lIColumn: Int32; begin Result := False; lIColumn := pColumns.Count; while not Result and (lIColumn > 0) do begin Dec(lIColumn); Result := string.SameText(lColumnName, pColumns[lIColumn].Name); if Result then begin pColumn := pColumns[lIColumn]; end; end; end; begin Result := False; lSeparatorPosition := pName.IndexOf(FTableSeparator); if lSeparatorPosition >= 0 then begin lTableName := pName.LeftFromPosition(lSeparatorPosition); lColumnName := pName.RightFromPosition(lSeparatorPosition); if string.SameText(lTableName, FMainTable.Name) then begin Result := FindColumn(FMainTable.Columns, pColumn); end else if HasSpecializations then begin lITable := FSpecializations.Count; while not Result and (lITable > 0) do begin Dec(lITable); Result := string.SameText(lTableName, FSpecializations[lITable].Attribute.Name); if Result then begin Result := FindColumn(FSpecializations[lITable].Columns, pColumn); lITable := 0; end; end; end; end else begin lColumnName := pName; Result := FindColumn(FMainTable.Columns, pColumn); if not Result and HasSpecializations then begin lITable := 0; while not Result and (lITable < FSpecializations.Count) do begin Result := FindColumn(FSpecializations[lITable].Columns, pColumn); Inc(lITable); end; end; end; end; function TAqDBORM.GetSpecializations: TAqReadList<TAqDBORMTable<AqSpecialization>>; begin Result := FSpecializations.GetTReadList; end; function TAqDBORM.GetTable(const pName: string; out pTable: TAqDBORMTable): Boolean; var lI: Int32; begin Result := string.SameText(FMainTable.Name, pName); if Result then begin pTable := FMainTable; end else if HasSpecializations then begin lI := FSpecializations.Count; while not Result and (lI > 0) do begin Dec(lI); Result := FSpecializations[lI].Name = pName; if Result then begin pTable := FSpecializations[lI]; end; end; end; end; class procedure TAqDBORM._Initialize; begin FTableSeparator := '.'; end; function TAqDBORM.GetInitialized: Boolean; begin Result := Assigned(FMainTable.Attribute); end; function TAqDBORM.GetPrimaryKeys: IAqResultList<TAqDBORMColumn>; var lResult: TAqResultList<TAqDBORMColumn>; lSpecialization: TAqDBORMTable; procedure AddPrimaryKeys(const pTable: TAqDBORMTable); var lColumn: TAqDBORMColumn; begin for lColumn in pTable.Columns do begin if Assigned(lColumn.Attribute) and (lColumn.Attribute.PrimaryKey) then begin lResult.Add(lColumn); end; end; end; begin lResult := TAqResultList<TAqDBORMCOlumn>.Create(False); try AddPrimaryKeys(FMainTable); if HasSpecializations then begin for lSpecialization in FSpecializations do begin AddPrimaryKeys(lSpecialization); end; end; except lResult.Free; raise; end; Result := lResult; end; function TAqDBORM.GetHasSpecializations: Boolean; begin Result := Assigned(FSpecializations); end; function TAqDBORM.GetActiveTable: TAqDBORMTable<AqTable>; begin if Assigned(FSpecializations) then begin Result := TAqDBORMTable<AqTable>(FSpecializations.Last); end else begin Result := FMainTable; end; end; { TAqDBORMColumn } constructor TAqDBORMColumn.Create(const pAttribute: AqColumn); begin FAttribute := pAttribute; end; function TAqDBORMColumn.GetAlias: string; begin if Assigned(FAttribute) and FAttribute.IsAliasDefined then begin Result := FAttribute.Alias; end else begin Result := ''; end; end; procedure TAqDBORMColumn.SetDBValue(const pInstance: TObject; pValue: IAqDBValue); function IsNullIfZeroActive: Boolean; begin Result := Assigned(FAttribute) and (TAqDBColumnAttribute.caNullIfZero in FAttribute.Attributes); end; function IsNullIfEmptyActive: Boolean; begin Result := Assigned(FAttribute) and (TAqDBColumnAttribute.caNullIfEmpty in FAttribute.Attributes); end; var lValue: TValue; begin lValue := GetValue(pInstance); case GetType of TAqDataType.adtBoolean: pValue.AsBoolean := lValue.AsBoolean; TAqDataType.adtEnumerated: pValue.AsInt64 := lValue.AsOrdinal; TAqDataType.adtUInt8: if (lValue.AsInteger = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtUInt8); end else begin pValue.AsUInt8 := lValue.AsInteger; end; TAqDataType.adtInt8: if (lValue.AsInteger = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtInt8); end else begin pValue.AsInt8 := lValue.AsInteger; end; TAqDataType.adtUInt16: if (lValue.AsInteger = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtUInt16); end else begin pValue.AsUInt16 := lValue.AsInteger; end; TAqDataType.adtInt16: if (lValue.AsInteger = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtInt16); end else begin pValue.AsInt16 := lValue.AsInteger; end; TAqDataType.adtUInt32: {$IF CompilerVersion >= 25} if (lValue.AsUInt64 = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtUInt32); end else begin pValue.AsUInt32 := lValue.AsUInt64; end; {$ELSE} if (lValue.AsInt64 = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtInt32); end else begin pValue.AsUInt32 := lValue.AsInt64; end; {$IFEND} TAqDataType.adtInt32: if (lValue.AsInteger = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtInt32); end else begin pValue.AsInt32 := lValue.AsInteger; end; TAqDataType.adtUInt64: {$IF CompilerVersion >= 25} if (lValue.AsUInt64 = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtUInt64); end else begin pValue.AsUInt64 := lValue.AsUInt64; end; {$ELSE} if (lValue.AsInt64 = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtInt32); end else begin pValue.AsUInt64 := lValue.AsInt64; end; {$IFEND} TAqDataType.adtInt64: if (lValue.AsInt64 = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtInt64); end else begin pValue.AsInt64 := lValue.AsInt64; end; TAqDataType.adtCurrency: if (lValue.AsCurrency = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtCurrency); end else begin pValue.AsCurrency := lValue.AsCurrency; end; TAqDataType.adtDouble: if (lValue.AsExtended = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtDouble); end else begin pValue.AsDouble := lValue.AsExtended; end; TAqDataType.adtSingle: if (lValue.AsExtended = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtSingle); end else begin pValue.AsSingle := lValue.AsExtended; end; TAqDataType.adtDatetime: if (lValue.AsExtended = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtDatetime); end else begin pValue.AsDateTime := lValue.AsExtended; end; TAqDataType.adtDate: if (lValue.AsExtended = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtDate); end else begin pValue.AsDate := lValue.AsExtended; end; TAqDataType.adtTime: if (lValue.AsExtended = 0) and IsNullIfZeroActive then begin pValue.SetNull(TAqDataType.adtTime); end else begin pValue.AsTime := lValue.AsExtended; end; {$IFNDEF AQMOBILE} TAqDataType.adtAnsiChar: if lValue.AsString.IsEmpty and IsNullIfEmptyActive then begin pValue.SetNull(TAqDataType.adtAnsiChar); end else begin pValue.AsAnsiString := AnsiString(lValue.AsString); end; {$ENDIF} TAqDataType.adtChar: if lValue.AsString.IsEmpty and IsNullIfEmptyActive then begin pValue.SetNull(TAqDataType.adtChar); end else begin pValue.AsString := lValue.AsString; end; {$IFNDEF AQMOBILE} TAqDataType.adtAnsiString: if lValue.AsString.IsEmpty and IsNullIfEmptyActive then begin pValue.SetNull(TAqDataType.adtAnsiString); end else begin pValue.AsAnsiString := AnsiString(lValue.AsString); end; {$ENDIF} TAqDataType.adtString, TAqDataType.adtWideString: if lValue.AsString.IsEmpty and IsNullIfEmptyActive then begin pValue.SetNull(TAqDataType.adtWideString); end else begin pValue.AsString := lValue.AsString; end; else raise EAqInternal.Create('Unexpected type when setting value to ' + Self.Name + ' DB Value.'); end; end; procedure TAqDBORMColumn.SetObjectValue(const pInstance: TObject; pValue: TValue); begin SetValue(pInstance, pValue); end; procedure TAqDBORMColumn.SetObjectValue(const pInstance: TObject; pValue: IAqDBReadValue); var lValue: TValue; begin case GetType of TAqDataType.adtBoolean: lValue := TValue.From<Boolean>(pValue.AsBoolean); TAqDataType.adtEnumerated: lValue := TValue.FromOrdinal(GetTypeInfo, pValue.AsInt64); TAqDataType.adtUInt8: lValue := TValue.From<UInt8>(pValue.AsUInt8); TAqDataType.adtInt8: lValue := TValue.From<Int8>(pValue.AsInt8); TAqDataType.adtUInt16: lValue := TValue.From<UInt16>(pValue.AsUInt16); TAqDataType.adtInt16: lValue := TValue.From<Int16>(pValue.AsInt16); TAqDataType.adtUInt32: lValue := TValue.From<UInt32>(pValue.AsUInt32); TAqDataType.adtInt32: lValue := TValue.From<Int32>(pValue.AsInt32); TAqDataType.adtUInt64: lValue := TValue.From<UInt64>(pValue.AsUInt64); TAqDataType.adtInt64: lValue := TValue.From<Int64>(pValue.AsInt64); TAqDataType.adtCurrency: lValue := TValue.From<Currency>(pValue.AsCurrency); TAqDataType.adtDouble: lValue := TValue.From<Double>(pValue.AsDouble); TAqDataType.adtSingle: lValue := TValue.From<Single>(pValue.AsSingle); TAqDataType.adtDatetime: lValue := TValue.From<TDateTime>(pValue.AsDateTime); TAqDataType.adtDate: lValue := TValue.From<TDate>(pValue.AsDate); TAqDataType.adtTime: lValue := TValue.From<TTime>(pValue.AsTime); {$IFNDEF AQMOBILE} TAqDataType.adtAnsiChar: lValue := TValue.From<AnsiChar>(AnsiChar(pValue.AsString.Chars[0])); {$ENDIF} TAqDataType.adtChar: lValue := TValue.From<Char>(pValue.AsString.Chars[0]); {$IFNDEF AQMOBILE} TAqDataType.adtAnsiString: lValue := TValue.From<AnsiString>(pValue.AsAnsiString); {$ENDIF} TAqDataType.adtString, TAqDataType.adtWideString: lValue := TValue.From<string>(pValue.AsString); else raise EAqInternal.Create('Unexpected type when setting value to ' + Self.Name + ' object value.'); end; SetValue(pInstance, lValue); end; { TAqDBORMTable } procedure TAqDBORMTable.AddColumn(const pField: TRttiField; const pAttribute: AqColumn); begin FColumns.Add(TAqDBORMColumnField.Create(pField, pAttribute)); end; procedure TAqDBORMTable.AddColumn(const pProperty: TRttiProperty; const pAttribute: AqColumn); begin FColumns.Add(TAqDBORMColumnProperty.Create(pProperty, pAttribute)); end; constructor TAqDBORMTable.Create(const pType: TRttiType); begin FType := pType; FColumns := TAqList<TAqDBORMColumn>.Create(True); end; destructor TAqDBORMTable.Destroy; begin FColumns.Free; inherited; end; function TAqDBORMTable.ExtractTableName(const pType: TRttiType): string; begin if (Length(pType.Name) > 1) and StartsStr('T', AnsiUpperCase(pType.Name)) then begin Result := RightStr(pType.Name, Length(pType.Name) - 1); end else begin Result := pType.Name; end; end; function TAqDBORMTable.GetColumns: TAqReadList<TAqDBORMColumn>; begin Result := FColumns.GetTReadList; end; function TAqDBORMTable.HasAutoIncrementColumn(out pColumn: TAqDBORMColumn): Boolean; var lI: Int32; begin Result := False; lI := 0; while not Result and (lI < FColumns.Count) do begin Result := Assigned(FColumns[lI].Attribute) and FColumns[lI].Attribute.AutoIncrement; if Result then begin pColumn := FColumns[lI]; end else begin Inc(lI); end; end; end; procedure TAqDBORMTable.SetType(const pType: TRttiType); begin FType := pType; end; { TAqDBORMTable<T> } constructor TAqDBORMTable<T>.Create(const pAttribute: T; const pType: TRttiType); begin inherited Create(pType); FAttribute := pAttribute; end; function TAqDBORMTable<T>.GetName: string; begin if Assigned(FAttribute) and FAttribute.IsNameDefined then begin Result := FAttribute.Name; end else if Assigned(&Type) then begin Result := ExtractTableName(&Type); end else begin raise EAqInternal.Create('Impossible to get the table name.'); end; end; procedure TAqDBORMTable<T>.SetAttribute(const pAttribute: T; const pType: TRttiType); begin SetType(pType); FAttribute := pAttribute; end; { TAqDBORMColumnField } constructor TAqDBORMColumnField.Create(const pField: TRttiField; const pAttribute: AqColumn); begin inherited Create(pAttribute); FField := pField; end; function TAqDBORMColumnField.ExtractColumnName(const pRttiObject: TRttiNamedObject): string; begin if (Length(pRttiObject.Name) > 1) and StartsStr('F', AnsiUpperCase(pRttiObject.Name)) then begin Result := RightStr(pRttiObject.Name, Length(pRttiObject.Name) - 1); end else begin Result := pRttiObject.Name; end; end; function TAqDBORMColumnField.GetName: string; begin if Assigned(Attribute) and Attribute.IsNameDefined then begin Result := Attribute.Name; end else begin Result := ExtractColumnName(FField); end; end; function TAqDBORMColumnField.GetType: TAqDataType; begin Result := FField.FieldType.GetDataType; end; function TAqDBORMColumnField.GetTypeInfo: PTypeInfo; begin Result := FField.FieldType.Handle; end; function TAqDBORMColumnField.GetValue(const pInstance: TObject): TValue; begin Result := FField.GetValue(pInstance); end; procedure TAqDBORMColumnField.SetValue(const pInstance: TObject; const pValue: TValue); begin FField.SetValue(pInstance, pValue); end; { TAqDBORMColumnProperty } constructor TAqDBORMColumnProperty.Create(const pProperty: TRttiProperty; const pAttribute: AqColumn); begin inherited Create(pAttribute); FProperty := pProperty; end; function TAqDBORMColumnProperty.GetName: string; begin if Assigned(Attribute) and Attribute.IsNameDefined then begin Result := Attribute.Name; end else begin Result := FProperty.Name; end; end; function TAqDBORMColumnProperty.GetType: TAqDataType; begin Result := FProperty.PropertyType.GetDataType; end; function TAqDBORMColumnProperty.GetTypeInfo: PTypeInfo; begin Result := FProperty.PropertyType.Handle; end; function TAqDBORMColumnProperty.GetValue(const pInstance: TObject): TValue; begin Result := FProperty.GetValue(pInstance); end; procedure TAqDBORMColumnProperty.SetValue(const pInstance: TObject; const pValue: TValue); begin if not FProperty.IsWritable then begin raise EAqInternal.Create('Property ' + FProperty.Name + ' is read only.'); end; FProperty.SetValue(pInstance, pValue); end; initialization TAqDBORM._Initialize; TAqDBORMReader._Initialize; finalization TAqDBORMReader._Finalize; end.
unit TFeld; interface Type TKarte = Class private grosse_x, grosse_y: Integer; Karte: Array of Array of Integer; public constructor create(breite, hoehe, inhalt: Integer); function Set_Kosten_Feld(x, y, feld: Integer): Boolean; function read_kosten_feld(x,y: Integer): Integer; function read_grosse_x(): Integer; function read_grosse_y(): Integer; function Grosse_anpassen(breite, Hoehe: Integer): Boolean; end; implementation { TKarte.read_grosse_x *Ließt die Länge der Karte aus } function TKarte.read_grosse_x(): Integer; begin result := grosse_x; end; { TKarte.read_grosse_x *Ließt die Höhe der Karte aus } function TKarte.read_grosse_y(): Integer; begin result := grosse_y; end; { TKarte.read_kosten_feld *Erwartet eine Positionsangabe als Parameter *gibt den Aufwand zurück den man betreiben muss um das Feld zu passieren } function TKarte.read_kosten_feld(x, y: Integer): Integer; begin if(x >= 1) and (x <= grosse_x) then if(y >= 1) and (y <= grosse_y) then result := Karte[x, y]; end; { TKarte.Set_Kosten_Feld(x, y, feld: Integer) *Erwartet eine Positionsangabe und den inhalt des feldes als Parameter *Setzt den Inhalt des Feldes auf den gegebenen Inhalt *Liefert True zurück falls es geklappt hat } function TKarte.Set_Kosten_Feld(x, y, feld: Integer): Boolean; begin if(x >= 1) and (x <= grosse_x) then if(y >= 1) and (y <= grosse_y) then begin Karte[x, y] := feld; result := TRUE; exit; end; result := FALSE; end; {TKarte.create *Erwartet Höhe, Breite und INhalt der Karte *Erstellt eine Karte mit der Gegebenen Höhe und Breite *Jedes Feld erhält den gegebenen Inhalt } constructor TKarte.create(breite, hoehe, inhalt: Integer); var i, j: Integer; begin if((breite > 0) and (hoehe > 0)) then begin grosse_x := breite; grosse_y := hoehe; Setlength(Karte, breite+1, hoehe+1); for i:= 1 to grosse_x do for j := 1 to grosse_y do Karte[i,j] := inhalt; end; end; {TKarte.Grosse_anpassen(breite, hoehe: Integer) * Erwartet eine Höhe und eine Breite als Parameter * Ändert die Größe der Karte in die gegeben Höhe und Breite * Liefert True zurück falls es geklappt hat } function TKarte.Grosse_anpassen(breite, hoehe: Integer): Boolean; begin if((breite >= 1) and (hoehe >= 1)) then begin grosse_x := breite; grosse_y := hoehe; Setlength(Karte, breite+1, hoehe+1); result := TRUE; exit; end; result := FALSE; end; end.
unit AccountService; interface uses Account, AccountServiceIntf, CurrencyServiceIntf; type TAccountService = class(TInterfacedObject, IAccountService) private FCurrencyService: ICurrencyService; public constructor Create(ACurrencyService: ICurrencyService); procedure TransferFunds(ASource, ATarget: TAccount; AAmount: Double); end; implementation { TAccountService } constructor TAccountService.Create(ACurrencyService: ICurrencyService); begin FCurrencyService := ACurrencyService; end; procedure TAccountService.TransferFunds(ASource, ATarget: TAccount; AAmount: Double); var LConversionRate: Double; LConvertedAmount: Currency; begin ASource.Withdraw(AAmount); LConversionRate := FCurrencyService.GetConversionRate(ASource.Currency, ATarget.Currency); LConvertedAmount := AAmount * LConversionRate; ATarget.Deposit(LConvertedAmount); end; end.
unit UImage; interface uses classes,sysutils,dateutils,ImageLoader,pngimage; Type TImage = class private Picture:TStringList; Anim_count:Word; last_time:TTime; public Alpha:Word; Anim_Speed:Word; constructor Create; destructor Destroy;override; function Bitmap(ImageLoader:TImageLoader):TPNGImage; procedure Add_anim(ImageLoader:TImageLoader;f:String); end; implementation destructor TImage.Destroy; begin Picture.Clear; Picture.Free; end; constructor TImage.Create; begin Picture:=TStringList.Create; Anim_count:=0; Anim_Speed:=200; Alpha:=255; end; procedure TImage.Add_anim(ImageLoader:TImageLoader;f: string); begin Picture.add(IntToStr(ImageLoader.add(f))); end; function TImage.Bitmap(ImageLoader:TImageLoader):TPNGImage; var P:TPNGImage;x,y:Word;DSTAlpha:PByteArray; begin result:=nil; if Picture.Count>0 then Begin P:=ImageLoader.get(StrToInt(Picture[Anim_count])); //Picture[Anim_count]; //result:=Picture[Anim_count]; //check animation speed if (now-last_time)>Anim_Speed/100000000 then Begin if Anim_count<Picture.count-1 then Begin Anim_Count:=Anim_Count+1; End else Anim_count:=0; last_time:=now; End; //Alpha modification for y:=0 to P.Height-1 do begin DstAlpha:=P.AlphaScanline[y]; for x:=0 to P.Width-1 do if DstAlpha[x]<>0 then DstAlpha[x]:=alpha; end; result:=P End; end; end.
unit Aio01; { ULAIO01.DPR================================================================ File: AIO01.PAS Library Call Demonstrated: cbGetStatus() cbStopBackground() Purpose: Run Simultaneous input/output functions using the same board. Demonstration: cbAoutScan function generates a ramp signal while cbAinScan Displays the analog input on one channel. Other Library Calls: cbAinScan() cbAoutScan() cbErrHandling() Special Requirements: Board 0 must support simultaneous paced input and paced output. See hardware documentation. (c) Copyright 1995 - 2002, Measurement Computing Corp. All rights reserved. ========================================================================== } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, cbw; type TfrmAInAoutScan = class(TForm) tmrCheckStatus: TTimer; cmdADStart: TButton; cmdQuit: TButton; Memo1: TMemo; lblShowADCount: TLabel; lblShowADIndex: TLabel; lblShowADStat: TLabel; cmdADStop: TButton; Panel1: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; cmdDAStart: TButton; cmdDAStop: TButton; lblShowDAStat: TLabel; lblShowDAIndex: TLabel; lblShowDACount: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Panel2: TPanel; procedure cmdADStartClick(Sender: TObject); procedure cmdDAStartClick(Sender: TObject); procedure cmdQuitClick(Sender: TObject); procedure cmdADStopClick(Sender: TObject); procedure cmdDAStopClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tmrCheckStatusTimer(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmAInAoutScan: TfrmAInAoutScan; implementation {$R *.DFM} var ULStat: Integer; ErrReporting: Integer; ErrHandling: Integer; ADData: array[0..10000] of Word; PrnNum: Integer; Rate: LongInt; NumPoints: LongInt; ADMemHandle: Integer; ADCurCount, ADCurIndex: LongInt; ADUserTerm: Boolean; DAMemHandle: Integer; DAData: array[0..10000] of Word; DACurCount, DACurIndex: LongInt; DAUserTerm: Boolean; FirstPoint: LongInt; RevLevel: Single; ADStatus,DAStatus: SmallInt; const BoardNum: Integer = 0; Count: LongInt = 10000; TargetRate: LongInt = 1000; LowChan: Integer = 0; HighChan: Integer = 0; Range: LongInt = BIP5VOLTS; Options: Integer = BACKGROUND; procedure TfrmAInAoutScan.FormCreate(Sender: TObject); var I: Integer; begin {declare Revision Level} RevLevel := CURRENTREVNUM; ULStat := cbDeclareRevision(RevLevel); { set up internal error handling for the Universal Library } ErrReporting := PRINTALL; {set Universal Library to print all errors} ErrHandling := STOPALL; {set Universal Library to stop on errors} ULStat := cbErrHandling(ErrReporting, ErrHandling); { set up a buffer in Windows to contain the data } ADMemHandle := cbWinBufAlloc (Count); Memo1.Text := 'Click start to acquire data'; { Generate D/A ramp data to be output via cbAoutScan function } for I:= 0 to Count-1 do begin DAData[I]:= 32768 + Trunc((I / Count) * 32768) - 16384; end; { Allocate memory to be used by cbAoutscan function } DAMemHandle := cbWinBufAlloc (Count); If DAMemHandle = 0 then exit; { Copy the data to Windows buffer to be used by cbAoutScan } ULStat := cbWinArrayToBuf (DAData[0], DaMemHandle, 0, Count); If ULStat <> 0 then exit; end; procedure TfrmAInAoutScan.cmdADStartClick(Sender: TObject); begin { Collect the values with cbAInScan() Parameters: (see Initialization section) BoardNum :the number used by CB.CFG to describe this board LowChan :low channel of the scan HighChan :high channel of the scan Count :the total number of A/D samples to collect Rate :sample rate in samples per second Gain :the gain for the board ADMemHandle :Windows memory set up with cbWinBufAlloc() Options :data collection options } Memo1.Text := ' '; ADUserTerm := False; PrnNum := 1000; Rate := TargetRate; ULStat := cbAInScan(BoardNum, LowChan, HighChan, Count, Rate, Range, ADMemHandle, Options); If ULStat <> 0 then exit; CmdADStop.Visible := True; CmdADStart.Visible := False; cmdQuit.Enabled := False; end; procedure TfrmAInAoutScan.cmdDAStartClick(Sender: TObject); begin { Send the values with cbAoutScan() Parameters: (see Initialization section) BoardNum :the number used by CB.CFG to describe this board LowChan :low channel of the scan HighChan :high channel of the scan Count :the total number of D/A samples to send to the DAC Rate :sample rate in samples per second Gain :the gain for the board DAMemHandle :Windows memory set up with cbWinBufAlloc() Options :data output options } Memo1.Text := ' '; DAUserTerm := False; PrnNum := 1000; Rate := TargetRate; ULStat := cbAoutScan(BoardNum, LowChan, HighChan, Count, Rate, Range, DAMemHandle, Options); If ULStat <> 0 then exit; CmdDAStop.Visible := True; CmdDAStart.Visible := False; cmdQuit.Enabled := False; end; procedure TfrmAInAoutScan.tmrCheckStatusTimer(Sender: TObject); var index: Integer; begin { This timer will check the status of the background data collection and the status of data output cbGetStatus Parameters: BoardNum :the number used by CB.CFG to describe this board ADStatus :current status of the background data collection ADCurCount :current number of samples collected ADCurIndex :index to the data buffer pointing to the start of the most recently collected scan Subsystem :the subsystem for which to get status(AIFUNCTION) } ULStat := cbGetStatus(BoardNum, ADStatus, ADCurCount, ADCurIndex, AIFUNCTION); If ULStat <> 0 Then Exit; lblShowADCount.Caption := IntToStr(ADCurCount); lblShowADIndex.Caption := IntToStr(ADCurIndex); { Check if the background operation has finished. If it has, then transfer the data from the memory buffer set up by Windows to an array for use by Delphi The BACKGROUND operation must be explicitly stopped } If (ADStatus = RUNNING) And (ADUserTerm = False) Then begin lblShowADStat.Caption := 'Running'; If (ADCurCount > PrnNum) then begin Memo1.Text := ''; NumPoints := 1; FirstPoint := PrnNum; ULStat := cbWinBufToArray (ADMemHandle, ADData[0], FirstPoint, NumPoints); If ULStat <> 0 then exit; Memo1.Lines.Add (Format('Sample number %d: %d',[PrnNum, ADData[0]])); Inc(PrnNum, 1000); end end Else begin ULStat := cbStopBackground(BoardNum,AIFUNCTION); CmdADStop.Visible := False; CmdADStart.Visible := True; If ULStat <> 0 Then Exit; lblShowADStat.Caption := 'Idle'; ULStat := cbGetStatus(BoardNum, ADStatus, ADCurCount, ADCurIndex, AIFUNCTION); If ULStat <> 0 Then Exit; lblShowADCount.Caption := IntToStr(ADCurCount); lblShowADIndex.Caption := IntToStr(ADCurIndex); If ADMemHandle = 0 Then Exit; { Transfer the data from the Windows buffer to an array. This data could also be accessed directly using a pointer. } FirstPoint := 0; ULStat := cbWinBufToArray (ADMemHandle, ADData[0], FirstPoint, Count); If ULStat <> 0 then exit; Memo1.Text := ''; index := 0; while index < 4 do begin Memo1.Lines.Add (Format('Channel 0, sample number %d: %d', [index, ADData[index]])); Memo1.Lines.Add (''); Inc(index, 2); end; end; { cbGetStatus Parameters: BoardNum :the number used by CB.CFG to describe this board ADStatus :current status of the background DAC operation ADCurCount :current number of samples sent to the DAC ADCurIndex :index to the data buffer pointing to the start of the most recently sent data Subsystem :the subsystem for which to get status(AOFUNCTION) } ULStat := cbGetStatus(BoardNum, DAStatus, DACurCount, DACurIndex, AOFUNCTION); If ULStat <> 0 Then Exit; lblShowDACount.Caption := IntToStr(DACurCount); lblShowDAIndex.Caption := IntToStr(DACurIndex); { Check if the background operation has finished. If it has, then The BACKGROUND operation must be explicitly stopped } If (DAStatus = RUNNING) And (DAUserTerm = False) Then begin lblShowDAStat.Caption := 'Running'; end Else begin ULStat := cbStopBackground(BoardNum,AOFUNCTION); CmdDAStop.Visible := False; CmdDAStart.Visible := True; If ULStat <> 0 Then Exit; lblShowDAStat.Caption := 'Idle'; ULStat := cbGetStatus(BoardNum, DAStatus, DACurCount, DACurIndex, AOFUNCTION); If ULStat <> 0 Then Exit; lblShowDACount.Caption := IntToStr(DACurCount); lblShowDAIndex.Caption := IntToStr(DACurIndex); end; If (ADStatus = IDLE) And (DAStatus = IDLE) Then begin cmdQuit.Enabled := True; end end; procedure TfrmAInAoutScan.cmdADStopClick(Sender: TObject); begin ADUserTerm := True; {ends background operation} end; procedure TfrmAInAoutScan.cmdDAStopClick(Sender: TObject); begin DAUserTerm := True; {ends background operation} end; procedure TfrmAInAoutScan.cmdQuitClick(Sender: TObject); begin tmrCheckStatus.Enabled := False; ULStat := cbStopBackground(BoardNum,AIFUNCTION); ULStat := cbStopBackground(BoardNum,AOFUNCTION); ULStat := cbWinBufFree (ADMemHandle); ULStat := cbWinBufFree (DAMemHandle); Close; end; end.
{ ============================================================================ } { DELPHI CONFERENCE 2012 - 23/10/2012 } { José Mário Silva Guedes - mario.guedes@arrayof.com.br } { } { Propósito: Oferecer classes de exeção para a correta identificação dos } { possíveis erros } { ============================================================================ } unit Unt_ClasseException; interface uses System.SysUtils, System.TypInfo; type /// <summary> /// Caracteriza um erro de tipo de propriedade não previsto /// </summary> EGerarLinhaTipoNaoPrevisto = class(Exception) public constructor Create(ATipo: string); end; implementation { EGerarLinhaTipoNaoPrevisto } constructor EGerarLinhaTipoNaoPrevisto.Create(ATipo: string); begin inherited Create(Format('Tipo de Propriedade não previsto: [%s]', [ATipo])); end; end.
unit RepositorioMateriaDoProduto; interface uses DB, Auditoria, Repositorio; type TRepositorioMateriaDoProduto = class(TRepositorio) protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; function SQLGetExiste(campo: String): String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; protected procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override; end; implementation uses SysUtils, MateriaDoProduto; { TRepositorioMateriaDoProduto } function TRepositorioMateriaDoProduto.Get(Dataset: TDataSet): TObject; var MateriaDoProduto :TMateriaDoProduto; begin MateriaDoProduto:= TMateriaDoProduto.Create; MateriaDoProduto.codigo := self.FQuery.FieldByName('codigo').AsInteger; MateriaDoProduto.codigo_item := self.FQuery.FieldByName('codigo_item').AsInteger; MateriaDoProduto.codigo_materia := self.FQuery.FieldByName('codigo_materia').AsInteger; MateriaDoProduto.quantidade := self.FQuery.FieldByName('quantidade').AsFloat; result := MateriaDoProduto; end; function TRepositorioMateriaDoProduto.GetIdentificador(Objeto: TObject): Variant; begin result := TMateriaDoProduto(Objeto).Codigo; end; function TRepositorioMateriaDoProduto.GetNomeDaTabela: String; begin result := 'MATERIAS_DO_PRODUTO'; end; function TRepositorioMateriaDoProduto.GetRepositorio: TRepositorio; begin result := TRepositorioMateriaDoProduto.Create; end; function TRepositorioMateriaDoProduto.IsInsercao(Objeto: TObject): Boolean; begin result := (TMateriaDoProduto(Objeto).Codigo <= 0); end; procedure TRepositorioMateriaDoProduto.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); var MateriaDoProdutoAntigo :TMateriaDoProduto; MateriaDoProdutoNovo :TMateriaDoProduto; begin MateriaDoProdutoAntigo := (AntigoObjeto as TMateriaDoProduto); MateriaDoProdutoNovo := (Objeto as TMateriaDoProduto); if (MateriaDoProdutoAntigo.codigo_item <> MateriaDoProdutoNovo.codigo_item) then Auditoria.AdicionaCampoAlterado('codigo_item', IntToStr(MateriaDoProdutoAntigo.codigo_item), IntToStr(MateriaDoProdutoNovo.codigo_item)); if (MateriaDoProdutoAntigo.codigo_materia <> MateriaDoProdutoNovo.codigo_materia) then Auditoria.AdicionaCampoAlterado('codigo_materia', IntToStr(MateriaDoProdutoAntigo.codigo_materia), IntToStr(MateriaDoProdutoNovo.codigo_materia)); if (MateriaDoProdutoAntigo.quantidade <> MateriaDoProdutoNovo.quantidade) then Auditoria.AdicionaCampoAlterado('quantidade', FloatToStr(MateriaDoProdutoAntigo.quantidade), FloatToStr(MateriaDoProdutoNovo.quantidade)); end; procedure TRepositorioMateriaDoProduto.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); var MateriaDoProduto :TMateriaDoProduto; begin MateriaDoProduto := (Objeto as TMateriaDoProduto); Auditoria.AdicionaCampoExcluido('codigo' , IntToStr(MateriaDoProduto.codigo)); Auditoria.AdicionaCampoExcluido('codigo_item' , IntToStr(MateriaDoProduto.codigo_item)); Auditoria.AdicionaCampoExcluido('codigo_materia', IntToStr(MateriaDoProduto.codigo_materia)); Auditoria.AdicionaCampoExcluido('quantidade' , FloatToStr(MateriaDoProduto.quantidade)); end; procedure TRepositorioMateriaDoProduto.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); var MateriaDoProduto :TMateriaDoProduto; begin MateriaDoProduto := (Objeto as TMateriaDoProduto); Auditoria.AdicionaCampoIncluido('codigo' , IntToStr(MateriaDoProduto.codigo)); Auditoria.AdicionaCampoIncluido('codigo_item' , IntToStr(MateriaDoProduto.codigo_item)); Auditoria.AdicionaCampoIncluido('codigo_materia', IntToStr(MateriaDoProduto.codigo_materia)); Auditoria.AdicionaCampoIncluido('quantidade' , FloatToStr(MateriaDoProduto.quantidade)); end; procedure TRepositorioMateriaDoProduto.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TMateriaDoProduto(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioMateriaDoProduto.SetParametros(Objeto: TObject); var MateriaDoProduto :TMateriaDoProduto; begin MateriaDoProduto := (Objeto as TMateriaDoProduto); self.FQuery.ParamByName('codigo').AsInteger := MateriaDoProduto.codigo; self.FQuery.ParamByName('codigo_item').AsInteger := MateriaDoProduto.codigo_item; self.FQuery.ParamByName('codigo_materia').AsInteger := MateriaDoProduto.codigo_materia; self.FQuery.ParamByName('quantidade').AsFloat := MateriaDoProduto.quantidade; end; function TRepositorioMateriaDoProduto.SQLGet: String; begin result := 'select * from MATERIAS_DO_PRODUTO where codigo = :ncod'; end; function TRepositorioMateriaDoProduto.SQLGetAll: String; begin result := 'select * from MATERIAS_DO_PRODUTO'; end; function TRepositorioMateriaDoProduto.SQLGetExiste(campo: String): String; begin result := 'select '+ campo +' from MATERIAS_DO_PRODUTO where '+ campo +' = :ncampo'; end; function TRepositorioMateriaDoProduto.SQLRemover: String; begin result := ' delete from MATERIAS_DO_PRODUTO where codigo = :codigo '; end; function TRepositorioMateriaDoProduto.SQLSalvar: String; begin result := 'update or insert into MATERIAS_DO_PRODUTO (CODIGO ,CODIGO_ITEM ,CODIGO_MATERIA ,QUANTIDADE) '+ ' values ( :CODIGO , :CODIGO_ITEM , :CODIGO_MATERIA , :QUANTIDADE) '; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Modified or written by Object Mentor, Inc. for inclusion with FitNesse. // Copyright (c) 2002 Cunningham & Cunningham, Inc. // Released under the terms of the GNU General Public License version 2 or later. unit FriendlyErrorTest; interface uses StrUtils, SysUtils, TestFramework; type TFriendlyErrorTest = class(TTestCase) published procedure testCantFindFixture; procedure testExceptionInMethod; procedure testNoSuchMethod; procedure testParseFailure; end; implementation uses Parse, Fixture, FixtureTests; //Test the FitFailureException mechanism. If this works, then all of the FitFailureException derivatives ought //to be working too. procedure TFriendlyErrorTest.testCantFindFixture(); var pageString : string; page : TParse; fixture : TFixture; fixtureName : string; begin pageString := '<table><tr><td>NoSuchFixture</td></tr></table>'; page := TParse.Create(pageString); fixture := TFixture.Create(); fixture.doTables(page); fixtureName := page.at(0, 0, 0).body; CheckTrue(Pos('Could not find fixture: NoSuchFixture.', fixtureName) <> 0); end; procedure TFriendlyErrorTest.testNoSuchMethod(); var page : TParse; columnHeader : string; table : T2dArrayOfString; begin SetLength(table, 2); SetLength(table[0], 1); SetLength(table[1], 1); table[0][0] := 'fitnesse.fixtures.ColumnFixtureTestFixture'; table[1][0] := 'no such method?'; page := TFixtureTests.executeFixture(table); columnHeader := page.at(0, 1, 0).body; CheckTrue(Pos('Could not find method: no such method?.', columnHeader) <> 0); end; procedure TFriendlyErrorTest.testParseFailure(); var page : TParse; table : T2dArrayOfString; colTwoResult : string; begin SetLength(table, 3); SetLength(table[0], 1); SetLength(table[1], 2); SetLength(table[2], 2); table[0][0] := 'fitnesse.fixtures.ColumnFixtureTestFixture'; table[1][0] := 'input'; table[1][1] := 'output?'; table[2][0] := '1'; table[2][1] := 'alpha'; page := TFixtureTests.executeFixture(table); colTwoResult := page.at(0, 2, 1).body; page.Free; CheckTrue(Pos('Could not parse: alpha expected type: Integer', colTwoResult) <> 0); end; procedure TFriendlyErrorTest.testExceptionInMethod(); var page : TParse; table : T2dArrayOfString; colTwoResult : string; begin SetLength(table, 3); SetLength(table[0], 1); SetLength(table[1], 2); SetLength(table[2], 2); table[0][0] := 'fitnesse.fixtures.ColumnFixtureTestFixture'; table[1][0] := 'input'; table[1][1] := 'exception?'; table[2][0] := '1'; table[2][1] := 'true'; page := TFixtureTests.executeFixture(table); colTwoResult := page.at(0, 2, 1).body; CheckTrue(Pos('I thowed up', colTwoResult) <> -1); end; initialization registerTest(TFriendlyErrorTest.Suite); end.
unit u_VectorItemProjected; interface uses Classes, t_GeoTypes, i_EnumDoublePoint, i_ProjectionInfo, i_VectorItemProjected; type TProjectedLineSet = class(TInterfacedObject) private FList: IInterfaceList; FProjection: IProjectionInfo; FBounds: TDoubleRect; private function GetCount: Integer; function GetProjection: IProjectionInfo; function GetBounds: TDoubleRect; public constructor Create( const AProjection: IProjectionInfo; const ABounds: TDoubleRect; const AList: IInterfaceList ); end; TProjectedPath = class(TProjectedLineSet, IProjectedPath) private function GetEnum: IEnumProjectedPoint; function IsPointOnPath( const APoint: TDoublePoint; const ADist: Double ): Boolean; function IsRectIntersectPath(const ARect: TDoubleRect): Boolean; function GetItem(AIndex: Integer): IProjectedPathLine; end; TProjectedPolygon = class(TProjectedLineSet, IProjectedPolygon) private function GetEnum: IEnumProjectedPoint; function IsPointInPolygon(const APoint: TDoublePoint): Boolean; function IsPointOnBorder( const APoint: TDoublePoint; const ADist: Double ): Boolean; function IsRectIntersectPolygon(const ARect: TDoubleRect): Boolean; function IsRectIntersectBorder(const ARect: TDoubleRect): Boolean; function CalcArea: Double; function GetItem(AIndex: Integer): IProjectedPolygonLine; end; TProjectedPathOneLine = class(TInterfacedObject, IProjectedPath) private FLine: IProjectedPathLine; private function GetProjection: IProjectionInfo; function GetCount: Integer; function GetEnum: IEnumProjectedPoint; function IsPointOnPath( const APoint: TDoublePoint; const ADist: Double ): Boolean; function IsRectIntersectPath(const ARect: TDoubleRect): Boolean; function GetBounds: TDoubleRect; function GetItem(AIndex: Integer): IProjectedPathLine; public constructor Create( const ALine: IProjectedPathLine ); end; TProjectedPolygonOneLine = class(TInterfacedObject, IProjectedPolygon) private FLine: IProjectedPolygonLine; private function GetProjection: IProjectionInfo; function GetCount: Integer; function GetEnum: IEnumProjectedPoint; function GetBounds: TDoubleRect; function IsPointInPolygon(const APoint: TDoublePoint): Boolean; function IsPointOnBorder( const APoint: TDoublePoint; const ADist: Double ): Boolean; function IsRectIntersectPolygon(const ARect: TDoubleRect): Boolean; function IsRectIntersectBorder(const ARect: TDoubleRect): Boolean; function CalcArea: Double; function GetItem(AIndex: Integer): IProjectedPolygonLine; public constructor Create( const ALine: IProjectedPolygonLine ); end; TProjectedLineSetEmpty = class(TInterfacedObject, IEnumDoublePoint, IEnumProjectedPoint) private FProjection: IProjectionInfo; private function GetProjection: IProjectionInfo; function GetCount: Integer; function GetEnum: IEnumProjectedPoint; function GetBounds: TDoubleRect; private function Next(out APoint: TDoublePoint): Boolean; public constructor Create( const AProjection: IProjectionInfo ); end; TProjectedPathEmpty = class(TProjectedLineSetEmpty, IProjectedPath) private function GetItem(AIndex: Integer): IProjectedPathLine; function IsPointOnPath( const APoint: TDoublePoint; const ADist: Double ): Boolean; function IsRectIntersectPath(const ARect: TDoubleRect): Boolean; end; TProjectedPolygonEmpty = class(TProjectedLineSetEmpty, IProjectedPolygon) private function IsPointInPolygon(const APoint: TDoublePoint): Boolean; function IsPointOnBorder( const APoint: TDoublePoint; const ADist: Double ): Boolean; function IsRectIntersectPolygon(const ARect: TDoubleRect): Boolean; function IsRectIntersectBorder(const ARect: TDoubleRect): Boolean; function CalcArea: Double; function GetItem(AIndex: Integer): IProjectedPolygonLine; end; implementation uses SysUtils, u_GeoFun, u_EnumDoublePointByLineSet; { TProjectedLineSet } constructor TProjectedLineSet.Create( const AProjection: IProjectionInfo; const ABounds: TDoubleRect; const AList: IInterfaceList ); begin inherited Create; FList := AList; FBounds := ABounds; FProjection := AProjection; end; function TProjectedLineSet.GetBounds: TDoubleRect; begin Result := FBounds; end; function TProjectedLineSet.GetCount: Integer; begin Result := FList.Count; end; function TProjectedLineSet.GetProjection: IProjectionInfo; begin Result := FProjection; end; { TProjectedPath } function TProjectedPath.GetEnum: IEnumProjectedPoint; begin Result := TEnumProjectedPointByPath.Create(Self); end; function TProjectedPath.GetItem(AIndex: Integer): IProjectedPathLine; begin if not Supports(FList[AIndex], IProjectedPathLine, Result) then begin Result := nil; end; end; function TProjectedPath.IsPointOnPath( const APoint: TDoublePoint; const ADist: Double ): Boolean; var i: Integer; VLine: IProjectedPathLine; begin Result := False; for i := 0 to FList.Count - 1 do begin VLine := GetItem(i); if VLine.IsPointOnPath(APoint, ADist) then begin Result := True; Break; end; end; end; function TProjectedPath.IsRectIntersectPath(const ARect: TDoubleRect): Boolean; var i: Integer; VLine: IProjectedPathLine; VIntersectRect: TDoubleRect; begin Result := False; if IntersecProjectedRect(VIntersectRect, ARect, FBounds) then begin for i := 0 to FList.Count - 1 do begin VLine := GetItem(i); if VLine.IsRectIntersectPath(ARect) then begin Result := True; Break; end; end; end; end; { TProjectedPolygon } function TProjectedPolygon.CalcArea: Double; var i: Integer; VLine: IProjectedPolygonLine; begin Result := 0; for i := 0 to FList.Count - 1 do begin VLine := GetItem(i); Result := Result + VLine.CalcArea; end; end; function TProjectedPolygon.GetEnum: IEnumProjectedPoint; begin Result := TEnumProjectedPointByPolygon.Create(Self); end; function TProjectedPolygon.GetItem(AIndex: Integer): IProjectedPolygonLine; begin if not Supports(FList[AIndex], IProjectedPolygonLine, Result) then begin Result := nil; end; end; function TProjectedPolygon.IsPointInPolygon( const APoint: TDoublePoint): Boolean; var i: Integer; VLine: IProjectedPolygonLine; begin Result := False; for i := 0 to FList.Count - 1 do begin VLine := GetItem(i); if VLine.IsPointInPolygon(APoint) then begin Result := True; Break; end; end; end; function TProjectedPolygon.IsPointOnBorder( const APoint: TDoublePoint; const ADist: Double ): Boolean; var i: Integer; VLine: IProjectedPolygonLine; begin Result := False; for i := 0 to FList.Count - 1 do begin VLine := GetItem(i); if VLine.IsPointOnBorder(APoint, ADist) then begin Result := True; Break; end; end; end; function TProjectedPolygon.IsRectIntersectBorder( const ARect: TDoubleRect): Boolean; var i: Integer; VLine: IProjectedPolygonLine; VIntersectRect: TDoubleRect; begin Result := False; if IntersecProjectedRect(VIntersectRect, ARect, FBounds) then begin for i := 0 to FList.Count - 1 do begin VLine := GetItem(i); if VLine.IsRectIntersectBorder(ARect) then begin Result := True; Break; end; end; end; end; function TProjectedPolygon.IsRectIntersectPolygon( const ARect: TDoubleRect ): Boolean; var i: Integer; VLine: IProjectedPolygonLine; VIntersectRect: TDoubleRect; begin Result := False; if IntersecProjectedRect(VIntersectRect, ARect, FBounds) then begin for i := 0 to FList.Count - 1 do begin VLine := GetItem(i); if VLine.IsRectIntersectPolygon(ARect) then begin Result := True; Break; end; end; end; end; { TProjectedPathOneLine } constructor TProjectedPathOneLine.Create(const ALine: IProjectedPathLine); begin inherited Create; FLine := ALine; end; function TProjectedPathOneLine.GetBounds: TDoubleRect; begin Result := FLine.Bounds; end; function TProjectedPathOneLine.GetCount: Integer; begin Result := 1; end; function TProjectedPathOneLine.GetEnum: IEnumProjectedPoint; begin Result := FLine.GetEnum; end; function TProjectedPathOneLine.GetItem(AIndex: Integer): IProjectedPathLine; begin if AIndex = 0 then begin Result := FLine; end else begin Result := nil; end; end; function TProjectedPathOneLine.GetProjection: IProjectionInfo; begin Result := FLine.Projection; end; function TProjectedPathOneLine.IsPointOnPath( const APoint: TDoublePoint; const ADist: Double ): Boolean; begin Result := FLine.IsPointOnPath(APoint, ADist); end; function TProjectedPathOneLine.IsRectIntersectPath( const ARect: TDoubleRect ): Boolean; begin Result := FLine.IsRectIntersectPath(ARect); end; { TProjectedPolygonOneLine } constructor TProjectedPolygonOneLine.Create(const ALine: IProjectedPolygonLine); begin inherited Create; FLine := ALine; end; function TProjectedPolygonOneLine.CalcArea: Double; begin Result := FLine.CalcArea; end; function TProjectedPolygonOneLine.GetBounds: TDoubleRect; begin Result := FLine.Bounds; end; function TProjectedPolygonOneLine.GetCount: Integer; begin Result := 1; end; function TProjectedPolygonOneLine.GetEnum: IEnumProjectedPoint; begin Result := FLine.GetEnum; end; function TProjectedPolygonOneLine.GetItem( AIndex: Integer): IProjectedPolygonLine; begin if AIndex = 0 then begin Result := FLine; end else begin Result := nil; end; end; function TProjectedPolygonOneLine.GetProjection: IProjectionInfo; begin Result := FLine.Projection; end; function TProjectedPolygonOneLine.IsPointInPolygon( const APoint: TDoublePoint): Boolean; begin Result := FLine.IsPointInPolygon(APoint); end; function TProjectedPolygonOneLine.IsPointOnBorder( const APoint: TDoublePoint; const ADist: Double ): Boolean; begin Result := FLine.IsPointOnBorder(APoint, ADist); end; function TProjectedPolygonOneLine.IsRectIntersectBorder( const ARect: TDoubleRect): Boolean; begin Result := FLine.IsRectIntersectBorder(ARect); end; function TProjectedPolygonOneLine.IsRectIntersectPolygon( const ARect: TDoubleRect ): Boolean; begin Result := FLine.IsRectIntersectPolygon(ARect); end; { TProjectedLineSetEmpty } constructor TProjectedLineSetEmpty.Create(const AProjection: IProjectionInfo); begin inherited Create; FProjection := AProjection; end; function TProjectedLineSetEmpty.GetBounds: TDoubleRect; begin Result := DoubleRect(CEmptyDoublePoint, CEmptyDoublePoint); end; function TProjectedLineSetEmpty.GetCount: Integer; begin Result := 0; end; function TProjectedLineSetEmpty.GetEnum: IEnumProjectedPoint; begin Result := Self; end; function TProjectedLineSetEmpty.GetProjection: IProjectionInfo; begin Result := FProjection; end; function TProjectedLineSetEmpty.Next(out APoint: TDoublePoint): Boolean; begin APoint := CEmptyDoublePoint; Result := False; end; { TLocalPathEmpty } function TProjectedPathEmpty.GetItem(AIndex: Integer): IProjectedPathLine; begin Result := nil; end; function TProjectedPathEmpty.IsPointOnPath( const APoint: TDoublePoint; const ADist: Double ): Boolean; begin Result := False; end; function TProjectedPathEmpty.IsRectIntersectPath( const ARect: TDoubleRect ): Boolean; begin Result := False; end; { TLocalPolygonEmpty } function TProjectedPolygonEmpty.CalcArea: Double; begin Result := 0; end; function TProjectedPolygonEmpty.GetItem(AIndex: Integer): IProjectedPolygonLine; begin Result := nil; end; function TProjectedPolygonEmpty.IsPointInPolygon( const APoint: TDoublePoint): Boolean; begin Result := False; end; function TProjectedPolygonEmpty.IsPointOnBorder( const APoint: TDoublePoint; const ADist: Double ): Boolean; begin Result := False; end; function TProjectedPolygonEmpty.IsRectIntersectBorder( const ARect: TDoubleRect): Boolean; begin Result := False; end; function TProjectedPolygonEmpty.IsRectIntersectPolygon( const ARect: TDoubleRect ): Boolean; begin Result := False; end; end.
unit uCliente; interface uses uPessoa,uEndereco; type TCliente = class(TPessoa) private FEndereco: TEndereco; procedure SetEndereco(const Value: TEndereco); public constructor Create; overload; constructor Create(value:string);overload; destructor Destroy; reintroduce; function RetornaNome:String;override;{indica que essa função está sobreescrevendo a função que foi definida na classe mãe} function MetodoAbstrato:string;override; property Endereco : TEndereco read FEndereco write SetEndereco; end; implementation constructor TCliente.Create; begin Nome := 'Novo Cliente'; end; constructor TCliente.Create(value:String); begin FEndereco := TEndereco.Create; Nome := value; end; function TCliente.RetornaNome:string; begin Result:= 'Essa classe é filha de: '+Nome; end; function TCliente.MetodoAbstrato:string; begin result:='Este é o método abstrato'; end; destructor TCliente.Destroy; begin FEndereco.Free; end; procedure TCliente.SetEndereco(const Value: TEndereco); begin FEndereco := Value; end; end.
unit UConsomeApiUser; interface uses UUser, UICrudUsuarioInterfaceaAPI, Rest.Json, Rest.Response.Adapter, Rest.Client, System.SysUtils, Vcl.Dialogs, System.Generics.Collections, Datasnap.DBClient; type TConsomeApiUser = class(TInterfacedObject, TICrudUsuarioInterfaceaAPI<TUser>) FRestClient : TRESTClient; FRestResponse : TRESTResponse; FRestRequest : TRESTRequest; procedure carregaComponentesRest(AUrl : String); private procedure CarregaDbGrid; public function validaLoginByUserAndPassword(ALogin, ASenha : String): Boolean; function insertUser(obj: TUser): Boolean; function updateUser(obj: TUser): Boolean; function deleteUser(obj: TUser): Boolean; constructor Create(); destructor Destroy(); end; implementation { TConsomeApiUser } uses UFrmLogin; procedure TConsomeApiUser.carregaComponentesRest(AUrl:String); begin FRestClient.BaseURL := AUrl; FRestRequest.Client := FRestClient; FRestRequest.Response := FRestResponse; end; procedure TConsomeApiUser.CarregaDbGrid; begin end; constructor TConsomeApiUser.Create; var lListUser : TUser; begin FRestClient := TRESTClient.Create(nil); FRestResponse := TRESTResponse.Create(nil); FRestRequest := TRESTRequest.Create(nil); // carregaComponentesRest('http://localhost:8080'); end; function TConsomeApiUser.deleteUser(obj: TUser): Boolean; begin end; destructor TConsomeApiUser.Destroy; begin FreeAndNil(FRestClient); FreeAndNil(FRestResponse); FreeAndNil(FRestRequest); end; function TConsomeApiUser.insertUser(obj: TUser): Boolean; begin end; function TConsomeApiUser.updateUser(obj: TUser): Boolean; begin end; function TConsomeApiUser.validaLoginByUserAndPassword(ALogin, ASenha : String): Boolean; begin FRestRequest.Resource := '/user/login/'+ALogin+'/senha/'+ASenha; try FRestRequest.Execute; except on e:Exception do raise Exception.Create('O serviço não conseguiu receber a requisição. Comunique o administrador do sistema!'); end; try if not StrToBool(FRestResponse.Content) then begin MessageDlg('Usuário ou senha incorreto. Verifique!',mtWarning,[mbOK],0); Exit; end else MessageDlg('OK Usuario e senha correto!',mtWarning,[mbOK],0); except on e:Exception do MessageDlg('Problema no retorno da API. Comunique o adminstrador do sistema.'+#13+#13 + e.Message,mtInformation, [mbOK],0); end; end; end.
unit Answered; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, Quiz, FMX.Layouts; type TAnsweredForm = class(TForm) ToolBar1: TToolBar; lTitle: TLabel; lAnswer: TLabel; iNo: TImage; Button1: TButton; bHome: TButton; iYes: TImage; bNext: TButton; Layout1: TLayout; procedure bHomeClick(Sender: TObject); procedure bNextClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormDeactivate(Sender: TObject); protected FQuizForm: TQuizForm; public procedure Prepare(const QuizForm: TQuizForm; Correct: Boolean; const State, Answer: string ); end; var AnsweredForm: TAnsweredForm = nil; procedure CreateAnswer(const Form: TForm); procedure ShowAnswer(const Form: TForm; Correct: Boolean; const State, Answer: string); implementation {$R *.fmx} uses Main; procedure CreateAnswer(const Form: TForm); begin if not Assigned(AnsweredForm) then AnsweredForm := TAnsweredForm.Create(Form); end; procedure ShowAnswer(const Form: TForm; Correct: Boolean; const State, Answer: string); begin CreateAnswer(Form); AnsweredForm.Prepare(TQuizForm(Form), Correct, State, Answer); AnsweredForm.Show; end; { TAnsweredForm } procedure TAnsweredForm.bHomeClick(Sender: TObject); begin Close; FQuizForm.GoHome; end; procedure TAnsweredForm.bNextClick(Sender: TObject); begin Close; FQuizForm.ReviewedAnswer; end; procedure TAnsweredForm.FormActivate(Sender: TObject); begin Log.d('Setting ad parent to answered form'); MainForm.TakeAdvertFromMainForm(Self); end; procedure TAnsweredForm.FormDeactivate(Sender: TObject); begin Log.d('Setting ad parent back to main form'); MainForm.PlaceAdvertOnMainForm; end; procedure TAnsweredForm.Prepare(const QuizForm: TQuizForm; Correct: Boolean; const State, Answer: string); const cCorrect = 'That is correct!'; cWrong = 'Oh, wow, sorry'; cAnswer = '%s is the capital of %s.'; begin FQuizForm := QuizForm; if Correct then lTitle.Text := cCorrect else lTitle.Text := cWrong; iYes.Visible := Correct; iNo.Visible := not Correct; lAnswer.Text := Format(cAnswer, [Answer, State]); end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 28.10.2020 15:24:33 unit IdOpenSSLHeaders_whrlpool; interface // Headers for OpenSSL 1.1.1 // whrlpool.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts; const WHIRLPOOL_DIGEST_LENGTH = 512 div 8; WHIRLPOOL_BBLOCK = 512; WHIRLPOOL_COUNTER = 256 div 8; type WHIRLPOOL_CTX_union = record case Byte of 0: (c: array[0 .. WHIRLPOOL_DIGEST_LENGTH -1] of Byte); (* double q is here to ensure 64-bit alignment *) 1: (q: array[0 .. (WHIRLPOOL_DIGEST_LENGTH div SizeOf(TIdC_DOUBLE)) -1] of TIdC_DOUBLE); end; WHIRLPOOL_CTX = record H: WHIRLPOOL_CTX_union; data: array[0 .. (WHIRLPOOL_BBLOCK div 8) -1] of Byte; bitoff: TIdC_UINT; bitlen: array[0 .. (WHIRLPOOL_COUNTER div SizeOf(TIdC_SIZET)) -1] of TIdC_SIZET; end; PWHIRLPOOL_CTX = ^WHIRLPOOL_CTX; function WHIRLPOOL_Init(c: PWHIRLPOOL_CTX): TIdC_INT cdecl; external CLibCrypto; function WHIRLPOOL_Update(c: PWHIRLPOOL_CTX; inp: Pointer; bytes: TIdC_SIZET): TIdC_INT cdecl; external CLibCrypto; procedure WHIRLPOOL_BitUpdate(c: PWHIRLPOOL_CTX; inp: Pointer; bits: TIdC_SIZET) cdecl; external CLibCrypto; function WHIRLPOOL_Final(md: PByte; c: PWHIRLPOOL_CTX): TIdC_INT cdecl; external CLibCrypto; function WHIRLPOOL(inp: Pointer; bytes: TIdC_SIZET; md: PByte): PByte cdecl; external CLibCrypto; implementation end.
unit PGmProtect; interface uses IdTCPServer; type SGameKind = (SGKsh, SGKsk, SGKddz); //游戏类型 PRWaiteTab = ^RWaiteTab; RWaiteTab = packed record TabID: Cardinal; TabKind: SGameKind; TabName: string[40]; TabPlayerCount: Byte; TabMaxCount:Byte; end; PRPlayer = ^Rplayer; Rplayer = record //玩家结构 Index: Byte; //自己的索引 ID: Cardinal; //id号 Name: string[20]; //呢称 Contenting: TIdPeerThread; //连接 ReadGame: boolean; //准备好开始游戏 PassCurrGame: boolean; //是否放弃了当前游戏 TotMoney: Integer; //总分 end; RHead = packed record Cmid: Cardinal; end; RCTS_login = packed record Acc: string[20]; psd: string[20]; end; RCTS_Login_RESP = packed record Code: string[20]; end; RCTS_CreateTab = packed record TabName: string[40]; TabKind: SGameKind; end; RCTS_CreateTab_RESP = packed record tabid: Cardinal; end; RCTS_JoinTab = packed record TabID: Cardinal; end; RCTS_JoinTab_RESP = packed record TabId: Cardinal; PlayerINDEX: byte; end; RCTS_ReadyGame = packed record TabID: Cardinal; PlayerINDEX: byte; STate: boolean; end; RCTS_LeaveTab = packed record TabID: Cardinal; PlayerID: Byte; end; RCTS_Chat=Packed Record SendIdx:Cardinal; TabID:Cardinal; PlayerID:Byte; Content:string[128]; end; RCTS_GetOnlinesUser=Packed Record Count:Integer; end; RCTS_UseWin=Packed Record TabId:Cardinal; PlayIdx:Byte; AddScore:Integer; end; RSTC_GiveCards = packed record CardsSize: Cardinal; Count: Byte; SupperState: boolean; //是否创建大小鬼 LoopCount: Byte; //循环次数 end; RSTC_ReSetPalyerIDX = packed record NewIdx: Byte; end; RSTC_GiveWaiteTabList = packed record ListSize: Cardinal; end; sTabChange = (TabAdd, TabFree, TabAddPlayer, TabDeletePlayer); RSTC_TabChange = packed record Kind: sTabChange; Param: Cardinal; WaiteTab: RWaiteTab; end; RSTC_GiveTabPlayerList = packed record size: Cardinal; Count: Cardinal; end; sPlayerChange = (PlayerIn, PlayerOut, PlayerReady, PlayernotReady); RSTC_PlayerIO = packed record Kind: sPlayerChange; Idx: Byte; Player: Rplayer; State: boolean; end; RSTC_GiveBeginPlayerIdx = packed record Index: Byte; end; RSTC_PlayerSendCards = packed record TabID: Cardinal; PlayerIdx: Byte; SendCards: string[20]; //牌的索引可以用|分隔 Scores: Integer; //下的注 end; RSTC_PlayerPass = packed record TabID: Cardinal; PLayerIdx: byte; end; Function TranstrlGameState(Ikind:SGameKind):String; const CappstateNormal = '正常状态'; CappStateStop = '服务停止状态'; CappStateTermintal = '程序结束状态'; CErrorCode = 99; Cmid_CTS_Login = 10001; //登陆 ClogRESP1 = '成功登陆'; ClogRESP2 = '用户名不存在'; ClogRESP3 = '用户名或者密码错误'; Cmid_CTS_ReadyGame = 10002; //准备开始游戏 CMid_CTS_DisConn = 10003; //断开连接 CMid_CTS_JoinTab = 10004; //加入Tab CMID_CTS_LeaveTab = 10005; //离开桌子 CMID_CTS_CreateTab = 10006; //创建桌子 Cmid_CTS_Chat=10007; //聊天 Cmid_CTS_GetOnlinesUser=10008;//获取在线用户 Cmid_CTS_Userwin=10009;//用户赢了+分 Cmid_STC_GiveCards = 20001; //接收牌局 CMID_STC_ReSetPlayerIDX = 20002; //重新设置玩家在这张桌子的索引iD号 Cmid_STC_GiveWaiteTabList = 20003; //发送在等待桌子的列表 Cmid_STC_TabChange = 20004; //桌子产生变动 Cmid_STC_GiveTabPlayerList = 20005; //给tab用户列表 Cmid_STC_PlayerIO = 20006; //玩家变动 Cmid_STC_GiveBeginPlayerIdx = 20007; //给开始玩家的索引 Cmid_STC_UserSendCards = 20008; //玩家出牌 Cmid_STC_UserPass = 20009; //玩家放弃或跳过 implementation Function TranstrlGameState(Ikind:SGameKind):String; Begin Case Ikind Of // SGKsh:Result:='梭哈'; Else Result:='不认识的类型'; End; // case End; end.
(*************************************************************************) (* *) (* SIMPLE MODEM v1.00 (c) Copyright S.J.Kay 18th April 1995 *) (* Using the Ward Christensen file transfer protocol *) (* *) (* Uses CP/M 3.0 AUXIN and AUXOUT routines *) (* *) (*************************************************************************) type registers = record case boolean of true : (AL, AH, BL, BH, CL, CH, DL, DH : byte); false : (AX, BX, CX, DX, BP, SI, DI, DS, ES, FLAGS : integer) end; const PthNme = ''; ENDBUF = $1FFF; { must be a multiple of 128 -1 } SOH = $01; { Start Of Header } EOT = $04; { End Of Transmission } ACK = $06; { Acknowledge } NAK = $15; { Negative Acknowledge } CAN = $18; { Cancel } var R : registers; F : file; ExtCde : byte; Check : byte; BufPos : integer; Abort : boolean; TmeOut : boolean; FleOpn : boolean; Buffer : array [$0000..ENDBUF] of byte; procedure ProcZ80 (Fn, Ax : byte; BCx, DEx, HLx : integer); begin inline ( $3A/Fn/ { ld a,(Fn) } $32/* + 17/ { ld (FNCNMB),a } $3A/Ax/ { ld a,(Ax) } $ED/$4B/BCx/ { ld bc,(BCx) } $ED/$5B/DEx/ { ld de,(DEx) } $2A/HLx/ { ld hl,(HLx) } $D3/$FF { out (FNCNMB),a } ) end; procedure Intr (Int : byte; var R : registers); begin ProcZ80($A1, Int, $AA55, $55AA, addr(R)) end; function SerialOutputStatus : byte; begin SerialOutputStatus := bios(18) { test if AUXOUT is ready } end; function SerialInputStatus : byte; begin SerialInputStatus := bios(17) { test if AUXIN has a character } end; procedure SerialOutput (x : byte); begin bios(5, x); end; function SerialInput : byte; begin SerialInput := bios(6); end; function TickCount : integer; begin R.AH := $00; intr($1A, R); TickCount := R.DX end; procedure TestAbort; var Key : char; begin while keypressed do begin read(kbd, Key); if (Key = ^[) or (Key = ^X) then begin Abort := true; ExtCde := 1 end end end; procedure WriteByte (BytVal : byte; TckVal : integer); var BytOut : boolean; T : integer; begin TmeOut := false; if SerialOutputStatus <> 0 then SerialOutput(BytVal) else begin BytOut := false; T := TickCount; repeat if SerialOutputStatus <> 0 then begin SerialOutput(BytVal); BytOut := true end else begin TmeOut := (TickCount - T) >= TckVal; if keypressed then TestAbort end until BytOut or TmeOut or Abort end end; function ReadByte (TckVal : integer) : byte; var BytInp : boolean; T : integer; begin TmeOut := false; if SerialInputStatus <> 0 then ReadByte := SerialInput else begin BytInp := false; T := TickCount; repeat if SerialInputStatus <> 0 then begin ReadByte := SerialInput; BytInp := true end else begin ReadByte := $FF; TmeOut := (TickCount - T) >= TckVal; if keypressed then TestAbort end until BytInp or TmeOut or Abort end end; procedure Purge; var Dummy : byte; begin repeat Dummy := ReadByte(19) { 1 sec time out } until TmeOut or Abort end; procedure SendCancel; var Dummy : byte; begin repeat Abort := false; Dummy := ReadByte(19) { 1 sec time out } until TmeOut; WriteByte(CAN, 91) { 5 sec time out } end; procedure StartNAK; var BytVal, Retry : byte; begin Retry := 15; repeat Purge; { 1 sec min time taken } if not Abort then begin WriteByte(NAK, 1820); { 100 sec time out } if TmeOut then begin Abort := true; ExtCde := 2 end; if not Abort then begin BytVal := ReadByte(56); { 3 sec time out waiting ACK } if Tmeout then Retry := Retry - 1; if Retry = 0 then begin Abort := true; ExtCde := 3 end end end until (BytVal = ACK) or Abort end; procedure BlockNAK; begin Purge; if not Abort then begin WriteByte(NAK, 1820); { 100 sec time out } if TmeOut then begin Abort := true; ExtCde := 4 end end end; procedure BlockACK; begin if not Abort then begin WriteByte(ACK, 1820); { 100 sec time out } if TmeOut then begin Abort := true; ExtCde := 5 end end end; procedure OpenFile; var i : integer; FleNme : string[12]; begin BufPos := 0; FleNme := ''; i := 0; while (i < 12) and (Buffer[i] <> 0) do begin FleNme := FleNme + chr(Buffer[i]); i := i + 1 end; gotoxy(42, 17); write(FleNme, '':12); assign(F, PthNme + FleNme); rewrite(F); FleOpn := true end; procedure FlushBuffer; begin blockwrite(F, Buffer, BufPos div 128); BufPos := 0 end; procedure CloseFile; begin if FleOpn then begin FlushBuffer; close(F); FleOpn := false end end; function ReadBlockByte (TckVal : integer) : byte; var BytVal : byte; begin BytVal := ReadByte(TckVal); Check := Check + BytVal; ReadBlockByte := BytVal end; function CheckHeader : boolean; var BytVal : byte; begin BytVal := ReadBlockByte(182); if (BytVal = EOT) and (not TmeOut) and (not Abort) then begin CloseFile; WriteByte(ACK, 1820); if TmeOut then Abort := true; if not Abort then WriteByte(ACK, 1820); if TmeOut then Abort := true; if Abort then ExtCde := 6 end; CheckHeader := BytVal = EOT end; procedure ReadBlocks; var Finish : boolean; i, SveBuf : integer; GetBlk, BlkNmb, BlkCpl, ChkSum : byte; BytVal : byte; begin BufPos := 0; GetBlk := 0; FleOpn := false; repeat i := 0; Check := 0; SveBuf := BufPos; Finish := CheckHeader; if not Finish then begin if (not TmeOut) and (not Abort) then BlkNmb := ReadBlockByte(19); if (not TmeOut) and (not Abort) then BlkCpl := ReadBlockByte(19); while (not TmeOut) and (not Abort) and (i < 128) do begin BytVal := ReadBlockByte(19); Buffer[BufPos] := BytVal; BufPos := BufPos + 1; i := i + 1 end; if (not TmeOut) and (not Abort) then ChkSum := ReadByte(19); if (not TmeOut) and (not Abort) then if ChkSum = Check then begin if not FleOpn and (BlkNmb = 0) then begin OpenFile; gotoxy(43, 18); write(BlkNmb, '': 2); BlockACK end; if BlkNmb = GetBlk then begin gotoxy(43, 18); write(BlkNmb, '': 2); GetBlk := GetBlk + 1; if BufPos > ENDBUF then FlushBuffer; BlockACK end else begin BufPos := SveBuf; if BlkNmb = (GetBlk - 1) then BlockACK else begin Abort := true; ExtCde := 7 end end end; if TmeOut or (Check <> ChkSum) then begin BlockNAK; BufPos := SveBuf end end until Abort or Finish end; procedure Receive; var Retry, Finish : boolean; BytVal : byte; begin Abort := false; Finish := false; ExtCde := 0; repeat StartNAK; { send NAK, then wait for ACK } if not Abort then begin Retry := true; while Retry and not Abort do begin BytVal := ReadByte(19); { 1st letter of filename or EOT } Retry := TmeOut; if not Retry then Finish := BytVal = EOT else BlockNAK end; if (not Finish) and (not Abort) then ReadBlocks end until Finish or Abort; if Abort then SendCancel; gotoxy(1, 23); case ExtCde of 1 : writeln('User cancelled by pressing abort key'); 2 : writeln('Unable to send initial NAK to sender'); 3 : writeln('No ACK response for initial NAK sent'); 4 : writeln('Unable to send NAK for bad block'); 5 : writeln('Unable to send ACK for block received'); 6 : writeln('Unable to send ACK for file end (EOT)'); 7 : writeln('Fatal loss of sync receiving blocks') end end; begin clrscr; writeln(' MODEM v1.00 (c) S.J.Kay 1st April 1995'); writeln; writeln(' Uses the Ward Christensen file transfer protocol'); writeln(' with file name support.'); writeln; writeln(' NOTE: Files will be written to the default drive.'); writeln; writeln(' Uses AUXIN and AUXOUT devices, set device for correct values'); writeln(' before using this program'); writeln; writeln(' To abort press the ESC or ^X keys at any time'); writeln; gotoxy(31, 17); write( 'Receiving:'); gotoxy(31, 18); write( ' Block: #'); Receive end.
unit Restourant.Consts.UserData; interface const Folder = 'userdata'; FileExt = '.json'; PROFILE = 'profile'; ORDERS = 'orders'; ORDERSNAME = 'ORD'; uLoginAppId = '60317ca0'; uLoginKey = 'Iw2kSe1HQsSbhKWxlLW5tA'; FieldUserID = 'ID'; FieldUserEMAIL = 'EMAIL'; FieldUserFIRSTNAME = 'FIRSTNAME'; FieldUserLASTNAME = 'LASTNAME'; FieldUserSEX = 'SEX'; FieldUserPHONE = 'PHONE'; FieldUserPWD = 'PWD'; FieldUserPWDNEW = 'PWDNEW'; FieldUserLang = 'LANG'; FieldUserNETWORK = 'NETWORK'; FieldOrderID = 'ID'; FieldOrderNAME = 'NAME'; FieldOrderUSER_ID = 'USER_ID'; FieldOrderDATE_CREATE = 'DATE_CREATE'; FieldOrderDATE_COMMIT = 'DATE_COMMIT'; FieldOrderPLATENO = 'PLATENO'; FieldOrderDOCNUMBERSTR = 'DOCNUMBERSTR'; FieldOrderDOCSUM = 'DOCSUM'; FieldOrder_DOCUMENT = 'DOCUMENT'; FieldDocNAME = 'NAME'; FieldDocTMC_ID = 'TMC_ID'; FieldDocPRICE = 'PRICE'; FieldDocQUANT = 'QUANT'; FieldDocTOTAL = 'TOTAL'; implementation end.
unit Unit1; interface uses winapi.WinHTTP, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, shellapi, ExtCtrls, ComCtrls, Menus, cxPCdxBarPopupMenu, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel, cxPC, cxRadioGroup, cxCheckBox, cxButtons, cxMemo, cxTextEdit, cxGroupBox, dxSkinsForm, dxSkinsCore, dxSkinFoggy, dxSkinscxPCPainter, cxSplitter, cxClasses, dxBarBuiltInMenu, Alcinoe.StringUtils, Alcinoe.WebSocket.Client.WinHTTP, dxCore; type TForm1 = class(TForm) PageControl1: TcxPageControl; TabSheet1: TcxTabSheet; TabSheet2: TcxTabSheet; GroupBox3: TcxGroupBox; Label18: TcxLabel; Label19: TcxLabel; EditUserName: TcxTextEdit; EditPassword: TcxTextEdit; GroupBox4: TcxGroupBox; Label14: TcxLabel; Label17: TcxLabel; Label20: TcxLabel; EditSendTimeout: TcxTextEdit; EditReceiveTimeout: TcxTextEdit; EditConnectTimeout: TcxTextEdit; GroupBox6: TcxGroupBox; GroupBox7: TcxGroupBox; GroupBox2: TcxGroupBox; RadioButtonAccessType_NAMED_PROXY: TcxRadioButton; RadioButtonAccessType_NO_PROXY: TcxRadioButton; RadioButtonAccessType_DEFAULT_PROXY: TcxRadioButton; GroupBox1: TcxGroupBox; Label15: TcxLabel; Label12: TcxLabel; Label11: TcxLabel; Label16: TcxLabel; Label13: TcxLabel; EdProxyPort: TcxTextEdit; EdProxyUserName: TcxTextEdit; EdProxyServer: TcxTextEdit; EdProxyPassword: TcxTextEdit; EdProxyBypass: TcxTextEdit; GroupBox5: TcxGroupBox; EditBufferSize: TcxTextEdit; CheckBoxInternetOption_BYPASS_PROXY_CACHE: TcxCheckBox; CheckBoxInternetOption_ESCAPE_DISABLE: TcxCheckBox; CheckBoxInternetOption_REFRESH: TcxCheckBox; CheckBoxInternetOption_SECURE: TcxCheckBox; CheckBoxInternetOption_ESCAPE_PERCENT: TcxCheckBox; CheckBoxInternetOption_NULL_CODEPAGE: TcxCheckBox; CheckBoxInternetOption_ESCAPE_DISABLE_QUERY: TcxCheckBox; GroupBox8: TcxGroupBox; MemoRequestRawHeader: TcxMemo; Label8: TcxLabel; RadioButtonProtocolVersion1_0: TcxRadioButton; RadioButtonProtocolVersion1_1: TcxRadioButton; GroupBox9: TcxGroupBox; editURL: TcxTextEdit; Label4: TcxLabel; MemoMessage: TcxMemo; Label1: TcxLabel; ButtonSend: TcxButton; ButtonConnect: TcxButton; CheckBoxInternetOption_KEEP_CONNECTION: TcxCheckBox; CheckBoxInternetOption_NO_COOKIES: TcxCheckBox; CheckBoxInternetOption_NO_AUTO_REDIRECT: TcxCheckBox; dxSkinController1: TdxSkinController; Panel4: TPanel; cxSplitter2: TcxSplitter; GroupBox10: TcxGroupBox; Panel5: TPanel; Label2: TcxLabel; MemoLogStatus: TcxMemo; Panel6: TPanel; Label3: TcxLabel; MemoLogMsgReceived: TcxMemo; cxSplitter1: TcxSplitter; Label24: TcxLabel; procedure ButtonConnectClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ButtonSendClick(Sender: TObject); private FWinHttpWebSocketClient: TalWinHttpWebSocketClient; procedure initWinHTTPWebSocketClient; public procedure OnWebSocketClientStatus( Sender: Tobject; InternetStatus: DWord; StatusInformation: Pointer; StatusInformationLength: DWord); procedure OnWebSocketClientError(sender: Tobject; const &Message: AnsiString); procedure OnWebSocketClientReceive(sender: Tobject; const Data: AnsiString; const IsUTF8: Boolean); end; var Form1: TForm1; implementation Uses system.AnsiStrings, DateUtils, HttpApp, Alcinoe.MultiPartParser, Alcinoe.Files, Alcinoe.Common, Alcinoe.Mime, Alcinoe.HTTP.Client.WinHTTP, Alcinoe.StringList, Alcinoe.HTTP.Client; {$R *.dfm} {******************************************} procedure TForm1.initWinHTTPWebSocketClient; Begin With FWinHttpWebSocketClient do begin UserName := AnsiString(EditUserName.Text); Password := AnsiString(EditPassword.Text); if AlIsInteger(AnsiString(EditConnectTimeout.Text)) then ConnectTimeout := StrToInt(EditConnectTimeout.Text); if AlIsInteger(AnsiString(EditsendTimeout.Text)) then SendTimeout := StrToInt(EditSendTimeout.Text); if AlIsInteger(AnsiString(EditReceiveTimeout.Text)) then ReceiveTimeout := StrToInt(EditReceiveTimeout.Text); if RadioButtonProtocolVersion1_0.Checked then ProtocolVersion := TALHTTPProtocolVersion.v1_0 else ProtocolVersion := TALHTTPProtocolVersion.v1_1; if AlIsInteger(AnsiString(EditBufferSize.Text)) then BufferSize := StrToInt(EditBufferSize.Text); ProxyParams.ProxyServer := AnsiString(EdProxyServer.Text); ProxyParams.ProxyPort := StrToInt(EdProxyPort.Text); ProxyParams.ProxyUserName := AnsiString(EdProxyUserName.Text); ProxyParams.ProxyPassword := AnsiString(EdProxyPassword.Text); ProxyParams.ProxyBypass := AnsiString(EdProxyBypass.Text); if RadioButtonAccessType_NO_PROXY.Checked then AccessType := wHttpAt_NO_PROXY else if RadioButtonAccessType_NAMED_PROXY.Checked then AccessType := wHttpAt_NAMED_PROXY else if RadioButtonAccessType_DEFAULT_PROXY.Checked then AccessType := wHttpAt_DEFAULT_PROXY; InternetOptions := []; If CheckBoxInternetOption_BYPASS_PROXY_CACHE.checked then InternetOptions := InternetOptions + [wHttpIo_BYPASS_PROXY_CACHE]; If CheckBoxInternetOption_ESCAPE_DISABLE.checked then InternetOptions := InternetOptions + [wHttpIo_ESCAPE_DISABLE]; If CheckBoxInternetOption_ESCAPE_DISABLE_QUERY.checked then InternetOptions := InternetOptions + [wHttpIo_ESCAPE_DISABLE_QUERY]; If CheckBoxInternetOption_ESCAPE_PERCENT.checked then InternetOptions := InternetOptions + [wHttpIo_ESCAPE_PERCENT]; If CheckBoxInternetOption_NULL_CODEPAGE.checked then InternetOptions := InternetOptions + [wHttpIo_NULL_CODEPAGE]; If CheckBoxInternetOption_REFRESH.checked then InternetOptions := InternetOptions + [wHttpIo_REFRESH]; If CheckBoxInternetOption_SECURE.checked then InternetOptions := InternetOptions + [wHttpIo_SECURE]; If CheckBoxInternetOption_NO_COOKIES.checked then InternetOptions := InternetOptions + [wHttpIo_NO_COOKIES]; If CheckBoxInternetOption_KEEP_CONNECTION.checked then InternetOptions := InternetOptions + [wHttpIo_KEEP_CONNECTION]; If CheckBoxInternetOption_NO_AUTO_REDIRECT.checked then InternetOptions := InternetOptions + [wHttpIo_NO_AUTO_REDIRECT]; RequestHeader.RawHeaderText := AnsiString(MemoRequestRawHeader.Text); end; end; {***************************************} procedure TForm1.OnWebSocketClientStatus( Sender: Tobject; InternetStatus: DWord; StatusInformation: Pointer; StatusInformationLength: DWord); var StatusStr: AnsiString; begin case InternetStatus of WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: StatusStr := 'Closing the connection to the server'; WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: StatusStr := 'Successfully connected to the server'; WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: StatusStr := 'Connecting to the server'; WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: StatusStr := 'Successfully closed the connection to the server'; WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: StatusStr := 'Data is available to be retrieved with WinHttpReadData'; WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: StatusStr := 'An HINTERNET handle has been created'; WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: StatusStr := 'This handle value has been terminated'; WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: StatusStr := 'The response header has been received and is available with WinHttpQueryHeaders'; WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE: StatusStr := 'Received an intermediate (100 level) status code message from the server'; WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: StatusStr := 'Successfully found the IP address of the server'; WINHTTP_CALLBACK_STATUS_READ_COMPLETE: StatusStr := 'Data was successfully read from the server'; WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: StatusStr := 'Waiting for the server to respond to a request'; WINHTTP_CALLBACK_STATUS_REDIRECT: StatusStr := 'An HTTP request is about to automatically redirect the request'; WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: StatusStr := 'An error occurred while sending an HTTP request'; WINHTTP_CALLBACK_STATUS_REQUEST_SENT: StatusStr := 'Successfully sent the information request to the server'; WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: StatusStr := 'Looking up the IP address of a server name'; WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: StatusStr := 'Successfully received a response from the server'; WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: StatusStr := 'One or more errors were encountered while retrieving a Secure Sockets Layer (SSL) certificate from the server'; WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: StatusStr := 'Sending the information request to the server'; WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: StatusStr := 'The request completed successfully'; WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: StatusStr := 'Data was successfully written to the server'; else StatusStr := 'Unknown status: ' + ALIntToStrA(InternetStatus); end; MemoLogStatus.Lines.Add(String(StatusStr)); end; {***********************************************************************************} procedure TForm1.OnWebSocketClientError(sender: Tobject; const &Message: AnsiString); begin MemoLogStatus.Lines.Add(String(&Message)); end; {********************************************************************************************************} procedure TForm1.OnWebSocketClientReceive(sender: Tobject; const Data: AnsiString; const IsUTF8: Boolean); begin MemoLogMsgReceived.Lines.Add(String(Data)); end; {***************************************************} procedure TForm1.ButtonConnectClick(Sender: TObject); begin Screen.Cursor := crHourGlass; try if ButtonConnect.tag = 0 then begin initWinHTTPWebSocketClient; MemoLogMsgReceived.Lines.Clear; MemoLogStatus.Lines.Clear; FWinHttpWebSocketClient.Connect(AnsiString(editURL.Text)); ButtonConnect.Caption := 'Disconnect'; ButtonConnect.Tag := 1; ButtonSend.Enabled := True; end else begin FWinHttpWebSocketClient.Disconnect; ButtonConnect.Caption := 'Connect'; ButtonConnect.Tag := 0; ButtonSend.Enabled := False; end; finally Screen.Cursor := crDefault; end; end; {************************************************} procedure TForm1.ButtonSendClick(Sender: TObject); begin FWinHttpWebSocketClient.Send(AnsiString(MemoMessage.Text)); end; {*******************************************} procedure TForm1.FormCreate(Sender: TObject); begin FWinHttpWebSocketClient := TaLWinHttpWebSocketClient.Create; with FWinHttpWebSocketClient do begin AccessType := wHttpAt_NO_PROXY; InternetOptions := []; OnStatus := OnWebSocketClientStatus; OnError := OnWebSocketClientError; OnReceive := OnWebSocketClientReceive; MemoRequestRawHeader.Text := String(RequestHeader.RawHeaderText); end; MemoLogStatus.Height := MemoLogStatus.Parent.Height - MemoLogStatus.top - 6; MemoLogMsgReceived.Height := MemoLogMsgReceived.Parent.Height - MemoLogMsgReceived.top - 6; MemoMessage.lines.Text := ALTrim(MemoMessage.lines.Text); end; {********************************************} procedure TForm1.FormDestroy(Sender: TObject); begin FWinHttpWebSocketClient.Free; end; initialization {$IFDEF DEBUG} ReporTMemoryleaksOnSHutdown := True; {$ENDIF} SetMultiByteConversionCodePage(CP_UTF8); end.
unit Angle; interface {$I Angles.inc} // Angle constants type TAngle = smallint; PAngleArray = ^TAngleArray; TAngleArray = array[0..0] of TAngle; TVector = array[0..1] of single; const DegreeToRadian = Pi/180; RadianToDegree = 180/Pi; vZero = 0.00001; // Zero Value in -vZero..vZero const Codes = $1000; CodesPerAngle = Codes/360; AnglesPerCode = 360/Codes; MaxVelocity = 100; {m/s} function CodeAngle( aCode : TAngle ) : single; function AngleCode( anAngle : single ) : TAngle; function Angle2Byte( anAngle : single ) : byte; function Byte2Angle( aByte : byte ) : single; function Velocity2Byte( aVel : single ) : byte; function Byte2Velocity( aByte : byte ) : integer; function Distance( A1, A2 : TAngle ) : TAngle; function Sine(anAngle: TAngle): single; function Cosine(anAngle: TAngle): single; function VADVector(v1, v2, az1, az2, el: single): TVector; function AngleReduc(anAngle: single): single; function Phi(Vx, Vy: single): single; //Vector's angle function Rho(Vx, Vy: single): single; //Vector's module function Vx(Rho, Phi: single): single; //Vector's x component function Vy(Rho, Phi: single): single; //Vector's y component implementation // Public procedures & functions uses Math; function Distance( A1, A2 : TAngle ) : TAngle; begin Result := A1 - A2; if Result >= 2048 then dec(Result, 4096); if Result < -2047 then inc(Result, 4096); end; function CodeAngle( aCode : TAngle ) : single; begin Result := aCode * AnglesPerCode; end; function AngleCode( anAngle : single ) : TAngle; begin Result := round(anAngle * CodesPerAngle) end; function Sine; begin Result := sin(CodeAngle(anAngle)*pi/180); end; function Cosine; begin Result := cos(CodeAngle(anAngle)*pi/180); end; function Angle2Byte; begin result := round(AngleReduc(anAngle)*256/2/pi); end; function Byte2Angle; begin result := aByte*2*pi/256; end; function Velocity2Byte; begin result := Round(aVel*256/MaxVelocity); end; function Byte2Velocity; begin result := Round(aByte*MaxVelocity/256*1.944); {kn} end; function VADVector; var saz1, saz2, caz1, caz2, cele, d, d1, d2, U, V, vel1, vel2, R, A: single; begin saz1 := Sin(az1*pi/180); saz2 := Sin(az2*pi/180); caz1 := Cos(az1*pi/180); caz2 := Cos(az2*pi/180); cele := Cos(el*pi/180); vel1 := v1; vel2 := v2; d := saz1*cele*caz2*cele - saz2*cele*caz1*cele; d1 := vel1*caz2*cele - vel2*caz1*cele; d2 := vel2*saz1*cele - vel1*saz2*cele; if not IsZero(d, vZero)then begin U := d1/d; V := d2/d; R := Rho(U, V); { if R > 5 then begin Result[0] := 0; Result[1] := 0; end else} begin Result[0] := U; Result[1] := V; end; end else begin Result[0] := 0; Result[1] := 0; end; end; function Phi; begin if IsZero(Vx, vZero) then begin if IsZero(Vy, vZero) then Result := 0 else if Vy > 0 then Result := pi/2 else Result := 3*pi/2 end else if IsZero(Vy, vZero) then begin if Vx > 0 then Result := 0 else Result := pi end else if (Vx > 0) and (Vy > 0) then Result := AngleReduc(arctan(Vy/Vx)) // 1 else if (Vx < 0) and (Vy > 0) then Result := AngleReduc(pi + arctan(Vy/Vx)) // 2 else if (Vx < 0) and (Vy < 0) then Result := AngleReduc(pi + arctan(Vy/Vx)) // 3 else if (Vx > 0) and (Vy < 0) then Result := AngleReduc(arctan(Vy/Vx)) // 4 ; end; function Rho; begin Result := sqrt(sqr(Vx) + sqr(Vy)); end; function Vx; begin Vx := Rho*cos(Phi); end; function Vy; begin Vy := Rho*sin(Phi); end; function AngleReduc; begin if anAngle > 2*pi then Result := AngleReduc(anAngle - 2*pi) else if anAngle < 0 then Result := AngleReduc(anAngle + 2*pi) else Result := anAngle end; end.
unit SystemAdministrationPrivilegeServices; interface uses SysUtils, Classes; type TSystemAdministrationPrivilegeServices = class public PrivilegeId: Variant; constructor Create(const PrivilegeId: Variant); end; implementation { TSystemAdministrationPrivilegeServices } constructor TSystemAdministrationPrivilegeServices.Create( const PrivilegeId: Variant); begin inherited Create; Self.PrivilegeId := PrivilegeId; end; end.
program DialogTest; {$mode objfpc}{$H+} uses SysUtils, MUIClass.Base, MUIClass.Window, MUIClass.Group, MUIClass.Dialog, MUIClass.Area, MUIClass.Image, MUIClass.Gadget, MUIClass.List; type TMyWindow = class(TMUIWindow) private Pages: TMUIRegister; SaveMode, Multi, Style, DrawMode,Overscan, Autoscroll, FrontPen, BackPen, FixedOnly, WidthEdit, HeightEdit, DepthEdit: TMUICheckMark; FileTitle, FontTitle, ScTitle, Pattern: TMUIString; Memo: TMUIFloatText; procedure FileStart(Sender: TObject); procedure FontStart(Sender: TObject); procedure ScreenStart(Sender: TObject); public constructor Create; override; end; constructor TMyWindow.Create; var FG, SG: TMUIGroup; begin inherited; Pages := TMUIRegister.Create; with Pages do begin Titles := ['File Dialog', 'Font Dialog', 'Screen Dialog']; Parent := Self; end; //###################### FileDialog FG := TMUIGroup.Create; with FG do begin Parent := Pages; end; SG := TMUIGroup.Create; with SG do begin Columns := 2; Parent := FG; end; with TMUIText.Create do begin Contents := 'Title Text'; Parent := SG; end; FileTitle := TMUIString.Create; FileTitle.Contents := 'Select File'; FileTitle.FixWidth := 150; FileTitle.Parent := SG; with TMUIText.Create do begin Contents := 'Pattern'; Parent := SG; end; Pattern := TMUIString.Create; Pattern.Contents := ''; Pattern.FixWidth := 150; Pattern.Parent := SG; with TMUIText.Create do begin Contents := 'MultiSelect'; Parent := SG; end; Multi := TMUICheckmark.Create; Multi.Parent := SG; with TMUIText.Create do begin Contents := 'SaveMode'; Parent := SG; end; SaveMode := TMUICheckmark.Create; SaveMode.Parent := SG; with TMUIButton.create do begin Contents := 'Execute'; OnClick := @FileStart; Parent := FG; end; // ################## FontDialog FG := TMUIGroup.Create; with FG do begin Parent := Pages; end; SG := TMUIGroup.Create; with SG do begin Columns := 2; Parent := FG; end; with TMUIText.Create do begin Contents := 'Title Text'; Parent := SG; end; FontTitle := TMUIString.Create; FontTitle.Contents := 'Select Font'; FontTitle.FixWidth := 150; FontTitle.Parent := SG; with TMUIText.Create do begin Contents := 'Style'; Parent := SG; end; Style := TMUICheckmark.Create; Style.Parent := SG; with TMUIText.Create do begin Contents := 'Draw Mode'; Parent := SG; end; DrawMode := TMUICheckmark.Create; DrawMode.Parent := SG; with TMUIText.Create do begin Contents := 'Front Pen'; Parent := SG; end; FrontPen := TMUICheckmark.Create; FrontPen.Parent := SG; with TMUIText.Create do begin Contents := 'Back Pen'; Parent := SG; end; BackPen := TMUICheckmark.Create; BackPen.Parent := SG; with TMUIText.Create do begin Contents := 'Fixed Fonts only'; Parent := SG; end; FixedOnly := TMUICheckmark.Create; FixedOnly.Parent := SG; with TMUIButton.create do begin Contents := 'Execute'; OnClick := @FontStart; Parent := FG; end; //####################### FScreenDialog FG := TMUIGroup.Create; with FG do begin Parent := Pages; end; SG := TMUIGroup.Create; with SG do begin Columns := 2; Parent := FG; end; with TMUIText.Create do begin Contents := 'Title Text'; Parent := SG; end; ScTitle := TMUIString.Create; ScTitle.Contents := 'Select ScreenMode'; ScTitle.FixWidth := 150; ScTitle.Parent := SG; with TMUIText.Create do begin Contents := 'Width Editable'; Parent := SG; end; WidthEdit := TMUICheckmark.Create; WidthEdit.Parent := SG; with TMUIText.Create do begin Contents := 'Height Editable'; Parent := SG; end; HeightEdit := TMUICheckmark.Create; HeightEdit.Parent := SG; with TMUIText.Create do begin Contents := 'Depth Editable'; Parent := SG; end; DepthEdit := TMUICheckmark.Create; DepthEdit.Parent := SG; with TMUIText.Create do begin Contents := 'Overscan Type'; Parent := SG; end; Overscan := TMUICheckmark.Create; Overscan.Parent := SG; with TMUIText.Create do begin Contents := 'Set AutoScroll'; Parent := SG; end; AutoScroll := TMUICheckmark.Create; AutoScroll.Parent := SG; with TMUIButton.create do begin Contents := 'Execute'; OnClick := @ScreenStart; Parent := FG; end; Memo := TMUIFloatText.Create; with Memo do begin Parent := Self; end; end; procedure TMyWindow.FileStart(Sender: TObject); var FD: TFileDialog; begin FD := TFileDialog.Create; FD.MultiSelect := Multi.Selected; FD.SaveMode := SaveMode.Selected; FD.TitleText := FileTitle.Contents; FD.Pattern := Pattern.Contents; if FD.Execute then begin if FD.SaveMode then Memo.Text := 'File selected to save: '#10 + FD.Filename else Memo.Text := 'File(s) selected to load: '#10 + FD.Filenames.Text; end; FD.Free; end; procedure TMyWindow.FontStart(Sender: TObject); var FO: TFontDialog; s: string; begin FO := TFontDialog.Create; Fo.TitleText := FontTitle.Contents; FO.Options := []; if FrontPen.Selected then FO.Options := FO.Options + [foFrontPen]; if BackPen.Selected then FO.Options := FO.Options + [foBackPen]; if DrawMode.Selected then FO.Options := FO.Options + [foDrawMode]; if Style.Selected then FO.Options := FO.Options + [foStyle]; if FixedOnly.Selected then FO.Options := FO.Options + [foFixedOnly]; if FO.Execute then begin s := 'Font Selected: '#10 + FO.Name + ': ' +IntToStr(FO.Size) + #10; if FrontPen.Selected then S := S + ' FrontPen: ' + IntToStr(FO.FrontPen) + #10; if BackPen.Selected then S := S + ' BackPen: ' + IntToStr(FO.BackPen) + #10; if DrawMode.Selected then S := S + ' DrawMode: ' + IntToStr(FO.DrawMode) + #10; if Style.Selected then S := S + ' Style: ' + IntToStr(FO.Style) + #10; Memo.Text := s; end; FO.Free; end; procedure TMyWindow.ScreenStart(Sender: TObject); var SD: TScreenDialog; s: string; begin SD := TScreenDialog.Create; SD.TitleText := ScTitle.Contents; SD.Options := []; if WidthEdit.Selected then SD.Options := SD.Options + [soWidth]; if HeightEdit.Selected then SD.Options := SD.Options + [soHeight]; if DepthEdit.Selected then SD.Options := SD.Options + [soDepth]; if Overscan.Selected then SD.Options := SD.Options + [soOverscanType]; if AutoScroll.Selected then SD.Options := SD.Options + [soAutoscroll]; if SD.Execute then begin s:= 'Screen Selected: ' + IntToStr(SD.DisplayID) + ' - ' + IntToStr(SD.DisplayWidth) + 'x' + IntToStr(SD.DisplayHeight) + 'x' + IntToStr(SD.DisplayDepth)+#10; if Overscan.Selected then s := s + ' Overscan: ' + IntToStr(SD.OverscanType) + #10; if Autoscroll.Selected then s := s + ' AutoScroll: ' + BoolToStr(SD.Autoscroll, True) + #10; Memo.Text := s; end; end; begin TMyWindow.Create; MUIApp.Run; end.
unit ImgLibObjs; // %ImgLibObjs : 包装ImageLib (***** Code Written By Huang YanLai *****) interface uses Windows, Messages, SysUtils, Classes, Graphics,ImageLibX,Controls,SimpBmp; { Wrap the ImageLib functions } const ESGetInfo = 'Get Image Info'; ESLoad = 'Load Image'; ESSave = 'Save Image'; ESOther = 'Other Operation'; procedure CheckImgLibCallError(ReturnCode : SmallInt); procedure CheckImgLibCallErrorEx(Const ErrorStr:string;ReturnCode : SmallInt); type TFileTypeStr = array[0..5] of char; TCompressTypeStr = array[0..10] of char; TImageType = (imUnknown,imJPEG, imGIF, imBMP, imPCX, imPNG,imTIFF); TImgLibError = class(Exception); TCustomImgLibObjClass = class of TCustomImgLibObj; TCustomImgLibObj = class(TGraphic) private FDither: boolean; FSaveResolution: integer; FHeight: SmallInt; FWidth: SmallInt; FCompressType: TCompressTypeStr; FFileTypeStr: TFileTypeStr; FAutoResolution: boolean; FSize: LongInt; FImageType: TImageType; FBitsPixel: SmallInt; FPlanes: SmallInt; FNumColors: SmallInt; FQuality: smallInt; Fstripsize: word; Fcompression: word; Finterlaced: smallInt; FAutoImageType: boolean; FShowErrorInt : smallInt; FLoadResolution: integer; FProgressed: boolean; //get ImageType based on FileTypeStr, and SaveResolution procedure UpdateInfo; //create a memory stream to copy stream, then call ReadBuffer procedure ReadStream(Stream : TStream); //call internalRead procedure ReadBuffer(Buffer : pointer); //call internalWrite procedure WriteBuffer(Buffer : pointer;MaxSize:integer); procedure SetShowError(const Value: boolean); function GetShowError: boolean; function StartLoading:boolean; function EndLoading(hBmp : HBitmap; hPal :HPalette): boolean; protected LastPercent : integer; Callback : TImgLibCallBackFunction; FIsCancel : boolean; // override inherited methods function GetEmpty: Boolean; override; procedure SetHeight(Value: Integer); override; procedure SetWidth(Value: Integer); override; //Read/Write in Delphi Resource Stream //get Size, then call ReadStream procedure ReadData(Stream: TStream); override; //write size, then call SaveToStream, then write size again procedure WriteData(Stream: TStream); override; procedure InternalLoadDIB(const FileName:string;var hBmp : HBitmap);virtual; procedure InternalLoadDDB(const FileName:string;var hBmp : HBitmap; var hPal:HPalette);virtual; procedure InternalSaveDIB(const FileName:string;hBitmap,hPal : THandle);virtual; procedure InternalSaveDDB(const FileName:string;hBitmap,hPal : THandle);virtual; procedure InternalLoadBufferDIB(Buffer:pointer;var hBmp : HBitmap);virtual; procedure InternalLoadBufferDDB(Buffer:pointer;var hBmp : HBitmap;var hPal : HPalette);virtual; procedure InternalSaveBufferDIB(Buffer:pointer;MaxSize:integer;hBitmap,hPal : THandle);virtual; procedure InternalSaveBufferDDB(Buffer:pointer;MaxSize:integer;hBitmap,hPal : THandle);virtual; function GetMaxSaveSize: integer; dynamic; procedure DoProgress(Percent : integer; var isContinue:boolean); procedure GetHandles(var hBmp : HBitmap; var hPal : HPalette); virtual;abstract; procedure SetHandles(hBmp : HBitmap; hPal : HPalette); virtual;abstract; function GetHandleType: TBitmapHandleType; virtual;abstract; public constructor Create; override; Destructor Destroy;override; procedure Assign(Source: TPersistent); override; procedure Clear; // these properties are used only in Read/Write property Size : LongInt read FSize; //return the FHeight and FWidth, that may differ from the values of Bitmap function GetInternalHeight: Integer; function GetInternalWidth: Integer; property FileTypeStr : TFileTypeStr read FFileTypeStr write FFileTypeStr; property CompressType: TCompressTypeStr read FCompressType write FCompressType; { compression : 1 - No compression 2 - CCITT compression (1 bit; not supported at this time) 5 - LZW compression 32773 - PackBits compression } property compression : word read Fcompression write Fcompression; { An integer value indicating the number of different strips to separate the image into. } property stripsize : word read Fstripsize write Fstripsize; property interlaced : smallInt read Finterlaced write Finterlaced; property BitsPixel : SmallInt read FBitsPixel; property Planes : SmallInt read FPlanes ; property NumColors : SmallInt read FNumColors; //Call set FileName then GetInfo; procedure GetFileInfo(const AFileName:string); //these methods may change the size . //LoadFromFile call InternalLoad procedure LoadFromFile(const AFileName:string); override; //SaveToFile call InternalSave procedure SaveToFile(const AFileName:string); override; //size = Stream.Size-Stream.Position, call ReadStream procedure LoadFromStream(Stream: TStream); override; //call WriteBuffer to write into a Sharedmem,then copy to Stream procedure SaveToStream(Stream: TStream); override; procedure Rotate90; procedure Rotate180; procedure Flip; property IsCancel : boolean read FIsCancel write FIsCancel; published // auto SaveResolution when load from file or stream property AutoResolution : boolean read FAutoResolution write FAutoResolution default true; // auto imageType when save to file property AutoImageType : boolean read FAutoImageType write FAutoImageType default true; // resolution for load/save property LoadResolution : integer read FLoadResolution write FLoadResolution default 8; property SaveResolution : integer read FSaveResolution write FSaveResolution default 8; property Dither : boolean read FDither write FDither; property ImageType : TImageType read FImageType write FImageType; property Quality : smallInt read FQuality write FQuality default 75; property ShowError : boolean read GetShowError write SetShowError default false; property Progressed : boolean read FProgressed write FProgressed; end; TImgLibObj = class(TCustomImgLibObj) private FBitmap: TBitmap; function GetTransparentColor: TColor; function GetTransparentMode: TTransparentMode; procedure SetTransparentColor(const Value: TColor); procedure SetTransparentMode(const Value: TTransparentMode); protected // return the width/height of bitmap function GetHeight: Integer; override; function GetWidth: Integer; override; procedure GetHandles(var hBmp : HBitmap; var hPal : HPalette); override; procedure SetHandles(hBmp : HBitmap; hPal : HPalette); override; procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; function GetHandleType: TBitmapHandleType; override; function GetPalette: HPALETTE; override; procedure SetPalette(Value: HPALETTE); override; function GetTransparent: boolean; override; procedure SetTransparent(Value: Boolean); override; public property Bitmap : TBitmap read FBitmap; constructor Create; override; Destructor Destroy;override; procedure Assign(Source: TPersistent); override; procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); override; procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle; var APalette: HPALETTE); override; published property TransparentColor: TColor read GetTransparentColor Write SetTransparentColor; property TransparentMode: TTransparentMode read GetTransparentMode Write SetTransparentMode default tmAuto; end; TImgLibViewObj = class(TCustomImgLibObj) private FBitmap: TSimpleBitmap; protected // return the width/height of bitmap function GetHeight: Integer; override; function GetWidth: Integer; override; procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; function GetHandleType: TBitmapHandleType; override; function GetPalette: HPALETTE; override; procedure SetPalette(Value: HPALETTE); override; public property Bitmap : TSimpleBitmap read FBitmap; constructor Create; override; Destructor Destroy;override; procedure Assign(Source: TPersistent); override; procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); override; procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle; var APalette: HPALETTE); override; procedure GetHandles(var hBmp : HBitmap; var hPal : HPalette); override; procedure SetHandles(hBmp : HBitmap; hPal : HPalette); override; published end; const {TIFF compression : 1 - No compression 2 - CCITT compression (1 bit; not supported at this time) 5 - LZW compression 32773 - PackBits compression} cmpNo = 1; cmpCCITT = 2; cmpLZW = 5; cmpPackBits = 32773; function GetImageTypeFromFileExt(const FileName:string): TImageType; type TCustomILImage = class(TGraphicControl) private FImageObj: TCustomImgLibObj; FStretch: Boolean; FScale: boolean; FCenter: boolean; procedure SetImageObj(const Value: TCustomImgLibObj); procedure Changed(sender : TObject); procedure SetStretch(const Value: Boolean); procedure SetScale(const Value: boolean); procedure SetTransparent(const Value: Boolean); function GetTransparent: Boolean; procedure SetCenter(const Value: boolean); function GetOnProgress: TProgressEvent; procedure SetOnProgress(const Value: TProgressEvent); protected procedure Paint; override; function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override; property Transparent: Boolean read GetTransparent write SetTransparent default False; { Stretch Scale F F 显示原始大小 F T 如果图象大于显示区域,缩小显示大小,保持长宽比 T F 放缩图象,不保持长宽比 T T 放缩图象,保持长宽比 } property Stretch: Boolean read FStretch write SetStretch default False; property Scale : boolean read FScale write SetScale default true; property Center : boolean read FCenter write SetCenter default true; property OnProgress: TProgressEvent read GetOnProgress write SetOnProgress; public constructor Create(AOwner : TComponent); override; Destructor Destroy;override; property ImageObj : TCustomImgLibObj read FImageObj write SetImageObj; published end; // %TILImage : 显示图像的控件。(使用TBitmap保存HBitmap) TILImage = class(TCustomILImage) private function GetImageObj: TImgLibObj; procedure SetImageObj(const Value: TImgLibObj); protected public constructor Create(AOwner : TComponent); override; published property ImageObj : TImgLibObj read GetImageObj write SetImageObj; property Transparent; property Stretch; property Scale; property Center; property OnProgress; property Align; property Anchors; property AutoSize; property Color; property Constraints; property DragCursor; property DragKind; property DragMode; property Enabled; //property IncrementalDisplay: Boolean read FIncrementalDisplay write FIncrementalDisplay default False; property ParentShowHint; property PopupMenu; property ShowHint; //property Stretch: Boolean read FStretch write SetStretch default False; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; // %TILImageView : 显示图像的控件。(使用TSimpleBitmap保存HBitmap) TILImageView = class(TCustomILImage) private function GetImageObj: TImgLibViewObj; procedure SetImageObj(const Value: TImgLibViewObj); protected public constructor Create(AOwner : TComponent); override; published property ImageObj : TImgLibViewObj read GetImageObj write SetImageObj; property Stretch; property Scale; property Center; property OnProgress; property Align; property Anchors; property AutoSize; property Color; property Constraints; property DragCursor; property DragKind; property DragMode; property Enabled; //property IncrementalDisplay: Boolean read FIncrementalDisplay write FIncrementalDisplay default False; property ParentShowHint; property PopupMenu; property ShowHint; //property Stretch: Boolean read FStretch write SetStretch default False; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; implementation uses ExtUtils,IPCUtils; procedure CheckImgLibCallError(ReturnCode : SmallInt); begin if ReturnCode<=0 then raise TImgLibError.Create('ImageLibCall Error('+IntToStr(ReturnCode)+')!'); end; procedure CheckImgLibCallErrorEx(Const ErrorStr:string;ReturnCode : SmallInt); begin if ReturnCode<=0 then raise TImgLibError.Create('ImageLibCall Error in '+'('+ErrorStr+':'+IntToStr(ReturnCode)+')'); end; procedure InvalidOperation; begin raise EInvalidGraphicOperation.Create('Invalid Operation'); end; procedure RegisterFileExt; begin TPicture.RegisterFileFormat('GIF','GIF File',TImgLibObj); TPicture.RegisterFileFormat('PCX','PCX File',TImgLibObj); TPicture.RegisterFileFormat('TIF','TIF File',TImgLibObj); TPicture.RegisterFileFormat('PNG','PNG File',TImgLibObj); {TPicture.RegisterFileFormat('JPG','ImageLib JPEG File',TCustomImgLibObj); TPicture.RegisterFileFormat('JPEG','ImageLib JPEG File',TCustomImgLibObj); TPicture.RegisterFileFormat('BMP','ImageLib BMP File',TCustomImgLibObj); } end; procedure UnRegisterFileExt; begin TPicture.UnregisterGraphicClass(TImgLibObj); end; function GetImageTypeFromFileExt(const FileName:string): TImageType; var Ext : string; begin Ext := Uppercase(ExtractFileExt(FileName)); if ext='.BMP' then result := imBMP else if ext='.PCX' then result := imPCX else if ext='.PNG' then result := imPNG else if ext='.GIF' then result := imGIF else if (ext='.JPG') or (ext='.JPEG') then result := imJPEG else if (ext='.TIF') or (ext='.TIFF') then result := imTIFF else result := imUnknown; end; threadvar ProgressImgObj : TCustomImgLibObj; function ImgLibProgress(I : Integer) : Integer cdecl; var isContinue : boolean; begin if ProgressImgObj<>nil then try isContinue := true; ProgressImgObj.DoProgress(i,isContinue); if isContinue then result := 1 else result := 0; except result := 0; end else result := 0; end; { TCustomImgLibObj } procedure TCustomImgLibObj.Assign(Source: TPersistent); begin if Source is TCustomImgLibObj then with Source as TCustomImgLibObj do begin self.Fsize := size; self.Fwidth := width; self.Fheight := height; self.FAutoResolution := AutoResolution; self.FAutoImageType := AutoImageType; self.FSaveResolution := SaveResolution; self.FLoadResolution := LoadResolution; self.FDither := Dither; self.FImageType := ImageType; self.FBitsPixel := BitsPixel; self.FPlanes := Planes; self.FNumColors := FNumColors; self.FQuality := Quality; self.Fstripsize := stripsize; self.Fcompression := compression; self.Finterlaced := interlaced; //self.Bitmap.Assign(Bitmap); end else if Source is TBitmap then //Bitmap.Assign(Source) else if source=nil then begin Clear; end else inherited Assign(Source); end; constructor TCustomImgLibObj.Create; begin inherited Create; FSize := 0; FAutoResolution := true; FAutoImageType := true; FDither := true; FImageType := imGIF; FQuality := 75; Fcompression := cmpLZW; Fstripsize := 10; Finterlaced := 1; FShowErrorInt := 0; FLoadResolution := 8; FSaveResolution := 8; end; destructor TCustomImgLibObj.Destroy; begin inherited Destroy; end; procedure TCustomImgLibObj.GetFileInfo(const AFileName: string); begin FillMemory(@FFileTypeStr,sizeof(TFileTypeStr),0); CheckImgLibCallErrorEx(ESGetInfo, ImageLibX.fileinfo( pchar(AFileName), pchar(@FFileTypeStr), FWidth,FHeight, Fbitspixel, Fplanes, Fnumcolors, pchar(@FCompressType), 0) ); FSize := GetFileSize(AFileName); UpdateInfo; end; procedure TCustomImgLibObj.LoadFromFile(const AFileName: string); var hBmp : HBitmap; hPal : HPalette; {$ifdef speed} _LastTick,_CurTick : integer; {$endif} begin hBmp := 0; hPal := 0; //FFileName := AFileName; GetFileInfo(AFileName); if StartLoading then begin //if Bitmap.HandleType=bmDIB then if GetHandleType=bmDIB then begin {$ifdef speed} _LastTick := GetTickCount; outputDebugString(pchar('before load'+IntToStr(_LastTick))); {$endif} InternalLoadDIB(AFileName,hBmp); {$ifdef speed} _curTick:=GetTickCount; outputDebugString(pchar(format('after load:%d,%d',[_curTick,_curTick-_lastTick]))); _lastTick:=_curTick; {$endif} if EndLoading(hBmp,hPal) then //Bitmap.Handle:=hBmp; SetHandles(hBmp,0); {$ifdef speed} _curTick:=GetTickCount; outputDebugString(pchar(format('after set to bitmap:%d,%d',[_curTick,_curTick-_lastTick]))); _lastTick:=_curTick; {$endif} end else begin {$ifdef speed} _LastTick := GetTickCount; outputDebugString(pchar('before load'+IntToStr(_LastTick))); {$endif} InternalLoadDDB(AFileName,hBmp,hPal); {$ifdef speed} _curTick:=GetTickCount; outputDebugString(pchar(format('after load:%d,%d',[_curTick,_curTick-_lastTick]))); _lastTick:=_curTick; {$endif} if EndLoading(hBmp,hPal) then begin {Bitmap.Handle:=hBmp; Bitmap.Palette :=hPal;} SetHandles(hBmp,hPal); end; {$ifdef speed} _curTick:=GetTickCount; outputDebugString(pchar(format('after set to bitmap:%d,%d',[_curTick,_curTick-_lastTick]))); _lastTick:=_curTick; {$endif} end; Changed(self); end; end; procedure TCustomImgLibObj.SaveToFile(const AFileName: string); var im : TImageType; hBmp : HBitmap; hPal : HPalette; begin //FFileName := AFileName; if AutoImageType then begin im := GetImageTypeFromFileExt(AFileName); if im<>imUnknown then ImageType := im; end; GetHandles(hBmp,hPal); //if Bitmap.HandleType=bmDIB then if GetHandleType=bmDIB then //InternalSaveDIB(AFileName,Bitmap.Handle,Bitmap.Palette) InternalSaveDIB(AFileName,hBmp,hPal) else //InternalSaveDDB(AFileName,Bitmap.Handle,Bitmap.Palette); InternalSaveDDB(AFileName,hBmp,hPal); Modified := false; end; function TCustomImgLibObj.GetEmpty: Boolean; var HBmp : HBitmap; HPal : HPALETTE; begin //result := FSize=0; GetHandles(hBmp,Hpal); result := hBmp=0; end; function TCustomImgLibObj.GetInternalHeight: Integer; begin result := FHeight; end; function TCustomImgLibObj.GetInternalWidth: Integer; begin result := FWidth; end; procedure TCustomImgLibObj.SetHeight(Value: Integer); begin InvalidOperation; end; procedure TCustomImgLibObj.SetWidth(Value: Integer); begin InvalidOperation; end; procedure TCustomImgLibObj.UpdateInfo; begin if StrIComp(FFileTypeStr,'BMP')=0 then FImageType := imBMP else if StrIComp(FFileTypeStr,'JPEG')=0 then FImageType := imJPEG else if StrIComp(FFileTypeStr,'TIFF')=0 then FImageType := imTIFF else if StrIComp(FFileTypeStr,'PCX')=0 then FImageType := imPCX else if StrIComp(FFileTypeStr,'PNG')=0 then FImageType := imPNG else if StrIComp(FFileTypeStr,'GIF')=0 then FImageType := imGIF else FImageType := imTIFF; //else InvalidOperation; if AutoResolution then LoadResolution:=Fbitspixel; end; procedure TCustomImgLibObj.InternalLoadDDB(const FileName:string;var hBmp : HBitmap; var hPal:HPalette); var theDither : smallInt; begin if Dither then theDither := 1 else theDither := 0; case FImageType of imJPEG: CheckImgLibCallErrorEx(EsLoad,readJPGfile(pchar(FileName),LoadResolution,1,theDither,hBmp,hPal,Callback,FShowErrorInt)); imGIF: CheckImgLibCallErrorEx(EsLoad,readGIFfile(pchar(FileName),LoadResolution,theDither,hBmp,hPal,Callback,FShowErrorInt,unilzw)); imBMP: CheckImgLibCallErrorEx(EsLoad,readBMPfile(pchar(FileName),LoadResolution,theDither,hBmp,hPal,Callback,FShowErrorInt)); imPCX: CheckImgLibCallErrorEx(EsLoad,readPCXfile(pchar(FileName),LoadResolution,theDither,hBmp,hPal,Callback,FShowErrorInt)); imPNG: CheckImgLibCallErrorEx(EsLoad,readpngfile(pchar(FileName),LoadResolution,theDither,hBmp,hPal,Callback,FShowErrorInt)); imTIFF: CheckImgLibCallErrorEx(EsLoad,readTIFfile(pchar(FileName),LoadResolution,theDither,hBmp,hPal,Callback,FShowErrorInt,unilzw)); end; end; procedure TCustomImgLibObj.InternalLoadDIB(const FileName:string;var hBmp: HBitmap); var theDither : smallInt; begin if Dither then theDither := 1 else theDither := 0; case FImageType of imJPEG: CheckImgLibCallErrorEx(EsLoad,RDJPGfileDIB(pchar(FileName),LoadResolution,1,TheDither,hBmp,0,Callback,FShowErrorInt)); imGIF: CheckImgLibCallErrorEx(EsLoad,RDGIFfileDIB(pchar(FileName),LoadResolution,TheDither,hBmp,0,Callback,FShowErrorInt,unilzw)); imBMP: CheckImgLibCallErrorEx(EsLoad,RDBMPfileDIB(pchar(FileName),LoadResolution,TheDither,hBmp,0,Callback,FShowErrorInt)); imPCX: CheckImgLibCallErrorEx(EsLoad,RDPCXfileDIB(pchar(FileName),LoadResolution,TheDither,hBmp,0,Callback,FShowErrorInt)); imPNG: CheckImgLibCallErrorEx(EsLoad,RDpngfileDIB(pchar(FileName),LoadResolution,TheDither,hBmp,0,Callback,FShowErrorInt)); imTIFF: CheckImgLibCallErrorEx(EsLoad,RDTIFfileDIB(pchar(FileName),LoadResolution,TheDither,hBmp,0,Callback,FShowErrorInt,unilzw)); end; end; procedure TCustomImgLibObj.InternalSaveDDB(const FileName:string;hBitmap, hPal: THandle); begin case FImageType of imJPEG: CheckImgLibCallErrorEx(ESSave,WriteJPGfile(pchar(FileName),Quality,1,SaveResolution,hBitmap,hPal,nil,FShowErrorInt)); imGIF: CheckImgLibCallErrorEx(ESSave,WriteGIFfile(pchar(FileName),SaveResolution,hBitmap,hPal,nil,FShowErrorInt,unilzw)); imBMP: CheckImgLibCallErrorEx(ESSave,WriteBMPfile(pchar(FileName),SaveResolution,hBitmap,hPal,nil,FShowErrorInt)); imPCX: CheckImgLibCallErrorEx(ESSave,WritePCXfile(pchar(FileName),SaveResolution,hBitmap,hPal,nil,FShowErrorInt)); imPNG: CheckImgLibCallErrorEx(ESSave,Writepngfile(pchar(FileName),SaveResolution,interlaced,hBitmap,hPal,nil,FShowErrorInt)); imTIFF: CheckImgLibCallErrorEx(ESSave,WriteTIFfile(pchar(FileName),compression,stripsize,SaveResolution,hBitmap,hPal,nil,FShowErrorInt,unilzw)); end; end; procedure TCustomImgLibObj.InternalSaveDIB(const FileName:string;hBitmap, hPal: THandle); begin case FImageType of imJPEG: CheckImgLibCallErrorEx(ESSave,WrJPGfileDIB(pchar(FileName),Quality,1,SaveResolution,hBitmap,nil,FShowErrorInt)); imGIF: CheckImgLibCallErrorEx(ESSave,WrGIFfileDIB(pchar(FileName),SaveResolution,hBitmap,nil,FShowErrorInt,unilzw)); imBMP: CheckImgLibCallErrorEx(ESSave,WrBMPfileDIB(pchar(FileName),SaveResolution,hBitmap,nil,FShowErrorInt)); imPCX: CheckImgLibCallErrorEx(ESSave,WrPCXfileDIB(pchar(FileName),SaveResolution,hBitmap,nil,FShowErrorInt)); imPNG: CheckImgLibCallErrorEx(ESSave,WrpngfileDIB(pchar(FileName),SaveResolution,interlaced,hBitmap,nil,FShowErrorInt)); imTIFF: CheckImgLibCallErrorEx(ESSave,WrTIFfileDIB(pchar(FileName),compression,stripsize,SaveResolution,hBitmap,nil,FShowErrorInt,unilzw)); end; end; procedure TCustomImgLibObj.LoadFromStream(Stream: TStream); begin Fsize := Stream.Size-Stream.Position; ReadStream(Stream); end; procedure TCustomImgLibObj.SaveToStream(Stream: TStream); {var Memory : TMemoryStream; begin Memory := TMemoryStream.Create; try Memory.Position := 0; Memory.size := Size; WriteBuffer(Memory.Memory); Memory.size := size; Memory.Position := 0; Stream.CopyFrom(Memory,size); finally Memory.free; end; end; } var Memory : TSharedMem; MaxSize : integer; begin MaxSize := GetMaxSaveSize; Memory := TSharedMem.Create('',MaxSize); try WriteBuffer(Memory.Buffer,MaxSize); Stream.WriteBuffer(Memory.Buffer^,size); finally Memory.free; end; Modified := false; end; procedure TCustomImgLibObj.ReadData(Stream: TStream); begin Stream.Read(FSize, SizeOf(FSize)); ReadStream(Stream); end; procedure TCustomImgLibObj.WriteData(Stream: TStream); var p1,p2 : integer; begin //Stream.Write(FImageType,sizeof(FImageType)); p1 := Stream.Position; Stream.WriteBuffer(FSize, SizeOf(FSize)); SaveToStream(Stream); p2 := Stream.Position; Stream.Position := p1; Stream.WriteBuffer(FSize, SizeOf(FSize)); Stream.Position := p2; //assert(FSize+sizeof(FSize)=p2-p1); if (FSize+sizeof(FSize))<>(p2-p1) then raise exception.create( format('size=%d,p1=%d,p2=%d',[size,p1,p2]) ); end; procedure TCustomImgLibObj.ReadStream(Stream: TStream); var Memory : TMemoryStream; begin Memory := TMemoryStream.Create; try Memory.position := 0; Memory.CopyFrom(Stream,size); FillMemory(@FFileTypeStr,sizeof(TFileTypeStr),0); CheckImgLibCallErrorEx(ESGetInfo, ImageLibX.streaminfo( Memory.Memory, size, pchar(@FFileTypeStr), FWidth,FHeight, Fbitspixel, Fplanes, Fnumcolors, pchar(@CompressType), 0) ); UpdateInfo; ReadBuffer(Memory.Memory); finally Memory.free; end; end; procedure TCustomImgLibObj.ReadBuffer(Buffer: pointer); var hBmp: HBitmap; hPal : hPalette; begin hBmp := 0; hPal := 0; //if Bitmap.HandleType=bmDIB then if GetHandleType=bmDIB then begin InternalLoadBufferDIB(Buffer,hBmp); //Bitmap.Handle:=hBmp; SetHandles(hBmp,0); end else begin InternalLoadBufferDDB(Buffer,hBmp,hPal); {Bitmap.Handle:=hBmp; Bitmap.Palette :=hPal;} SetHandles(hBmp,hPal); end; Changed(self); end; procedure TCustomImgLibObj.InternalLoadBufferDDB(Buffer: pointer; var hBmp : HBitmap;var hPal : HPalette); var theDither : smallInt; begin if Dither then theDither := 1 else theDither := 0; case FImageType of imJPEG: CheckImgLibCallErrorEx(EsLoad,readJPGStream(pchar(Buffer),size,LoadResolution,1,theDither,hBmp,hPal,nil,FShowErrorInt)); imGIF: CheckImgLibCallErrorEx(EsLoad,readGIFStream(pchar(Buffer),size,LoadResolution,theDither,hBmp,hPal,nil,FShowErrorInt,unilzw)); imBMP: CheckImgLibCallErrorEx(EsLoad,readBMPStream(pchar(Buffer),size,LoadResolution,theDither,hBmp,hPal,nil,FShowErrorInt)); imPCX: CheckImgLibCallErrorEx(EsLoad,readPCXStream(pchar(Buffer),size,LoadResolution,theDither,hBmp,hPal,nil,FShowErrorInt)); imPNG: CheckImgLibCallErrorEx(EsLoad,readpngStream(pchar(Buffer),size,LoadResolution,theDither,hBmp,hPal,nil,FShowErrorInt)); imTIFF: CheckImgLibCallErrorEx(EsLoad,readTIFStream(pchar(Buffer),size,LoadResolution,theDither,hBmp,hPal,nil,FShowErrorInt,unilzw)); end; end; procedure TCustomImgLibObj.InternalLoadBufferDIB(Buffer: pointer; var hBmp : HBitmap); var theDither : smallInt; begin if Dither then theDither := 1 else theDither := 0; case FImageType of imJPEG: CheckImgLibCallErrorEx(EsLoad,RDJPGStreamDIB(pchar(Buffer),size,LoadResolution,1,theDither,hBmp,nil,FShowErrorInt)); imGIF: CheckImgLibCallErrorEx(EsLoad,RDGIFStreamDIB(pchar(Buffer),size,LoadResolution,theDither,hBmp,nil,FShowErrorInt,unilzw)); imBMP: CheckImgLibCallErrorEx(EsLoad,RDBMPStreamDIB(pchar(Buffer),size,LoadResolution,theDither,hBmp,nil,FShowErrorInt)); imPCX: CheckImgLibCallErrorEx(EsLoad,RDPCXStreamDIB(pchar(Buffer),size,LoadResolution,theDither,hBmp,nil,FShowErrorInt)); imPNG: CheckImgLibCallErrorEx(EsLoad,RDpngStreamDIB(pchar(Buffer),size,LoadResolution,theDither,hBmp,nil,FShowErrorInt)); imTIFF: CheckImgLibCallErrorEx(EsLoad,RDTIFStreamDIB(pchar(Buffer),size,LoadResolution,theDither,hBmp,nil,FShowErrorInt,unilzw)); end; end; procedure TCustomImgLibObj.InternalSaveBufferDDB(Buffer: pointer; MaxSize:integer;hBitmap, hPal: THandle); begin case FImageType of imJPEG: CheckImgLibCallErrorEx(ESSave,WritejpgStream(pchar(Buffer),MaxSize,Quality,1,SaveResolution,hBitmap,hPal,nil,FShowErrorInt)); imGIF: CheckImgLibCallErrorEx(ESSave,WriteGIFStream(pchar(Buffer),MaxSize,SaveResolution,hBitmap,hPal,nil,FShowErrorInt,unilzw)); imBMP: CheckImgLibCallErrorEx(ESSave,WriteBMPStream(pchar(Buffer),MaxSize,SaveResolution,hBitmap,hPal,nil,FShowErrorInt)); imPCX: CheckImgLibCallErrorEx(ESSave,WritePCXStream(pchar(Buffer),MaxSize,SaveResolution,hBitmap,hPal,nil,FShowErrorInt)); imPNG: CheckImgLibCallErrorEx(ESSave,WritepngStream(pchar(Buffer),MaxSize,SaveResolution,interlaced,hBitmap,hPal,nil,FShowErrorInt)); imTIFF: CheckImgLibCallErrorEx(ESSave,WriteTIFStream(pchar(Buffer),MaxSize,compression,stripsize,SaveResolution,hBitmap,hPal,nil,FShowErrorInt,unilzw)); else exit; end; FSize := MaxSize; end; procedure TCustomImgLibObj.InternalSaveBufferDIB(Buffer: pointer; MaxSize:integer;hBitmap, hPal: THandle); begin case FImageType of imJPEG: CheckImgLibCallErrorEx(ESSave,WrjpgStreamDIB(pchar(Buffer),MaxSize,Quality,1,SaveResolution,hBitmap,nil,FShowErrorInt)); imGIF: CheckImgLibCallErrorEx(ESSave,WrGIFStreamDIB(pchar(Buffer),MaxSize,SaveResolution,hBitmap,nil,FShowErrorInt,unilzw)); imBMP: CheckImgLibCallErrorEx(ESSave,WrBMPStreamDIB(pchar(Buffer),MaxSize,SaveResolution,hBitmap,nil,FShowErrorInt)); imPCX: CheckImgLibCallErrorEx(ESSave,WrPCXStreamDIB(pchar(Buffer),MaxSize,SaveResolution,hBitmap,nil,FShowErrorInt)); imPNG: CheckImgLibCallErrorEx(ESSave,WrpngStreamDIB(pchar(Buffer),MaxSize,SaveResolution,interlaced,hBitmap,nil,FShowErrorInt)); imTIFF: CheckImgLibCallErrorEx(ESSave,WrTIFStreamDIB(pchar(Buffer),MaxSize,compression,stripsize,SaveResolution,hBitmap,nil,FShowErrorInt,unilzw)); else exit; end; FSize := MaxSize; end; procedure TCustomImgLibObj.WriteBuffer(Buffer: pointer;MaxSize:integer); var hBmp: HBitmap; hPal : hPalette; begin {hBmp := Bitmap.Handle; hPal := Bitmap.Palette;} GetHandles(hBmp,hPal); //if Bitmap.HandleType=bmDIB then if GetHandleType=bmDIB then InternalSaveBufferDIB(Buffer,MaxSize,hBmp,hPal) else InternalSaveBufferDDB(Buffer,MaxSize,hBmp,hPal); end; const MaxHeaderSize = 1024; PalSize = 256*4; function TCustomImgLibObj.GetMaxSaveSize: integer; var W,H : integer; BitsPixels : integer; LineSize : integer; begin {W := Bitmap.width; H := Bitmap.Height;} W := width; H := Height; BitsPixels := SaveResolution; if BitsPixels=0 then BitsPixels:=4; LineSize := (BitsPixels * w + 8) div 8 + 4; result := MaxHeaderSize + PalSize + LineSize * H; end; procedure TCustomImgLibObj.Clear; begin FSize := 0; Fwidth := 0; FHeight := 0; {Bitmap.Handle := 0; Bitmap.Palette := 0;} SetHandles(0,0); Changed(self); end; procedure TCustomImgLibObj.SetShowError(const Value: boolean); begin if value then FShowErrorInt := 1 else FShowErrorInt := 0; end; function TCustomImgLibObj.GetShowError: boolean; begin result := FShowErrorInt = 1; end; procedure TCustomImgLibObj.Flip; var hBMP : HBitmap; hPAL : HPalette; begin {hBMP:=Bitmap.Handle; HPAL:=Bitmap.Palette;} GetHandles(hBMP,HPAL); //if Bitmap.HandleType=bmDIB then if GetHandleType=bmDIB then begin CheckImgLibCallErrorEx(ESOther,FlipDIB(LoadResolution,hBMP,0)); //Bitmap.Handle :=hBMP; SetHandles(hBMP,HPAL); end else begin CheckImgLibCallErrorEx(ESOther,FlipDDB(LoadResolution,hBMP,HPAL,0)); {Bitmap.Palette :=HPAL; Bitmap.Handle :=hBMP;} SetHandles(hBMP,HPAL); end; Changed(self); end; procedure TCustomImgLibObj.Rotate180; var hBMP : HBitmap; hPAL : HPalette; begin {hBMP:=Bitmap.Handle; HPAL:=Bitmap.Palette;} GetHandles(hBMP,HPAL); //if Bitmap.HandleType=bmDIB then if GetHandleType=bmDIB then begin CheckImgLibCallErrorEx(ESOther,ROTATEDIB180(LoadResolution,hBMP,0)); //Bitmap.Handle :=hBMP; SetHandles(hBMP,HPAL); end else begin CheckImgLibCallErrorEx(ESOther,ROTATEDDB180(LoadResolution,hBMP,HPAL,0)); {Bitmap.Palette :=HPAL; Bitmap.Handle :=hBMP;} SetHandles(hBMP,HPAL); end; Changed(self); end; procedure TCustomImgLibObj.Rotate90; var hBMP : HBitmap; hPAL : HPalette; begin {hBMP:=Bitmap.Handle; HPAL:=Bitmap.Palette;} GetHandles(hBMP,HPAL); //if Bitmap.HandleType=bmDIB then if GetHandleType=bmDIB then begin CheckImgLibCallErrorEx(ESOther,ROTATEDIB90(LoadResolution,hBMP,0)); //Bitmap.Handle :=hBMP; SetHandles(hBMP,HPAL); end else begin CheckImgLibCallErrorEx(ESOther,ROTATEDDB90(LoadResolution,hBMP,HPAL,0)); {Bitmap.Palette :=HPAL; Bitmap.Handle :=hBMP;} SetHandles(hBMP,HPAL); end; Changed(self); end; procedure TCustomImgLibObj.DoProgress(Percent: integer; var isContinue: boolean); begin LastPercent := Percent; Progress(self,psRunning,Percent,false,rect(0,0,0,0),''); isContinue := not IsCancel; end; function TCustomImgLibObj.EndLoading(hBmp: HBitmap; hPal: HPalette): boolean; begin if Progressed then begin Progress(self,psEnding,LastPercent,false,rect(0,0,0,0),''); ProgressImgObj := nil; result := not isCancel; if isCancel then begin DeleteObject(hPal); DeleteObject(hBmp); end; Callback := nil; end else result:=true; end; function TCustomImgLibObj.StartLoading:boolean; begin IsCancel := false; if Progressed then begin LastPercent := 0; Callback := ImgLibProgress; ProgressImgObj := self; Progress(self,psStarting,0,false,rect(0,0,0,0),''); end else Callback := nil; result := not IsCancel; end; { TCustomILImage } function TCustomILImage.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; begin Result := True; if not (csDesigning in ComponentState) or (ImageObj.Width > 0) and (ImageObj.Height > 0) then begin if Align in [alNone, alLeft, alRight] then NewWidth := ImageObj.Width; if Align in [alNone, alTop, alBottom] then NewHeight := ImageObj.Height; end; end; procedure TCustomILImage.Changed(sender: TObject); begin if autoSize and not FImageObj.empty then SetBounds(Left, Top, FImageObj.Width, FImageObj.Height); Invalidate; end; constructor TCustomILImage.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable,csOpaque]; width := 100; height := 100; FStretch := false; FScale := true; FCenter := true; end; destructor TCustomILImage.Destroy; begin FImageObj.OnChange := nil; FImageObj.free; inherited destroy; end; procedure TCustomILImage.Paint; var x,y,DestW,DestH : integer; begin if not transparent then begin Canvas.brush.style := bsSolid; Canvas.brush.Color := color; Canvas.FillRect(Rect(0,0,width,height)); end; if ImageObj.Empty or (ImageObj.Width<=0) or (ImageObj.Height<=0) then exit; (* { Stretch Scale F F 显示原始大小 F T 如果图象大于显示区域,缩小显示大小,保持长宽比 T F 放缩图象,不保持长宽比 T T 放缩图象,保持长宽比 } if not FStretch then if not scale then //显示原始大小 Canvas.Draw(0,0,FImageObj) else begin //如果图象大于显示区域,缩小显示大小,保持长宽比 {if (FImageObj.width>width) or (FImageObj.Height>.Height) then begin //缩小显示大小,保持长宽比 AdjustWH(DestW,DestH,FImageObj.width,FImageObj.Height,width,height,true); FImageObj.Draw(Canvas,Rect(0,0,DestW,DestH)); end else //显示原始大小 Canvas.Draw(0,0,FImageObj);} AdjustWH(DestW,DestH,FImageObj.width,FImageObj.Height,width,height,false); FImageObj.Draw(Canvas,Rect(0,0,DestW,DestH)); end else if not scale then //放缩图象,不保持长宽比 FImageObj.Draw(Canvas,Rect(0,0,width,height)) else begin //放缩图象,保持长宽比 AdjustWH(DestW,DestH,FImageObj.width,FImageObj.Height,width,height,true); FImageObj.Draw(Canvas,Rect(0,0,DestW,DestH)); end; *) x:=0; y:=0; DestW:=ImageObj.Width; DestH:=ImageObj.Height; if not FStretch then begin if scale then //如果图象大于显示区域,缩小显示大小,保持长宽比 AdjustWH(DestW,DestH,FImageObj.width,FImageObj.Height,width,height,false); end else if not scale then begin //放缩图象,不保持长宽比 DestW:=width; DestH:=height; end else //放缩图象,保持长宽比 AdjustWH(DestW,DestH,FImageObj.width,FImageObj.Height,width,height,true); if Center then begin if DestW<width then x := (width-DestW) div 2; if DestH<Height then y := (Height-DestH) div 2; end; FImageObj.Draw(Canvas,Rect(x,y,x+DestW,y+DestH)); end; procedure TCustomILImage.SetImageObj(const Value: TCustomImgLibObj); begin if FImageObj <> Value then begin FImageObj.Assign(Value); end; end; procedure TCustomILImage.SetScale(const Value: boolean); begin if FScale <> Value then begin FScale := Value; invalidate; end; end; procedure TCustomILImage.SetStretch(const Value: Boolean); begin if FStretch <> Value then begin FStretch := Value; invalidate; end; end; function TCustomILImage.GetTransparent: Boolean; begin result := ImageObj.Transparent; end; procedure TCustomILImage.SetTransparent(const Value: Boolean); begin ImageObj.Transparent := Value; if ImageObj.Transparent then ControlStyle := ControlStyle - [csOpaque] else ControlStyle := ControlStyle + [csOpaque]; end; procedure TCustomILImage.SetCenter(const Value: boolean); begin if FCenter <> Value then begin FCenter := Value; invalidate; end; end; function TCustomILImage.GetOnProgress: TProgressEvent; begin result := ImageObj.OnProgress; end; procedure TCustomILImage.SetOnProgress(const Value: TProgressEvent); begin ImageObj.OnProgress := value; end; { TImgLibObj } constructor TImgLibObj.Create; begin inherited Create; FBitmap := TBitmap.Create; FBitmap.HandleType:=bmDDB; FBitmap.OnChange := Changed; TransparentMode := tmAuto; end; destructor TImgLibObj.Destroy; begin FBitmap.free; inherited Destroy; end; function TImgLibObj.GetHeight: Integer; begin result := Bitmap.Height; end; function TImgLibObj.GetWidth: Integer; begin result := Bitmap.Width; end; procedure TImgLibObj.GetHandles(var hBmp: HBitmap; var hPal: HPalette); begin hBmp:=Bitmap.Handle; hPal:=Bitmap.Palette; end; procedure TImgLibObj.SetHandles(hBmp: HBitmap; hPal: HPalette); begin Bitmap.Handle:=hBmp; Bitmap.Palette:=hPal; end; type TBitmapAccess = class(TBitmap); procedure TImgLibObj.Draw(ACanvas: TCanvas; const Rect: TRect); begin TBitmapAccess(FBitmap).Draw(ACanvas,Rect); end; function TImgLibObj.GetHandleType: TBitmapHandleType; begin result := Bitmap.HandleType; end; function TImgLibObj.GetPalette: HPALETTE; begin result := Bitmap.Palette; end; procedure TImgLibObj.SetPalette(Value: HPALETTE); begin Bitmap.Palette := value; end; procedure TImgLibObj.LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); begin Bitmap.LoadFromClipboardFormat(AFormat,AData,APalette); end; procedure TImgLibObj.SaveToClipboardFormat(var AFormat: Word; var AData: THandle; var APalette: HPALETTE); begin Bitmap.SaveToClipboardFormat(AFormat,AData,APalette); end; function TImgLibObj.GetTransparent: boolean; begin result := FBitmap.Transparent; end; procedure TImgLibObj.SetTransparent(Value: Boolean); begin FBitmap.Transparent := value; end; function TImgLibObj.GetTransparentColor: TColor; begin result := Bitmap.TransparentColor; end; function TImgLibObj.GetTransparentMode: TTransparentMode; begin result := Bitmap.TransparentMode; end; procedure TImgLibObj.SetTransparentColor(const Value: TColor); begin Bitmap.TransparentColor := value; end; procedure TImgLibObj.SetTransparentMode(const Value: TTransparentMode); begin Bitmap.TransparentMode := value; end; procedure TImgLibObj.Assign(Source: TPersistent); begin if Source is TImgLibObj then begin inherited Assign(Source); Bitmap.Assign(TImgLibObj(Source).Bitmap); end else if Source is TBitmap then Bitmap.Assign(TBitmap(Source)) else inherited Assign(Source); end; { TILImage } constructor TILImage.Create(AOwner: TComponent); begin inherited Create(AOwner); FImageObj := TImgLibObj.Create; FImageObj.OnChange := Changed; FImageObj.Transparent := false; end; function TILImage.GetImageObj: TImgLibObj; begin result := TImgLibObj(inherited ImageObj); end; procedure TILImage.SetImageObj(const Value: TImgLibObj); begin inherited ImageObj:=value; end; { TImgLibViewObj } constructor TImgLibViewObj.Create; begin inherited Create; FBitmap := TSimpleBitmap.Create; FBitmap.OnChange := Changed; end; destructor TImgLibViewObj.Destroy; begin FBitmap.free; inherited Destroy; end; function TImgLibViewObj.GetHeight: Integer; begin result := Bitmap.Height; end; function TImgLibViewObj.GetWidth: Integer; begin result := Bitmap.Width; end; procedure TImgLibViewObj.GetHandles(var hBmp: HBitmap; var hPal: HPalette); begin hBmp:=Bitmap.Handle; hPal:=Bitmap.Palette; end; procedure TImgLibViewObj.SetHandles(hBmp: HBitmap; hPal: HPalette); begin Bitmap.Handle:=hBmp; Bitmap.Palette:=hPal; Bitmap.OwnHandle:=true; end; procedure TImgLibViewObj.Draw(ACanvas: TCanvas; const Rect: TRect); begin FBitmap.Draw(ACanvas,Rect); end; function TImgLibViewObj.GetHandleType: TBitmapHandleType; begin result := bmDDB; end; function TImgLibViewObj.GetPalette: HPALETTE; begin result := Bitmap.Palette; end; procedure TImgLibViewObj.SetPalette(Value: HPALETTE); begin Bitmap.Palette := value; end; procedure TImgLibViewObj.LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); begin Bitmap.LoadFromClipboardFormat(AFormat,AData,APalette); end; procedure TImgLibViewObj.SaveToClipboardFormat(var AFormat: Word; var AData: THandle; var APalette: HPALETTE); begin Bitmap.SaveToClipboardFormat(AFormat,AData,APalette); end; procedure TImgLibViewObj.Assign(Source: TPersistent); begin if Source is TImgLibViewObj then begin inherited Assign(Source); Bitmap.Assign(TImgLibViewObj(Source).Bitmap); end else inherited Assign(Source); end; { TILImageView } constructor TILImageView.Create(AOwner: TComponent); begin inherited Create(AOwner); FImageObj := TImgLibViewObj.Create; FImageObj.OnChange := Changed; end; function TILImageView.GetImageObj: TImgLibViewObj; begin result := TImgLibViewObj(inherited ImageObj); end; procedure TILImageView.SetImageObj(const Value: TImgLibViewObj); begin inherited ImageObj:=Value; end; initialization RegisterFileExt; finalization UnRegisterFileExt; end.
unit IdTestCoderMIME; interface uses IdCoder, IdCoderMIME, IdSys, IdGlobal, IdObjs, IdTest; type TIdTestCoderMIME = class(TIdTest) published procedure TestDecodeLineByLine; procedure TestDecodeMIME; end; implementation const cEnc1: string = 'VGhpcyBpcyBhIHNpbXBsZSB0ZXN0IGZvciBNSU1FIGVuY29kaW5nIHNpbXBsZSBzdHJpbmdzLg=='; cDec1 = 'This is a simple test for MIME encoding simple strings.'; procedure TIdTestCoderMIME.TestDecodeMIME; var s:string; begin s:=DecodeString(TIdDecoderMIME,cEnc1); Assert(s=cDec1); end; procedure TIdTestCoderMIME.TestDecodeLineByLine; var s: string; d: TIdDecoderMIMELineByLine; TempStream: TIdMemoryStream; begin //using class method s:=DecodeString(TIdDecoderMIMELineByLine,cEnc1); Assert(s=cDec1,s); //using 'manually' d := TIdDecoderMIMELineByLine.Create; try TempStream := TIdMemoryStream.Create; try d.DecodeBegin(TempStream); d.Decode(cEnc1); TempStream.Position := 0; s := ReadStringFromStream(TempStream); Assert(s = cDec1, Sys.Format('Is "%s", should be "%s"', [s, cDec1])); finally d.DecodeEnd; Sys.FreeAndNil(TempStream); end; finally Sys.FreeAndNil(d); end; end; initialization TIdTest.RegisterTest(TIdTestCoderMIME); end.
unit ATViewerMsg; interface uses Windows; function MsgBox(const Msg, Title: WideString; Flags: Integer; hWnd: THandle = 0): Integer; procedure MsgInfo(const Msg: WideString; hWnd: THandle = 0); procedure MsgError(const Msg: WideString; hWnd: THandle = 0); procedure MsgWarning(const Msg: WideString; hWnd: THandle = 0); var ATViewerMessagesEnabled: Boolean = True; var MsgViewerCaption: AnsiString = 'Viewer'; MsgViewerShowCfm: AnsiString = 'Format not known'#13'Click here to show binary dump'; MsgViewerErrCannotFindFile: AnsiString = 'File not found: "%s"'; MsgViewerErrCannotFindFolder: AnsiString = 'Folder not found: "%s"'; MsgViewerErrCannotOpenFile: AnsiString = 'Cannot open file: "%s"'; MsgViewerErrCannotLoadFile: AnsiString = 'Cannot load file: "%s"'; MsgViewerErrCannotReadFile: AnsiString = 'Cannot read file: "%s"'; MsgViewerErrCannotReadStream: AnsiString = 'Cannot read stream'; MsgViewerErrCannotReadPos: AnsiString = 'Read error at offset %s'; MsgViewerErrImage: AnsiString = 'Unknown image format'; MsgViewerErrMedia: AnsiString = 'Unknown multimedia format'; MsgViewerErrInitControl: AnsiString = 'Cannot initialize %s'; MsgViewerErrCannotCopyData: AnsiString = 'Cannot copy data to Clipboard'; MsgViewerWlxException: AnsiString = 'Exception in plugin "%s" in function "%s"'; MsgViewerWlxParentNotSpecified: AnsiString = 'Cannot load plugins: parent form not specified'; MsgViewerAniTitle: AnsiString = 'Title: '; MsgViewerAniCreator: AnsiString = 'Creator: '; MsgViewerPageHint: AnsiString = 'Previous/Next page'#13'Current page: %d of %d'; implementation uses SysUtils, Forms; function MsgBox(const Msg, Title: WideString; Flags: Integer; hWnd: THandle = 0): Integer; begin if ATViewerMessagesEnabled then //MessageBoxW supported under Win9x Result := MessageBoxW(hWnd, PWideChar(Msg), PWideChar(Title), Flags or MB_SETFOREGROUND or MB_TASKMODAL) else Result := IDCANCEL; end; procedure MsgInfo(const Msg: WideString; hWnd: THandle = 0); begin MsgBox(Msg, MsgViewerCaption, MB_OK or MB_ICONINFORMATION, hWnd); end; procedure MsgError(const Msg: WideString; hWnd: THandle = 0); begin MsgBox(Msg, MsgViewerCaption, MB_OK or MB_ICONERROR, hWnd); end; procedure MsgWarning(const Msg: WideString; hWnd: THandle = 0); begin MsgBox(Msg, MsgViewerCaption, MB_OK or MB_ICONEXCLAMATION, hWnd); end; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Client.CustomResource; {$I ..\Core\WiRL.inc} interface uses System.SysUtils, System.Classes, WiRL.Client.Application, WiRL.http.Client; type TWiRLClientProc = TProc; TWiRLClientResponseProc = TProc<TStream>; TWiRLClientExceptionProc = TProc<Exception>; {$IFDEF HAS_NEW_PIDS} [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator32 or pidiOSDevice32 or pidAndroid32Arm)] {$ELSE} [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)] {$ENDIF} TWiRLClientCustomResource = class(TComponent) private FResource: string; FApplication: TWiRLClientApplication; FSpecificClient: TWiRLClient; FPathParamsValues: TStrings; FQueryParams: TStrings; FSpecificAccept: string; FSpecificContentType: string; procedure SetPathParamsValues(const Value: TStrings); procedure SetQueryParams(const Value: TStrings); protected function GetClient: TWiRLClient; virtual; function GetPath: string; virtual; function GetURL: string; virtual; function GetApplication: TWiRLClientApplication; virtual; function GetAccept: string; function GetContentType: string; procedure BeforeGET; virtual; procedure AfterGET; virtual; procedure BeforePOST(AContent: TMemoryStream); virtual; procedure AfterPOST; virtual; procedure BeforePUT(AContent: TMemoryStream); virtual; procedure AfterPUT; virtual; procedure BeforePATCH(AContent: TMemoryStream); virtual; procedure AfterPATCH; virtual; procedure BeforeHEAD; virtual; procedure AfterHEAD; virtual; procedure BeforeDELETE; virtual; procedure AfterDELETE; virtual; procedure BeforeOPTIONS; virtual; procedure AfterOPTIONS; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // http verbs procedure GET(const ABeforeExecute: TWiRLClientProc = nil; const AAfterExecute: TWiRLClientResponseProc = nil; const AOnException: TWiRLClientExceptionProc = nil); overload; function GETAsString(AEncoding: TEncoding = nil; const ABeforeExecute: TWiRLClientProc = nil; const AOnException: TWiRLClientExceptionProc = nil): string; overload; procedure GETAsync(const ACompletionHandler: TWiRLClientProc = nil; const AOnException: TWiRLClientExceptionProc = nil; ASynchronize: Boolean = True); procedure POST(const ABeforeExecute: TProc<TMemoryStream> = nil; const AAfterExecute: TWiRLClientResponseProc = nil; const AOnException: TWiRLClientExceptionProc = nil); procedure POSTAsync(const ACompletionHandler: TWiRLClientProc = nil; const AOnException: TWiRLClientExceptionProc = nil; ASynchronize: Boolean = True); procedure PUT(const ABeforeExecute: TProc<TMemoryStream> = nil; const AAfterExecute: TWiRLClientResponseProc = nil; const AOnException: TWiRLClientExceptionProc = nil); procedure DELETE(const ABeforeExecute: TWiRLClientProc = nil; const AAfterExecute: TWiRLClientProc = nil; const AOnException: TWiRLClientExceptionProc = nil); procedure PATCH(const ABeforeExecute: TProc<TMemoryStream> = nil; const AAfterExecute: TWiRLClientResponseProc = nil; const AOnException: TWiRLClientExceptionProc = nil); procedure HEAD(const ABeforeExecute: TWiRLClientProc = nil; const AAfterExecute: TWiRLClientProc = nil; const AOnException: TWiRLClientExceptionProc = nil); procedure OPTIONS(const ABeforeExecute: TWiRLClientProc = nil; const AAfterExecute: TWiRLClientResponseProc = nil; const AOnException: TWiRLClientExceptionProc = nil); public property Accept: string read GetAccept; property ContentType: string read GetContentType; property Application: TWiRLClientApplication read GetApplication write FApplication; property Client: TWiRLClient read GetClient; property SpecificAccept: string read FSpecificAccept write FSpecificAccept; property SpecificContentType: string read FSpecificContentType write FSpecificContentType; property SpecificClient: TWiRLClient read FSpecificClient write FSpecificClient; property Resource: string read FResource write FResource; property Path: string read GetPath; property PathParamsValues: TStrings read FPathParamsValues write SetPathParamsValues; property QueryParams: TStrings read FQueryParams write SetQueryParams; property URL: string read GetURL; end; implementation uses WiRL.Client.Utils, WiRL.http.URL, WiRL.Core.Utils; { TWiRLClientCustomResource } procedure TWiRLClientCustomResource.AfterDELETE; begin end; procedure TWiRLClientCustomResource.AfterGET; begin end; procedure TWiRLClientCustomResource.AfterHEAD; begin end; procedure TWiRLClientCustomResource.AfterOPTIONS; begin end; procedure TWiRLClientCustomResource.AfterPATCH; begin end; procedure TWiRLClientCustomResource.AfterPOST; begin end; procedure TWiRLClientCustomResource.AfterPUT; begin end; procedure TWiRLClientCustomResource.BeforeDELETE; begin end; procedure TWiRLClientCustomResource.BeforeGET; begin end; procedure TWiRLClientCustomResource.BeforeHEAD; begin end; procedure TWiRLClientCustomResource.BeforeOPTIONS; begin end; procedure TWiRLClientCustomResource.BeforePATCH(AContent: TMemoryStream); begin end; procedure TWiRLClientCustomResource.BeforePOST(AContent: TMemoryStream); begin end; procedure TWiRLClientCustomResource.BeforePUT(AContent: TMemoryStream); begin end; constructor TWiRLClientCustomResource.Create(AOwner: TComponent); begin inherited; FResource := 'main'; if TWiRLComponentHelper.IsDesigning(Self) then FApplication := TWiRLComponentHelper.FindDefault<TWiRLClientApplication>(Self); FPathParamsValues := TStringList.Create; FQueryParams := TStringList.Create; end; function TWiRLClientCustomResource.GetClient: TWiRLClient; begin Result := nil; if Assigned(FSpecificClient) then Result := FSpecificClient else begin if Assigned(FApplication) then Result := FApplication.Client; end; end; function TWiRLClientCustomResource.GetContentType: string; begin Result := FSpecificContentType; if (Result = '') and Assigned(Application) then Result := Application.DefaultMediaType; end; function TWiRLClientCustomResource.GetPath: string; var LEngine: string; LApplication: string; begin LEngine := ''; if Assigned(Client) then LEngine := Client.WiRLEngineURL; LApplication := ''; if Assigned(Application) then LApplication := Application.AppName; Result := TWiRLURL.CombinePath([LEngine, LApplication, Resource]); end; function TWiRLClientCustomResource.GetURL: string; begin Result := TWiRLURL.CombinePath([ Path, TWiRLURL.CombinePath(TWiRLURL.URLEncode(FPathParamsValues.ToStringArray)) ]); if FQueryParams.Count > 0 then Result := Result + '?' + SmartConcat(TWiRLURL.URLEncode(FQueryParams.ToStringArray), '&'); end; procedure TWiRLClientCustomResource.HEAD(const ABeforeExecute, AAfterExecute: TWiRLClientProc; const AOnException: TWiRLClientExceptionProc); begin try BeforeHEAD; if Assigned(ABeforeExecute) then ABeforeExecute(); Client.Request.Accept := Accept; Client.Request.ContentType := ContentType; Client.Head(URL); AfterHEAD(); if Assigned(AAfterExecute) then AAfterExecute(); except on E: Exception do begin if Assigned(AOnException) then AOnException(E) else raise; end; end; end; procedure TWiRLClientCustomResource.OPTIONS(const ABeforeExecute: TWiRLClientProc = nil; const AAfterExecute: TWiRLClientResponseProc = nil; const AOnException: TWiRLClientExceptionProc = nil); var LResponseStream: TMemoryStream; begin LResponseStream := TMemoryStream.Create; try try BeforeOPTIONS(); if Assigned(ABeforeExecute) then ABeforeExecute(); Client.Request.Accept := Accept; Client.Request.ContentType := ContentType; Client.Options(URL, LResponseStream); AfterOPTIONS(); if Assigned(AAfterExecute) then AAfterExecute(LResponseStream); except on E: Exception do begin if Assigned(AOnException) then AOnException(E) else raise; end; end; finally LResponseStream.Free; end; end; procedure TWiRLClientCustomResource.DELETE(const ABeforeExecute, AAfterExecute: TWiRLClientProc; const AOnException: TWiRLClientExceptionProc); var LResponseStream: TMemoryStream; begin LResponseStream := TMemoryStream.Create; try try BeforeDELETE(); if Assigned(ABeforeExecute) then ABeforeExecute(); Client.Request.Accept := Accept; Client.Request.ContentType := ContentType; Client.Delete(URL, LResponseStream); AfterDELETE(); if Assigned(AAfterExecute) then AAfterExecute(); except on E: Exception do begin if Assigned(AOnException) then AOnException(E) else raise; end; end; finally LResponseStream.Free; end; end; destructor TWiRLClientCustomResource.Destroy; begin FPathParamsValues.Free; FQueryParams.Free; inherited; end; procedure TWiRLClientCustomResource.GET(const ABeforeExecute: TWiRLCLientProc; const AAfterExecute: TWiRLClientResponseProc; const AOnException: TWiRLClientExceptionProc); var LResponseStream: TMemoryStream; begin LResponseStream := TMemoryStream.Create; try try BeforeGET(); if Assigned(ABeforeExecute) then ABeforeExecute(); Client.Request.Accept := Accept; Client.Request.ContentType := ContentType; Client.Get(URL, LResponseStream); AfterGET(); if Assigned(AAfterExecute) then AAfterExecute(LResponseStream); except on E: Exception do begin if Assigned(AOnException) then AOnException(E) else raise; end; end; finally LResponseStream.Free; end; end; function TWiRLClientCustomResource.GETAsString(AEncoding: TEncoding; const ABeforeExecute: TWiRLClientProc; const AOnException: TWiRLClientExceptionProc): string; var LResult: string; LEncoding: TEncoding; begin LResult := ''; LEncoding := AEncoding; if not Assigned(LEncoding) then LEncoding := TEncoding.Default; GET(ABeforeExecute, procedure (AResponse: TStream) var LStreamReader: TStreamReader; begin AResponse.Position := 0; LStreamReader := TStreamReader.Create(AResponse, LEncoding); try LResult := LStreamReader.ReadToEnd; finally LStreamReader.Free; end; end, AOnException ); Result := LResult; end; function TWiRLClientCustomResource.GetAccept: string; begin Result := FSpecificAccept; if (Result = '') and Assigned(Application) then Result := Application.DefaultMediaType; end; function TWiRLClientCustomResource.GetApplication: TWiRLClientApplication; begin Result := FApplication; end; procedure TWiRLClientCustomResource.GETAsync( const ACompletionHandler: TWiRLClientProc; const AOnException: TWiRLClientExceptionProc; ASynchronize: Boolean); begin Client.ExecuteAsync( procedure begin GET(nil, nil, AOnException); if Assigned(ACompletionHandler) then begin if ASynchronize then TThread.Queue(nil, TThreadProcedure(ACompletionHandler)) else ACompletionHandler(); end; end ); end; procedure TWiRLClientCustomResource.PATCH(const ABeforeExecute: TProc<TMemoryStream> = nil; const AAfterExecute: TWiRLClientResponseProc = nil; const AOnException: TWiRLClientExceptionProc = nil); var LResponseStream: TMemoryStream; LContent: TMemoryStream; begin LContent := TMemoryStream.Create; try LResponseStream := TMemoryStream.Create; try try BeforePATCH(LContent); if Assigned(ABeforeExecute) then ABeforeExecute(LContent); Client.Request.Accept := Accept; Client.Request.ContentType := ContentType; Client.Patch(URL, LContent, LResponseStream); AfterPATCH(); if Assigned(AAfterExecute) then AAfterExecute(LResponseStream); except on E: Exception do begin if Assigned(AOnException) then AOnException(E) else raise; end; end; finally LResponseStream.Free; end; finally LContent.Free; end; end; procedure TWiRLClientCustomResource.POST( const ABeforeExecute: TProc<TMemoryStream>; const AAfterExecute: TWiRLClientResponseProc; const AOnException: TWiRLClientExceptionProc); var LResponseStream: TMemoryStream; LContent: TMemoryStream; begin LContent := TMemoryStream.Create; try LResponseStream := TMemoryStream.Create; try try BeforePOST(LContent); if Assigned(ABeforeExecute) then ABeforeExecute(LContent); Client.Request.Accept := Accept; Client.Request.ContentType := ContentType; Client.Post(URL, LContent, LResponseStream); AfterPOST(); if Assigned(AAfterExecute) then AAfterExecute(LResponseStream); except on E: Exception do begin if Assigned(AOnException) then AOnException(E) else raise; end; end; finally LResponseStream.Free; end; finally LContent.Free; end; end; procedure TWiRLClientCustomResource.POSTAsync( const ACompletionHandler: TWiRLClientProc; const AOnException: TWiRLClientExceptionProc; ASynchronize: Boolean); begin Client.ExecuteAsync( procedure begin POST(nil, nil, AOnException); if Assigned(ACompletionHandler) then begin if ASynchronize then TThread.Queue(nil, TThreadProcedure(ACompletionHandler)) else ACompletionHandler(); end; end ); end; procedure TWiRLClientCustomResource.PUT(const ABeforeExecute: TProc<TMemoryStream> = nil; const AAfterExecute: TWiRLClientResponseProc = nil; const AOnException: TWiRLClientExceptionProc = nil); var LResponseStream: TMemoryStream; LContent: TMemoryStream; begin LContent := TMemoryStream.Create; try LResponseStream := TMemoryStream.Create; try try BeforePUT(LContent); if Assigned(ABeforeExecute) then ABeforeExecute(LContent); Client.Request.Accept := Accept; Client.Request.ContentType := ContentType; Client.Put(URL, LContent, LResponseStream); AfterPUT(); if Assigned(AAfterExecute) then AAfterExecute(LResponseStream); except on E: Exception do begin if Assigned(AOnException) then AOnException(E) else raise; end; end; finally LResponseStream.Free; end; finally LContent.Free; end; end; procedure TWiRLClientCustomResource.SetPathParamsValues(const Value: TStrings); begin FPathParamsValues.Assign(Value); end; procedure TWiRLClientCustomResource.SetQueryParams(const Value: TStrings); begin FQueryParams.Assign(Value); end; end.
PROGRAM PrintEnvironments(INPUT, OUTPUT); Uses Dos; VAR Str: STRING; PROCEDURE PrintEnvToFile(VAR OutputFile: TEXT; VAR Env: STRING); BEGIN WRITE(OutputFile, Env, ' = '); Env := GetEnv(Env); WRITELN(OutputFile, Env) END; BEGIN {PrintEnv} WRITELN('Content-Type: text/plain'); WRITELN; WRITELN('Enviroments:'); Str := 'REQUEST_METHOD'; PrintEnvToFile(OUTPUT, Str); Str := 'CONTENT_LENGTH'; PrintEnvToFile(OUTPUT, Str); Str := 'HTTP_USER_AGENT'; PrintEnvToFile(OUTPUT, Str); Str := 'HTTP_HOST'; PrintEnvToFile(OUTPUT, Str); Str := 'QUERY_STRING'; PrintEnvToFile(OUTPUT, Str); END. {PrintEnv}
unit DW.FirebaseApp.Android; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface type TPlatformFirebaseApp = class(TObject) private class var FStarted: Boolean; public class procedure Start; end; implementation uses // Android Androidapi.Helpers, // DW DW.Androidapi.JNI.Firebase; { TPlatformFirebaseApp } class procedure TPlatformFirebaseApp.Start; begin if not FStarted then begin TJFirebaseApp.JavaClass.initializeApp(TAndroidHelper.Context); FStarted := True; end; end; end.
unit ItemEditor.Graphics; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ItemEditor.Base, StdCtrls, ComCtrls, ExtCtrls, pngimage, Buttons, PngBitBtn; type TItemEditorFrame_GPU = class(TItemEditorBaseFrame) CustomTabSheet: TTabSheet; GPUCombo: TComboBox; CaptionLabel_C1: TLabel; BusCombo: TComboBox; CaptionLabel_C4: TLabel; CaptionLabel_C2: TLabel; InterfaceCombo: TComboBox; CaptionLabel_C3: TLabel; CoolingCombo: TComboBox; CaptionLabel_C5: TLabel; MemTypeCombo: TComboBox; CaptionLabel_C6: TLabel; DXCombo: TComboBox; SLICheck: TCheckBox; HDMICheck: TCheckBox; WidthEdit: TEdit; CaptionLabel_C7: TLabel; CaptionLabel_C8: TLabel; GPUFreqEdit: TEdit; CaptionLabel_C9: TLabel; MemFreqEdit: TEdit; protected procedure Initialize; override; procedure Finalize; override; procedure ValidateFields(var Valid: Boolean); override; procedure TrimFields; override; public procedure GetDataEx(const Data: Pointer); override; procedure SetDataEx(const Data: Pointer); override; function GetShortDescription(const ExData: Pointer): String; override; function GetDescription(const ExData: Pointer): String; override; end; implementation {$R *.dfm} uses CCDBv2; { TItemEditorFrame_GPU } procedure TItemEditorFrame_GPU.Finalize; begin inherited; Dispose(PDataStructGraphics(FDefaultDataEx)); end; procedure TItemEditorFrame_GPU.GetDataEx(const Data: Pointer); begin with PDataStructGraphics(Data)^ do begin {$WARNINGS OFF} GPU := GPUCombo.Text; ConnInterface := InterfaceCombo.ItemIndex; Cooling := CoolingCombo.ItemIndex; Width := StrToInt(WidthEdit.Text); GPUFreq := StrToInt(GPUFreqEdit.Text); MemFreq := StrToInt(MemFreqEdit.Text); Bus := BusCombo.ItemIndex; MemType := MemTypeCombo.ItemIndex; DirectX := DXCombo.ItemIndex; SLI := SLICheck.Checked; HDMI := HDMICheck.Checked; {$WARNINGS ON} end; end; function TItemEditorFrame_GPU.GetDescription(const ExData: Pointer): String; begin end; function TItemEditorFrame_GPU.GetShortDescription(const ExData: Pointer): String; var R: PDataStructGraphics absolute ExData; begin {$WARNINGS OFF} Result := 'GPU ' + R^.GPU + #32 + '(' + IntToStr(R^.GPUFreq) + #32 + 'ÌÃö)' + #44#32; Result := Result + MemTypeCombo.Items[R^.MemType] + #44#32; Result := Result + 'øèíà' + #32 + BusCombo.Items[R^.Bus] + #44#32; Result := Result + 'DirectX' + #32 + DXCombo.Items[R^.DirectX] + #44#32; Result := Result + InterfaceCombo.Items[R^.ConnInterface]; {$WARNINGS ON} end; procedure TItemEditorFrame_GPU.Initialize; begin inherited; New(PDataStructGraphics(FDefaultDataEx)); GetDataEx(PDataStructGraphics(FDefaultDataEx)); with VendorCombo.Items do begin Add('AMD'); Add('ASUS'); Add('Club 3D'); Add('EVGA'); Add('Gainward'); Add('Gigabyte'); Add('Inno3D'); Add('MSI'); Add('Palit'); Add('Point of View'); Add('PowerColor'); Add('Sapphire'); Add('XFX'); Add('ZOTAC'); end; end; procedure TItemEditorFrame_GPU.SetDataEx(const Data: Pointer); begin if not Assigned(Data) then Exit; with PDataStructGraphics(Data)^ do begin {$WARNINGS OFF} GPUCombo.Text := GPU; InterfaceCombo.ItemIndex := ConnInterface; CoolingCombo.ItemIndex := Cooling; WidthEdit.Text := IntToStr(Width); GPUFreqEdit.Text := IntToStr(GPUFreq); MemFreqEdit.Text := IntToStr(MemFreq); BusCombo.ItemIndex := Bus; MemTypeCombo.ItemIndex := MemType; DXCombo.ItemIndex := DirectX; SLICheck.Checked := SLI; HDMICheck.Checked := HDMI; {$WARNINGS ON} end; end; procedure TItemEditorFrame_GPU.TrimFields; begin inherited; GPUCombo.Text := Trim(GPUCombo.Text); end; procedure TItemEditorFrame_GPU.ValidateFields(var Valid: Boolean); begin inherited; Valid := Valid and (GPUCombo.Text <> '') and ValueInRange(StrToInt(GPUFreqEdit.Text), 0, High(Word)) and ValueInRange(StrToInt(MemFreqEdit.Text), 0, High(Word)) and ValueInRange(StrToInt(WidthEdit.Text), 0, 350); end; end.
// **************************************************************************** // // Software to make a connection between the Prism astronomical software // www.hyperion-astronomy.com and the Good Night System (GNS) // from lunatico.es. // // Niklas Storck // Hallongränd 23, 182 45 Enebyberg, Sweden // niklas@family-storck.se // // 2018-02-02 // // **************************************************************************** unit Main; interface uses ShellApi, System.UITypes, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls; type TForm1 = class(TForm) OpenDialog1: TOpenDialog; EditFolder: TLabeledEdit; RichEdit: TRichEdit; TimerSlow: TTimer; LabelInfo: TLabel; TimerFast: TTimer; LabeledEditTimeout: TLabeledEdit; Button2: TButton; Panel1: TPanel; Panel2: TPanel; Button1: TButton; procedure Button1Click(Sender: TObject); procedure TimerSlowTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TimerFastTimer(Sender: TObject); procedure LabeledEditTimeoutChange(Sender: TObject); procedure Button2Click(Sender: TObject); private SLast: String; TimeOut: Integer; procedure CallGNS(var Return: integer; SNew: string); function ObsEnd(SNew: String):Boolean; function StripTimeFromString(var STemp: string):String; procedure Welcome; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin TimerSlow.Interval:=10000; TimerSlow.Enabled:= False; Button1.Caption:= 'Run'; TimerFast.Enabled:=False; LabelInfo.caption:='Idle'; Form1.Caption:='GNS for Prism'; Form1.Color:=RGB(100,100,100); SLast:=''; TimeOut:=120; LabelInfo.Font.Color:=RGB(255,25,25); LabeledEditTimeout.Text:='120'; Welcome; end; procedure TForm1.LabeledEditTimeoutChange(Sender: TObject); var s: String; begin s:=LabeledEditTimeOut.Text; Try TimeOut:=StrToInt(s) Except TimeOut:=120; s:=s+' must be a number'; Application.MessageBox(PWideChar(s),'Error!',MB_OK); End end; function TForm1.ObsEnd(SNew:String): Boolean; // Check if observation has ended by comparing tha string // with a standarstring. // Probably I should cahnge this to someting more dynamic // that the user can change if Prism changes the message. // It works today. begin ObsEnd:=False; if SNew = 'Auto Observations process has been released' then ObsEnd:=True end; function TForm1.StripTimeFromString(var STemp: string):String; // Deletes the timestamp from the line. // This is because it was to much information for GNS to show in // its main window. var Position: Integer; begin // Extract string after ':' in line Position := Pos(':', STemp) + 1; // +1 is to delete the space after ":". Delete(STemp, 1, Position); Result:=STemp; end; procedure TForm1.Welcome; // Welcome message begin Panel1.Caption:=''; Panel2.Caption:=''; RichEdit.Lines.Clear; RichEdit.Lines.Add('Welcome!'); RichEdit.Lines.Add(''); RichEdit.Lines.Add('1. Start an automatic session with Prism.'); RichEdit.Lines.Add('2. Open the new observation log file. It usually has a name like "Obsauto__UTC_2018-02-04__13h31m04s".'); RichEdit.Lines.Add('2 b. You might want to change the timeout depending on your requirements. (Sorry I dont sawe between sesions)'); RichEdit.Lines.Add('3. Press <Run>'); RichEdit.Lines.Add(''); RichEdit.Lines.Add('At the moment it is necessary that GNS is in it''s default directory C:\Program Files (x86)\GNS'); RichEdit.Lines.Add(''); RichEdit.Lines.Add('The software is a tool made for my own use. Its free for anyone to use in their observatory'); RichEdit.Lines.Add('but I can not take any responsibility for any damage to equipment that might happen due'); RichEdit.Lines.Add('to any malfunction of the software.'); RichEdit.Lines.Add('With that said I believe it to work well.'); RichEdit.Lines.Add(''); RichEdit.Lines.Add('Please drop me a mail if there is some problems: niklas@storckholmen.se'); RichEdit.Lines.Add(''); RichEdit.Lines.Add('Clear skies!'); RichEdit.Lines.Add(''); RichEdit.Lines.Add('Niklas Storck'); end; procedure TForm1.Button1Click(Sender: TObject); // Switch to handle turn on/off sampling of logfile. begin if TimerSlow.enabled then // Turn off begin TimerSlow.Enabled:= False; Button1.Caption:= 'Run'; TimerFast.Enabled:=False; LabelInfo.caption:='Idle'; LabelInfo.Font.Color:=RGB(255,25,25) end else // Turn on begin RichEdit.Lines.Clear; LabelInfo.caption := ''; LabelInfo.Font.Color := RGB(25,255,25); RichEdit.SelAttributes.Color := clGreen; RichEdit.SelAttributes.Style := [fsBold]; RichEdit.Lines.Add('Start of sampling at: '+ DateTimeToStr(Now)); RichEdit.Lines.Add('Timeout is '+ IntToStr(TimeOut)+' s.'); RichEdit.Lines.Add('Log file is: '+EditFolder.Text+'.'); RichEdit.Lines.Add('--------------------------------------------------'); RichEdit.Lines.Add(''); TimerSlow.Enabled:= True; Button1.Caption:='Stop'; TimerFast.Enabled:=True; TimerSlowTimer(self) end; end; procedure TForm1.Button2Click(Sender: TObject); begin if OpenDialog1.execute then EditFolder.Text:= OpenDialog1.FileName; end; procedure TForm1.CallGNS(var Return: integer; SNew: string); // Calls GNS // SNew is the Message that is sent // Return is returncode from ShellExecute. Should be > 32 if ewerything is ok. var parameters, filename: String; begin RichEdit.Lines.Add(SNew); filename:='C:\Program Files (x86)\GNS\update.vbs'; parameters:=' "'+StripTimeFromString(SNew)+'"'+' '+IntToStr(TimeOut); return:=ShellExecute(handle,'open',Pchar(filename),PChar(parameters),'',SW_MINIMIZE); if ObsEnd(SNew) then // Observation ended ok. Send stop instruction to GNS begin filename:='C:\Program Files (x86)\GNS\switchoff.vbs'; return:=ShellExecute(handle,'open',Pchar(filename),'','',SW_MINIMIZE); RichEdit.Lines.Add(''); RichEdit.Lines.Add('--------------------------------------------------'); RichEdit.SelAttributes.Color:=clGreen; RichEdit.SelAttributes.Style := [fsBold]; RichEdit.Lines.Add('The session has ended. Shutdown is sent to GNS.'); Button1Click(self); LabelInfo.caption:='Ready'; LabelInfo.Font.Color:=RGB(25,25,255) end; end; procedure TForm1.TimerFastTimer(Sender: TObject); // Ticks the clock begin LabelInfo.caption:='Running :'+DateTimeToStr(now) end; procedure TForm1.TimerSlowTimer(Sender: TObject); // Reads the last line of the selected logfile var F: TextFile; SNew, STemp: String; return: Integer; begin STemp:=''; RichEdit.Brush.Color:=RGB(200,200,200); RichEdit.SelAttributes.Color:=clBlack; if fileexists(EditFolder.Text) then begin AssignFile(F,EditFolder.Text); Reset(F); repeat Readln(F,SNew); until EOF(F); STemp:=Snew; if SNew <> SLast then begin CallGNS(return, SNew); if return < 32 then begin RichEdit.Lines.Add('--------------------------------------------------'); RichEdit.Lines.Add(''); RichEdit.SelAttributes.Color:=clRed; RichEdit.Lines.Add('Problem with talking to gns. Error: '+ intToStr(Return)); end; end; SLast:=STemp; CloseFile(F) end else begin RichEdit.SelAttributes.Color:=clRed; RichEdit.Lines.Add('File '+EditFolder.Text+' not found!'); RichEdit.SelAttributes.Style := [fsBold]; RichEdit.Lines.Add('Session ended!'); Button1Click(self); end; end; end.
unit DW.PermissionsRequester; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses DW.PermissionsTypes; type TPermissionsResultEvent = procedure(Sender: TObject; const RequestCode: Integer; const Results: TPermissionResults) of object; TPermissionsRequester = class; TCustomPlatformPermissionsRequester = class(TObject) private FPermissionsRequester: TPermissionsRequester; protected procedure RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); virtual; abstract; public constructor Create(const APermissionsRequester: TPermissionsRequester); virtual; property PermissionsRequester: TPermissionsRequester read FPermissionsRequester; end; TPermissionsRequester = class(TObject) private FIsRequesting: Boolean; FPlatformPermissionsRequester: TCustomPlatformPermissionsRequester; FOnPermissionsResult: TPermissionsResultEvent; protected procedure DoPermissionsResult(const RequestCode: Integer; const Results: TPermissionResults); public constructor Create; destructor Destroy; override; procedure RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); property IsRequesting: Boolean read FIsRequesting; property OnPermissionsResult: TPermissionsResultEvent read FOnPermissionsResult write FOnPermissionsResult; end; implementation uses DW.OSLog, DW.OSDevice, {$IF Defined(ANDROID)} DW.PermissionsRequester.Android; {$ELSE} DW.PermissionsRequester.Default; {$ENDIF} { TCustomPlatformPermissionsRequester } constructor TCustomPlatformPermissionsRequester.Create(const APermissionsRequester: TPermissionsRequester); begin inherited Create; FPermissionsRequester := APermissionsRequester; end; { TPermissionsRequester } constructor TPermissionsRequester.Create; begin inherited; FPlatformPermissionsRequester := TPlatformPermissionsRequester.Create(Self); end; destructor TPermissionsRequester.Destroy; begin FPlatformPermissionsRequester.Free; inherited; end; procedure TPermissionsRequester.DoPermissionsResult(const RequestCode: Integer; const Results: TPermissionResults); begin if Assigned(FOnPermissionsResult) then FOnPermissionsResult(Self, RequestCode, Results); FIsRequesting := False; end; procedure TPermissionsRequester.RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); var LResults: TPermissionResults; begin FIsRequesting := True; if TOSDevice.CheckPermissions(APermissions, LResults) then DoPermissionsResult(ARequestCode, LResults) else FPlatformPermissionsRequester.RequestPermissions(APermissions, ARequestCode); end; end.
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (the "License"); you may not use this } { file except in compliance with the License. You may obtain } { a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Eric Grange / Creative IT } { } {**********************************************************************} unit dwsXPlatformTests; interface uses Classes, SysUtils, Math, {$ifdef FPC} fpcunit, testutils, testregistry {$else} TestFrameWork {$endif} ; type {$ifdef FPC} TTestCaseFPC = fpcunit.TTestCase; TTestCase = class (TTestCaseFPC) public procedure CheckEquals(const expected, actual: UnicodeString; const msg: String = ''); overload; procedure CheckEquals(const expected : String; const actual: UnicodeString; const msg: String = ''); overload; procedure CheckEquals(const expected, actual: Double; const msg: String = ''); overload; end; ETestFailure = class (Exception); {$else} TTestCase = TestFrameWork.TTestCase; ETestFailure = TestFrameWork.ETestFailure; {$endif} procedure RegisterTest(const testName : String; aTest : TTestCaseClass); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // RegisterTest // procedure RegisterTest(const testName : String; aTest : TTestCaseClass); begin {$ifdef FPC} testregistry.RegisterTest(aTest); {$else} TestFrameWork.RegisterTest(testName, aTest.Suite); {$endif} end; // CheckEquals // {$ifdef FPC} procedure TTestCase.CheckEquals(const expected, actual: Double; const msg: String = ''); const DZeroResolution = 1E-12; var vDelta: Double; begin vDelta:=Math.Max(Math.Min(Abs(expected),Abs(actual))*DZeroResolution,DZeroResolution); AssertEquals(Msg, expected, actual, vDelta); end; procedure TTestCase.CheckEquals(const expected, actual: UnicodeString; const msg: String = ''); begin AssertTrue(msg + ComparisonMsg(Expected, Actual), AnsiCompareStr(Expected, Actual) = 0); end; procedure TTestCase.CheckEquals(const expected : String; const actual: UnicodeString; const msg: String = ''); begin AssertTrue(msg + ComparisonMsg(Expected, Actual), AnsiCompareStr(Expected, Actual) = 0); end; {$endif} end.
unit UPrefFToolPlugIn; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This is the Frame that contains the Tools > Plug-In Preferences} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids_ts, TSGrid, StdCtrls, ExtCtrls, UContainer; type TPrefToolPlugIn = class(TFrame) PlugToolList: TtsGrid; Panel1: TPanel; StaticText1: TStaticText; StaticText2: TStaticText; Panel2: TPanel; procedure ToolListsChanged(Sender: TObject; DataCol, DataRow: Integer; ByUser: Boolean); procedure LocatePlugInTool(Sender: TObject; DataCol, DataRow: Integer); procedure PlugToolListEndCellEdit(Sender: TObject; DataCol, DataRow: Integer; var Cancel: Boolean); private FDoc: TContainer; FToolsChged: boolean; FLastToolDir: String; public constructor CreateFrame(AOwner: TComponent; ADoc: TContainer); procedure LoadPrefs; //loads in the prefs from the app procedure SavePrefs; //saves the changes function LocateToolExe(var Name, FullPath: String): Boolean; end; implementation uses UGlobals, UStatus, UUtil1, UInit, UMain; {$R *.dfm} constructor TPrefToolPlugIn.CreateFrame(AOwner: TComponent; ADoc: TContainer); begin inherited Create(AOwner); FDoc := ADoc; LoadPrefs; end; procedure TPrefToolPlugIn.LoadPrefs; var i, numItems: integer; begin //load the Plug-in Tools preference numItems := length(appPref_PlugTools); PlugToolList.Rows := numItems; for i := 0 to numItems-1 do begin PlugToolList.Cell[1,i+1] := appPref_PlugTools[i].AppName; PlugToolList.Cell[2,i+1] := appPref_PlugTools[i].MenuName; PlugToolList.Cell[3,i+1] := appPref_PlugTools[i].AppPath; if (appPref_PlugTools[i].AppPath = CAutomaticToolPath) then begin PlugToolList.CellButtonType[4, i + 1] := btNone; PlugToolList.CellReadOnly[4, i + 1] := roOn; end; if (appPref_PlugTools[i].AppName = '') then PlugToolList.RowVisible[i + 1] := False; end; PlugToolList.CellReadOnly[2,7] := roOn; //prevents AreaSketch from disappearing //init some vars FLastToolDir := ''; FToolsChged := False; end; procedure TPrefToolPlugIn.SavePrefs; var i, numItems: integer; begin //save preference for plug-in tools numItems := Length(appPref_PlugTools); for i := 1 to numItems do begin appPref_PlugTools[i-1].MenuName := PlugToolList.Cell[2,i]; appPref_PlugTools[i-1].AppPath := PlugToolList.Cell[3,i]; if (i = 5) then //apex special appPref_PlugTools[i-1].MenuVisible := Length(PlugToolList.Cell[2,i])>0 //is the APEX name there else appPref_PlugTools[i-1].MenuVisible := Length(PlugToolList.Cell[3,i])>0; if (i = 8) then //RapidSketch special appPref_PlugTools[i-1].MenuVisible := Length(PlugToolList.Cell[2,i])>0 //is the APEX name there else appPref_PlugTools[i-1].MenuVisible := Length(PlugToolList.Cell[3,i])>0; appPref_PlugTools[i-1].MenuEnabled := (Length(PlugToolList.Cell[2,i])>0) and (Length(PlugToolList.Cell[3,i])>0); end; Main.UpdateToolsMenu; Main.UpdatePlugInToolsToolbar; end; procedure TPrefToolPlugIn.ToolListsChanged(Sender: TObject; DataCol, DataRow: Integer; ByUser: Boolean); begin FToolsChged := True; end; procedure TPrefToolPlugIn.PlugToolListEndCellEdit(Sender: TObject; DataCol, DataRow: Integer; var Cancel: Boolean); begin if (DataCol = 2) and (DataRow <> 5) then //special for APEX begin if Length(PlugToolList.Cell[2,dataRow]) = 0 then PlugToolList.Cell[3,dataRow] := ''; end; end; procedure TPrefToolPlugIn.LocatePlugInTool(Sender: TObject; DataCol, DataRow: Integer); var name, path: String; n: Integer; begin Path := PlugToolList.Cell[3,dataRow]; if LocateToolExe(Name, Path) then begin n := Pos('.', Name); //remove the '.exe' from text if n > 0 then delete(Name, n, length(Name)-n+1); PlugToolList.Cell[2,dataRow] := Name; //show new menu name PlugToolList.Cell[3,dataRow] := Path; //show full path to plug-in tool FToolsChged := True; FLastToolDir := ExtractFilePath(path); //remember where we are end; end; function TPrefToolPlugIn.LocateToolExe(var Name, FullPath: String): Boolean; var selectEXE: TOpenDialog; n: Integer; begin selectEXE := TOpenDialog.Create(self); try if FileExists(FullPath) then begin selectEXE.InitialDir := ExtractFilePath(FullPath); selectEXE.Filename := ExtractFileName(FullPath); end else selectEXE.InitialDir := VerifyInitialDir(FLastToolDir, ApplicationFolder); (* out if length(FLastToolDir) = 0 then selectEXE.InitialDir := ApplicationFolder else selectEXE.InitialDir := FLastToolDir; *) selectEXE.DefaultExt := 'exe'; selectEXE.Filter := 'Application.exe (*.exe)|*.exe|All Files (*.*)|*.*'; selectEXE.FilterIndex := 1; selectEXE.Title := 'Select a Tool:'; result := selectEXE.Execute; if result then begin FullPath := selectEXE.Filename; Name := ExtractFileName(selectEXE.Filename); n := Pos('.EXE', UpperCase(Name)); if n = 0 then result := OK2Continue('This tool ' + Name+ ' does not have an EXE extension. Are you sure it is an application?'); end; finally selectEXE.Free; end; end; end.
unit UHistory; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ActnList, ImgList, ComCtrls, ToolWin, StdCtrls, Contnrs, RPDesignInfo, UToolForm; type TfmHistory = class(TToolForm) lsStates: TListBox; ToolBar1: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ImageList: TImageList; ActionList: TActionList; acSaveCurrent: TAction; acRestore: TAction; acDelete: TAction; acClear: TAction; ToolButton4: TToolButton; procedure acSaveCurrentExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure acClearExecute(Sender: TObject); procedure acDeleteExecute(Sender: TObject); procedure acRestoreExecute(Sender: TObject); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); private { Private declarations } FStateData : TObjectList; FHistoryCouting : integer; public { Public declarations } procedure ClearStates; procedure AfterFileOperation; override; end; var fmHistory: TfmHistory; implementation uses UMain; {$R *.DFM} procedure TfmHistory.FormCreate(Sender: TObject); begin inherited; FStateData := TObjectList.Create; lsStates.Items.Clear; FHistoryCouting := 1; end; procedure TfmHistory.FormDestroy(Sender: TObject); begin inherited; FStateData.Free; end; procedure TfmHistory.ClearStates; begin FHistoryCouting := 1; //FStateMenus.Clear; FStateData.Clear; lsStates.Items.Clear; end; procedure TfmHistory.acSaveCurrentExecute(Sender: TObject); var Notes : string; MS : TMemoryStream; begin Notes := IntToStr(FHistoryCouting); if InputQuery('Save design state','Notes',Notes) then begin lsStates.Items.Add(Notes); MS := TMemoryStream.Create; FStateData.Add(MS); ReportDesigner.StopDesignning(False); ReportInfo.SaveToStream(MS); ReportDesigner.StartDesignning; //BuildHistoryMenu; Inc(FHistoryCouting); end; end; procedure TfmHistory.acClearExecute(Sender: TObject); begin ClearStates; end; procedure TfmHistory.acDeleteExecute(Sender: TObject); begin if lsStates.ItemIndex>=0 then begin FStateData.Delete(lsStates.ItemIndex); lsStates.Items.Delete(lsStates.ItemIndex); end; end; procedure TfmHistory.acRestoreExecute(Sender: TObject); var Index : Integer; MS : TMemoryStream; begin Index := lsStates.ItemIndex; if (Index>=0) and (Index<FStateData.Count) then begin MS := TMemoryStream(FStateData[Index]); MS.Position := 0; ReportDesigner.StopDesignning; try ReportInfo.LoadFromStream(MS); ReportDesigner.UpdateDesignArea; finally ReportDesigner.StartDesignning; end; end; end; procedure TfmHistory.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin acDelete.Enabled := lsStates.ItemIndex>=0; acRestore.Enabled := acDelete.Enabled; acClear.Enabled := FStateData.Count>0; end; procedure TfmHistory.AfterFileOperation; begin inherited; fmHistory.ClearStates; end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 28.10.2020 15:24:13 unit IdOpenSSLHeaders_cterr; interface // Headers for OpenSSL 1.1.1 // cterr.h {$i IdCompilerDefines.inc} uses Classes, IdCTypes, IdGlobal, IdOpenSSLConsts; const ///* // * CT function codes. // */ CT_F_CTLOG_NEW = 117; CT_F_CTLOG_NEW_FROM_BASE64 = 118; CT_F_CTLOG_NEW_FROM_CONF = 119; CT_F_CTLOG_STORE_LOAD_CTX_NEW = 122; CT_F_CTLOG_STORE_LOAD_FILE = 123; CT_F_CTLOG_STORE_LOAD_LOG = 130; CT_F_CTLOG_STORE_NEW = 131; CT_F_CT_BASE64_DECODE = 124; CT_F_CT_POLICY_EVAL_CTX_NEW = 133; CT_F_CT_V1_LOG_ID_FROM_PKEY = 125; CT_F_I2O_SCT = 107; CT_F_I2O_SCT_LIST = 108; CT_F_I2O_SCT_SIGNATURE = 109; CT_F_O2I_SCT = 110; CT_F_O2I_SCT_LIST = 111; CT_F_O2I_SCT_SIGNATURE = 112; CT_F_SCT_CTX_NEW = 126; CT_F_SCT_CTX_VERIFY = 128; CT_F_SCT_NEW = 100; CT_F_SCT_NEW_FROM_BASE64 = 127; CT_F_SCT_SET0_LOG_ID = 101; CT_F_SCT_SET1_EXTENSIONS = 114; CT_F_SCT_SET1_LOG_ID = 115; CT_F_SCT_SET1_SIGNATURE = 116; CT_F_SCT_SET_LOG_ENTRY_TYPE = 102; CT_F_SCT_SET_SIGNATURE_NID = 103; CT_F_SCT_SET_VERSION = 104; ///* // * CT reason codes. // */ CT_R_BASE64_DECODE_ERROR = 108; CT_R_INVALID_LOG_ID_LENGTH = 100; CT_R_LOG_CONF_INVALID = 109; CT_R_LOG_CONF_INVALID_KEY = 110; CT_R_LOG_CONF_MISSING_DESCRIPTION = 111; CT_R_LOG_CONF_MISSING_KEY = 112; CT_R_LOG_KEY_INVALID = 113; CT_R_SCT_FUTURE_TIMESTAMP = 116; CT_R_SCT_INVALID = 104; CT_R_SCT_INVALID_SIGNATURE = 107; CT_R_SCT_LIST_INVALID = 105; CT_R_SCT_LOG_ID_MISMATCH = 114; CT_R_SCT_NOT_SET = 106; CT_R_SCT_UNSUPPORTED_VERSION = 115; CT_R_UNRECOGNIZED_SIGNATURE_NID = 101; CT_R_UNSUPPORTED_ENTRY_TYPE = 102; CT_R_UNSUPPORTED_VERSION = 103; procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); procedure UnLoad; var ERR_load_CT_strings: function: TIdC_INT cdecl = nil; implementation procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); function LoadFunction(const AMethodName: string; const AFailed: TStringList): Pointer; begin Result := LoadLibFunction(ADllHandle, AMethodName); if not Assigned(Result) then AFailed.Add(AMethodName); end; begin ERR_load_CT_strings := LoadFunction('ERR_load_CT_strings', AFailed); end; procedure UnLoad; begin ERR_load_CT_strings := nil; end; end.
unit DebuggerUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ToolWin, ExtCtrls, Menus, IniFiles, TypInfo, ShellApi, Buttons, math, typesUnit, PropertyEditUnit, SynEdit, FreeBasicRTTI, ELSuperEdit, PageSheetUnit; type TDebugger=class(TStringList) private fEdit:TELSuperEdit; fFiles:TStrings; public constructor create; destructor destroy; override; procedure AddFile(v:string); function FileDebugExists(v:string):integer; function isFileOpen(v:string):TPageSheet; procedure Scan; procedure Reset; property Edit:TELSuperEdit read fEdit write fEdit; property Files:TStrings read ffiles; end; implementation uses LauncherUnit, MainUnit, CodeUnit; { TDebugger } constructor TDebugger.create; begin fFiles:=TStringList.Create; end; destructor TDebugger.destroy; begin fFiles.Free; inherited; end; procedure TDebugger.AddFile(v:string); begin if ffiles.IndexOf(v)=-1 then ffiles.Add(v); end; function TDebugger.FileDebugExists(v:string):integer; var i:integer; begin result:=-1; if v='' then exit; i:=IndexOf(v); result:=i; end; procedure TDebugger.Scan; var i,fd,ln,e,eNumber:integer; s,p,v,en:string; Ps:TPageSheet; eKind:TErrorKind; Error:TError; label Skip; function Number(v:string):string; var i:integer; begin result:=''; if v='' then exit; for i:=1 to length(v) do if v[i] in ['0'..'9'] then result:=result+v[i]; end; begin if Count=0 then exit; i:=0; repeat s:=trim(Self[i]); eKind:=erkNone; if s='' then goto skip; if Count>0 then begin p:=''; v:=''; if pos(' error ',lowercase(s))>0 then begin en:=trim(copy(s,pos(' error ',lowercase(s))+6,length(s))); en:=trim(copy(en,1,pos(':',en)-1)); eKind:=erkError; p:=copy(s,1,pos('(',s)-1); v:=copy(s,pos('(',s)+1,pos(')',s)-pos('(',s)-1); end ; if pos(' warning ',lowercase(s))>0 then begin en:=trim(copy(s,pos(' warning ',lowercase(s))+8,length(s))); en:=trim(copy(en,1,pos(':',en)-1)); eKind:=erkWarning; p:=copy(s,1,pos('(',s)-1); v:=copy(s,pos('(',s)+1,pos(')',s)-pos('(',s)-1); end ; if fileexists(p) then begin ps:=Launcher.isOpen(p); if ps=nil then ps:=Launcher.NewEditor(p); fd:=FileDebugExists(p); if fd>-1 then AddFile(p); v:=number(v); en:=number(en); val(v,ln,e); if e=0 then begin val(en,eNumber,e); Error:=TError.Create; ps.Frame.Edit.AddError(Error); Error.Kind:=eKind; Error.Number:=eNumber; Error.Line:=ln; Error.Kind:=eKind; ps.Frame.Edit.Repaint; end end; end; skip: inc(i); until i>Count-1; end; function TDebugger.isFileOpen(v:string):TPageSheet; var i:integer; begin result:=nil; if v='' then exit; for i:=0 to Code.PageControl.PageCount-1 do begin if comparetext(TPageSheet(Code.PageControl.Pages[i]).FileName,v)=0 then begin result:=TPageSheet(Code.PageControl.Pages[i]); Code.PageControl.ActivePage:=result; if not Launcher.AllowMultipleFileInstances then break ; end end end; procedure TDebugger.Reset; var i:integer; begin for i:=0 to Code.PageControl.PageCount-1 do TPageSheet(Code.PageControl.Pages[i]).Frame.Edit.Reset; ffiles.Clear; end; end.
unit OlegTypePart2; interface uses IniFiles, OlegType; type IName = interface ['{5B51E68D-11D9-4410-8396-05DB50F07F35}'] function GetName:string; property Name:string read GetName; end; //TSimpleFreeAndAiniObject=class(TInterfacedObject) // protected // public // procedure Free;//virtual; // procedure ReadFromIniFile(ConfigFile: TIniFile);virtual; // procedure WriteToIniFile(ConfigFile: TIniFile);virtual; //// destructor Destroy;override; // end; {як варіант позбавлення від проблеми знищення інтерфейсу-змінної при виході з процедури - див.https://habr.com/ru/post/181107/ є ще інший варіант(??? а може й ні) https://habr.com/ru/post/219685/} TSimpleFreeAndAiniObject=class(TObject) protected function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; public procedure ReadFromIniFile(ConfigFile: TIniFile);virtual; procedure WriteToIniFile(ConfigFile: TIniFile);virtual; end; //TNamedInterfacedObject=class(TInterfacedObject) TNamedInterfacedObject=class(TSimpleFreeAndAiniObject,IName) protected fName:string; function GetName:string; public property Name:string read GetName; end; //TNamedInterfacedMeasObject=class(TNamedInterfacedObject) // protected // fName:string; // function GetDeviceKod:byte;virtual; // public // property DeviceKod:byte read GetDeviceKod; // end; TNamedObject=class(TObject) private // fName:string; function GetName:string; protected fName:string; public property Name:string read GetName; Constructor Create(Nm:string); end; TObjectArray=class private function GetHighIndex:integer; function ObjectGet(Number:integer):TSimpleFreeAndAiniObject; public ObjectArray:array of TSimpleFreeAndAiniObject; property SFIObject[Index:Integer]:TSimpleFreeAndAiniObject read ObjectGet;default; property HighIndex:integer read GetHighIndex; Constructor Create();overload; Constructor Create(InitArray:array of TSimpleFreeAndAiniObject);overload; procedure Add(AddedArray:array of TSimpleFreeAndAiniObject);overload; procedure Add(AddedObject:TSimpleFreeAndAiniObject);overload; procedure ReadFromIniFile(ConfigFile:TIniFile); procedure WriteToIniFileAndFree(ConfigFile:TIniFile); procedure ObjectFree; end; implementation uses Math, Dialogs, SysUtils, OlegFunction; { TNamedDevice } function TNamedInterfacedObject.GetName: string; begin Result:=fName; end; { TSimpleFreeAndAiniObject } function TSimpleFreeAndAiniObject.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TSimpleFreeAndAiniObject._AddRef: Integer; begin Result := -1; end; function TSimpleFreeAndAiniObject._Release: Integer; begin Result := -1; end; procedure TSimpleFreeAndAiniObject.ReadFromIniFile(ConfigFile: TIniFile); begin end; procedure TSimpleFreeAndAiniObject.WriteToIniFile(ConfigFile: TIniFile); begin end; Constructor TObjectArray.Create(); begin inherited; SetLength(ObjectArray,0); end; procedure TObjectArray.Add(AddedObject: TSimpleFreeAndAiniObject); begin Add([AddedObject]); end; Constructor TObjectArray.Create(InitArray:array of TSimpleFreeAndAiniObject); begin Create(); Add(InitArray); end; function TObjectArray.GetHighIndex: integer; begin Result:=High(ObjectArray); end; procedure TObjectArray.ObjectFree; var i:integer; begin for i:=0 to High(ObjectArray) do // FreeAndNil(ObjectArray[i]) ObjectArray[i].Free end; function TObjectArray.ObjectGet(Number: integer): TSimpleFreeAndAiniObject; begin Result:=ObjectArray[Number]; end; procedure TObjectArray.ReadFromIniFile(ConfigFile:TIniFile); var i:integer; begin for i:=0 to High(ObjectArray) do ObjectArray[i].ReadFromIniFile(ConfigFile); end; procedure TObjectArray.WriteToIniFileAndFree(ConfigFile: TIniFile); var i:integer; begin for i:=0 to High(ObjectArray) do begin ObjectArray[i].WriteToIniFile(ConfigFile); ObjectArray[i].Free end; end; procedure TObjectArray.Add(AddedArray:array of TSimpleFreeAndAiniObject); var i:integer; begin SetLength(ObjectArray,High(ObjectArray)+High(AddedArray)+2); for I := 0 to High(AddedArray) do ObjectArray[High(ObjectArray)-High(AddedArray)+i]:=AddedArray[i]; end; { TNamedObject } constructor TNamedObject.Create(Nm: string); begin inherited Create; fName:=Nm; end; function TNamedObject.GetName: string; begin Result:=fName; end; //{ TNamedInterfacedMeasObject } // //function TNamedInterfacedMeasObject.GetDeviceKod: byte; //begin // Result:=0; //end; end.
unit AqDrop.DB.FD.FB; interface uses Data.DB, {$IF CompilerVersion >= 26} FireDAC.Phys.FB, {$ELSE} uADPhysIB, {$ENDIF} AqDrop.Core.Types, AqDrop.DB.Adapter, AqDrop.DB.FB, AqDrop.DB.FD, AqDrop.DB.FD.TypeMapping; type TAqFDFBDataConverter = class(TAqFDDataConverter) public function FieldToBoolean(const pField: TField): Boolean; override; function FieldToGUID(const pField: TField): TGUID; override; procedure BooleanToParam(const pParameter: TAqFDMappedParam; const pValue: Boolean); override; procedure GUIDToParam(const pParameter: TAqFDMappedParam; const pValue: TGUID); override; function AqDataTypeToFieldType(const pDataType: TAqDataType): TFieldType; override; end; TAqFDFBAdapter = class(TAqFDAdapter) strict protected function GetAutoIncrementType: TAqDBAutoIncrementType; override; class function GetDefaultSolver: TAqDBSQLSolverClass; override; class function GetDefaultDataConverter: TAqFDDataConverterClass; override; end; TAqFDFBConnection = class(TAqFDCustomConnection) strict protected function GetParameterValueByIndex(const pIndex: Int32): string; override; procedure SetParameterValueByIndex(const pIndex: Int32; const pValue: string); override; class function GetDefaultAdapter: TAqDBAdapterClass; override; public constructor Create; override; property DataBase: string index $80 read GetParameterValueByIndex write SetParameterValueByIndex; property UserName: string index $81 read GetParameterValueByIndex write SetParameterValueByIndex; property Password: string index $82 read GetParameterValueByIndex write SetParameterValueByIndex; property RoleName: string index $83 read GetParameterValueByIndex write SetParameterValueByIndex; property CharacterSet: string index $84 read GetParameterValueByIndex write SetParameterValueByIndex; end; implementation uses System.Types, System.SysUtils, {$IF CompilerVersion >= 26} FireDAC.Stan.Param, {$ENDIF} AqDrop.Core.Exceptions, AqDrop.Core.Helpers, AqDrop.DB.Types; { TAqFDFBDataConverter } function TAqFDFBDataConverter.AqDataTypeToFieldType(const pDataType: TAqDataType): TFieldType; begin if pDataType = TAqDataType.adtBoolean then begin Result := TFieldType.ftWideString; end else begin Result := inherited; end; end; procedure TAqFDFBDataConverter.BooleanToParam(const pParameter: TAqFDMappedParam; const pValue: Boolean); begin if pValue then begin pParameter.AsString := '1'; end else begin pParameter.AsString := '0'; end; end; function TAqFDFBDataConverter.FieldToBoolean(const pField: TField): Boolean; begin if pField.IsNull then begin Result := False; end else begin Result := inherited; end; end; function TAqFDFBDataConverter.FieldToGUID(const pField: TField): TGUID; var lBytes: TArray<UInt8>; begin if pField.IsNull then begin Result := inherited; end else begin lBytes := pField.AsBytes; Result := TGUID.Create(lBytes); end; end; procedure TAqFDFBDataConverter.GUIDToParam(const pParameter: TAqFDMappedParam; const pValue: TGUID); var lBytes: TBytes; begin if TAqGUIDFunctions.IsEmpty(pValue) then begin inherited; end else begin pParameter.DataType := ftString; lBytes := pValue.ToByteArray; pParameter.SetData(@lBytes[0], 16); end; end; { TAqFDFBAdapter } function TAqFDFBAdapter.GetAutoIncrementType: TAqDBAutoIncrementType; begin Result := TAqDBAutoIncrementType.aiGenerator; end; class function TAqFDFBAdapter.GetDefaultDataConverter: TAqFDDataConverterClass; begin Result := TAqFDFBDataConverter; end; class function TAqFDFBAdapter.GetDefaultSolver: TAqDBSQLSolverClass; begin Result := TAqDBFBSQLSolver; end; { TAqFDFBConnection } constructor TAqFDFBConnection.Create; begin inherited; {$IF CompilerVersion >= 26} DriverName := 'FB'; {$ELSE} DriverName := 'IB'; {$ENDIF} end; class function TAqFDFBConnection.GetDefaultAdapter: TAqDBAdapterClass; begin Result := TAqFDFBAdapter; end; function TAqFDFBConnection.GetParameterValueByIndex(const pIndex: Int32): string; begin case pIndex of $80: Result := Params.Values['Database']; $81: Result := Params.Values['User_Name']; $82: Result := Params.Values['Password']; $83: Result := Params.Values['RoleName']; $84: Result := Params.Values['CharacterSet']; else Result := inherited; end; end; procedure TAqFDFBConnection.SetParameterValueByIndex(const pIndex: Int32; const pValue: string); begin case pIndex of $80: Params.Values['Database'] := pValue; $81: Params.Values['User_Name'] := pValue; $82: Params.Values['Password'] := pValue; $83: Params.Values['RoleName'] := pValue; $84: Params.Values['CharacterSet'] := pValue; else inherited; end; end; end.
{ Copyright (c) 2021 Karoly Balogh System info/System variables access on a Sinclair QL Example program for Free Pascal's Sinclair QL support This example program is in the Public Domain under the terms of Unlicense: http://unlicense.org/ **********************************************************************} program mtinf; uses qdos; type Tver = array[0..3] of char; var job_id: longint; ver_ascii: longint; system_vars: pbyte; function get_id_str(const id: dword): string; const QDOS = $D2540000; SMS = $53324154; { S2AT } SMSQ = $534D5351; { SMSQ } ARGOS_THOR = $DC010000; begin case id of QDOS: get_id_str:='QDOS'; SMS: get_id_str:='SMS'; SMSQ: get_id_str:='SMSQ'; ARGOS_THOR: get_id_str:='Thor (ARGOS)'; else get_id_str:='unknown ($'+hexstr(id,8)+')'; end; end; begin job_id:=mt_inf(@system_vars,@ver_ascii); writeln('Job ID:',lo(job_id),' Tag:',hi(job_id)); writeln('Identification: ',get_id_str(pdword(@system_vars[SV_IDENT])^)); writeln('Version: ',Tver(ver_ascii)); writeln('System vars are at: $',hexstr(system_vars)); writeln('Processor type: 680',hexstr(system_vars[SV_PTYP],2)); writeln('Monitor mode: ',system_vars[SV_TVMOD]); writeln('Random number: ',pword(@system_vars[SV_RAND])^); end.
object dwsBackgroundWorkersLib: TdwsBackgroundWorkersLib OldCreateOrder = False OnCreate = DataModuleCreate OnDestroy = DataModuleDestroy Left = 695 Top = 86 Height = 129 Width = 220 object dwsBackgroundWorkers: TdwsUnit Classes = < item Name = 'BackgroundWorkers' IsStatic = True Methods = < item Name = 'CreateWorkQueue' Parameters = < item Name = 'name' DataType = 'String' end> ResultType = 'Boolean' Attributes = [maStatic] OnEval = dwsBackgroundWorkersClassesBackgroundWorkersMethodsCreateWorkQueueEval Kind = mkClassFunction end item Name = 'DestroyWorkQueue' Parameters = < item Name = 'name' DataType = 'String' end> ResultType = 'Boolean' Attributes = [maStatic] OnEval = dwsBackgroundWorkersClassesBackgroundWorkersMethodsDestroyWorkQueueEval Kind = mkClassFunction end item Name = 'QueueWork' Parameters = < item Name = 'name' DataType = 'String' end item Name = 'task' DataType = 'String' end item Name = 'data' DataType = 'String' HasDefaultValue = True DefaultValue = '' end> Attributes = [maStatic] OnEval = dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueWorkEval Kind = mkClassProcedure end item Name = 'QueueSize' Parameters = < item Name = 'name' DataType = 'String' end> ResultType = 'Integer' Attributes = [maStatic] OnEval = dwsBackgroundWorkersClassesBackgroundWorkersMethodsQueueSizeEval Kind = mkClassFunction end> end> UnitName = 'System.Workers' StaticSymbols = False Left = 80 Top = 16 end end
unit AwComCtrls; {$I AwFramework.inc} interface uses Windows, Classes, Controls, ComCtrls, Messages; type TAwTabSheet = class(TTabSheet) protected procedure CreateParams(var Params: TCreateParams); override; procedure Resize; override; procedure WndProc(var Message: TMessage); override; end; TAwPageControl = class(TPageControl) private function GetPage(Index: Integer): TAwTabSheet; protected procedure CreateParams(var Params: TCreateParams); override; public constructor Create(AOwner: TComponent); override; property Pages[Index: Integer]: TAwTabSheet read GetPage; default; end; implementation { TAwTabSheet } procedure TAwTabSheet.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do WindowClass.Style := WindowClass.Style and not (CS_HREDRAW or CS_VREDRAW); end; procedure TAwTabSheet.Resize; begin KillTimer(Handle, 1); SetTimer(Handle, 1, 50, nil); inherited Resize; end; procedure TAwTabSheet.WndProc(var Message: TMessage); begin if Message.Msg = WM_TIMER then begin KillTimer(Handle, 1); Invalidate; end else inherited WndProc(Message); end; { TAwPageControl } constructor TAwPageControl.Create(AOwner: TComponent); begin inherited Create(AOwner); DoubleBuffered := True; end; procedure TAwPageControl.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do WindowClass.Style := WindowClass.Style and not (CS_HREDRAW or CS_VREDRAW); end; function TAwPageControl.GetPage(Index: Integer): TAwTabSheet; begin Result := TAwTabSheet(inherited Pages[Index]); end; end.
unit unGlobals; interface const APP_ID = 'C5B7B5E3-5AEA-4589-AF35-77C5629F806B'; function HashMD5(source: string): string; function GenerateUUID: string; function GenerateSerial(clientId: string): string; function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string; function GetComputerName: string; function GetClientId: string; function ValidateLicence: Byte; procedure SaveSerialNumber(serial: string); implementation uses System.SysUtils, System.Classes, IdGlobal, IdHash, IdHashMessageDigest, ShlObj, Windows; function HashMD5(source: string): string; var md5: TIdHashMessageDigest5; begin md5 := TIdHashMessageDigest5.Create; try Result := md5.HashStringAsHex(source); finally FreeAndNil(md5); end; end; function GenerateUUID: string; var Uid: TGuid; res: HResult; begin res := CreateGuid(Uid); if res = S_OK then begin result := GuidToString(Uid); result := Copy(result, 2, result.Length - 2); end else result := '' end; function GenerateSerial(clientId: string): string; begin Result := HashMD5(clientId + APP_ID); end; // Gets path of special system folders // Call this routine as follows: // GetSpecialFolderPath (CSIDL_PERSONAL, false) // returns folder as result function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string; var FilePath: array [0..255] of char; begin SHGetSpecialFolderPath(0, @FilePath[0], FOLDER, CanCreate); Result := FilePath; end; function GetComputerName: string; var dwLength: dword; begin dwLength := 253; SetLength(result, dwLength+1); if not Windows.GetComputerName(pchar(result), dwLength) then raise exception.create('Computer name not detected'); result := pchar(result); end; function GetClientId: string; var licenceFile: TStringList; localAppFolder, uuid, computerName: string; begin licenceFile := TStringList.Create; try localAppFolder := GetSpecialFolderPath(CSIDL_LOCAL_APPDATA, false); if FileExists(localAppFolder+'\.appgincana') then licenceFile.LoadFromFile(localAppFolder+'\.appgincana'); if licenceFile.Count >= 2 then Result := licenceFile[1] else begin computerName := HashMD5(GetComputerName); uuid := GenerateUUID; licenceFile.Clear; licenceFile.Add(computerName); licenceFile.Add(uuid); licenceFile.SaveToFile(localAppFolder+'\.appgincana'); Result := uuid; end; finally FreeAndNil(licenceFile); end; end; // REALIZA VERIFICAÇÃO DE VALIDADE DA LICENÇA // RETORNOS // 0: OK // 1: INVALID_COMPUTER // 2: WITHOUT_SERIAL_NUMBER // 3: INVALID_SERIAL_NUMBER function ValidateLicence: byte; var localAppFolder, uuid, computerName, serialNumber: string; licenceFile: TStringList; begin Result := 0; localAppFolder := GetSpecialFolderPath(CSIDL_LOCAL_APPDATA, false); if not FileExists(localAppFolder+'\.appgincana') then Result := 2 else begin computerName := HashMD5(GetComputerName); licenceFile := TStringList.Create; try licenceFile.LoadFromFile(localAppFolder+'\.appgincana'); try if licenceFile[0] <> computerName then Result := 1 else begin case licenceFile.Count of // possui somente identificação do computador // cria client_id 1: begin uuid := GenerateUUID; licenceFile.Add(uuid); licenceFile.SaveToFile(localAppFolder+'\.appgincana'); Result := 2; end; // possui somente id do computador e client_id 2: begin Result := 2; end; // possui também número de série // verifica se é válido 3: begin serialNumber := GenerateSerial(licenceFile[1]); if licenceFile[2] <> serialNumber then Result := 3; end; end; end; except Result := 2; end; finally FreeAndNil(licenceFile); end; end; end; procedure SaveSerialNumber(serial: string); var licenceFile: TStringList; localAppFolder: string; begin licenceFile := TStringList.Create; try localAppFolder := GetSpecialFolderPath(CSIDL_LOCAL_APPDATA, false); licenceFile.LoadFromFile(localAppFolder+'\.appgincana'); case licenceFile.Count of 2: licenceFile.Add(serial); 3: licenceFile[2] := serial; end; licenceFile.SaveToFile(localAppFolder+'\.appgincana'); finally FreeAndNil(licenceFile); end; end; end.
unit TipoAmbienteNFe; interface type TTipoAmbienteNFe = (tanfeNenhum=-1, tanfeProducao=0, tanfeHomologacao=1); type TTipoAmbienteNFeUtilitario = class public class function DeEnumeradoParaString (TipoAmbiente :TTipoAmbienteNFe) :String; class function DeEnumeradoParaInteger(TipoAmbiente :TTipoAmbienteNFe) :Integer; class function DeStringParaEnumerado (TipoAmbiente :String) :TTipoAmbienteNFe; class function DeIntegerParaEnumerado(TipoAmbiente :Integer) :TTipoAmbienteNFe; end; implementation { TTipoAmbienteNFeUtilitario } class function TTipoAmbienteNFeUtilitario.DeEnumeradoParaInteger( TipoAmbiente: TTipoAmbienteNFe): Integer; begin case TipoAmbiente of tanfeProducao: result := 0; tanfeHomologacao: result := 1; else result := -1; end; end; class function TTipoAmbienteNFeUtilitario.DeEnumeradoParaString( TipoAmbiente: TTipoAmbienteNFe): String; begin case TipoAmbiente of tanfeProducao: result := 'P'; tanfeHomologacao: result := 'H'; else result := ''; end; end; class function TTipoAmbienteNFeUtilitario.DeIntegerParaEnumerado( TipoAmbiente: Integer): TTipoAmbienteNFe; begin case TipoAmbiente of 0: result := tanfeProducao; 1: result := tanfeHomologacao; else result := tanfeNenhum; end; end; class function TTipoAmbienteNFeUtilitario.DeStringParaEnumerado( TipoAmbiente: String): TTipoAmbienteNFe; begin case TipoAmbiente[1] of 'P': result := tanfeProducao; 'H': result := tanfeHomologacao; else result := tanfeNenhum; end; end; end.
unit U_Traceroute.View; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, ipwcore, ipwtypes, ipwtraceroute, FMX.StdCtrls, FMX.Edit, FMX.Objects, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.Layouts, System.ImageList, FMX.ImgList, System.StrUtils; type TTracerouteView = class(TForm) ImageList1: TImageList; LayoutContent: TLayout; MemoTrace: TMemo; LayoutHeader: TLayout; Layout1: TLayout; Text1: TText; Text2: TText; Edit1: TEdit; Edit2: TEdit; SpeedButton1: TSpeedButton; StatusBar1: TStatusBar; Text3: TText; ipwTraceRoute1: TipwTraceRoute; Text4: TText; Timer1: TTimer; procedure SpeedButton1Click(Sender: TObject); procedure ipwTraceRoute1Hop(Sender: TObject; HopNumber: Integer; const HostAddress: string; Duration: Integer); procedure Timer1Timer(Sender: TObject); private var fFim : boolean; fTempoTotal : Integer; fMediaTempo : Single; fTempo : TDateTime; public constructor create(Sender : TComponent; address : String); end; implementation {$R *.fmx} { TForm2 } constructor TTracerouteView.create(Sender: TComponent; address: String); begin inherited Create(Sender); ipwTraceRoute1.Config('ReceiveAllMode=0'); ipwTraceRoute1.LocalHost := address; end; procedure TTracerouteView.ipwTraceRoute1Hop(Sender: TObject; HopNumber: Integer; const HostAddress: string; Duration: Integer); begin if not fFim then begin inc(fTempoTotal, Duration); MemoTrace.Lines.Add( format( '%d - %s %dms %s', [HopNumber, HostAddress, Duration, ifthen(ipwTraceRoute1.Idle, 'Final', EmptyStr)] ) ); if ipwTraceRoute1.Idle then begin fMediaTempo := fTempoTotal / MemoTrace.Lines.Count; Text3.Text := Format( 'Tempo total: %dms Média: %.1fms', [fTempoTotal, fMediaTempo] ); Timer1.Enabled := False; fFim := not fFim; ipwTraceRoute1.Reset; end; end; end; procedure TTracerouteView.SpeedButton1Click(Sender: TObject); begin MemoTrace.Lines.Clear; fFim := False; fTempo := now(); fTempoTotal := 0; fMediaTempo := 0; Text3.Text := EmptyStr; Timer1.Enabled := true; if Edit1.Text <> EmptyStr then begin with ipwTraceRoute1 do begin HopLimit := ifThen(Edit2.Text <> EmptyStr, Edit2.Text, '64').ToInteger; RemoteHost := Edit1.Text; TraceTo(Edit1.Text); end; end; end; procedure TTracerouteView.Timer1Timer(Sender: TObject); begin Text4.Text := 'Processando: '+ FormatDateTime('hh:nn:ss', now - fTempo); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Image1: TImage; Timer1: TTimer; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } Type TCircle= Record rad:integer; xmin:integer; xmax:integer; ymin:integer; ymax:integer; sx:integer; sy:integer; dx:integer; dy:integer; end; Type TColor= Record R:integer; G:integer; B:integer; end; var Circle:TCircle; i:integer; circles:array[0..5] of TCircle; color:array[0..5] of TColor; procedure LoadCircles; var i:integer; begin for i:=1 to 5 do begin circles[i].rad:=10+random(40); circles[i].xmin:=circles[i].rad; circles[i].ymin:=circles[i].rad; circles[i].xmax:=Form1.Image1.Canvas.Width-circles[i].rad; circles[i].ymax:=Form1.Image1.Canvas.Height-circles[i].rad; circles[i].sx:=circles[i].xmin+random(circles[i].xmax-circles[i].xmin+1); circles[i].sy:=circles[i].ymin+random(circles[i].ymax-circles[i].ymin+1); circles[i].dx:=1+random(10-1+1); circles[i].dy:=circles[i].dx; end; end; procedure LoadColor; var i:integer; begin for i:=1 to 5 do begin color[i].R:=random(256); color[i].G:=random(256); color[i].B:=random(256); end; end; procedure Move; begin if (circles[i].sx>=circles[i].xmax) or (circles[i].sx<=circles[i].rad) then circles[i].dx:=0-circles[i].dx; circles[i].sx:=circles[i].sx+circles[i].dx; if (circles[i].sy>=circles[i].ymax) or (circles[i].sy<=circles[i].rad) then circles[i].dy:=0-circles[i].dy; circles[i].sy:=circles[i].sy+circles[i].dy; end; procedure Draw; begin Form1.Image1.Canvas.Brush.Color:=(color[i].R*color[i].G*color[i].B); Form1.Image1.Canvas.Pen.Color:=clWhite; Form1.Image1.Canvas.Ellipse(circles[i].sx-circles[i].rad,circles[i].sy-circles[i].rad,circles[i].sx+circles[i].rad,circles[i].sy+circles[i].rad); end; procedure Clear(); begin Form1.Image1.Canvas.Pen.Color:=clWhite; Form1.Image1.Canvas.Brush.Color:=clWhite; Form1.Image1.Canvas.Rectangle(Form1.Image1.ClientRect); end; procedure TForm1.Button1Click(Sender: TObject); begin LoadCircles; LoadColor; Form1.Timer1.Enabled:=true; Form1.Timer1.Interval:=1+random(10-1+1); {Clear; for i:=1 to 5 do begin; Move; Draw; end;} end; procedure TForm1.Button2Click(Sender: TObject); begin Form1.Timer1.Enabled:=false; end; procedure TForm1.FormCreate(Sender: TObject); begin Image1.Canvas.Rectangle(Image1.ClientRect); Canvas.Pen.Color:=clBlack; Randomize; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Clear; for i:=1 to 5 do begin; Move; Draw; end; end; end.
unit BmpUtils; interface uses Windows, Graphics, Global, ExtCtrls;//, Bitmap; type T3x3StructuredElement = array[1..3,1..3] of Boolean; T2x2StructuredElement = array[1..2,1..2] of Boolean; const Simple3x3Element : T3x3StructuredElement = ((True,True,True),(True,True,True),(True,True,True)); function CreateImageBmp:TBitmap; procedure ClearBmp(Bmp:TBitmap;Color:TColor); procedure ClearBmpAsm(Bmp:TBitmap); procedure DrawSobelBmp(SrcBmp,SobelBmp:TBitmap;Threshold:Integer); procedure DrawAnalogSobelBmp(SrcBmp,SobelBmp:TBitmap;Scale:Single); procedure DrawShadows(Bmp:TBitmap;Threshold:Integer); procedure DrawGradientBmp(SrcBmp,DestBmp:TBitmap;Threshold:Integer); procedure DrawSmoothBmp(SrcBmp,DestBmp:TBitmap); procedure DrawMonoBmp(SrcBmp,DestBmp:TBitmap); procedure SubtractBmp(Bmp1,Bmp2,Bmp3:TBitmap); procedure IntensifyBmp(Bmp:TBitmap;Scale:Single); procedure ThresholdBmp(Bmp:TBitmap;Threshold:Integer); procedure ConvertBmpToIntensityMap(Bmp:TBitmap;Threshold:Byte); procedure DrawHistogram(SourceBmp,DestBmp:TBitmap); procedure DrawTextOnBmp(Bmp:TBitmap;TextStr:String); procedure DrawTextOnBmp2(TextStr:String;Bmp:TBitmap); procedure ShowFrameRateOnBmp(Bmp:TBitmap;FrameRate:Single); procedure SubtractColorBmp(Bmp1,Bmp2,Bmp3:TBitmap); procedure MagnifyScreen(Bmp:TBitmap;Scale:Integer); procedure MagnifyCopy(SrcBmp,IBmp,DestBmp:TBitmap;Xc,Yc,Scale:Integer); procedure SwapRB(Bmp:TBitmap); procedure SubtractBmpAsm(Bmp1,Bmp2,TargetBmp:TBitmap); procedure SubtractBmpAsmAbs(Bmp1,Bmp2,TargetBmp:TBitmap); procedure SubtractBmpAsmAbsSquared(Bmp1,Bmp2,TargetBmp:TBitmap); procedure SubtractColorBmpAsm(Bmp1,Bmp2,TargetBmp:TBitmap); procedure DrawSmoothBmpAsm(SrcBmp,DestBmp:TBitmap); procedure DilateBmp3x3Asm(SrcBmp,DestBmp:TBitmap;Threshold:Byte); procedure ThresholdBmpAsm(Bmp:TBitmap;Threshold:Byte); function BytesPerPixel(Bmp:TBitmap):Integer; procedure DrawXHairs(Bmp:TBitmap;X,Y,R:Integer); procedure FlipBmp(SrcBmp,DestBmp:TBitmap); procedure MirrorBmp(SrcBmp,DestBmp:TBitmap); procedure FlipAndMirrorBmp(SrcBmp,DestBmp:TBitmap); procedure OrientBmp(SrcBmp,DestBmp:TBitmap;FlipImage,MirrorImage:Boolean); function CreateBmpForPaintBox(PaintBox:TPaintBox):TBitmap; procedure InitBmpDataFromBmp(BmpData:PByte;Bmp:TBitmap;X1,Y1,X2,Y2:Integer); procedure InitBmpFromBmpData(Bmp:TBitmap;BmpData:PByte;BmpW,BmpH:Integer); procedure SubtractColorBmpAsmAbs(Bmp1,Bmp2,TargetBmp:TBitmap); procedure OutlinePixel(Bmp:TBitmap;X,Y:Integer); procedure DrawTestPatternOnBmp(Bmp:TBitmap;BackColor,LineColor:TColor;Spacing:Integer); procedure HalfScaleBmp(SrcBmp,DestBmp:TBitmap); procedure QuarterScaleBmp(SrcBmp,DestBmp:TBitmap); function AverageI(Bmp:TBitmap):Single; function BiggestFontSize(Bmp:TBitmap;Txt:String;W,H:Integer):Integer; implementation uses SysUtils, Classes, CameraU; function BiggestFontSize(Bmp:TBitmap;Txt:String;W,H:Integer):Integer; var TW,TH : Integer; begin Result:=6; repeat Inc(Result); Bmp.Canvas.Font.Size:=Result; TW:=Bmp.Canvas.TextWidth(Txt); TH:=Bmp.Canvas.TextHeight(Txt); until (TW>W) or (TH>H); Dec(Result); end; function CreateBmpForPaintBox(PaintBox:TPaintBox):TBitmap; begin Result:=TBitmap.Create; Result.Width:=PaintBox.Width; Result.Height:=PaintBox.Height; Result.PixelFormat:=pf24Bit; end; function CreateImageBmp:TBitmap; begin Result:=TBitmap.Create; Result.PixelFormat:=pf24Bit; end; procedure ClearBmp(Bmp:TBitmap;Color:TColor); begin Bmp.Canvas.Brush.Color:=Color; Bmp.Canvas.FillRect(Rect(0,0,Bmp.Width,Bmp.Height)); end; procedure DrawSobelBmp(SrcBmp,SobelBmp:TBitmap;Threshold:Integer); var Line1 : PByteArray; Line2 : PByteArray; Line3 : PByteArray; SobelLine : PByteArray; S1,S2,S : Integer; X,Y : Integer; P1,P2,P3 : Integer; P4,P5,P6 : Integer; P7,P8,P9 : Integer; begin SobelBmp.Canvas.Brush.Color:=clBlack; SobelBmp.Canvas.FillRect(Rect(0,0,SobelBmp.Width,SobelBmp.Height)); for Y:=1 to SrcBmp.Height-2 do begin Line1:=SrcBmp.ScanLine[Y-1]; Line2:=SrcBmp.ScanLine[Y]; Line3:=SrcBmp.ScanLine[Y+1]; SobelLine:=SobelBmp.ScanLine[Y]; for X:=1 to SrcBmp.Width-2 do begin P1:=Line1^[(X-1)*3]; P2:=Line1^[X*3]; P3:=Line1^[(X+1)*3]; P4:=Line2^[(X-1)*3]; P5:=Line2^[X*3]; P6:=Line2^[(X+1)*3]; P7:=Line3^[(X-1)*3]; P8:=Line3^[X*3]; P9:=Line3^[(X+1)*3]; S1:=P3+2*P6+P9-P1-2*P4-P7; S2:=P1+2*P2+P3-P7-2*P8-P9; S:=Sqr(S1)+Sqr(S2); if S>Threshold then SobelLine^[X*3+0]:=255; end; end; end; //////////////////////////////////////////////////////////////////////////////// // Same as "DrawSobelBmp" except that the actual intensity value is scaled // instead of set to 255 or 0 //////////////////////////////////////////////////////////////////////////////// procedure DrawAnalogSobelBmp(SrcBmp,SobelBmp:TBitmap;Scale:Single); var Line1 : PByteArray; Line2 : PByteArray; Line3 : PByteArray; SobelLine : PByteArray; S1,S2,S : Integer; X,Y : Integer; P1,P2,P3 : Integer; P4,P5,P6 : Integer; P7,P8,P9 : Integer; begin SobelBmp.Canvas.Brush.Color:=clBlack; SobelBmp.Canvas.FillRect(Rect(0,0,SobelBmp.Width,SobelBmp.Height)); for Y:=1 to SrcBmp.Height-2 do begin Line1:=SrcBmp.ScanLine[Y-1]; Line2:=SrcBmp.ScanLine[Y]; Line3:=SrcBmp.ScanLine[Y+1]; SobelLine:=SobelBmp.ScanLine[Y]; for X:=1 to SrcBmp.Width-2 do begin P1:=Line1^[(X-1)*3]; P2:=Line1^[X*3]; P3:=Line1^[(X+1)*3]; P4:=Line2^[(X-1)*3]; P5:=Line2^[X*3]; P6:=Line2^[(X+1)*3]; P7:=Line3^[(X-1)*3]; P8:=Line3^[X*3]; P9:=Line3^[(X+1)*3]; S1:=P3+2*P6+P9-P1-2*P4-P7; S2:=P1+2*P2+P3-P7-2*P8-P9; S:=Round((Sqr(S1)+Sqr(S2))*Scale); if S>255 then SobelLine^[X*3+0]:=255 else SobelLine^[X*3+0]:=S; end; end; end; procedure DrawShadows(Bmp:TBitmap;Threshold:Integer); const EdgeColor = clRed; MinSize = 3; var X,Y,DarkY,LightY : Integer; LookingForDark,Dark : Boolean; Intensity : Single; begin for X:=0 to Bmp.Width-1 do begin LookingForDark:=True; Y:=0; DarkY:=0; LightY:=0; Bmp.Canvas.Pen.Color:=EdgeColor; repeat Inc(Y,MinSize); Intensity:=Bmp.Canvas.Pixels[X,Y]; Dark:=Intensity<Threshold; if LookingForDark and Dark then begin DarkY:=Y; // back up until we're in the light again repeat Dec(DarkY); Intensity:=Bmp.Canvas.Pixels[X,DarkY] and $FF; Dark:=Intensity<Threshold; until (not Dark) or (DarkY=LightY); Bmp.Canvas.Pixels[X,DarkY]:=EdgeColor; DarkY:=Y; LookingForDark:=False; end else if (not LookingForDark) and (not Dark) then begin LightY:=Y; // back up until we're in the dark again repeat Dec(LightY); Intensity:=Bmp.Canvas.Pixels[X,LightY] and $FF; Dark:=Intensity<Threshold; until Dark or (LightY=DarkY); Bmp.Canvas.Pixels[X,LightY+1]:=EdgeColor; LookingForDark:=True; LightY:=Y; end; until (Y+MinSize>=Bmp.Height-1); end; end; procedure DrawGradientBmp(SrcBmp,DestBmp:TBitmap;Threshold:Integer); var X,Y,I1,I2 : Integer; Gx,Gy,Gt : Single; Line1,Line2 : PByteArray; DestLine : PByteArray; begin DestBmp.Canvas.Brush.Color:=clBlack; DestBmp.Canvas.FillRect(Rect(0,0,DestBmp.Width,DestBmp.Height)); for Y:=1 to SrcBmp.Height-1 do begin Line1:=SrcBmp.ScanLine[Y-1]; Line2:=SrcBmp.ScanLine[Y]; DestLine:=DestBmp.ScanLine[Y]; for X:=1 to SrcBmp.Width-1 do begin I1:=Line2[X*3]; I2:=Line2[(X-1)*3]; Gx:=I1-I2; I2:=Line1[X*3]; Gy:=I1-I2; Gt:=Sqr(Gx)+Sqr(Gy); if Gt>Threshold then DestLine[X*3]:=255; end; end; end; //////////////////////////////////////////////////////////////////////////////// // 123 // 456 Pixel #5 = (P2+P4+P5+P6+P8)/5 // 789 //////////////////////////////////////////////////////////////////////////////// procedure DrawSmoothBmp(SrcBmp,DestBmp:TBitmap); var Line1,Line2,Line3 : PByteArray; DestLine : PByteArray; X,Y,V4,V6,V,I : Integer; begin for Y:=0 to SrcBmp.Height-1 do begin if Y=0 then Line1:=SrcBmp.ScanLine[0] else Line1:=SrcBmp.ScanLine[Y-1]; Line2:=SrcBmp.ScanLine[Y]; DestLine:=DestBmp.ScanLine[Y]; if Y=SrcBmp.Height-1 then Line3:=Line2 else Line3:=SrcBmp.ScanLine[Y+1]; for X:=0 to SrcBmp.Width-1 do begin I:=X*3; if X=0 then V4:=Line2[0] else V4:=Line2[I-3]; if X=SrcBmp.Width-1 then V6:=Line2[I] else V6:=Line2[I+3]; V:=(Line1[I]+V4+Line2[I]+V6+Line3[I]) div 5; if V>255 then V:=255; DestLine[I+0]:=V; // blue DestLine[I+1]:=V; // green DestLine[I+2]:=V; // red end; end; end; procedure DrawMonoBmp(SrcBmp,DestBmp:TBitmap); var I,V,X,Y : Integer; SrcLine,DestLine : PByteArray; begin for Y:=0 to SrcBmp.Height-1 do begin SrcLine:=SrcBmp.ScanLine[Y]; DestLine:=DestBmp.ScanLine[Y]; for X:=0 to SrcBmp.Width-1 do begin I:=X*3; V:=SrcLine[I]; DestLine[I+0]:=V; DestLine[I+1]:=V; DestLine[I+2]:=V; end; end; end; //////////////////////////////////////////////////////////////////////////////// // Bmp3 = Bmp1 - Bmp2 //////////////////////////////////////////////////////////////////////////////// procedure SubtractBmp(Bmp1,Bmp2,Bmp3:TBitmap); var Line1,Line2,Line3 : PByteArray; X,Y,I,V : Integer; begin for Y:=0 to Bmp1.Height-1 do begin Line1:=Bmp1.ScanLine[Y]; Line2:=Bmp2.ScanLine[Y]; Line3:=Bmp3.ScanLine[Y]; for X:=0 to Bmp1.Width-1 do begin I:=X*3; V:=Line1^[I]-Line2^[I]; if V<0 then V:=0; Line3^[I+0]:=V; Line3^[I+1]:=V; Line3^[I+2]:=V; end; end; end; //////////////////////////////////////////////////////////////////////////////// // Bmp3 = Bmp1 - Bmp2 //////////////////////////////////////////////////////////////////////////////// procedure SubtractColorBmp(Bmp1,Bmp2,Bmp3:TBitmap); var Line1,Line2,Line3 : PByteArray; X,Y,I,V : Integer; begin for Y:=0 to Bmp1.Height-1 do begin Line1:=Bmp1.ScanLine[Y]; Line2:=Bmp2.ScanLine[Y]; Line3:=Bmp3.ScanLine[Y]; for X:=0 to Bmp1.Width-1 do begin V:=0; for I:=X*3 to X*3+2 do begin V:=V+Abs(Line1^[I]-Line2^[I]); end; if V>255 then V:=255; for I:=X*3 to X*3+2 do Line3^[I]:=V; end; end; end; function ClipToByte(V:Single):Byte; begin if V<0 then Result:=0 else if V>255 then Result:=255 else Result:=Round(V); end; procedure IntensifyBmp(Bmp:TBitmap;Scale:Single); var I,X,Y : Integer; Line : PByteArray; begin for Y:=0 to Bmp.Height-1 do begin Line:=Bmp.ScanLine[Y]; for X:=0 to Bmp.Width-1 do begin I:=X*3; Line^[I+0]:=ClipToByte(Line^[I+0]*Scale); Line^[I+1]:=ClipToByte(Line^[I+1]*Scale); Line^[I+2]:=ClipToByte(Line^[I+2]*Scale); end; end; end; procedure ThresholdBmp(Bmp:TBitmap;Threshold:Integer); var I,X,Y : Integer; Line : PByteArray; begin for Y:=0 to Bmp.Height-1 do begin Line:=Bmp.ScanLine[Y]; for X:=0 to Bmp.Width-1 do begin I:=X*3; if Line^[I+0]<Threshold then begin Line^[I+0]:=0; Line^[I+1]:=0; Line^[I+2]:=0; end; end; end; end; procedure ConvertBmpToIntensityMap(Bmp:TBitmap;Threshold:Byte); var X,Y,V : Integer; Line : PByteArray; begin for Y:=0 to Bmp.Height-1 do begin Line:=Bmp.ScanLine[Y]; for X:=0 to Bmp.Width-1 do begin if Line^[X*3]>Threshold then V:=$FF else V:=0; Line^[X*3+0]:=0; // blue Line^[X*3+1]:=V; // green Line^[X*3+2]:=V; // red end; end; end; procedure DrawHistogram(SourceBmp,DestBmp:TBitmap); var Red : array[0..255] of Integer; Green : array[0..255] of Integer; Blue : array[0..255] of Integer; Line : PByteArray; X,Y,I : Integer; Max : Integer; R,G,B : Integer; begin if SourceBmp.Width=0 then Exit; // find the values FillChar(Red,SizeOf(Red),0); FillChar(Green,SizeOf(Green),0); FillChar(Blue,SizeOf(Blue),0); for Y:=0 to SourceBmp.Height-1 do begin Line:=SourceBmp.ScanLine[Y]; for X:=0 to SourceBmp.Width-1 do begin I:=X*3; R:=Line^[I+2]; G:=Line^[I+1]; B:=Line^[I+0]; Inc(Red[R]); Inc(Green[G]); Inc(Blue[B]); end; end; // find the peak value for scaling Max:=0; for I:=0 to 255 do begin if Red[I]>Max then Max:=Red[I]; if Green[I]>Max then Max:=Green[I]; if Blue[I]>Max then Max:=Blue[I]; end; // draw the bmp with DestBmp.Canvas do begin // clear it Brush.Color:=$C8FAFA; FillRect(Rect(0,0,DestBmp.Width,DestBmp.Height)); // draw the red for I:=0 to 255 do begin X:=Round(DestBmp.Width*I/255); Y:=Round(DestBmp.Height*(1-Red[I]/Max)); Pen.Color:=clRed; if I=0 then MoveTo(X,Y) else LineTo(X,Y); end; // draw the green for I:=0 to 255 do begin X:=Round(DestBmp.Width*I/255); Y:=Round(DestBmp.Height*(1-Green[I]/Max)); Pen.Color:=clGreen; if I=0 then MoveTo(X,Y) else LineTo(X,Y); end; // draw the blue for I:=0 to 255 do begin X:=Round(DestBmp.Width*I/255); Y:=Round(DestBmp.Height*(1-Blue[I]/Max)); Pen.Color:=clBlue; if I=0 then MoveTo(X,Y) else LineTo(X,Y); end; end; end; procedure DrawTextOnBmp(Bmp:TBitmap;TextStr:String); var X,Y : Integer; begin with Bmp.Canvas do begin Font.Color:=clYellow; Font.Size:=12; Brush.Color:=clBlack; FillRect(Rect(0,0,Bmp.Width,Bmp.Height)); X:=(Bmp.Width-TextWidth(TextStr)) div 2; Y:=(Bmp.Height-TextHeight(TextStr)) div 2; TextOut(X,Y,TextStr); end; end; procedure DrawTextOnBmp2(TextStr:String;Bmp:TBitmap); var X,Y : Integer; begin with Bmp.Canvas do begin X:=(Bmp.Width-TextWidth(TextStr)) div 2; Y:=(Bmp.Height-TextHeight(TextStr)) div 2; TextOut(X,Y,TextStr); end; end; procedure ShowFrameRateOnBmp(Bmp:TBitmap;FrameRate:Single); begin with Bmp.Canvas do begin Font.Color:=clYellow; Font.Size:=8; Brush.Color:=clBlack; TextOut(5,Bmp.Height-15,FloatToStrF(FrameRate,ffFixed,9,3)); end; end; //////////////////////////////////////////////////////////////////////////////// // Magnifies a region of the screen around the mouse cursor. // Source rect width = scale*bmp.width // Source rect height = scale*bmp.height ////////////////////////////////////////////////////////////////////////////////// procedure MagnifyScreen(Bmp:TBitmap;Scale:Integer); var DeskTopHandle : THandle; DeskTopDC : HDC; MousePt : TPoint; SrcW,SrcH,X,Y : Integer; begin GetCursorPos(MousePt); DeskTopHandle:=GetDeskTopWindow; if DeskTopHandle>0 then with Bmp do begin DeskTopDC:=GetDC(DeskTopHandle); SrcW:=Width div Scale; SrcH:=Height div Scale; X:=MousePt.X-SrcW div 2; Y:=MousePt.Y-SrcH div 2; StretchBlt(Canvas.Handle,0,0,Width,Height,DeskTopDC,X,Y,SrcW,SrcH,SRCCOPY); end; end; procedure MagnifyCopy(SrcBmp,IBmp,DestBmp:TBitmap;Xc,Yc,Scale:Integer); const ShortR = 3; LongR = 8; var SrcW,SrcH,X,Y : Integer; begin SrcW:=DestBmp.Width div Scale; SrcH:=DestBmp.Height div Scale; X:=Xc-SrcW div 2; Y:=Yc-SrcH div 2; // copy the source over onto the intermediate bmp BitBlt(IBmp.Canvas.Handle,0,0,SrcW,SrcH,SrcBmp.Canvas.Handle,X,Y,SrcCopy); // draw some cross hairs in the middle with IBmp.Canvas do begin Pen.Color:=clLime; X:=SrcW div 2; Y:=SrcH div 2; MoveTo(X-LongR,Y); LineTo(X-ShortR+1,Y); MoveTo(X+ShortR,Y); LineTo(X+LongR+1,Y); MoveTo(X,Y-LongR); LineTo(X,Y-ShortR+1); MoveTo(X,Y+ShortR); LineTo(X,Y+LongR+1); end; // stretch it onto the dest bmp StretchBlt(DestBmp.Canvas.Handle,0,0,DestBmp.Width,DestBmp.Height, IBmp.Canvas.Handle,0,0,SrcW,SrcH,SrcCopy); end; procedure SwapRB(Bmp:TBitmap); var X,Y,R,B : Integer; Bpp,I : Integer; Line : PByteArray; begin Bpp:=BytesPerPixel(Bmp); for Y:=0 to Bmp.Height-1 do begin Line:=Bmp.ScanLine[Y]; for X:=0 to Bmp.Width-1 do begin I:=X*Bpp; B:=Line^[I]; R:=Line^[I+2]; Line^[I]:=R; Line^[I+2]:=B; end; end; end; function BytesPerPixel(Bmp:TBitmap):Integer; begin Case Bmp.PixelFormat of pf8Bit : Result:=1; pf16Bit : Result:=2; pf24Bit : Result:=3; pf32Bit : Result:=4; else Result:=4; end; end; //////////////////////////////////////////////////////////////////////////////// // 123 // 456 Pixel #5 = (P2+P4+P5+P6+P8)/5 // 789 //////////////////////////////////////////////////////////////////////////////// procedure DrawSmoothBmpAsm24Bit(SrcBmp,DestBmp:TBitmap); var Line1,Line2,Line3,DestLine : Pointer; BytesPerRow,MaxX,Row : DWord; Bpp : Integer; begin // Windows bitmaps start from the bottom Line1:=SrcBmp.ScanLine[0]; Line2:=SrcBmp.ScanLine[1]; Line3:=SrcBmp.ScanLine[2]; DestLine:=DestBmp.ScanLine[1]; // find how many bytes per row there are -> width*Bpp + a byte or two for padding BytesPerRow:=Integer(SrcBmp.ScanLine[0])-Integer(SrcBmp.ScanLine[1]); Bpp:=BytesPerPixel(SrcBmp); MaxX:=(SrcBmp.Width-2)*Bpp; Row:=DWord(SrcBmp.Height-3); asm PUSHA MOV EBX, Line1 // EBX = Line1 MOV ECX, Line2 // ECX = Line2 MOV ESI, Line3 // ESI = Line3 MOV EDI, DestLine // EDI = DestLine @YLoop : MOV EDX, 3 // EDX = column offset @XLoop : XOR AH, AH MOV AL, BYTE Ptr[EBX+EDX] // pixel #2 ADD AL, BYTE Ptr[ECX+EDX-3] // + pixel #4 JNC @NC1 INC AH @NC1 : ADD AL, BYTE Ptr[ECX+EDX] // + pixel #5 JNC @NC2 INC AH @NC2 : ADD AL, BYTE Ptr[ECX+EDX+3] // + pixel #6 JNC @NC3 INC AH @NC3 : ADD AL, BYTE Ptr[ESI+EDX] // + pixel #7 JNC @NC4 INC AH @NC4 : SHR AX, 2 CMP AX, 256 JL @Store MOV AX, 255 @Store : MOV BYTE Ptr[EDI+EDX+0], AL // store it in the target's blue pixel MOV BYTE Ptr[EDI+EDX+1], AL // store it in the target's green pixel MOV BYTE Ptr[EDI+EDX+2], AL // store it in the target's red pixel ADD EDX, 3 // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row SUB EBX, BytesPerRow // go to the next row SUB ECX, BytesPerRow SUB ESI, BytesPerRow // go to the next row SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; //////////////////////////////////////////////////////////////////////////////// // 123 // 456 Pixel #5 = (P2+P4+P5+P6+P8)/5 // 789 //////////////////////////////////////////////////////////////////////////////// procedure DrawSmoothBmpAsm32Bit(SrcBmp,DestBmp:TBitmap); var Line1,Line2,Line3,DestLine : Pointer; BytesPerRow,MaxX,Row : DWord; begin // Windows bitmaps start from the bottom Line1:=SrcBmp.ScanLine[0]; Line2:=SrcBmp.ScanLine[1]; Line3:=SrcBmp.ScanLine[2]; DestLine:=DestBmp.ScanLine[1]; // find how many bytes per row there are -> width*Bpp + a byte or two for padding BytesPerRow:=Integer(SrcBmp.ScanLine[0])-Integer(SrcBmp.ScanLine[1]); MaxX:=(SrcBmp.Width-2)*4; Row:=DWord(SrcBmp.Height-3); asm PUSHA MOV EBX, Line1 // EBX = Line1 MOV ECX, Line2 // ECX = Line2 MOV ESI, Line3 // ESI = Line3 MOV EDI, DestLine // EDI = DestLine @YLoop : MOV EDX, 4 // EDX = column offset @XLoop : XOR AH, AH MOV AL, BYTE Ptr[EBX+EDX] // pixel #2 ADD AL, BYTE Ptr[ECX+EDX-4] // + pixel #4 JNC @NC1 INC AH @NC1 : ADD AL, BYTE Ptr[ECX+EDX] // + pixel #5 JNC @NC2 INC AH @NC2 : ADD AL, BYTE Ptr[ECX+EDX+4] // + pixel #6 JNC @NC3 INC AH @NC3 : ADD AL, BYTE Ptr[ESI+EDX] // + pixel #7 JNC @NC4 INC AH @NC4 : SHR AX, 2 CMP AX, 256 JL @Store MOV AX, 255 @Store : MOV BYTE Ptr[EDI+EDX+0], AL // store it in the target's blue pixel MOV BYTE Ptr[EDI+EDX+1], AL // store it in the target's green pixel MOV BYTE Ptr[EDI+EDX+2], AL // store it in the target's red pixel ADD EDX, 4 // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row SUB EBX, BytesPerRow // go to the next row SUB ECX, BytesPerRow SUB ESI, BytesPerRow // go to the next row SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; //////////////////////////////////////////////////////////////////////////////// // 123 // 456 Pixel #5 = (P2+P4+P5+P6+P8)/5 // 789 //////////////////////////////////////////////////////////////////////////////// procedure DrawSmoothBmpAsm(SrcBmp,DestBmp:TBitmap); var Bpp : Integer; begin Bpp:=BytesPerPixel(SrcBmp); if Bpp=3 then DrawSmoothBmpAsm24Bit(SrcBmp,DestBmp) else DrawSmoothBmpAsm32Bit(SrcBmp,DestBmp); end; procedure DilateBmp3x3Asm24Bit(SrcBmp,DestBmp:TBitmap;Threshold:Byte); var SrcLine,DestLine1,DestLine2,DestLine3 : Pointer; BytesPerRow,MaxX,Row : DWord; begin // ClearBmp(SrcBmp,clBlack); ClearBmp(DestBmp,clBlack); // Windows bitmaps start from the bottom SrcLine:=SrcBmp.ScanLine[1]; DestLine1:=DestBmp.ScanLine[0]; DestLine2:=DestBmp.ScanLine[1]; DestLine3:=DestBmp.ScanLine[2]; // find how many bytes per row there are -> width*Bpp + a byte or two for padding BytesPerRow:=Integer(SrcBmp.ScanLine[0])-Integer(SrcBmp.ScanLine[1]); MaxX:=(SrcBmp.Width-2)*3; Row:=DWord(SrcBmp.Height-3); asm PUSHA MOV EBX, SrcLine // EBX = SrcLine1 MOV ECX, DestLine1 // ECX = DestLine1 MOV ESI, DestLine2 // ESI = DestLine2 MOV EDI, DestLine3 // EDI = DestLine3 MOV AL, Threshold @YLoop : MOV EDX, 3 // EDX = column offset @XLoop : // MOV AH, BYTE Ptr[EBX+EDX] // CMP AH, AL // JL @NextX // CMP AL, BYTE Ptr[EBX+EDX] CMP AL, BYTE Ptr[EBX+EDX] //, AL JA @NextX MOV BYTE Ptr[ECX+EDX+0], 255 MOV BYTE Ptr[ESI+EDX-3], 255 MOV BYTE Ptr[ESI+EDX+0], 255 MOV BYTE Ptr[ESI+EDX+3], 255 MOV BYTE Ptr[EDI+EDX+0], 255 @NextX : ADD EDX, 3 // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row // go to the next row SUB EBX, BytesPerRow SUB ECX, BytesPerRow SUB ESI, BytesPerRow SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; procedure DilateBmp3x3Asm32Bit(SrcBmp,DestBmp:TBitmap;Threshold:Byte); var SrcLine,DestLine1,DestLine2,DestLine3 : Pointer; BytesPerRow,MaxX,Row : DWord; begin // ClearBmp(SrcBmp,clBlack); ClearBmp(DestBmp,clBlack); // Windows bitmaps start from the bottom SrcLine:=SrcBmp.ScanLine[1]; DestLine1:=DestBmp.ScanLine[0]; DestLine2:=DestBmp.ScanLine[1]; DestLine3:=DestBmp.ScanLine[2]; // find how many bytes per row there are -> width*Bpp + a byte or two for padding BytesPerRow:=Integer(SrcBmp.ScanLine[0])-Integer(SrcBmp.ScanLine[1]); MaxX:=(SrcBmp.Width-2)*4; Row:=DWord(SrcBmp.Height-3); asm PUSHA MOV EBX, SrcLine // EBX = SrcLine1 MOV ECX, DestLine1 // ECX = DestLine1 MOV ESI, DestLine2 // ESI = DestLine2 MOV EDI, DestLine3 // EDI = DestLine3 MOV AL, Threshold @YLoop : MOV EDX, 4 // EDX = column offset @XLoop : // MOV AH, BYTE Ptr[EBX+EDX] // CMP AH, AL // JL @NextX // CMP AL, BYTE Ptr[EBX+EDX] CMP AL, BYTE Ptr[EBX+EDX] //, AL JA @NextX MOV BYTE Ptr[ECX+EDX+0], 255 MOV BYTE Ptr[ESI+EDX-4], 255 MOV BYTE Ptr[ESI+EDX+0], 255 MOV BYTE Ptr[ESI+EDX+4], 255 MOV BYTE Ptr[EDI+EDX+0], 255 @NextX : ADD EDX, 4 // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row // go to the next row SUB EBX, BytesPerRow SUB ECX, BytesPerRow SUB ESI, BytesPerRow SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; procedure DilateBmp3x3Asm(SrcBmp,DestBmp:TBitmap;Threshold:Byte); var Bpp : Integer; begin Bpp:=BytesPerPixel(SrcBmp); if Bpp=3 then DilateBmp3x3Asm24Bit(SrcBmp,DestBmp,Threshold) else DilateBmp3x3Asm32Bit(SrcBmp,DestBmp,Threshold); end; procedure ThresholdBmpAsm(Bmp:TBitmap;Threshold:Byte); var Line : Pointer; MaxX,Row : DWord; BytesPerRow : DWord; Bpp : Integer; begin // Windows bitmaps start from the bottom Line:=Bmp.ScanLine[0]; // find how many bytes per row there are -> width*Bpp+ a byte or two BytesPerRow:=Integer(Bmp.ScanLine[0])-Integer(Bmp.ScanLine[1]); Bpp:=BytesPerPixel(Bmp); MaxX:=Bmp.Width*Bpp; Row:=DWord(Bmp.Height-2); asm PUSHA MOV EBX, Line // EBX = Line MOV AL, Threshold @YLoop : MOV EDX, 0 // EDX = column offset @XLoop : CMP AL, BYTE Ptr[EBX+EDX] JA @ClearPixel MOV BYTE Ptr[EBX+EDX+0], 255 // store it in the target's blue pixel MOV BYTE Ptr[EBX+EDX+1], 255 // store it in the target's green pixel MOV BYTE Ptr[EBX+EDX+2], 255 // store it in the target's red pixel JMP @NextX @ClearPixel : MOV BYTE Ptr[EBX+EDX+0], 0 // store it in the target's blue pixel MOV BYTE Ptr[EBX+EDX+1], 0 // store it in the target's green pixel MOV BYTE Ptr[EBX+EDX+2], 0 // store it in the target's red pixel @NextX : ADD EDX, Bpp // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row // go to the next row SUB EBX, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; //////////////////////////////////////////////////////////////////////////////// // TargetBmp = Bmp1 - Bmp2 // They should probably all be the same size. :) //////////////////////////////////////////////////////////////////////////////// procedure SubtractBmpAsmAbs(Bmp1,Bmp2,TargetBmp:TBitmap); var Bmp1Ptr,Bmp2Ptr : Pointer; TargetPtr : Pointer; MaxX,Row : DWord; BytesPerRow : DWord; Bpp : Integer; begin // Windows bitmaps start from the bottom Bmp1Ptr:=Bmp1.ScanLine[0]; Bmp2Ptr:=Bmp2.ScanLine[0]; TargetPtr:=TargetBmp.ScanLine[0]; // find how many bytes per row there are -> width*4+ a byte or two BytesPerRow:=Integer(Bmp1.ScanLine[0])-Integer(Bmp1.ScanLine[1]); Bpp:=BytesPerPixel(Bmp1); MaxX:=Bmp1.Width*Bpp; Row:=DWord(Bmp1.Height-1); asm PUSHA MOV ESI, Bmp1Ptr // ESI = Bmp1 MOV EBX, Bmp2Ptr // EBX = Bmp2 MOV EDI, TargetPtr // EDI = TargetBmp @YLoop : MOV EDX, 0 // EDX = column offset @XLoop : MOV AL, BYTE Ptr[ESI+EDX] // load bmp1's blue pixel SUB AL, BYTE Ptr[EBX+EDX] // subtract bmp2's blue pixel JNC @Positive MOV AL, BYTE Ptr[EBX+EDX] // load bmp2's blue pixel SUB AL, BYTE Ptr[ESI+EDX] // subtract bmp1's blue pixel @Positive: MOV BYTE Ptr[EDI+EDX+0], AL // store it in the target's blue pixel MOV BYTE Ptr[EDI+EDX+1], AL // store it in the target's green pixel MOV BYTE Ptr[EDI+EDX+2], AL // store it in the target's red pixel ADD EDX, Bpp // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row SUB ESI, BytesPerRow // go to the next row SUB EBX, BytesPerRow SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; //////////////////////////////////////////////////////////////////////////////// // TargetBmp = Bmp1 - Bmp2 // They should probably all be the same size. :) //////////////////////////////////////////////////////////////////////////////// procedure SubtractBmpAsmAbs32Bit(Bmp1,Bmp2,TargetBmp:TBitmap); var Bmp1Ptr,Bmp2Ptr : Pointer; TargetPtr : Pointer; MaxX,Row : DWord; BytesPerRow : DWord; Bpp : Integer; begin // Windows bitmaps start from the bottom Bmp1Ptr:=Bmp1.ScanLine[0]; Bmp2Ptr:=Bmp2.ScanLine[0]; TargetPtr:=TargetBmp.ScanLine[0]; // find how many bytes per row there are -> width*4+ a byte or two BytesPerRow:=Integer(Bmp1.ScanLine[0])-Integer(Bmp1.ScanLine[1]); Bpp:=BytesPerPixel(Bmp1); MaxX:=Bmp1.Width*Bpp; Row:=DWord(Bmp1.Height-2); asm PUSHA MOV ESI, Bmp1Ptr // ESI = Bmp1 MOV EBX, Bmp2Ptr // EBX = Bmp2 MOV EDI, TargetPtr // EDI = TargetBmp @YLoop : MOV EDX, 0 // EDX = column offset @XLoop : MOV AL, BYTE Ptr[ESI+EDX] // load bmp1's blue pixel SUB AL, BYTE Ptr[EBX+EDX] // subtract bmp2's blue pixel JNC @Positive MOV AL, BYTE Ptr[EBX+EDX] // load bmp2's blue pixel SUB AL, BYTE Ptr[ESI+EDX] // subtract bmp1's blue pixel @Positive: MOV BYTE Ptr[EDI+EDX+0], AL // store it in the target's blue pixel MOV BYTE Ptr[EDI+EDX+1], AL // store it in the target's green pixel MOV BYTE Ptr[EDI+EDX+2], AL // store it in the target's red pixel ADD EDX, Bpp // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row SUB ESI, BytesPerRow // go to the next row SUB EBX, BytesPerRow SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; //////////////////////////////////////////////////////////////////////////////// // TargetBmp = Bmp1 - Bmp2 // They should probably all be the same size. :) //////////////////////////////////////////////////////////////////////////////// procedure SubtractBmpAsm(Bmp1,Bmp2,TargetBmp:TBitmap); var Bmp1Ptr,Bmp2Ptr : Pointer; TargetPtr : Pointer; MaxX,Row : DWord; BytesPerRow : DWord; Bpp : Integer; begin // Windows bitmaps start from the bottom Bmp1Ptr:=Bmp1.ScanLine[0]; Bmp2Ptr:=Bmp2.ScanLine[0]; TargetPtr:=TargetBmp.ScanLine[0]; // find how many bytes per row there are -> width*4+ a byte or two BytesPerRow:=Integer(Bmp1.ScanLine[0])-Integer(Bmp1.ScanLine[1]); Bpp:=BytesPerPixel(Bmp1); MaxX:=Bmp1.Width*Bpp; // 3 Row:=DWord(Bmp1.Height-2); asm PUSHA MOV ESI, Bmp1Ptr // ESI = Bmp1 MOV EBX, Bmp2Ptr // EBX = Bmp2 MOV EDI, TargetPtr // EDI = TargetBmp @YLoop : MOV EDX, 0 // EDX = column offset @XLoop : MOV AL, BYTE Ptr[ESI+EDX] // load bmp1's blue pixel SUB AL, BYTE Ptr[EBX+EDX] // subtract bmp2's blue pixel JNC @Positive XOR AL, AL @Positive: MOV BYTE Ptr[EDI+EDX+0], AL // store it in the target's blue pixel MOV BYTE Ptr[EDI+EDX+1], AL // store it in the target's green pixel MOV BYTE Ptr[EDI+EDX+2], AL // store it in the target's red pixel ADD EDX, Bpp // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row SUB ESI, BytesPerRow // go to the next row SUB EBX, BytesPerRow SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; procedure SubtractBmpAsmAbsSquared(Bmp1,Bmp2,TargetBmp:TBitmap); var Bmp1Ptr,Bmp2Ptr : Pointer; TargetPtr : Pointer; MaxX,Row : DWord; BytesPerRow : DWord; begin // Windows bitmaps start from the bottom Bmp1Ptr:=Bmp1.ScanLine[0]; Bmp2Ptr:=Bmp2.ScanLine[0]; TargetPtr:=TargetBmp.ScanLine[0]; // find how many bytes per row there are -> width*4+ a byte or two BytesPerRow:=Integer(Bmp1.ScanLine[0])-Integer(Bmp1.ScanLine[1]); MaxX:=Bmp1.Width*4; // 3 Row:=DWord(Bmp1.Height-2); asm PUSHA MOV ESI, Bmp1Ptr // ESI = Bmp1 MOV EBX, Bmp2Ptr // EBX = Bmp2 MOV EDI, TargetPtr // EDI = TargetBmp @YLoop : MOV EDX, 0 // EDX = column offset @XLoop : MOV AL, BYTE Ptr[ESI+EDX] // load bmp1's blue pixel SUB AL, BYTE Ptr[EBX+EDX] // subtract bmp2's blue pixel JNC @Positive MOV AL, BYTE Ptr[EBX+EDX] // load bmp2's blue pixel SUB AL, BYTE Ptr[ESI+EDX] // subtract bmp1's blue pixel @Positive: CMP AL, 16 JL @NoOverV MOV AL, 255 JMP @Store @NoOverV: MUL AL, AL @Store: MOV BYTE Ptr[EDI+EDX+0], AL // store it in the target's blue pixel MOV BYTE Ptr[EDI+EDX+1], AL // store it in the target's green pixel MOV BYTE Ptr[EDI+EDX+2], AL // store it in the target's red pixel ADD EDX, 4 // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row SUB ESI, BytesPerRow // go to the next row SUB EBX, BytesPerRow SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; procedure DrawXHairs(Bmp:TBitmap;X,Y,R:Integer); begin with Bmp.Canvas do begin MoveTo(X-R,Y); LineTo(X+R+1,Y); MoveTo(X,Y-R); LineTo(X,Y+R+1); end; end; procedure ClearBmpAsm(Bmp:TBitmap); var DestPtr : PByte; BytesPerRow : Integer; Bpp : DWord; LineOffset : DWord; MaxOffset : Integer; RowsLeft : Integer; begin // find how many bytes per row there are -> width*3+ a byte or two for padding BytesPerRow:=Integer(Bmp.ScanLine[0])-Integer(Bmp.ScanLine[1]); Bpp:=BytesPerPixel(Bmp); // pointer to the bmp's data area - highest address is the top line DestPtr:=Pointer(Bmp.ScanLine[0]); // start at the given X,Y upper left corner MaxOffset:=(Bmp.Width-1)*Bpp-1; RowsLeft:=Bmp.Height-1; asm PUSHA MOV EAX, 0 // AL is a temp holder MOV EBX, DestPtr // EBX = Bmp @YLoop : MOV ESI, 0 @XLoop : MOV [EBX+ESI], EAX // store it in the bmp ADD ESI, Bpp // select the next Bmp line offset CMP ESI, MaxOffset // done this row? JLE @XLoop // no: continue to the next pixel in the row SUB EBX, BytesPerRow // select the next bmp scanline DEC DWord Ptr[RowsLeft] JGE @YLOOP POPA end; end; procedure SubtractColorBmpAsm(Bmp1,Bmp2,TargetBmp:TBitmap); var Bmp1Ptr,Bmp2Ptr : Pointer; TargetPtr : Pointer; MaxX,Row : DWord; BytesPerRow : DWord; Bpp : Integer; begin // Windows bitmaps start from the bottom Bmp1Ptr:=Bmp1.ScanLine[0]; Bmp2Ptr:=Bmp2.ScanLine[0]; TargetPtr:=TargetBmp.ScanLine[0]; // find how many bytes per row there are -> width*4+ a byte or two BytesPerRow:=Integer(Bmp1.ScanLine[0])-Integer(Bmp1.ScanLine[1]); Bpp:=BytesPerPixel(Bmp1); MaxX:=Bmp1.Width*Bpp; // 3 Row:=DWord(Bmp1.Height-1); asm PUSHA MOV ESI, Bmp1Ptr // ESI = Bmp1 MOV EBX, Bmp2Ptr // EBX = Bmp2 MOV EDI, TargetPtr // EDI = TargetBmp @YLoop : MOV EDX, 0 // EDX = column offset @XLoop : // blue MOV AL, BYTE Ptr[ESI+EDX] // load bmp1's blue pixel SUB AL, BYTE Ptr[EBX+EDX] // subtract bmp2's blue pixel JNC @Green MOV AL, BYTE Ptr[EBX+EDX] // load bmp2's blue pixel SUB AL, BYTE Ptr[ESI+EDX] // subtract bmp1's blue pixel @Green : MOV CL, AL MOV AL, BYTE Ptr[ESI+EDX+1] // load bmp1's green pixel SUB AL, BYTE Ptr[EBX+EDX+1] // subtract bmp2's green pixel JNC @Red MOV AL, BYTE Ptr[EBX+EDX+1] // load bmp2's green pixel SUB AL, BYTE Ptr[ESI+EDX+1] // subtract bmp1's green pixel @Red : ADD CL, AL JC @ClipTo255 MOV AL, BYTE Ptr[ESI+EDX+2] // load bmp1's red pixel SUB AL, BYTE Ptr[EBX+EDX+2] // subtract bmp2's red pixel JNC @DoneRed MOV AL, BYTE Ptr[EBX+EDX+2] // load bmp2's red pixel SUB AL, BYTE Ptr[ESI+EDX+2] // subtract bmp1's red pixel @DoneRed : ADD CL, AL JNC @StoreResult @ClipTo255 : MOV CL, 255 @StoreResult : MOV BYTE Ptr[EDI+EDX+0], CL // store it in the target's blue pixel MOV BYTE Ptr[EDI+EDX+1], CL // store it in the target's green pixel MOV BYTE Ptr[EDI+EDX+2], CL // store it in the target's red pixel ADD EDX, Bpp // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row SUB ESI, BytesPerRow // go to the next row SUB EBX, BytesPerRow SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; procedure FlipBmp(SrcBmp,DestBmp:TBitmap); var Bpp,Bpr,Y : Integer; SrcLine : PByteArray; DestLine : PByteArray; begin Bpp:=BytesPerPixel(SrcBmp); Bpr:=Bpp*SrcBmp.Width; for Y:=0 to SrcBmp.Height-1 do begin SrcLine:=SrcBmp.ScanLine[Y]; DestLine:=DestBmp.ScanLine[(SrcBmp.Height-1)-Y]; Move(SrcLine^,DestLine^,Bpr); end; end; procedure MirrorBmp(SrcBmp,DestBmp:TBitmap); var Bpr,X,Y : Integer; DestX : Integer; Bpp : Integer; SrcLine : PByteArray; DestLine : PByteArray; begin Bpp:=BytesPerPixel(SrcBmp); Bpr:=Bpp*SrcBmp.Width; for Y:=0 to SrcBmp.Height-1 do begin SrcLine:=SrcBmp.ScanLine[Y]; DestLine:=DestBmp.ScanLine[Y]; DestX:=SrcBmp.Width-1; for X:=0 to SrcBmp.Width-1 do begin Move(SrcLine^[X*Bpp],DestLine^[DestX*Bpp],3); Dec(DestX); end; end; end; procedure FlipAndMirrorBmp(SrcBmp,DestBmp:TBitmap); var Bpr,X,Y : Integer; DestX : Integer; Bpp : Integer; SrcLine : PByteArray; DestLine : PByteArray; begin Bpp:=BytesPerPixel(SrcBmp); Bpr:=Bpp*SrcBmp.Width; for Y:=0 to SrcBmp.Height-1 do begin SrcLine:=SrcBmp.ScanLine[Y]; DestLine:=DestBmp.ScanLine[(SrcBmp.Height-1)-Y]; DestX:=SrcBmp.Width-1; for X:=0 to SrcBmp.Width-1 do begin Move(SrcLine^[X*Bpp],DestLine^[DestX*Bpp],3); Dec(DestX); end; end; end; procedure OrientBmp(SrcBmp,DestBmp:TBitmap;FlipImage,MirrorImage:Boolean); begin if FlipImage then begin if MirrorImage then FlipAndMirrorBmp(SrcBmp,DestBmp) else FlipBmp(SrcBmp,DestBmp); end else if MirrorImage then MirrorBmp(SrcBmp,DestBmp) else DestBmp.Canvas.Draw(0,0,SrcBmp); end; procedure InitBmpDataFromBmp(BmpData:PByte;Bmp:TBitmap;X1,Y1,X2,Y2:Integer); var W,H,Y,Bpr : Integer; SrcPtr : PByte; DestPtr : PByte; begin Assert(Y2<Bmp.Height); W:=X2-X1+1; H:=Y2-Y1+1; Bpr:=W*3; DestPtr:=PByte(BmpData); // for Y:=Y2 downto Y1 do begin for Y:=Y1 to Y2 do begin SrcPtr:=PByte(Bmp.ScanLine[Y]); Inc(SrcPtr,X1*3); Move(SrcPtr^,DestPtr^,Bpr); Inc(DestPtr,Bpr); end; end; procedure InitBmpFromBmpData(Bmp:TBitmap;BmpData:PByte;BmpW,BmpH:Integer); var Bpr,Y : Integer; DataPtr : PByte; Line : PByteArray; begin Bpr:=BmpW*3; DataPtr:=BmpData; for Y:=BmpH-1 downto 0 do begin Line:=Bmp.ScanLine[Y]; Move(DataPtr^,Line^,Bpr); Inc(DataPtr,Bpr); end; end; procedure SubtractColorBmpAsmAbs(Bmp1,Bmp2,TargetBmp:TBitmap); var Bmp1Ptr,Bmp2Ptr : Pointer; TargetPtr : Pointer; MaxX,Row : DWord; BytesPerRow : DWord; Bpp : Integer; begin // Windows bitmaps start from the bottom Bmp1Ptr:=Bmp1.ScanLine[0]; Bmp2Ptr:=Bmp2.ScanLine[0]; TargetPtr:=TargetBmp.ScanLine[0]; // find how many bytes per row there are -> width*4+ a byte or two BytesPerRow:=Integer(Bmp1.ScanLine[0])-Integer(Bmp1.ScanLine[1]); Bpp:=BytesPerPixel(Bmp1); MaxX:=Bmp1.Width*Bpp; Row:=DWord(Bmp1.Height-1); asm PUSHA MOV ESI, Bmp1Ptr // ESI = Bmp1 MOV EBX, Bmp2Ptr // EBX = Bmp2 MOV EDI, TargetPtr // EDI = TargetBmp @YLoop : MOV EDX, 0 // EDX = column offset @XLoop : MOV AL, BYTE Ptr[ESI+EDX] // load bmp1's blue pixel SUB AL, BYTE Ptr[EBX+EDX] // subtract bmp2's blue pixel JNC @BluePositive MOV AL, BYTE Ptr[EBX+EDX] // load bmp2's blue pixel SUB AL, BYTE Ptr[ESI+EDX] // subtract bmp1's blue pixel @BluePositive: MOV BYTE Ptr[EDI+EDX+0], AL // store it in the target's blue pixel MOV AL, BYTE Ptr[ESI+EDX+1] // load bmp1's green pixel SUB AL, BYTE Ptr[EBX+EDX+1] // subtract bmp2's green pixel JNC @GreenPositive MOV AL, BYTE Ptr[EBX+EDX+1] // load bmp2's green pixel SUB AL, BYTE Ptr[ESI+EDX+1] // subtract bmp1's green pixel @GreenPositive: MOV BYTE Ptr[EDI+EDX+1], AL // store it in the target's blue pixel MOV AL, BYTE Ptr[ESI+EDX+2] // load bmp1's red pixel SUB AL, BYTE Ptr[EBX+EDX+2] // subtract bmp2's red pixel JNC @RedPositive MOV AL, BYTE Ptr[EBX+EDX+2] // load bmp2's red pixel SUB AL, BYTE Ptr[ESI+EDX+2] // subtract bmp1's red pixel @RedPositive: MOV BYTE Ptr[EDI+EDX+2], AL // store it in the target's red pixel ADD EDX, Bpp // select the next pixel index CMP EDX, MaxX // done this row? JL @XLoop // no: continue to the next pixel in the row SUB ESI, BytesPerRow // go to the next row SUB EBX, BytesPerRow SUB EDI, BytesPerRow DEC DWord Ptr[Row] JGE @YLOOP POPA end; end; procedure OutlinePixel(Bmp:TBitmap;X,Y:Integer); const Red = 128;//255; Green = 128;//255; Blue = 128;//255; var X2,Y2,I : Integer; Line : PByteArray; begin for Y2:=Y-1 to Y do if (Y2>=0) and (Y2<Bmp.Height) then begin Line:=Bmp.ScanLine[Y2]; for X2:=X-1 to X do if (X2>0) and (X2<(Bmp.Width-1)) then begin I:=X2*3; Line^[I+0]:=Blue; Line^[I+1]:=Green; Line^[I+2]:=Red; end; end; end; procedure DrawTestPatternOnBmp(Bmp:TBitmap;BackColor,LineColor:TColor;Spacing:Integer); var I : Integer; begin ClearBmp(Bmp,BackColor); Bmp.Canvas.Pen.Color:=LineColor; I:=Spacing; while (I<Bmp.Width) do begin Bmp.Canvas.MoveTo(I,0); Bmp.Canvas.LineTo(I,Bmp.Height); Inc(I,Spacing); end; I:=Spacing; while (I<Bmp.Height) do begin Bmp.Canvas.MoveTo(0,I); Bmp.Canvas.LineTo(Bmp.Width,I); Inc(I,Spacing); end; end; procedure HalfScaleBmp(SrcBmp,DestBmp:TBitmap); var X,Y,SrcY,DestY : Integer; SrcI,DestI : Integer; SrcLine,DestLine : PByteArray; begin for DestY:=0 to DestBmp.Height-1 do begin SrcY:=DestY*2; SrcLine:=SrcBmp.ScanLine[SrcY]; DestLine:=DestBmp.ScanLine[DestY]; for X:=0 to DestBmp.Width-1 do begin SrcI:=(X*6); DestI:=X*3; DestLine^[DestI]:=SrcLine^[SrcI]; DestLine^[DestI+1]:=SrcLine^[SrcI+1]; DestLine^[DestI+2]:=SrcLine^[SrcI+2]; end; end; end; procedure QuarterScaleBmp(SrcBmp,DestBmp:TBitmap); var X,Y,SrcY,DestY : Integer; SrcI,DestI : Integer; SrcLine,DestLine : PByteArray; begin for DestY:=0 to DestBmp.Height-1 do begin SrcY:=DestY*4; SrcLine:=SrcBmp.ScanLine[SrcY]; DestLine:=DestBmp.ScanLine[DestY]; for X:=0 to DestBmp.Width-1 do begin SrcI:=(X*12); DestI:=X*3; DestLine^[DestI]:=SrcLine^[SrcI]; DestLine^[DestI+1]:=SrcLine^[SrcI+1]; DestLine^[DestI+2]:=SrcLine^[SrcI+2]; end; end; end; function AverageI(Bmp:TBitmap):Single; var X,Y,I : Integer; Sum : Integer; Line : PByteArray; begin Sum:=0; for Y:=0 to Bmp.Height-1 do begin Line:=Bmp.ScanLine[Y]; for X:=0 to Bmp.Width-1 do begin I:=X*3; Sum:=Sum+Line^[I]+Line^[I+1]+Line^[I+2]; end; end; Result:=Sum/(Bmp.Width*Bmp.Height*3); end; end.
unit uLanguages; interface uses System.Classes, System.SysUtils, System.JSon; type [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)] TLanguage = class(TComponent) private FLang: string; FCurrLang: string; FIds: TJSONArray; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //set resource/language procedure setSource(const resName: string); procedure setLanguage(const langId: string = 'Default'); //localization function function localize(const id: string): string; end; procedure Register; implementation procedure Register; begin RegisterComponents('AlbertoComp.', [TLanguage]); end; { TLanguage } constructor TLanguage.Create(AOwner: TComponent); begin inherited Create(AOwner); FLang := ' '; FCurrLang := 'Default'; end; destructor TLanguage.Destroy; begin FIds.Free; inherited; end; function TLanguage.localize(const id: string): string; var FValue, FValueInner, FValueData: TJSONValue; begin Result := ''; try for FValue in FIds do begin if (FValue is TJSONObject) then begin FValueInner := TJSONObject(FValue).Values[FCurrLang]; if (FValueInner is TJSONArray) then begin for FValueData in TJSONArray(FValueInner) do begin Result := FvalueData.GetValue<string>(id); end; end; end; end; except Result := '-'; end; end; procedure TLanguage.setLanguage(const langId: string); begin FCurrLang := langId; end; procedure TLanguage.setSource(const resName: string); var rs: TResourceStream; sl: TStringList; begin FLang := resName; //in System.Types > const RT_RCDATA = PChar(10); rs := TResourceStream.Create(HInstance, FLang, PChar(10)); try sl := TStringList.Create; try sl.LoadFromStream(rs, TEncoding.UTF8); FIds := TJSONObject.ParseJSONValue(sl.Text) as TJSONArray; finally sl.Free; end finally rs.Free; end; end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} unit IdOpenSSLHeaders_uierr; interface // Headers for OpenSSL 1.1.1 // uierr.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts; const (* * UI function codes. *) UI_F_CLOSE_CONSOLE = 115; UI_F_ECHO_CONSOLE = 116; UI_F_GENERAL_ALLOCATE_BOOLEAN = 108; UI_F_GENERAL_ALLOCATE_PROMPT = 109; UI_F_NOECHO_CONSOLE = 117; UI_F_OPEN_CONSOLE = 114; UI_F_UI_CONSTRUCT_PROMPT = 121; UI_F_UI_CREATE_METHOD = 112; UI_F_UI_CTRL = 111; UI_F_UI_DUP_ERROR_STRING = 101; UI_F_UI_DUP_INFO_STRING = 102; UI_F_UI_DUP_INPUT_BOOLEAN = 110; UI_F_UI_DUP_INPUT_STRING = 103; UI_F_UI_DUP_USER_DATA = 118; UI_F_UI_DUP_VERIFY_STRING = 106; UI_F_UI_GET0_RESULT = 107; UI_F_UI_GET_RESULT_LENGTH = 119; UI_F_UI_NEW_METHOD = 104; UI_F_UI_PROCESS = 113; UI_F_UI_SET_RESULT = 105; UI_F_UI_SET_RESULT_EX = 120; (* * UI reason codes. *) UI_R_COMMON_OK_AND_CANCEL_CHARACTERS = 104; UI_R_INDEX_TOO_LARGE = 102; UI_R_INDEX_TOO_SMALL = 103; UI_R_NO_RESULT_BUFFER = 105; UI_R_PROCESSING_ERROR = 107; UI_R_RESULT_TOO_LARGE = 100; UI_R_RESULT_TOO_SMALL = 101; UI_R_SYSASSIGN_ERROR = 109; UI_R_SYSDASSGN_ERROR = 110; UI_R_SYSQIOW_ERROR = 111; UI_R_UNKNOWN_CONTROL_COMMAND = 106; UI_R_UNKNOWN_TTYGET_ERRNO_VALUE = 108; UI_R_USER_DATA_DUPLICATION_UNSUPPORTED = 112; var function ERR_load_UI_strings: TIdC_INT; implementation end.
{ **************************************************************************** } { Project: ConnectFour3D { Module: { Author: Josef Schuetzenberger { E-Mail: schutzenberger@hotmail.com { WWW: http://members.fortunecity.com/schutzenberger/download/en.html#ConnectFour3D { **************************************************************************** } { Copyright ©2006 Josef Schuetzenberger { This programme 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 any later version. { { This programme is distributed for educational purposes in the hope that it { will be useful, but WITHOUT ANY WARRANTY. See the GNU General Public License { for more details at http://www.gnu.org/licenses/gpl.html { **************************************************************************** } unit BoardForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,MainForm,OpenGL, ExtCtrls{,jpeg}, ImgList; type TFormBoard = class(TFormMain) Timer1: TTimer; Timer2: TTimer; ImageListSmiley: TImageList; procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormPaint(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure Timer2Timer(Sender: TObject); private Palette: HPALETTE; DC: HDC; hrc: HGLRC; procedure SetDCPixelFormat; function ScreenVectorIntersectWithPlaneXY(const ScreenX,ScreenY,z : Single; var Xintersect,Yintersect : Single) : Boolean; public procedure InitScene; procedure FreeScene; procedure DrawScene; procedure SetSquare(x,y,Player,Score:integer);override; end; var FormBoard: TFormBoard; procedure glGenTextures(n: GLsizei; var textures: GLuint); stdcall; external opengl32; procedure glBindTexture(target: GLenum; texture: GLuint); stdcall; external opengl32; implementation {$R *.dfm} uses OpenGLUtil; function TFormBoard.ScreenVectorIntersectWithPlaneXY(const ScreenX,ScreenY,Z : Single; var Xintersect,Yintersect : Single) : Boolean; var wx, wy, wz : Double; ViewPort : array[0..3]of gluint; ProjectionMatrix:TMatrix4f; ModelViewMatrix:TMatrix4f; d,t:Single; rayStart,rayVector,planeNormal,planePoint,intersectPoint:TAffineVector; begin result:=false; wglMakeCurrent(DC, hrc); glpushmatrix; glGetIntegerv(GL_VIEWPORT, @ViewPort); glGetDoublev(GL_MODELVIEW_MATRIX, @ModelViewMatrix); glGetDoublev(GL_PROJECTION_MATRIX, @ProjectionMatrix); gluUnProject(ScreenX, ViewPort[3]-ScreenY, 0, @ModelViewMatrix, @ProjectionMatrix, @ViewPort, wx, wy, wz); rayStart[0]:=Camera.xpos; rayStart[1]:=Camera.ypos; rayStart[2]:=Camera.zpos; rayVector[0]:=wx-Camera.xpos; rayVector[1]:=wy-Camera.ypos; rayVector[2]:=wz-Camera.zpos; planePoint[0]:=-Camera.xpos; planePoint[1]:=-Camera.ypos; planePoint[2]:=z-Camera.zpos; planeNormal[0]:=0; planeNormal[1]:=0; planeNormal[2]:=1; d:=VectorDotProduct(rayVector, planeNormal); if abs(d) > 0.0001 then begin d:=1/d; t:=VectorDotProduct(planePoint, planeNormal)*d; if t>0 then begin VectorCombine(rayStart, rayVector, 1, t, intersectPoint); Xintersect:=intersectPoint[0]; Yintersect:=intersectPoint[1]; result:=true; end; end; glpopmatrix; wglMakeCurrent(0, 0); end; //--------------------------------------------------------------------------- const MinFilter=GL_LINEAR; MaxFilter=GL_LINEAR; procedure LoadTex(Filename:string); function RoundUpToPowerOf2(value : Integer) : Integer; begin Result:=1; while (Result<value) do Result:=Result*2; end; procedure DoBGRtoRGB(data : Pointer; size : Integer); asm // swap blue with red to go from bgr to rgb // data in eax // size in edx @@loop: mov cl,[eax] // red mov ch,[eax+2] // blue mov [eax+2],cl mov [eax],ch add eax,3 dec edx jnz @@loop end; type PPixelArray = ^TByteArray; var bmp24,bmp : TBitmap; // jp : TJPEGImage; BMInfo: TBitmapInfo; Buffer: PPixelArray; ImageSize : Integer; MemDC : HDC; begin { if ExtractFileExt(Filename)='.jpg' then begin jp := TJPEGImage.Create; jp.LoadFromFile(Filename); bmp24:=TBitmap.Create; bmp24.PixelFormat:=pf24Bit; bmp24.Width:=jp.Width; bmp24.Height:=jp.Height; bmp24.Canvas.Draw(0, 0, jp); jp.Free; end else } if ExtractFileExt(Filename)='.bmp' then begin bmp := TBitmap.Create; bmp.LoadFromFile(Filename); bmp24:=TBitmap.Create; bmp24.PixelFormat:=pf24Bit; bmp24.Width:=bmp.Width; bmp24.Height:=bmp.Height; bmp24.Canvas.Draw(0, 0, bmp); bmp.Free; end else if ExtractFileExt(Filename)='.IL' then begin bmp := TBitmap.Create; FormBoard.ImageListSmiley.GetBitmap(StrtoInt(ChangeFileExt(Filename,'')),bmp); bmp24:=TBitmap.Create; bmp24.PixelFormat:=pf24Bit; bmp24.Width:=bmp.Width; bmp24.Height:=bmp.Height; bmp24.Canvas.Draw(0, 0, bmp); bmp.Free; end else exit; // create description of the required image format FillChar(BMInfo, sizeof(BMInfo),0); BMInfo.bmiHeader.biSize:=sizeof(TBitmapInfoHeader); BMInfo.bmiHeader.biBitCount:=24; BMInfo.bmiHeader.biWidth:=RoundUpToPowerOf2(bmp24.Width); BMInfo.bmiHeader.biHeight:=RoundUpToPowerOf2(bmp24.Height); BMInfo.bmiHeader.biPlanes:=1; BMInfo.bmiHeader.biCompression:=BI_RGB; ImageSize:=BMInfo.bmiHeader.biWidth*BMInfo.bmiHeader.biHeight; Getmem(Buffer, ImageSize*3); MemDC:=CreateCompatibleDC(0); // get the actual bits of the image GetDIBits(MemDC, bmp24.Handle, 0, BMInfo.bmiHeader.biHeight, Buffer, BMInfo, DIB_RGB_COLORS); // swap blue with red to go from bgr to rgb DoBGRtoRGB(Buffer,ImageSize); glTexImage2d(GL_TEXTURE_2D,0, 3, BMInfo.bmiHeader.biWidth,BMInfo.bmiHeader.biHeight,0, GL_RGB, GL_UNSIGNED_BYTE, Buffer); FreeMem(Buffer); DeleteDC(MemDC); bmp24.Free; end; //--------------------------------------------------------------------------- procedure InitTex; type PPixelArray = ^TByteArray; procedure MakeWood(Buffer:PPixelArray;ImageSize:integer); var red,green,blue: byte; b:byte; i : Integer; begin red := 147; green := 110; blue := 58; {$IFOPT R+} {$DEFINE RangeCheck} {$R-} {$ENDIF} for i:=0 TO ImageSize-1 do begin b:=i mod 9; Buffer^[I*3] := red+b; Buffer^[I*3+1] := green+b; Buffer^[I*3+2] := blue+b; end; {$IFDEF RangeCheck} {$UNDEF RangeCheck} {$R+} {$ENDIF} end; var Buffer: PPixelArray; ImageSize,biWidth,biHeight : Integer; begin glGenTextures(3,texture[0]); glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,MinFilter); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,MaxFilter); biWidth:=64; biHeight:=64; ImageSize:=biWidth*biHeight; Getmem(Buffer, ImageSize*3); MakeWood(Buffer,ImageSize); glTexImage2d(GL_TEXTURE_2D,0, 3, biWidth,biHeight,0, GL_RGB, GL_UNSIGNED_BYTE, Buffer); FreeMem(Buffer); glBindTexture(GL_TEXTURE_2D, texture[1]); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,MinFilter); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,MaxFilter); // LoadTex('smileyHappy4.bmp'); LoadTex('0.IL'); glBindTexture(GL_TEXTURE_2D, texture[2]); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,MinFilter); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,MaxFilter); LoadTex('1.IL'); // LoadTex('smileySad4.bmp'); end; //--------------------------------------------------------------------------- procedure TFormBoard.InitScene; var aQuad: gluQuadricObj; const lightcolor : array[0..3] of glfloat =(0.7,0.7,0.7,1); const lightpos : array[0..3] of glfloat =(0.0,10,0.0,0); procedure MakePlank(x,y,z : glFloat); var aQuadVertex:array[0..7,0..2] of glfloat; const aQuadPoints:array[0..7,0..2] of glfloat= (( 1, 1, 1), (-1, 1, 1), ( 1,-1, 1), (-1,-1, 1), ( 1, 1,-1), (-1, 1,-1), ( 1,-1,-1), (-1,-1,-1)); const aQuadTexture:array[0..7,0..2] of glfloat= (( 1, 1, 1), ( 0, 1, 1), ( 1, 0, 1), ( 0, 0, 1), ( 1, 1,-1), (-1, 1,-1), ( 1,-1,-1), (-1,-1,-1)); const Surface : array[0..5,0..3] of integer = ((1,2,4,3), (2,1,5,6), (6,5,7,8), (8,7,3,4), (1,3,7,5), (2,6,8,4)); const Normals : array[0..5,0..2] of glfloat = (( 0, 0, 1), ( 0, 1, 0), ( 0, 0,-1), ( 0,-1, 0), ( 1, 0, 0), (-1, 0, 0)); var i,j : integer; begin for i := 0 to 7 do begin aQuadvertex[i,0]:=aQuadPoints[i,0]*x/2; aQuadvertex[i,1]:=aQuadPoints[i,1]*y/2; aQuadvertex[i,2]:=aQuadPoints[i,2]*z/2; end; glbegin(GL_QUADs); for i := 0 to 5 do begin glnormal3fv(@normals[i,0]); for j :=0 to 3 do begin glTexCoord2f(aQuadTexture[Surface[i,j]-1,0],aQuadTexture[Surface[i,j]-1,1]); glvertex3fv(@aQuadvertex[Surface[i,j]-1,0]); end; end; glend; end; //--------------------------------------------------------------------------- procedure MakeStone(FMinorRadius,FMajorRadius:glFloat;FRings,FSides:integer); var I, J,start : Integer; Theta, Phi, Theta1, cosPhi, sinPhi, dist : TGLFloat; cosTheta, sinTheta: TGLFloat; cosTheta1, sinTheta1, cosTheta2, sinTheta2: TGLFloat; ringDelta, sideDelta: TGLFloat; const c2PI : Single = 6.283185307; begin // handle texture generation ringDelta:=c2PI/FRings; sideDelta:=c2PI/FSides; theta:=0; cosTheta:=1; sinTheta:=0; start:=FSides div 4 ; FSides:=FSides-start ; for I:=FRings-1 downto 0 do begin theta1:=theta+ringDelta; SinCos(theta1, sinTheta1, cosTheta1); SinCos(theta1+ringDelta, sinTheta2, cosTheta2); glBegin(GL_QUAD_STRIP); phi:=sideDelta*(FSides-1); SinCos(phi+sideDelta, sinPhi, cosPhi); glNormal3f(-1, 0, 0); glTexCoord2f(0.5, 0.5); glVertex3f(0, 0, FMinorRadius*sinPhi); // glNormal3f(-1, 0, 0); // glVertex3f(0,0, FMinorRadius*sinPhi); for J:=FSides downto start do begin phi:=phi+sideDelta; SinCos(phi, sinPhi, cosPhi); dist:=FMajorRadius+FMinorRadius*cosPhi; glTexCoord2f((sinTheta2+1)/2, (cosTheta2+1)/2); glNormal3f(cosTheta1*cosPhi, -sinTheta1*cosPhi, sinPhi); glVertex3f(cosTheta1*dist, -sinTheta1*dist, FMinorRadius*sinPhi); glTexCoord2f((sinTheta1+1)/2, (cosTheta1+1)/2); glNormal3f(cosTheta*cosPhi, -sinTheta*cosPhi, sinPhi); glVertex3f(cosTheta*dist, -sinTheta*dist, FMinorRadius*sinPhi); end; glNormal3f(1, 0, 0); glTexCoord2f(0.5, 0.5); glVertex3f(0, 0, FMinorRadius*sinPhi); // glNormal3f(1, 0, 0); // glVertex3f(0,0, FMinorRadius*sinPhi); glEnd; theta:=theta1; cosTheta:=cosTheta1; sinTheta:=sinTheta1; end; end; //--------------------------------------------------------------------------- procedure MakeBoard1; var i:integer; const Square:glFloat=1.; Radius:glFloat=0.4; Thickness:glFloat=0.1; procedure MakeCylinders(x,y,z : glFloat); var j:integer; begin gluQuadricOrientation(aquad,GLU_INSIDE); glpushmatrix; gltranslatef(0,Radius,0); for j:=0 to 6 do begin gltranslatef(Square,0,0); gluCylinder(aquad,Radius,Radius,Thickness,4*3,2); end; glpopmatrix; gluQuadricOrientation(aquad,GLU_OUTSIDE); end; procedure MakeRow(Radius,Border:glFloat;Holes,Stripes:integer); var I,J: Integer; Phi,cosPhi,sinPhi,stripeDelta,y,x: TGLFloat; const c2PI: Single = 6.283185307; begin stripeDelta:=c2PI/Stripes/2; glBegin(GL_QUAD_STRIP); phi:=-stripeDelta; for J:=Stripes downto 0 do begin phi:=phi+stripeDelta; SinCos(phi, sinPhi, cosPhi); y:=Radius*(1+cosPhi); x:=Border-Radius*sinPhi; glVertex3f(0,y,0); glVertex3f(x, y,0); end; glEnd; for i:=1 to Holes-1 do begin glBegin(GL_QUAD_STRIP); phi:=-stripeDelta; for J:=Stripes downto 0 do begin phi:=phi+stripeDelta; SinCos(phi, sinPhi, cosPhi); y:=Radius*(1+cosPhi); x:=Border-Radius*sinPhi; glVertex3f(i*Border+Radius*sinPhi,y,0); glVertex3f(i*Border+x, y,0); end; glEnd; end; glBegin(GL_QUAD_STRIP); phi:=-stripeDelta; for J:=Stripes downto 0 do begin phi:=phi+stripeDelta; SinCos(phi, sinPhi, cosPhi); y:=Radius*(1+cosPhi); glVertex3f(Holes*Border+Radius*sinPhi,y,0); glVertex3f((Holes+1)*Border, y,0); end; glEnd; end; begin glMaterialfv(GL_FRONT, GL_AMBIENT, @MCBoard1); glMaterialfv(GL_FRONT, GL_diffuse, @MCBoard2); glMaterialfv(GL_FRONT, GL_specular,@MCBoard3); glpushmatrix; for i:=0 to 5 do //front begin MakeCylinders(1,1,1); MakeRow(Radius,Square,7,2*3); glrectf(0,0,8*Square,-(Square-2*Radius)); gltranslatef(0,Square,0); end; glrectf(0,0,8*Square,-(Square-2*Radius)); glpopmatrix; glpushmatrix; glrotatef(180,0,1,0); gltranslatef(-8*Square,0,-0.1); for i:=0 to 5 do //back begin MakeRow(Radius,Square,7,2*3); glrectf(0,0,8*Square,-(Square-2*Radius)); gltranslatef(0,Square,0); end; glrectf(0,0,8*Square,-(Square-2*Radius)); glpopmatrix; glpushmatrix; gltranslatef(0,Square*6,Thickness*0.5); glrotatef(90,0,1,0); gluCylinder(aquad,Thickness*0.5,Thickness*0.5,Square*8,8,2); glrotatef(90,1,0,0); gluCylinder(aquad,Thickness*0.5,Thickness*0.5,Square*8,8,2); gluSphere(aquad,Thickness*0.5,8,8); gltranslatef(0,Square*8,0); gluCylinder(aquad,Thickness*0.5,Thickness*0.5,Square*8,8,2); gluSphere(aquad,Thickness*0.5,18,8); glpopmatrix; end; begin inherited; aquad :=gluNewQuadric; gluQuadricDrawStyle(aquad,GLU_Fill); glNewList(Side,GL_COMPILE); glpushmatrix; gltranslatef(0,1,0); gltranslatef(10,0,0); glMaterialfv(GL_FRONT, GL_AMBIENT, @MCBorder1); glMaterialfv(GL_FRONT, GL_diffuse, @MCBorder2); glMaterialfv(GL_FRONT, GL_specular,@MCBorder3); makePlank(0.1,2,20); gltranslatef(-20,0,0); makePlank(0.1,2,20); gltranslatef(10,0,10); makePlank(20,2,0.1); gltranslatef(0,0,-20); makePlank(20,2,0.1); glpopmatrix; glEndlist; glNewList(Floor,GL_COMPILE); glbegin(gl_quads); glMaterialfv(GL_FRONT, GL_AMBIENT, @MCFloor1); glMaterialfv(GL_FRONT, GL_diffuse, @MCFloor2); glMaterialfv(GL_FRONT, GL_specular,@MCFloor3); glnormal3f(0,1,0); glvertex3f(-10,0,-10); glvertex3f(-10,0, 10); glvertex3f( 10,0, 10); glvertex3f( 10,0,-10); glend; glEndlist; gluQuadricDrawStyle(aquad,GLU_Fill); glNewList(Board,GL_COMPILE); glpushmatrix; gltranslatef(-4,1,-BoardPosZ+1); MakeBoard1; gltranslatef(0,0,-0.2); MakeBoard1; glpopmatrix; glEndlist; glNewList(Marker,GL_COMPILE); glpushmatrix; gltranslatef(-0.2,1.39,{-2.360}-BoardPosZ+0.64); glBegin(GL_POLYGON); glVertex2f(0.4, 0.2); glVertex2f(0.2, 0); glVertex2f(0, 0.2); glEnd; glpopmatrix; glEndlist; glNewList(Stone,GL_COMPILE); glpushmatrix; glMaterialfv(GL_FRONT, GL_AMBIENT, @Player2MC1); glMaterialfv(GL_FRONT, GL_diffuse, @Player2MC2); glMaterialfv(GL_FRONT, GL_specular,@Player2MC3); gltranslatef(-3,1,-BoardPosZ+1); gltranslatef(0,0,-0.2); MakeStone(0.05,0.35,16,20); glpopmatrix; glEndlist; glNewList(StonePlayer1,GL_COMPILE); glpushmatrix; glMaterialfv(GL_FRONT, GL_AMBIENT, @Player1MC1); glMaterialfv(GL_FRONT, GL_diffuse, @Player1MC2); glMaterialfv(GL_FRONT, GL_specular,@Player1MC3); gltranslatef(-0,1,-BoardPosZ+1); gltranslatef(0,0,-0.2); MakeStone(0.05,0.35,16,20); glpopmatrix; glEndlist; glNewList(StonePlayer2,GL_COMPILE); glpushmatrix; glMaterialfv(GL_FRONT, GL_AMBIENT, @Player2MC1); glMaterialfv(GL_FRONT, GL_diffuse, @Player2MC2); glMaterialfv(GL_FRONT, GL_specular,@Player2MC3); gltranslatef(-0,1,-BoardPosZ+1); gltranslatef(0,0,-0.2); MakeStone(0.05,0.35,16,20); glpopmatrix; glEndlist; gluDeleteQuadric(aquad); glenable(gl_lighting); glLightfv(GL_LIGHT0,GL_DIFFUSE,@Lightcolor); glLightfv(GL_LIGHT0,GL_AMBIENT,@Lightcolor); glLightfv(GL_LIGHT0,GL_POSITION,@Lightpos); glEnable(GL_LIGHT0); //InitTextures; InitTex; glclearcolor(0.5,0.5,0.7,0); glenable(gl_depth_test); end; //--------------------------------------------------------------------------- function CountStones(Player:TBoardPos):integer; var i,j:integer; begin result:=0; for i:=0 to 6 do for j:=0 to 5 do if BoardState[i,j]=Player then inc(result); end; //--------------------------------------------------------------------------- procedure TFormBoard.DrawScene; var i,j,k,g : integer; begin inherited; glEnable(GL_TEXTURE_2D); glShadeModel(GL_SMOOTH); // glClearColor(0.0, 0.0, 0.0, 0.5); glClearDepth(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); glfrontface(gl_ccw); //orientation of front-facing polygons glenable(gl_cull_face); //enable facet culling glpushmatrix; glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture[0]); glcalllist(Side); glDisable(GL_TEXTURE_2D); glpushName(18); glLoadName(18); glcalllist(Floor); glpopmatrix; glpushmatrix; glcalllist(Board); glpushName(21); glLoadName(21); glpopmatrix; glpushmatrix; k:=CountStones(Player1); j:=CountStones(Player2); g:=k-j; k:=k+1-g; j:=j+g; gltranslatef(5,0.75-BoardPosZ,-BoardPosZ); glrotatef(90,1,0,0); for i:=1 to 21-j do begin gltranslatef(0,0,-0.13); glcalllist(StonePlayer2); end; if g=1 then begin glrotatef(-90,1,0,0); gltranslatef(0.9,-0.5+BoardPosZ,BoardPosZ); glrotatef(65,0,0,1); if LastMove.score<>0 then begin glEnable(GL_TEXTURE_2D); if LastMove.score<0 then glBindTexture(GL_TEXTURE_2D, texture[1]) else glBindTexture(GL_TEXTURE_2D, texture[2]); end; glcalllist(StonePlayer2); glDisable(GL_TEXTURE_2D); end; glpopmatrix; glpushmatrix; gltranslatef(-5,0.75-BoardPosZ,-BoardPosZ); glrotatef(90,1,0,0); for i:=1 to 21-k do begin gltranslatef(0,0,-0.13); glcalllist(StonePlayer1); end; if g=0 then begin glrotatef(-90,1,0,0); gltranslatef(1,-0.5+BoardPosZ,BoardPosZ); glrotatef(65,0,0,1); if LastMove.score<>0 then begin glEnable(GL_TEXTURE_2D); if LastMove.score<0 then glBindTexture(GL_TEXTURE_2D, texture[1]) else glBindTexture(GL_TEXTURE_2D, texture[2]); end; glcalllist(StonePlayer1); glDisable(GL_TEXTURE_2D); end; glpopmatrix; for j:=0 to 6 do begin for i:=0 to 5 do begin if BoardState[j,i]<>Empty then if (BoardWinLine[j,i]=Empty) or (TimerCount mod 2=0) then begin glpushmatrix; gltranslatef(3-j*1,i*1+0.40,0.15); if BoardState[j,i]=Player1 then glcalllist(StonePlayer1) else glcalllist(StonePlayer2); if (LastMove.x=j) and (LastMove.y=i) then glcalllist(Marker); glpopmatrix; end; end; end; end; //--------------------------------------------------------------------------- procedure TFormBoard.FreeScene; begin end; //--------------------------------------------------------------------------- procedure TFormBoard.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin LastMouseClickX:=X; LastMouseClickY:=Y; end; //--------------------------------------------------------------------------- procedure TFormBoard.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var v : TAffineVector; r : Single; begin if Shift=[ssLeft] then begin r:= LastMouseClickX-x; v[0]:=Camera.xpos; v[1]:=Camera.ypos; v[2]:=Camera.zpos; v:=VectorRotateAroundY(v,r*0.01); Camera.xpos:=v[0]; Camera.ypos:=v[1]; Camera.zpos:=v[2]; v[0]:=Camera.xtop; v[1]:=Camera.ytop; v[2]:=Camera.ztop; v:=VectorRotateAroundY(v,r*0.01); Camera.xtop:=v[0]; Camera.ytop:=v[1]; Camera.ztop:=v[2]; r:= LastMouseClickY-y; Camera.ypos:=Camera.ypos+r*0.1; if Camera.ypos<4.1 then Camera.ypos:=4.1; InvalidateRect(Handle, nil, False); end else if Shift=[ssRight] then begin { r:= LastMouseClickX-x; Camera.xtop:=v[0]; Camera.ytop:=v[1]; Camera.ztop:=Camera.ztop+r; InvalidateRect(Handle, nil, False); } end; LastMouseClickX:=X; LastMouseClickY:=Y; end; //--------------------------------------------------------------------------- procedure TFormBoard.FormPaint(Sender: TObject); begin wglMakeCurrent(DC, hrc); try glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT or GL_ACCUM_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glulookat(Camera.xpos,Camera.ypos,Camera.zpos,Camera.xat,Camera.yat,Camera.zat,Camera.xtop,Camera.ytop,Camera.ztop); DrawScene; swapbuffers(DC); finally wglMakeCurrent(0, 0); end; end; //--------------------------------------------------------------------------- procedure TFormBoard.FormResize(Sender: TObject); var x,y:integer; begin inherited; wglMakeCurrent(DC, hrc); glMatrixMode(GL_PROJECTION); glLoadIdentity; glViewport(0, 0,ClientWidth,ClientHeight); x:=ClientWidth; y:=ClientHeight; glShadeModel(GL_SMOOTH); //Enables Smooth Color Shading InvalidateRect(Handle, nil, False); gluPerspective(45.0, // Field-of-view angle x/y, // Aspect ratio of viewing volume 1.0, // Distance to near clipping plane 200.0); // Distance to far clipping plane wglMakeCurrent(0, 0); end; //--------------------------------------------------------------------------- procedure TFormBoard.SetDCPixelFormat; var hHeap: THandle; nColors, i: Integer; lpPalette: PLogPalette; byRedMask, byGreenMask, byBlueMask: Byte; nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); with pfd do begin nSize := sizeof(pfd); // Size of this structure nVersion := 1; // Version number dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; // Flags iPixelType:= PFD_TYPE_RGBA; // RGBA pixel values cColorBits:= 24; // 24-bit color cDepthBits:= 32; // 32-bit depth buffer iLayerType:= PFD_MAIN_PLANE; // Layer type end; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); DescribePixelFormat(DC, nPixelFormat, sizeof(TPixelFormatDescriptor), pfd); if ((pfd.dwFlags and PFD_NEED_PALETTE) <> 0) then begin nColors := 1 shl pfd.cColorBits; hHeap := GetProcessHeap; lpPalette := HeapAlloc(hHeap, 0, sizeof(TLogPalette) + (nColors * sizeof(TPaletteEntry))); lpPalette^.palVersion := $300; lpPalette^.palNumEntries := nColors; byRedMask := (1 shl pfd.cRedBits) - 1; byGreenMask := (1 shl pfd.cGreenBits) - 1; byBlueMask := (1 shl pfd.cBlueBits) - 1; for i := 0 to nColors - 1 do begin lpPalette^.palPalEntry[i].peRed := (((i shr pfd.cRedShift) and byRedMask) * 255) DIV byRedMask; lpPalette^.palPalEntry[i].peGreen := (((i shr pfd.cGreenShift) and byGreenMask) * 255) DIV byGreenMask; lpPalette^.palPalEntry[i].peBlue := (((i shr pfd.cBlueShift) and byBlueMask) * 255) DIV byBlueMask; lpPalette^.palPalEntry[i].peFlags := 0; end; Palette := CreatePalette(lpPalette^); HeapFree(hHeap, 0, lpPalette); if (Palette <> 0) then begin SelectPalette(DC, Palette, False); RealizePalette(DC); end; end; end; //--------------------------------------------------------------------------- procedure TFormBoard.FormCreate(Sender: TObject); begin inherited; DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); InitScene; wglMakeCurrent(0, 0); Camera.xpos:=0; Camera.ypos:=16; Camera.zpos:=-12; Camera.xat :=0; Camera.yat :=4; Camera.zat :=-2*0; Camera.xtop:=0; Camera.ytop:=10+2; Camera.ztop:=16; end; //--------------------------------------------------------------------------- procedure TFormBoard.FormDestroy(Sender: TObject); begin inherited; Timer1.Enabled := False; FreeScene; wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); if (Palette <> 0) then DeleteObject(Palette); end; //--------------------------------------------------------------------------- function IsBoardWon:boolean; var i,j:integer; function CheckGetWinLine(xd,yd:integer;Player:TBoardPos;GetIt:boolean):boolean; var x,y,k:integer; begin x:=i;y:=j;k:=0; if GetIt then BoardWinLine[x,y]:=Player; while BoardState[x,y]=Player do begin x:=x+xd;y:=y+yd; if (x>=0) and (x<=6) and (y>=0) and (y<=5) and (BoardState[x,y]=Player) then begin if GetIt then BoardWinLine[x,y]:=Player; inc(k) end else break; end; x:=i;y:=j; while BoardState[x,y]=Player do begin x:=x-xd;y:=y-yd; if (x>=0) and (x<=6) and (y>=0) and (y<=5) and (BoardState[x,y]=Player) then begin if GetIt then BoardWinLine[x,y]:=Player; inc(k) end else break; end; if k>=3 then result:=true else result:=false; end; function IsWinLine(xd,yd:integer):boolean; begin result:=true; if CheckGetWinLine(xd,yd,Player1,false) then begin CheckGetWinLine(xd,yd,Player1,true); exit; end; if CheckGetWinLine(xd,yd,Player2,false) then begin CheckGetWinLine(xd,yd,Player2,true); exit; end; result:=false; end; begin for i:=0 to 6 do for j:=0 to 5 do BoardWinLine[i,j]:=empty; result:=true; for i:=0 to 6 do for j:=0 to 5 do begin if IsWinline(0,1) then exit; if IsWinline(1,0) then exit; if IsWinline(1,1) then exit; if IsWinline(-1,1) then exit; end; result:=false; end; //--------------------------------------------------------------------------- function GetPlayer:TBoardPos; var i,j,k:integer; begin k:=0; for i:=0 to 6 do for j:=0 to 5 do if BoardState[i,j]<> empty then inc(k); if k mod 2 =0 then result:=Player1 else result:=Player2; end; //--------------------------------------------------------------------------- procedure TFormBoard.FormClick(Sender: TObject); var i,j:integer; x,y:single; begin inherited; if not ScreenVectorIntersectWithPlaneXY(LastMouseClickX,LastMouseClickY,0.9-BoardPosZ,x,y) then exit; j:=0; i:=round(3-x); if (i>=0) and (i<=6) then begin while (j<6) and (BoardState[i,j]<> empty) do inc(j); if (j<6) and not Timer1.Enabled and TrySquareSet(i,j) then begin LastMove.x:=i; LastMove.y:=j; LastMove.Score:=0; BoardState[i,j]:=GetPlayer; Timer1.Enabled:=IsBoardWon; InvalidateRect(Handle, nil, False); end; end; end; //--------------------------------------------------------------------------- procedure TFormBoard.SetSquare(x,y,Player,Score:integer); var ActPlayer:TBoardPos; begin inherited; case Player of 0:ActPlayer:=empty; else ActPlayer:=GetPlayer; end; LastMove.x:=x; LastMove.y:=y; LastMove.Score:=Score; BoardState[x,y]:=ActPlayer; Timer1.Enabled:=IsBoardWon; InvalidateRect(Handle, nil, False); end; procedure TFormBoard.Timer1Timer(Sender: TObject); begin inherited; if TimerCount<1000000 then inc(TimerCount) else TimerCount:=0; InvalidateRect(Handle, nil, False); end; procedure TFormBoard.Timer2Timer(Sender: TObject); begin inherited; if TimerCount<25 then begin inc(TimerCount); Camera.ypos:=Camera.ypos-0.51; if Camera.ypos<4.1 then Camera.ypos:=4.1; FormPaint(nil); end else begin TimerCount:=0; Timer2.Enabled:=false; end; end; end.
unit ULicAreaSketch; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 2007 by Bradford Technologies, Inc. } { AreaSketch Registration Unit } { This is where the ClickForms determines if AreaSketch has } { been purchased and has been registered on the AreaSketch } { registeration server. It handles Demo and Live registrations.} {$WARN SYMBOL_PLATFORM OFF} {$WARN UNIT_PLATFORM OFF} interface Uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Commctrl, IniFiles, FileCtrl, Registry, ULicUser, AreaSketchService, UStatus, UWebConfig, UWebUtils; function IsAreaSketchLicensed: Boolean; function IsAWAreaSketchLicensed: Boolean; implementation uses UGlobals, UUtil2, UAWSI_Utils, AWSI_Server_AreaSketch; const AREASKETCH_KEY = '\Software\FieldNotes\AreaSketchControl\Registration'; ERROR_SERVER_UNREACHABLE = 'ClickFORMS encountered errors while communicating with the Registration Server.'; ERROR_READING_ASLIC = 'ClickFORMS encountered problems reading AreaSketch Registration Information.'; ERROR_WRITING_ASLIC = 'ClickFORMS encountered problems saving AreaSketch Registration Information.'; ERROR_NO_CUSTID = 'ClickFORMS was unable to read your customer identification. Please make sure you have registered ClickFORMS.'; ERROR_READING_INSTALLID = 'ClickFORMS encountered errors reading the AreaSketch Installation ID.'; ERROR_NO_WWW_CONNECTION = 'ClickFORMS could not connect to Internet. Please make sure you are connected and your firewall is not blocking ClickFORMS.'; ERROR_NEED_CUST_INFO = 'Additional contact information is required to get a trial version of AreaSketch. Make sure you have entered your email address and phone number.'; ERROR_READING_ASEXP = 'ClickFORMS encountered errors while reading AreaSketch evaluation expiration.'; ERROR_WRITING_ASEXP = 'ClickFORMS encountered errors while writing AreaSketch evaluation expiration.'; STUDENT_EVAL_DAYS = 90; MAX_EVAL_DAYS = 14; MAX_REG_DAYS = 365; function IsAreaSketchRegistered: Boolean; forward; function RegisterAreaSketchUsage(demoUsage: Boolean): Boolean; forward; function RegisterAWAreaSketchUsage(demoUsage: Boolean): Boolean; forward; function GetAreaSketchRegFlag: String; forward; function SetAreaSketchRegFlag(Value: String): Boolean; forward; function GetAreaSketchInstallationID: String; forward; // new functions to add exp date into registry for preventing // the AreaSketch registration dialog to show up function SetAreaSketchEvalExp: boolean; forward; function IsAreaSketchEvalExpired: Boolean; forward; procedure UpdateAreaSketchEvalExp; forward; function IsAreaSketchLicensed: Boolean; begin try //has someone on this computer purchased AreaSketch? if LicensedUsers.HasRegisteredUserFor(pidAreaSketchDesktop) then begin if IsAreaSketchRegistered then result := True else result := RegisterAreaSketchUsage(False); //False = Live usage end //not purchased - allow usage in demo mode else begin result := True; //may have self-registered if not IsAreaSketchRegistered then result := RegisterAreaSketchUsage(True); //True = Demo usage end; except on E: Exception do begin ShowAlert(atWarnAlert, E.Message); result := False; end; end; end; function IsAWAreaSketchLicensed: Boolean; begin try //has someone on this computer purchased AreaSketch? if LicensedUsers.HasRegisteredUserFor(pidAreaSketchDesktop) then begin if IsAreaSketchRegistered then result := True else result := RegisterAWAreaSketchUsage(False); //False = Live usage end //not purchased - allow usage in demo mode else begin result := True; //may have self-registered if not IsAreaSketchRegistered then result := RegisterAWAreaSketchUsage(True); //True = Demo usage end; except on E: Exception do begin ShowAlert(atWarnAlert, E.Message); result := False; end; end; end; //this function will check whether AreaSketch has been //registered and unlocked by the FieldNotes server function IsAreaSketchRegistered: Boolean; begin result := false; //check windows registery setting if (Length(GetAreaSketchRegFlag) = 32) {and (IsAreaSketchEvalExpired = False)} then //comment out check for now - needs testing Result := True; end; function SetAreaSketchRegFlag(Value: String): boolean; var Reg: TRegistry; begin Result := False; Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; try if Reg.OpenKey(AREASKETCH_KEY, True) then begin Reg.DeleteKey('Lic'); Reg.WriteString('Lic',TRIM(Value)); Reg.CloseKey; Result := True; end; except Raise Exception.Create(ERROR_WRITING_ASLIC); end; finally Reg.Free; end; end; function GetAreaSketchRegFlag: String; var Reg: TRegistry; begin Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := HKEY_LOCAL_MACHINE; try // False because we do not want to create it if it doesn't exist Reg.OpenKey(AREASKETCH_KEY, False); Result := Reg.ReadString('Lic'); //get flag from registry except Raise Exception.Create(ERROR_READING_ASLIC); end; finally Reg.Free; end; end; function SetAreaSketchEvalExp: boolean; var Reg: TRegistry; begin Result := False; Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; try if Reg.OpenKey(AREASKETCH_KEY, True) then begin Reg.WriteDateTime('Exp',Date + MAX_EVAL_DAYS); //14 days from today Reg.CloseKey; Result := True; end; except Raise Exception.Create(ERROR_WRITING_ASEXP); end; finally Reg.Free; end; end; function IsAreaSketchEvalExpired: Boolean; var Reg: TRegistry; ExpDt: TDateTime; begin Result := False; Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := HKEY_LOCAL_MACHINE; try // False because we do not want to create it if it doesn't exist if Reg.OpenKey(AREASKETCH_KEY, False) then begin if Reg.KeyExists('Exp') then begin ExpDt := Reg.ReadDate('Exp'); //get expiration Date from registry //if its not expired return true if ExpDt < Date() then Result := True; end; end; except Raise Exception.Create(ERROR_READING_ASEXP); end; finally Reg.Free; end; end; procedure UpdateAreaSketchEvalExp; var Reg: TRegistry; begin Reg := TRegistry.Create(KEY_READ or KEY_WRITE); try Reg.RootKey := HKEY_LOCAL_MACHINE; try // False because we do not want to create it if it doesn't exist Reg.OpenKey(AREASKETCH_KEY, False); //delete and create the new key with 365 days exp, later on we might bring //back the actual exp date from the AreaSketch Registration Server. if Reg.ValueExists('Exp') then Reg.DeleteValue('Exp'); Reg.WriteDateTime('Exp', (Date() + MAX_REG_DAYS)); except Raise Exception.Create(ERROR_READING_ASEXP); end; finally Reg.Free; end; end; //this funciton gets the Installation ID for AreaSketch //function is based on Hongs Document function GetAreaSketchInstallationID: String; var RootPath: array[0..20] of char; VolName: array[0..255] of char; SerialNumber, MaxCLength,FileSysFlag: DWORD; FileSystemName: array[0..255] of char; InstallID : String; pBuf : array[0..3] of byte; begin try RootPath := 'C:\'; //get the volume information GetVolumeInformation(RootPath,VolName,255,@SerialNumber, MaxCLength, FileSysFlag, FileSystemName, 255); //build InstallID Move(SerialNumber, pBuf, SizeOf(SerialNumber)); //SerialNumber is a DWORD which can only hold 4 BYTE, Hong is overreading the //buffer for 5th and 6th Byte in his function but it will always result into //0000, so this function is changed to always have 0000 as last 2 bytes InstallID := Format('%2.2x%2.2x%2.2x%2.2x',[pBuf[0],pBuf[1],pBuf[2],pBuf[3]]); Result := InstallID + '0000'; except result := ''; Raise Exception.Create(ERROR_READING_INSTALLID); end; end; function HasMandatoryCustomerInfo(demoCustomer: TrialCustomer): Boolean; begin result := False; //these are mandatory if (length(demoCustomer.FName) > 0) and (length(demoCustomer.LName) > 0) and (length(demoCustomer.Email) > 0) and (length(demoCustomer.Phone) > 0) and (length(demoCustomer.DeviceID) > 0) then result := True; //these are not critical, but server wants something if length(demoCustomer.CompanyName) = 0 then demoCustomer.CompanyName := 'NONE'; if length(demoCustomer.Street) = 0 then demoCustomer.Street := 'NONE'; if length(demoCustomer.City) = 0 then demoCustomer.City := 'NONE'; if length(demoCustomer.State) = 0 then demoCustomer.State := 'XX'; if length(demoCustomer.Zip) = 0 then demoCustomer.Zip := '00000'; end; //this is the routine for registering AreaSketch on //the Field Notes server and getting the stored the results function RegisterAreaSketchUsage(demoUsage: Boolean): Boolean; var demoCustomer: TrialCustomer; sMsgs, sEvaluateResult, sRegResult, sInstallID: WideString; iMsgCode, iCustID: Integer; begin sMsgs := ''; iMsgCode := 0; Result := False; if Not IsconnectedtoWeb Then begin Raise Exception.Create(Error_no_www_connection); end; if demoUsage then begin sEvaluateResult := ''; //create the demoCustomer, its a remotable class defined in the WSDL demoCustomer := TrialCustomer.Create; try demoCustomer.FName := ULicUser.CurrentUser.UserInfo.FirstName; if length(demoCustomer.FName) = 0 then demoCustomer.FName := GetNamePart(ULicUser.CurrentUser.SWLicenseName, 1); if length(demoCustomer.FName) = 0 then demoCustomer.FName := 'FIRST'; demoCustomer.LName := ULicUser.CurrentUser.UserInfo.LastName; if length(demoCustomer.LName) = 0 then demoCustomer.LName := GetNamePart(ULicUser.CurrentUser.SWLicenseName, 2); if length(demoCustomer.LName) = 0 then demoCustomer.LName := 'LAST'; demoCustomer.CompanyName := ULicUser.CurrentUser.SWLicenseCoName; if length(demoCustomer.CompanyName) = 0 then demoCustomer.CompanyName := 'COMPANY'; demoCustomer.Street := ULicUser.CurrentUser.UserInfo.Address; demoCustomer.City := ULicUser.CurrentUser.UserInfo.City; demoCustomer.State := ULicUser.CurrentUser.UserInfo.State; demoCustomer.Zip := ULicUser.CurrentUser.UserInfo.Zip; demoCustomer.Email := ULicUser.CurrentUser.UserInfo.Email; if length(demoCustomer.Email)= 0 then demoCustomer.Email := 'sales@bradfordsoftware.com'; demoCustomer.Phone := ULicUser.CurrentUser.UserInfo.Phone; if length(demoCustomer.Phone) = 0 then demoCustomer.Phone := '408-360-8520'; demoCustomer.DeviceID := GetAreaSketchInstallationID; //has the mandatory info been entered, if not punt. if not HasMandatoryCustomerInfo(demoCustomer) then Raise Exception.Create(ERROR_NEED_CUST_INFO); try //call the AsreaSketch Web Service evaluate funtion to evaluate with GetAreaSketchServiceSoap(True, UWebConfig.GetURLForAreaSketch) do EvaluateAreaSketch(demoCustomer, 0, UWebConfig.WSASketch_Password, sEvaluateResult, iMsgCode, sMsgs); if (iMsgCode = 0) and (Length(sEvaluateResult) = 32) then begin //save the authorization key to the registry SetAreaSketchRegFlag(sEvaluateResult); SetAreaSketchEvalExp; ShowNotice('You have been registered for a 90 day demo of AreaSketch.'); Result := True; end else ShowAlert(atWarnAlert, sMsgs); except Raise Exception.Create(ERROR_SERVER_UNREACHABLE); Result := False; end; finally demoCustomer.Free; end; end //register a live version else begin // procedure RegisterAreaSketch(const sPass: WideString; const iCustID: Integer; const sDeviceID: WideString; const IsPPC: Boolean; out RegisterAreaSketchResult: WideString; out iMsgCode: Integer; out sMsgs: WideString); stdcall; try iCustID := StrToIntDef(CurrentUser.UserCustUID, 0); except raise exception.Create(ERROR_NO_CUSTID); end; try sInstallID := GetAreaSketchInstallationID; with GetAreaSketchServiceSoap(True, UWebConfig.GetURLForAreaSketch) do RegisterAreaSketch(UWebConfig.WSASketch_Password, iCustID, sInstallID, 0, sRegResult, iMsgCode, sMsgs); except Raise Exception.Create(ERROR_SERVER_UNREACHABLE); end; if (iMsgCode = 0) and (Length(Trim(sRegResult)) = 32) then begin //save the authorization key to the registry SetAreaSketchRegFlag(sRegResult); //update the eval expiration key UpdateAreaSketchEvalExp; Result := True; end else begin Raise Exception.Create(sMsgs); result := False; end; end; end; function HasAWMandatoryCustomerInfo(demoCustomer: clsTrialCustomer): Boolean; begin result := False; //these are mandatory if (length(demoCustomer.FName) > 0) and (length(demoCustomer.LName) > 0) and (length(demoCustomer.Email) > 0) and (length(demoCustomer.Phone) > 0) and (length(demoCustomer.DeviceID) > 0) then result := True; //these are not critical, but server wants something if length(demoCustomer.CompanyName) = 0 then demoCustomer.CompanyName := 'NONE'; if length(demoCustomer.Street) = 0 then demoCustomer.Street := 'NONE'; if length(demoCustomer.City) = 0 then demoCustomer.City := 'NONE'; if length(demoCustomer.State) = 0 then demoCustomer.State := 'XX'; if length(demoCustomer.Zip) = 0 then demoCustomer.Zip := '00000'; end; //this is the routine for registering AreaSketch on //the Field Notes server and getting the stored the results function RegisterAWAreaSketchUsage(demoUsage: Boolean): Boolean; var demoCustomer: clsTrialCustomer; sMsgs, sEvaluateResult, sRegResult: WideString; iCustID: Integer; Request: clsRegisterAreaSketchRequest; begin sMsgs := ''; Result := False; if Not IsconnectedtoWeb Then begin Raise Exception.Create(Error_no_www_connection); end; Request := clsRegisterAreaSketchRequest.Create; Request.DeviceID := GetAreaSketchInstallationID; Request.IsPPC := 0; if demoUsage then begin sEvaluateResult := ''; //create the demoCustomer, its a remotable class defined in the WSDL demoCustomer := clsTrialCustomer.Create; try demoCustomer.FName := ULicUser.CurrentUser.UserInfo.FirstName; if length(demoCustomer.FName) = 0 then demoCustomer.FName := GetNamePart(ULicUser.CurrentUser.SWLicenseName, 1); if length(demoCustomer.FName) = 0 then demoCustomer.FName := 'FIRST'; demoCustomer.LName := ULicUser.CurrentUser.UserInfo.LastName; if length(demoCustomer.LName) = 0 then demoCustomer.LName := GetNamePart(ULicUser.CurrentUser.SWLicenseName, 2); if length(demoCustomer.LName) = 0 then demoCustomer.LName := 'LAST'; demoCustomer.CompanyName := ULicUser.CurrentUser.SWLicenseCoName; if length(demoCustomer.CompanyName) = 0 then demoCustomer.CompanyName := 'COMPANY'; demoCustomer.Street := ULicUser.CurrentUser.UserInfo.Address; demoCustomer.City := ULicUser.CurrentUser.UserInfo.City; demoCustomer.State := ULicUser.CurrentUser.UserInfo.State; demoCustomer.Zip := ULicUser.CurrentUser.UserInfo.Zip; demoCustomer.Email := ULicUser.CurrentUser.UserInfo.Email; if length(demoCustomer.Email)= 0 then demoCustomer.Email := 'sales@bradfordsoftware.com'; demoCustomer.Phone := ULicUser.CurrentUser.UserInfo.Phone; if length(demoCustomer.Phone) = 0 then demoCustomer.Phone := '408-360-8520'; demoCustomer.DeviceID := GetAreaSketchInstallationID; //has the mandatory info been entered, if not punt. if not HasAWMandatoryCustomerInfo(demoCustomer) then Raise Exception.Create(ERROR_NEED_CUST_INFO); try //call the AW AreaSketch Web Service evaluate funtion to evaluate if AWSI_SetCFAreaSketchEvaluation(AWCustomerID, AWCustomerPSW, CurrentUser.UserCustUID, demoCustomer, sRegResult) then begin //save the authorization key to the registry SetAreaSketchRegFlag(sEvaluateResult); SetAreaSketchEvalExp; ShowNotice('You have been registered for a 90 day demo of AreaSketch.'); Result := True; end else ShowAlert(atWarnAlert, sMsgs); except Raise Exception.Create(ERROR_SERVER_UNREACHABLE); Result := False; end; finally demoCustomer.Free; end; end //register a live version else begin try iCustID := StrToIntDef(CurrentUser.UserCustUID, 0); except raise exception.Create(ERROR_NO_CUSTID); end; if AWSI_SetCFAreaSketchRegistration(AWCustomerID, AWCustomerPSW, CurrentUser.UserCustUID, Request, sRegResult) then begin //save the authorization key to the registry SetAreaSketchRegFlag(sRegResult); //update the eval expiration key UpdateAreaSketchEvalExp; Result := True; end else begin Raise Exception.Create(sMsgs); result := False; end; end; Request.Free; end; end.
unit ULicSelectUser; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 2018 by Bradford Technologies, Inc. } { when there are multiple licensed users files, this allows one to be selected} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, UForms; type TSelectLicUser = class(TAdvancedForm) btnSelect: TButton; btnCancel: TButton; UserList: TListBox; cbxIsDefault: TCheckBox; procedure UserListClick(Sender: TObject); procedure UserListDblClick(Sender: TObject); procedure btnSelectClick(Sender: TObject); procedure btnNewClick(Sender: TObject); private procedure ProcessLicFile(Sender: TObject; FileName: string); procedure LoadUserList; public constructor Create(AOwner: TComponent); override; procedure GatherUserLicFiles; end; //main routin for calling this object //function SelectLicUserFile: String; var SelectLicUser: TSelectLicUser; implementation uses UGlobals, UFileFinder,ULicUser,ULicRegistration2; {$R *.dfm} { TSelectLicUser } constructor TSelectLicUser.Create(AOwner: TComponent); begin inherited; // btnSelect.Enabled := False; end; procedure TSelectLicUser.ProcessLicFile(Sender: TObject; FileName: string); var fName: String; begin fName := ExtractFileName(fileName); if compareText('Owner.lic', fName) <> 0 then UserList.Items.Add(fName); end; procedure TSelectLicUser.GatherUserLicFiles; begin FileFinder.OnFileFound := ProcessLicFile; FileFinder.Find(appPref_DirLicenses, False, '*.lic'); //find all lic files UserList.Sorted := True; end; procedure TSelectLicUser.UserListClick(Sender: TObject); begin btnSelect.Enabled := (UserList.ItemIndex > -1); end; procedure TSelectLicUser.UserListDblClick(Sender: TObject); begin btnSelect.Enabled := (UserList.ItemIndex > -1); btnSelectClick(Sender); end; procedure TSelectLicUser.btnSelectClick(Sender: TObject); begin if (UserList.ItemIndex > -1) then ModalResult := mrOK; end; procedure TSelectLicUser.LoadUserList; var i: Integer; fName: String; begin UserList.Items.Clear; if assigned(LicensedUsers) then for i := 0 to LicensedUsers.count -1 do begin fName := TUser(LicensedUsers.Items[i]).FLicName; UserList.Items.add(fName); end; end; //#1476: we now allow multiple user registration to create registration for new user through //multi select dialog procedure TSelectLicUser.btnNewClick(Sender: TObject); var UserReg: TRegistration2; ModalResult: TModalResult; User:TLicensedUser; begin User := TLicensedUser.create; try UserReg := TRegistration2.CreateRegistar(nil, User, rtPaidLicMode, False); ModalResult := UserReg.ShowModal; if ModalResult = mrOK then CurrentUser := User else if ModalResult = mrCancel then btnCancel.Click; finally UserReg.Free; end; end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 23.07.2021 14:40:17 unit IdOpenSSLHeaders_evp; interface // Headers for OpenSSL 1.1.1 // evp.h {$i IdCompilerDefines.inc} uses Classes, IdCTypes, IdGlobal, IdOpenSSLConsts, IdOpenSSlHeaders_bio, IdOpenSSLHeaders_obj_mac, IdOpenSSlHeaders_ossl_typ; const EVP_MAX_MD_SIZE = 64; // longest known is SHA512 EVP_MAX_KEY_LENGTH = 64; EVP_MAX_IV_LENGTH = 16; EVP_MAX_BLOCK_LENGTH = 32; PKCS5_SALT_LEN = 8; // Default PKCS#5 iteration count PKCS5_DEFAULT_ITER = 2048; EVP_PK_RSA = $0001; EVP_PK_DSA = $0002; EVP_PK_DH = $0004; EVP_PK_EC = $0008; EVP_PKT_SIGN = $0010; EVP_PKT_ENC = $0020; EVP_PKT_EXCH = $0040; EVP_PKS_RSA = $0100; EVP_PKS_DSA = $0200; EVP_PKS_EC = $0400; EVP_PKEY_NONE = NID_undef; EVP_PKEY_RSA = NID_rsaEncryption; EVP_PKEY_RSA2 = NID_rsa; EVP_PKEY_RSA_PSS = NID_rsassaPss; EVP_PKEY_DSA = NID_dsa; EVP_PKEY_DSA1 = NID_dsa_2; EVP_PKEY_DSA2 = NID_dsaWithSHA; EVP_PKEY_DSA3 = NID_dsaWithSHA1; EVP_PKEY_DSA4 = NID_dsaWithSHA1_2; EVP_PKEY_DH = NID_dhKeyAgreement; EVP_PKEY_DHX = NID_dhpublicnumber; EVP_PKEY_EC = NID_X9_62_id_ecPublicKey; EVP_PKEY_SM2 = NID_sm2; EVP_PKEY_HMAC = NID_hmac; EVP_PKEY_CMAC = NID_cmac; EVP_PKEY_SCRYPT = NID_id_scrypt; EVP_PKEY_TLS1_PRF = NID_tls1_prf; EVP_PKEY_HKDF = NID_hkdf; EVP_PKEY_POLY1305 = NID_poly1305; EVP_PKEY_SIPHASH = NID_siphash; EVP_PKEY_X25519 = NID_X25519; EVP_PKEY_ED25519 = NID_ED25519; EVP_PKEY_X448 = NID_X448; EVP_PKEY_ED448 = NID_ED448; EVP_PKEY_MO_SIGN = $0001; EVP_PKEY_MO_VERIFY = $0002; EVP_PKEY_MO_ENCRYPT = $0004; EVP_PKEY_MO_DECRYPT = $0008; // digest can only handle a single block /// EVP_MD_FLAG_ONESHOT = $0001; // digest is extensible-output function; XOF /// EVP_MD_FLAG_XOF = $0002; // DigestAlgorithmIdentifier flags... /// EVP_MD_FLAG_DIGALGID_MASK = $0018; // NULL or absent parameter accepted. Use NULL /// EVP_MD_FLAG_DIGALGID_NULL = $0000; // NULL or absent parameter accepted. Use NULL for PKCS#1 otherwise absent /// EVP_MD_FLAG_DIGALGID_ABSENT = $0008; // Custom handling via ctrl /// EVP_MD_FLAG_DIGALGID_CUSTOM = $0018; // Note if suitable for use in FIPS mode /// EVP_MD_FLAG_FIPS = $0400; // Digest ctrls /// EVP_MD_CTRL_DIGALGID = $1; EVP_MD_CTRL_MICALG = $2; EVP_MD_CTRL_XOF_LEN = $3; // Minimum Algorithm specific ctrl value /// EVP_MD_CTRL_ALG_CTRL = $1000; // not EVP_MD /// // values for EVP_MD_CTX flags /// EVP_MD_CTX_FLAG_ONESHOT = $0001; EVP_MD_CTX_FLAG_CLEANED = $0002; EVP_MD_CTX_FLAG_REUSE = $0004; // // FIPS and pad options are ignored in 1.0.0; definitions are here so we // don't accidentally reuse the values for other purposes. /// EVP_MD_CTX_FLAG_NON_FIPS_ALLOW = $0008; // // The following PAD options are also currently ignored in 1.0.0; digest // parameters are handled through EVP_DigestSign//() and EVP_DigestVerify//() // instead. /// EVP_MD_CTX_FLAG_PAD_MASK = $F0; EVP_MD_CTX_FLAG_PAD_PKCS1 = $00; EVP_MD_CTX_FLAG_PAD_X931 = $10; EVP_MD_CTX_FLAG_PAD_PSS = $20; EVP_MD_CTX_FLAG_NO_INIT = $0100; // // Some functions such as EVP_DigestSign only finalise copies of internal // contexts so additional data can be included after the finalisation call. // This is inefficient if this functionality is not required: it is disabled // if the following flag is set. /// EVP_MD_CTX_FLAG_FINALISE = $0200; // NOTE: $0400 is reserved for internal usage /// // Values for cipher flags /// // Modes for ciphers /// EVP_CIPH_STREAM_CIPHER = $0; EVP_CIPH_ECB_MODE = $1; EVP_CIPHC_MODE = $2; EVP_CIPH_CFB_MODE = $3; EVP_CIPH_OFB_MODE = $4; EVP_CIPH_CTR_MODE = $5; EVP_CIPH_GCM_MODE = $6; EVP_CIPH_CCM_MODE = $7; EVP_CIPH_XTS_MODE = $10001; EVP_CIPH_WRAP_MODE = $10002; EVP_CIPH_OCB_MODE = $10003; EVP_CIPH_MODE = $F0007; // Set if variable length cipher /// EVP_CIPH_VARIABLE_LENGTH = $8; // Set if the iv handling should be done by the cipher itself /// EVP_CIPH_CUSTOM_IV = $10; // Set if the cipher's init() function should be called if key is NULL /// EVP_CIPH_ALWAYS_CALL_INIT = $20; // Call ctrl() to init cipher parameters /// EVP_CIPH_CTRL_INIT = $40; // Don't use standard key length function /// EVP_CIPH_CUSTOM_KEY_LENGTH = $80; // Don't use standard block padding /// EVP_CIPH_NO_PADDING = $100; // cipher handles random key generation /// EVP_CIPH_RAND_KEY = $200; // cipher has its own additional copying logic /// EVP_CIPH_CUSTOM_COPY = $400; // Don't use standard iv length function /// EVP_CIPH_CUSTOM_IV_LENGTH = $800; // Allow use default ASN1 get/set iv /// EVP_CIPH_FLAG_DEFAULT_ASN1 = $1000; // Buffer length in bits not bytes: CFB1 mode only /// EVP_CIPH_FLAG_LENGTH_BITS = $2000; // Note if suitable for use in FIPS mode /// EVP_CIPH_FLAG_FIPS = $4000; // Allow non FIPS cipher in FIPS mode /// EVP_CIPH_FLAG_NON_FIPS_ALLOW = $8000; // // Cipher handles any and all padding logic as well as finalisation. /// EVP_CIPH_FLAG_CUSTOM_CIPHER = $100000; EVP_CIPH_FLAG_AEAD_CIPHER = $200000; EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK = $400000; // Cipher can handle pipeline operations /// EVP_CIPH_FLAG_PIPELINE = $800000; // // Cipher context flag to indicate we can handle wrap mode: if allowed in // older applications it could overflow buffers. /// EVP_CIPHER_CTX_FLAG_WRAP_ALLOW = $1; // ctrl() values /// EVP_CTRL_INIT = $0; EVP_CTRL_SET_KEY_LENGTH = $1; EVP_CTRL_GET_RC2_KEY_BITS = $2; EVP_CTRL_SET_RC2_KEY_BITS = $3; EVP_CTRL_GET_RC5_ROUNDS = $4; EVP_CTRL_SET_RC5_ROUNDS = $5; EVP_CTRL_RAND_KEY = $6; EVP_CTRL_PBE_PRF_NID = $7; EVP_CTRL_COPY = $8; EVP_CTRL_AEAD_SET_IVLEN = $9; EVP_CTRL_AEAD_GET_TAG = $10; EVP_CTRL_AEAD_SET_TAG = $11; EVP_CTRL_AEAD_SET_IV_FIXED = $12; EVP_CTRL_GCM_SET_IVLEN = EVP_CTRL_AEAD_SET_IVLEN; EVP_CTRL_GCM_GET_TAG = EVP_CTRL_AEAD_GET_TAG; EVP_CTRL_GCM_SET_TAG = EVP_CTRL_AEAD_SET_TAG; EVP_CTRL_GCM_SET_IV_FIXED = EVP_CTRL_AEAD_SET_IV_FIXED; EVP_CTRL_GCM_IV_GEN = $13; EVP_CTRL_CCM_SET_IVLEN = EVP_CTRL_AEAD_SET_IVLEN; EVP_CTRL_CCM_GET_TAG = EVP_CTRL_AEAD_GET_TAG; EVP_CTRL_CCM_SET_TAG = EVP_CTRL_AEAD_SET_TAG; EVP_CTRL_CCM_SET_IV_FIXED = EVP_CTRL_AEAD_SET_IV_FIXED; EVP_CTRL_CCM_SET_L = $14; EVP_CTRL_CCM_SET_MSGLEN = $15; // // AEAD cipher deduces payload length and returns number of bytes required to // store MAC and eventual padding. Subsequent call to EVP_Cipher even // appends/verifies MAC. /// EVP_CTRL_AEAD_TLS1_AAD = $16; // Used by composite AEAD ciphers; no-op in GCM; CCM... /// EVP_CTRL_AEAD_SET_MAC_KEY = $17; // Set the GCM invocation field; decrypt only /// EVP_CTRL_GCM_SET_IV_INV = $18; EVP_CTRL_TLS1_1_MULTIBLOCK_AAD = $19; EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT = $1a; EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT = $1b; EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE = $1c; EVP_CTRL_SSL3_MASTER_SECRET = $1d; // EVP_CTRL_SET_SBOX takes the PIdAnsiChar// specifying S-boxes/// EVP_CTRL_SET_SBOX = $1e; // // EVP_CTRL_SBOX_USED takes a 'TIdC_SIZET' and 'PIdAnsiChar//'; pointing at a // pre-allocated buffer with specified size /// EVP_CTRL_SBOX_USED = $1f; // EVP_CTRL_KEY_MESH takes 'TIdC_SIZET' number of bytes to mesh the key after; // 0 switches meshing off /// EVP_CTRL_KEY_MESH = $20; // EVP_CTRL_BLOCK_PADDING_MODE takes the padding mode/// EVP_CTRL_BLOCK_PADDING_MODE = $21; // Set the output buffers to use for a pipelined operation/// EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS = $22; // Set the input buffers to use for a pipelined operation/// EVP_CTRL_SET_PIPELINE_INPUT_BUFS = $23; // Set the input buffer lengths to use for a pipelined operation/// EVP_CTRL_SET_PIPELINE_INPUT_LENS = $24; EVP_CTRL_GET_IVLEN = $25; // Padding modes/// EVP_PADDING_PKCS7 = 1; EVP_PADDING_ISO7816_4 = 2; EVP_PADDING_ANSI923 = 3; EVP_PADDING_ISO10126 = 4; EVP_PADDING_ZERO = 5; // RFC 5246 defines additional data to be 13 bytes in length/// EVP_AEAD_TLS1_AAD_LEN = 13; // GCM TLS constants/// // Length of fixed part of IV derived from PRF/// EVP_GCM_TLS_FIXED_IV_LEN = 4; // Length of explicit part of IV part of TLS records/// EVP_GCM_TLS_EXPLICIT_IV_LEN = 8; // Length of tag for TLS EVP_GCM_TLS_TAG_LEN = 16; /// CCM TLS constants /// /// Length of fixed part of IV derived from PRF /// EVP_CCM_TLS_FIXED_IV_LEN = 4; /// Length of explicit part of IV part of TLS records /// EVP_CCM_TLS_EXPLICIT_IV_LEN = 8; /// Total length of CCM IV length for TLS /// EVP_CCM_TLS_IV_LEN = 12; /// Length of tag for TLS /// EVP_CCM_TLS_TAG_LEN = 16; /// Length of CCM8 tag for TLS /// EVP_CCM8_TLS_TAG_LEN = 8; /// Length of tag for TLS /// EVP_CHACHAPOLY_TLS_TAG_LEN = 16; (* Can appear as the outermost AlgorithmIdentifier *) EVP_PBE_TYPE_OUTER = $0; (* Is an PRF type OID *) EVP_PBE_TYPE_PRF = $1; (* Is a PKCS#5 v2.0 KDF *) EVP_PBE_TYPE_KDF = $2; ASN1_PKEY_ALIAS = $1; ASN1_PKEY_DYNAMIC = $2; ASN1_PKEY_SIGPARAM_NULL = $4; ASN1_PKEY_CTRL_PKCS7_SIGN = $1; ASN1_PKEY_CTRL_PKCS7_ENCRYPT = $2; ASN1_PKEY_CTRL_DEFAULT_MD_NID = $3; ASN1_PKEY_CTRL_CMS_SIGN = $5; ASN1_PKEY_CTRL_CMS_ENVELOPE = $7; ASN1_PKEY_CTRL_CMS_RI_TYPE = $8; ASN1_PKEY_CTRL_SET1_TLS_ENCPT = $9; ASN1_PKEY_CTRL_GET1_TLS_ENCPT = $a; EVP_PKEY_OP_UNDEFINED = 0; EVP_PKEY_OP_PARAMGEN = (1 shl 1); EVP_PKEY_OP_KEYGEN = (1 shl 2); EVP_PKEY_OP_SIGN = (1 shl 3); EVP_PKEY_OP_VERIFY = (1 shl 4); EVP_PKEY_OP_VERIFYRECOVER = (1 shl 5); EVP_PKEY_OP_SIGNCTX = (1 shl 6); EVP_PKEY_OP_VERIFYCTX = (1 shl 7); EVP_PKEY_OP_ENCRYPT = (1 shl 8); EVP_PKEY_OP_DECRYPT = (1 shl 9); EVP_PKEY_OP_DERIVE = (1 shl 10); EVP_PKEY_OP_TYPE_SIG = EVP_PKEY_OP_SIGN or EVP_PKEY_OP_VERIFY or EVP_PKEY_OP_VERIFYRECOVER or EVP_PKEY_OP_SIGNCTX or EVP_PKEY_OP_VERIFYCTX; EVP_PKEY_OP_TYPE_CRYPT = EVP_PKEY_OP_ENCRYPT or EVP_PKEY_OP_DECRYPT; EVP_PKEY_OP_TYPE_NOGEN = EVP_PKEY_OP_TYPE_SIG or EVP_PKEY_OP_TYPE_CRYPT or EVP_PKEY_OP_DERIVE; EVP_PKEY_OP_TYPE_GEN = EVP_PKEY_OP_PARAMGEN or EVP_PKEY_OP_KEYGEN; EVP_PKEY_CTRL_MD = 1; EVP_PKEY_CTRL_PEER_KEY = 2; EVP_PKEY_CTRL_PKCS7_ENCRYPT = 3; EVP_PKEY_CTRL_PKCS7_DECRYPT = 4; EVP_PKEY_CTRL_PKCS7_SIGN = 5; EVP_PKEY_CTRL_SET_MAC_KEY = 6; EVP_PKEY_CTRL_DIGESTINIT = 7; (* Used by GOST key encryption in TLS *) EVP_PKEY_CTRL_SET_IV = 8; EVP_PKEY_CTRL_CMS_ENCRYPT = 9; EVP_PKEY_CTRL_CMS_DECRYPT = 10; EVP_PKEY_CTRL_CMS_SIGN = 11; EVP_PKEY_CTRL_CIPHER = 12; EVP_PKEY_CTRL_GET_MD = 13; EVP_PKEY_CTRL_SET_DIGEST_SIZE = 14; EVP_PKEY_ALG_CTRL = $1000; EVP_PKEY_FLAG_AUTOARGLEN = 2; // // Method handles all operations: don't assume any digest related defaults. // EVP_PKEY_FLAG_SIGCTX_CUSTOM = 4; type EVP_MD_meth_init = function(ctx: PEVP_MD_CTX): TIdC_INT; cdecl; EVP_MD_meth_update = function(ctx: PEVP_MD_CTX; const data: Pointer; count: TIdC_SIZET): TIdC_INT; cdecl; EVP_MD_meth_final = function(ctx: PEVP_MD_CTX; const md: PByte): TIdC_INT; cdecl; EVP_MD_meth_copy = function(to_: PEVP_MD_CTX; const from: PEVP_MD_CTX): TIdC_INT; cdecl; EVP_MD_meth_cleanup = function(ctx: PEVP_MD_CTX): TIdC_INT; cdecl; EVP_MD_meth_ctrl = function(ctx: PEVP_MD_CTX; cmd: TIdC_INT; p1: TIdC_INT; p2: Pointer): TIdC_INT; cdecl; EVP_CIPHER_meth_init = function(ctx: PEVP_CIPHER_CTX; const key: PByte; const iv: PByte; enc: TIdC_SIZET): TIdC_INT; cdecl; EVP_CIPHER_meth_do_cipher = function(ctx: PEVP_CIPHER_CTX; out_: PByte; const in_: PByte; inl: TIdC_SIZET): TIdC_INT; cdecl; EVP_CIPHER_meth_cleanup = function(v1: PEVP_CIPHER_CTX): TIdC_INT; cdecl; EVP_CIPHER_meth_set_asn1_params = function(v1: PEVP_CIPHER_CTX; v2: PASN1_TYPE): TIdC_INT; cdecl; EVP_CIPHER_meth_get_asn1_params = function(v1: PEVP_CIPHER_CTX; v2: PASN1_TYPE): TIdC_INT; cdecl; EVP_CIPHER_meth_ctrl = function(v1: PEVP_CIPHER_CTX; type_: TIdC_INT; arg: TIdC_INT; ptr: Pointer): TIdC_INT; cdecl; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM = record out_: PByte; inp: PByte; len: TIdC_SIZET; interleave: TidC_UINT; end; evp_cipher_info_st = record cipher: PEVP_CIPHER; iv: array[0 .. EVP_MAX_IV_LENGTH - 1] of PByte; end; EVP_CIPHER_INFO = evp_cipher_info_st; EVP_MD_CTX_update = function(ctx: PEVP_MD_CTX; const data: Pointer; count: TIdC_SIZET): TIdC_INT; cdecl; fn = procedure(const ciph: PEVP_CIPHER; const from: PIdAnsiChar; const to_: PIdAnsiChar; x: Pointer); cdecl; pub_decode = function(pk: PEVP_PKEY; pub: PX509_PUBKEY): TIdC_INT; cdecl; pub_encode = function(pub: PX509_PUBKEY; const pk: PEVP_PKEY): TIdC_INT; cdecl; pub_cmd = function(const a: PEVP_PKEY; const b: PEVP_PKEY): TIdC_INT; cdecl; pub_print = function(out_: PBIO; const pkey: PEVP_PKEY; indent: TIdC_INT; pctx: PASN1_PCTX): TIdC_INT; cdecl; pkey_size = function(const pk: PEVP_PKEY): TIdC_INT; cdecl; pkey_bits = function(const pk: PEVP_PKEY): TIdC_INT; cdecl; priv_decode = function(pk: PEVP_PKEY; const p8inf: PKCS8_PRIV_KEY_INFO): TIdC_INT; cdecl; priv_encode = function(p8: PPKCS8_PRIV_KEY_INFO; const pk: PEVP_PKEY): TIdC_INT; cdecl; priv_print = function(out_: PBIO; const pkea: PEVP_PKEY; indent: TIdC_INT; pctx: PASN1_PCTX): TIdC_INT; cdecl; param_decode = function(pkey: PEVP_PKEY; const pder: PPByte; derlen: TIdC_INT): TIdC_INT; cdecl; param_encode = function(const pkey: PEVP_PKEY; pder: PPByte): TIdC_INT; cdecl; param_missing = function(const pk: PEVP_PKEY): TIdC_INT; cdecl; param_copy = function(to_: PEVP_PKEY; const from: PEVP_PKEY): TIdC_INT; cdecl; param_cmp = function(const a: PEVP_PKEY; const b: PEVP_PKEY): TIdC_INT; cdecl; param_print = function(out_: PBIO; const pkey: PEVP_PKEY; indent: TIdC_INT; pctx: PASN1_PCTX): TIdC_INT; cdecl; pkey_free = procedure(pkey: PEVP_PKEY); cdecl; pkey_ctrl = function(pkey: PEVP_PKEY; op: TIdC_INT; arg1: TIdC_LONG; arg2: Pointer): TIdC_INT; cdecl; item_verify = function(ctx: PEVP_MD_CTX; const it: PASN1_ITEM; asn: Pointer; a: PX509_ALGOR; sig: PASN1_BIT_STRING; pkey: PEVP_PKEY): TIdC_INT; cdecl; item_sign = function(ctx: PEVP_MD_CTX; const it: PASN1_ITEM; asn: Pointer; alg1: PX509_ALGOR; alg2: PX509_ALGOR; sig: PASN1_BIT_STRING): TIdC_INT; cdecl; siginf_set = function(siginf: PX509_SIG_INFO; const alg: PX509_ALGOR; const sig: PASN1_STRING): TIdC_INT; cdecl; pkey_check = function(const pk: PEVP_PKEY): TIdC_INT; cdecl; pkey_pub_check = function(const pk: PEVP_PKEY): TIdC_INT; cdecl; pkey_param_check = function(const pk: PEVP_PKEY): TIdC_INT; cdecl; set_priv_key = function(pk: PEVP_PKEY; const priv: PByte; len: TIdC_SIZET): TIdC_INT; cdecl; set_pub_key = function(pk: PEVP_PKEY; const pub: PByte; len: TIdC_SIZET): TIdC_INT; cdecl; get_priv_key = function(const pk: PEVP_PKEY; priv: PByte; len: PIdC_SIZET): TIdC_INT; cdecl; get_pub_key = function(const pk: PEVP_PKEY; pub: PByte; len: PIdC_SIZET): TIdC_INT; cdecl; pkey_security_bits = function(const pk: PEVP_PKEY): TIdC_INT; cdecl; EVP_PKEY_gen_cb = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; // PEVP_PKEY_gen_cb = ^EVP_PKEY_gen_cb; EVP_PKEY_meth_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_init = ^EVP_PKEY_meth_init; EVP_PKEY_meth_copy_cb = function(dst: PEVP_PKEY_CTX; src: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_copy = ^EVP_PKEY_meth_copy_cb; EVP_PKEY_meth_cleanup = procedure(ctx: PEVP_PKEY_CTX); cdecl; PEVP_PKEY_meth_cleanup = ^EVP_PKEY_meth_cleanup; EVP_PKEY_meth_paramgen_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_paramgen_init = ^EVP_PKEY_meth_paramgen_init; EVP_PKEY_meth_paramgen = function(ctx: PEVP_PKEY_CTX; pkey: PEVP_PKEY): TIdC_INT; cdecl; PEVP_PKEY_meth_paramgen = ^EVP_PKEY_meth_paramgen; EVP_PKEY_meth_keygen_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_keygen_init = ^EVP_PKEY_meth_keygen_init; EVP_PKEY_meth_keygen = function(ctx: PEVP_PKEY_CTX; pkey: PEVP_PKEY): TIdC_INT; cdecl; PEVP_PKEY_meth_keygen = ^EVP_PKEY_meth_keygen; EVP_PKEY_meth_sign_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_sign_init = ^EVP_PKEY_meth_sign_init; EVP_PKEY_meth_sign = function(ctx: PEVP_PKEY_CTX; sig: PByte; siglen: TIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT; cdecl; PEVP_PKEY_meth_sign = ^EVP_PKEY_meth_sign; EVP_PKEY_meth_verify_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_verify_init = ^EVP_PKEY_meth_verify_init; EVP_PKEY_meth_verify = function(ctx: PEVP_PKEY_CTX; const sig: PByte; siglen: TIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT; cdecl; PEVP_PKEY_meth_verify = ^EVP_PKEY_meth_verify; EVP_PKEY_meth_verify_recover_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_verify_recover_init = ^EVP_PKEY_meth_verify_recover_init; EVP_PKEY_meth_verify_recover = function(ctx: PEVP_PKEY_CTX; sig: PByte; siglen: TIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT; cdecl; PEVP_PKEY_meth_verify_recover = ^EVP_PKEY_meth_verify_recover; EVP_PKEY_meth_signctx_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_signctx_init = ^EVP_PKEY_meth_signctx_init; EVP_PKEY_meth_signctx = function(ctx: PEVP_PKEY_CTX; sig: Pbyte; siglen: TIdC_SIZET; mctx: PEVP_MD_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_signctx = ^EVP_PKEY_meth_signctx; EVP_PKEY_meth_verifyctx_init = function(ctx: PEVP_PKEY_CTX; mctx: PEVP_MD_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_verifyctx_init = ^EVP_PKEY_meth_verifyctx_init; EVP_PKEY_meth_verifyctx = function(ctx: PEVP_PKEY_CTX; const sig: PByte; siglen: TIdC_INT; mctx: PEVP_MD_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_verifyctx = ^EVP_PKEY_meth_verifyctx; EVP_PKEY_meth_encrypt_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_encrypt_init = ^EVP_PKEY_meth_encrypt_init; EVP_PKEY_meth_encrypt = function(ctx: PEVP_PKEY_CTX; out_: PByte; outlen: TIdC_SIZET; const in_: PByte): TIdC_INT; cdecl; PEVP_PKEY_meth_encrypt = ^ EVP_PKEY_meth_encrypt; EVP_PKEY_meth_decrypt_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_decrypt_init = ^EVP_PKEY_meth_decrypt_init; EVP_PKEY_meth_decrypt = function(ctx: PEVP_PKEY_CTX; out_: PByte; outlen: TIdC_SIZET; const in_: PByte; inlen: TIdC_SIZET): TIdC_INT; cdecl; PEVP_PKEY_meth_decrypt = ^EVP_PKEY_meth_decrypt; EVP_PKEY_meth_derive_init = function(ctx: PEVP_PKEY_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_derive_init = ^EVP_PKEY_meth_derive_init; EVP_PKEY_meth_derive = function(ctx: PEVP_PKEY_CTX; key: PByte; keylen: PIdC_SIZET): TIdC_INT; cdecl; PEVP_PKEY_meth_derive = ^EVP_PKEY_meth_derive; EVP_PKEY_meth_ctrl = function(ctx: PEVP_PKEY_CTX; type_: TIdC_INT; p1: TIdC_INT; p2: Pointer): TIdC_INT; cdecl; PEVP_PKEY_meth_ctrl = ^EVP_PKEY_meth_ctrl; EVP_PKEY_meth_ctrl_str = function(ctx: PEVP_PKEY_CTX; key: PByte; keylen: PIdC_SIZET): TIdC_INT; cdecl; PEVP_PKEY_meth_ctrl_str = ^EVP_PKEY_meth_ctrl_str; EVP_PKEY_meth_digestsign = function(ctx: PEVP_PKEY_CTX; sig: PByte; siglen: PIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT; cdecl; PEVP_PKEY_meth_digestsign = ^EVP_PKEY_meth_digestsign; EVP_PKEY_meth_digestverify = function(ctx: PEVP_MD_CTX; const sig: PByte; siglen: TIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT; cdecl; PEVP_PKEY_meth_digestverify = ^EVP_PKEY_meth_digestverify; EVP_PKEY_meth_check = function(pkey: PEVP_PKEY): TIdC_INT; cdecl; PEVP_PKEY_meth_check = ^EVP_PKEY_meth_check; EVP_PKEY_meth_public_check = function(pkey: PEVP_PKEY): TIdC_INT; cdecl; PEVP_PKEY_meth_public_check = ^EVP_PKEY_meth_public_check; EVP_PKEY_meth_param_check = function(pkey: PEVP_PKEY): TIdC_INT; cdecl; PEVP_PKEY_meth_param_check = ^EVP_PKEY_meth_param_check; EVP_PKEY_meth_digest_custom = function(pkey: PEVP_PKEY; mctx: PEVP_MD_CTX): TIdC_INT; cdecl; PEVP_PKEY_meth_digest_custom = ^EVP_PKEY_meth_digest_custom; // Password based encryption function EVP_PBE_KEYGEN = function(ctx: PEVP_CIPHER_CTX; const pass: PIdAnsiChar; passlen: TIdC_INT; param: PASN1_TYPE; const cipher: PEVP_CIPHER; const md: PEVP_MD; en_de: TIdC_INT): TIdC_INT; cdecl; PEVP_PBE_KEYGEN = ^EVP_PBE_KEYGEN; PPEVP_PBE_KEYGEN = ^PEVP_PBE_KEYGEN; function EVP_PKEY_assign_RSA(pkey: PEVP_PKEY; rsa: Pointer): TIdC_INT; function EVP_PKEY_assign_DSA(pkey: PEVP_PKEY; dsa: Pointer): TIdC_INT; function EVP_PKEY_assign_DH(pkey: PEVP_PKEY; dh: Pointer): TIdC_INT; function EVP_PKEY_assign_EC_KEY(pkey: PEVP_PKEY; eckey: Pointer): TIdC_INT; function EVP_PKEY_assign_SIPHASH(pkey: PEVP_PKEY; shkey: Pointer): TIdC_INT; function EVP_PKEY_assign_POLY1305(pkey: PEVP_PKEY; polykey: Pointer): TIdC_INT; procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); procedure UnLoad; var EVP_MD_meth_new: function(md_type: TIdC_INT; pkey_type: TIdC_INT): PEVP_MD cdecl = nil; EVP_MD_meth_dup: function(const md: PEVP_MD): PEVP_MD cdecl = nil; EVP_MD_meth_free: procedure(md: PEVP_MD) cdecl = nil; EVP_MD_meth_set_input_blocksize: function(md: PEVP_MD; blocksize: TIdC_INT): TIdC_INT cdecl = nil; EVP_MD_meth_set_result_size: function(md: PEVP_MD; resultsize: TIdC_INT): TIdC_INT cdecl = nil; EVP_MD_meth_set_app_datasize: function(md: PEVP_MD; datasize: TIdC_INT): TIdC_INT cdecl = nil; EVP_MD_meth_set_flags: function(md: PEVP_MD; flags: TIdC_ULONG): TIdC_INT cdecl = nil; EVP_MD_meth_set_init: function(md: PEVP_MD; init: EVP_MD_meth_init): TIdC_INT cdecl = nil; EVP_MD_meth_set_update: function(md: PEVP_MD; update: EVP_MD_meth_update): TIdC_INT cdecl = nil; EVP_MD_meth_set_final: function(md: PEVP_MD; final_: EVP_MD_meth_final): TIdC_INT cdecl = nil; EVP_MD_meth_set_copy: function(md: PEVP_MD; copy: EVP_MD_meth_copy): TIdC_INT cdecl = nil; EVP_MD_meth_set_cleanup: function(md: PEVP_MD; cleanup: EVP_MD_meth_cleanup): TIdC_INT cdecl = nil; EVP_MD_meth_set_ctrl: function(md: PEVP_MD; ctrl: EVP_MD_meth_ctrl): TIdC_INT cdecl = nil; EVP_MD_meth_get_input_blocksize: function(const md: PEVP_MD): TIdC_INT cdecl = nil; EVP_MD_meth_get_result_size: function(const md: PEVP_MD): TIdC_INT cdecl = nil; EVP_MD_meth_get_app_datasize: function(const md: PEVP_MD): TIdC_INT cdecl = nil; EVP_MD_meth_get_flags: function(const md: PEVP_MD): TIdC_ULONG cdecl = nil; EVP_MD_meth_get_init: function(const md: PEVP_MD): EVP_MD_meth_init cdecl = nil; EVP_MD_meth_get_update: function(const md: PEVP_MD): EVP_MD_meth_update cdecl = nil; EVP_MD_meth_get_final: function(const md: PEVP_MD): EVP_MD_meth_final cdecl = nil; EVP_MD_meth_get_copy: function(const md: PEVP_MD): EVP_MD_meth_copy cdecl = nil; EVP_MD_meth_get_cleanup: function(const md: PEVP_MD): EVP_MD_meth_cleanup cdecl = nil; EVP_MD_meth_get_ctrl: function(const md: PEVP_MD): EVP_MD_meth_ctrl cdecl = nil; EVP_CIPHER_meth_new: function(cipher_type: TIdC_INT; block_size: TIdC_INT; key_len: TIdC_INT): PEVP_CIPHER cdecl = nil; EVP_CIPHER_meth_dup: function(const cipher: PEVP_CIPHER): PEVP_CIPHER cdecl = nil; EVP_CIPHER_meth_free: procedure(cipher: PEVP_CIPHER) cdecl = nil; EVP_CIPHER_meth_set_iv_length: function(cipher: PEVP_CIPHER; iv_len: TIdC_INT): TIdC_INT cdecl = nil; EVP_CIPHER_meth_set_flags: function(cipher: PEVP_CIPHER; flags: TIdC_ULONG): TIdC_INT cdecl = nil; EVP_CIPHER_meth_set_impl_ctx_size: function(cipher: PEVP_CIPHER; ctx_size: TIdC_INT): TIdC_INT cdecl = nil; EVP_CIPHER_meth_set_init: function(cipher: PEVP_CIPHER; init: EVP_CIPHER_meth_init): TIdC_INT cdecl = nil; EVP_CIPHER_meth_set_do_cipher: function(cipher: PEVP_CIPHER; do_cipher: EVP_CIPHER_meth_do_cipher): TIdC_INT cdecl = nil; EVP_CIPHER_meth_set_cleanup: function(cipher: PEVP_CIPHER; cleanup: EVP_CIPHER_meth_cleanup): TIdC_INT cdecl = nil; EVP_CIPHER_meth_set_set_asn1_params: function(cipher: PEVP_CIPHER; set_asn1_parameters: EVP_CIPHER_meth_set_asn1_params): TIdC_INT cdecl = nil; EVP_CIPHER_meth_set_get_asn1_params: function(cipher: PEVP_CIPHER; get_asn1_parameters: EVP_CIPHER_meth_get_asn1_params): TIdC_INT cdecl = nil; EVP_CIPHER_meth_set_ctrl: function(cipher: PEVP_CIPHER; ctrl: EVP_CIPHER_meth_ctrl): TIdC_INT cdecl = nil; EVP_CIPHER_meth_get_init: function(const cipher: PEVP_CIPHER): EVP_CIPHER_meth_init cdecl = nil; EVP_CIPHER_meth_get_do_cipher: function(const cipher: PEVP_CIPHER): EVP_CIPHER_meth_do_cipher cdecl = nil; EVP_CIPHER_meth_get_cleanup: function(const cipher: PEVP_CIPHER): EVP_CIPHER_meth_cleanup cdecl = nil; EVP_CIPHER_meth_get_set_asn1_params: function(const cipher: PEVP_CIPHER): EVP_CIPHER_meth_set_asn1_params cdecl = nil; EVP_CIPHER_meth_get_get_asn1_params: function(const cipher: PEVP_CIPHER): EVP_CIPHER_meth_get_asn1_params cdecl = nil; EVP_CIPHER_meth_get_ctrl: function(const cipher: PEVP_CIPHER): EVP_CIPHER_meth_ctrl cdecl = nil; /// Add some extra combinations /// //# define EVP_get_digestbynid(a) EVP_get_digestbyname(OBJ_nid2sn(a)); //# define EVP_get_digestbyobj(a) EVP_get_digestbynid(OBJ_obj2nid(a)); //# define EVP_get_cipherbynid(a) EVP_get_cipherbyname(OBJ_nid2sn(a)); //# define EVP_get_cipherbyobj(a) EVP_get_cipherbynid(OBJ_obj2nid(a)); EVP_MD_type: function(const md: PEVP_MD): TIdC_INT cdecl = nil; //# define EVP_MD_nid(e) EVP_MD_type(e) //# define EVP_MD_name(e) OBJ_nid2sn(EVP_MD_nid(e)) EVP_MD_pkey_type: function(const md: PEVP_MD): TIdC_INT cdecl = nil; EVP_MD_size: function(const md: PEVP_MD): TIdC_INT cdecl = nil; EVP_MD_block_size: function(const md: PEVP_MD): TIdC_INT cdecl = nil; EVP_MD_flags: function(const md: PEVP_MD): PIdC_ULONG cdecl = nil; EVP_MD_CTX_md: function(ctx: PEVP_MD_CTX): PEVP_MD cdecl = nil; EVP_MD_CTX_update_fn: function(ctx: PEVP_MD_CTX): EVP_MD_CTX_update cdecl = nil; EVP_MD_CTX_set_update_fn: procedure(ctx: PEVP_MD_CTX; update: EVP_MD_CTX_update) cdecl = nil; // EVP_MD_CTX_size(e) EVP_MD_size(EVP_MD_CTX_md(e)) // EVP_MD_CTX_block_size(e) EVP_MD_block_size(EVP_MD_CTX_md(e)) // EVP_MD_CTX_type(e) EVP_MD_type(EVP_MD_CTX_md(e)) EVP_MD_CTX_pkey_ctx: function(const ctx: PEVP_MD_CTX): PEVP_PKEY_CTX cdecl = nil; EVP_MD_CTX_set_pkey_ctx: procedure(ctx: PEVP_MD_CTX; pctx: PEVP_PKEY_CTX) cdecl = nil; EVP_MD_CTX_md_data: function(const ctx: PEVP_MD_CTX): Pointer cdecl = nil; EVP_CIPHER_nid: function(const ctx: PEVP_MD_CTX): TIdC_INT cdecl = nil; //# define EVP_CIPHER_name(e) OBJ_nid2sn(EVP_CIPHER_nid(e)) EVP_CIPHER_block_size: function(const cipher: PEVP_CIPHER): TIdC_INT cdecl = nil; EVP_CIPHER_impl_ctx_size: function(const cipher: PEVP_CIPHER): TIdC_INT cdecl = nil; EVP_CIPHER_key_length: function(const cipher: PEVP_CIPHER): TIdC_INT cdecl = nil; EVP_CIPHER_iv_length: function(const cipher: PEVP_CIPHER): TIdC_INT cdecl = nil; EVP_CIPHER_flags: function(const cipher: PEVP_CIPHER): TIdC_ULONG cdecl = nil; //# define EVP_CIPHER_mode(e) (EVP_CIPHER_flags(e) & EVP_CIPH_MODE) EVP_CIPHER_CTX_cipher: function(const ctx: PEVP_CIPHER_CTX): PEVP_CIPHER cdecl = nil; EVP_CIPHER_CTX_encrypting: function(const ctx: PEVP_CIPHER_CTX): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_nid: function(const ctx: PEVP_CIPHER_CTX): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_block_size: function(const ctx: PEVP_CIPHER_CTX): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_key_length: function(const ctx: PEVP_CIPHER_CTX): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_iv_length: function(const ctx: PEVP_CIPHER_CTX): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_iv: function(const ctx: PEVP_CIPHER_CTX): PByte cdecl = nil; EVP_CIPHER_CTX_original_iv: function(const ctx: PEVP_CIPHER_CTX): PByte cdecl = nil; EVP_CIPHER_CTX_iv_noconst: function(ctx: PEVP_CIPHER_CTX): PByte cdecl = nil; EVP_CIPHER_CTX_buf_noconst: function(ctx: PEVP_CIPHER_CTX): PByte cdecl = nil; EVP_CIPHER_CTX_num: function(const ctx: PEVP_CIPHER_CTX): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_set_num: procedure(ctx: PEVP_CIPHER_CTX; num: TIdC_INT) cdecl = nil; EVP_CIPHER_CTX_copy: function(out_: PEVP_CIPHER_CTX; const in_: PEVP_CIPHER_CTX): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_get_app_data: function(const ctx: PEVP_CIPHER_CTX): Pointer cdecl = nil; EVP_CIPHER_CTX_set_app_data: procedure(ctx: PEVP_CIPHER_CTX; data: Pointer) cdecl = nil; EVP_CIPHER_CTX_get_cipher_data: function(const ctx: PEVP_CIPHER_CTX): Pointer cdecl = nil; EVP_CIPHER_CTX_set_cipher_data: function(ctx: PEVP_CIPHER_CTX; cipher_data: Pointer): Pointer cdecl = nil; //# define EVP_CIPHER_CTX_type(c) EVP_CIPHER_type(EVP_CIPHER_CTX_cipher(c)) //# if OPENSSL_API_COMPAT < 0x10100000L //# define EVP_CIPHER_CTX_flags(c) EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(c)) //# endif //# define EVP_CIPHER_CTX_mode(c) EVP_CIPHER_mode(EVP_CIPHER_CTX_cipher(c)) // //# define EVP_ENCODE_LENGTH(l) ((((l)+2)/3*4)+((l)/48+1)*2+80) //# define EVP_DECODE_LENGTH(l) (((l)+3)/4*3+80) // //# define EVP_SignInit_ex(a;b;c) EVP_DigestInit_ex(a;b;c) //# define EVP_SignInit(a;b) EVP_DigestInit(a;b) //# define EVP_SignUpdate(a;b;c) EVP_DigestUpdate(a;b;c) //# define EVP_VerifyInit_ex(a;b;c) EVP_DigestInit_ex(a;b;c) //# define EVP_VerifyInit(a;b) EVP_DigestInit(a;b) //# define EVP_VerifyUpdate(a;b;c) EVP_DigestUpdate(a;b;c) //# define EVP_OpenUpdate(a;b;c;d;e) EVP_DecryptUpdate(a;b;c;d;e) //# define EVP_SealUpdate(a;b;c;d;e) EVP_EncryptUpdate(a;b;c;d;e) //# define EVP_DigestSignUpdate(a;b;c) EVP_DigestUpdate(a;b;c) //# define EVP_DigestVerifyUpdate(a;b;c) EVP_DigestUpdate(a;b;c) BIO_set_md: procedure(v1: PBIO; const md: PEVP_MD) cdecl = nil; //# define BIO_get_md(b;mdp) BIO_ctrl(b;BIO_C_GET_MD;0;(PIdAnsiChar)(mdp)) //# define BIO_get_md_ctx(b;mdcp) BIO_ctrl(b;BIO_C_GET_MD_CTX;0; (PIdAnsiChar)(mdcp)) //# define BIO_set_md_ctx(b;mdcp) BIO_ctrl(b;BIO_C_SET_MD_CTX;0; (PIdAnsiChar)(mdcp)) //# define BIO_get_cipher_status(b) BIO_ctrl(b;BIO_C_GET_CIPHER_STATUS;0;NULL) //# define BIO_get_cipher_ctx(b;c_pp) BIO_ctrl(b;BIO_C_GET_CIPHER_CTX;0; (PIdAnsiChar)(c_pp)) //function EVP_Cipher(c: PEVP_CIPHER_CTX; out_: PByte; const in_: PByte; in1: TIdC_UINT): TIdC_INT; //# define EVP_add_cipher_alias(n;alias) OBJ_NAME_add((alias);OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS;(n)) //# define EVP_add_digest_alias(n;alias) OBJ_NAME_add((alias);OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS;(n)) //# define EVP_delete_cipher_alias(alias) OBJ_NAME_remove(alias;OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS); //# define EVP_delete_digest_alias(alias) OBJ_NAME_remove(alias;OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS); EVP_MD_CTX_ctrl: function(ctx: PEVP_MD_CTX; cmd: TIdC_INT; p1: TIdC_INT; p2: Pointer): TIdC_INT cdecl = nil; EVP_MD_CTX_new: function: PEVP_MD_CTX cdecl = nil; EVP_MD_CTX_reset: function(ctx: PEVP_MD_CTX): TIdC_INT cdecl = nil; EVP_MD_CTX_free: procedure(ctx: PEVP_MD_CTX) cdecl = nil; //# define EVP_MD_CTX_create() EVP_MD_CTX_new() //# define EVP_MD_CTX_init(ctx) EVP_MD_CTX_reset((ctx)) //# define EVP_MD_CTX_destroy(ctx) EVP_MD_CTX_free((ctx)) EVP_MD_CTX_copy_ex: function(out_: PEVP_MD_CTX; const in_: PEVP_MD_CTX): TIdC_INT cdecl = nil; EVP_MD_CTX_set_flags: procedure(ctx: PEVP_MD_CTX; flags: TIdC_INT) cdecl = nil; EVP_MD_CTX_clear_flags: procedure(ctx: PEVP_MD_CTX; flags: TIdC_INT) cdecl = nil; EVP_MD_CTX_test_flags: function(const ctx: PEVP_MD_CTX; flags: TIdC_INT): TIdC_INT cdecl = nil; EVP_DigestInit_ex: function(ctx: PEVP_MD_CTX; const type_: PEVP_MD; impl: PENGINE): TIdC_INT cdecl = nil; EVP_DigestUpdate: function(ctx: PEVP_MD_CTX; const d: Pointer; cnt: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_DigestFinal_ex: function(ctx: PEVP_MD_CTX; md: PByte; s: PIdC_UINT): TIdC_INT cdecl = nil; EVP_Digest: function(const data: Pointer; count: TIdC_SIZET; md: PByte; size: PIdC_UINT; const type_: PEVP_MD; impl: PENGINE): TIdC_INT cdecl = nil; EVP_MD_CTX_copy: function(out_: PEVP_MD_CTX; const in_: PEVP_MD_CTX): TIdC_INT cdecl = nil; EVP_DigestInit: function(ctx: PEVP_MD_CTX; const type_: PEVP_MD): TIdC_INT cdecl = nil; EVP_DigestFinal: function(ctx: PEVP_MD_CTX; md: PByte; s: PIdC_UINT): TIdC_INT cdecl = nil; EVP_DigestFinalXOF: function(ctx: PEVP_MD_CTX; md: PByte; len: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_read_pw_string: function(buf: PIdAnsiChar; length: TIdC_INT; const prompt: PIdAnsiChar; verify: TIdC_INT): TIdC_INT cdecl = nil; EVP_read_pw_string_min: function(buf: PIdAnsiChar; minlen: TIdC_INT; maxlen: TIdC_INT; const prompt: PIdAnsiChar; verify: TIdC_INT): TIdC_INT cdecl = nil; EVP_set_pw_prompt: procedure(const prompt: PIdAnsiChar) cdecl = nil; EVP_get_pw_prompt: function: PIdAnsiChar cdecl = nil; EVP_BytesToKey: function(const type_: PEVP_CIPHER; const md: PEVP_MD; const salt: PByte; const data: PByte; data1: TIdC_INT; count: TIdC_INT; key: PByte; iv: PByte): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_set_flags: procedure(ctx: PEVP_CIPHER_CTX; flags: TIdC_INT) cdecl = nil; EVP_CIPHER_CTX_clear_flags: procedure(ctx: PEVP_CIPHER_CTX; flags: TIdC_INT) cdecl = nil; EVP_CIPHER_CTX_test_flags: function(const ctx: PEVP_CIPHER_CTX; flags: TIdC_INT): TIdC_INT cdecl = nil; EVP_EncryptInit: function(ctx: PEVP_CIPHER_CTX; const cipher: PEVP_CIPHER; const key: PByte; const iv: PByte): TIdC_INT cdecl = nil; EVP_EncryptInit_ex: function(ctx: PEVP_CIPHER_CTX; const cipher: PEVP_CIPHER; impl: PENGINE; const key: PByte; const iv: PByte): TIdC_INT cdecl = nil; EVP_EncryptUpdate: function(ctx: PEVP_CIPHER_CTX; out_: PByte; out1: PIdC_INT; const in_: PByte; in_1: TIdC_INT): TIdC_INT cdecl = nil; EVP_EncryptFinal_ex: function(ctx: PEVP_CIPHER_CTX; out_: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_EncryptFinal: function(ctx: PEVP_CIPHER_CTX; out_: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_DecryptInit: function(ctx: PEVP_CIPHER_CTX; out_: PByte; out1: PidC_INT): TIdC_INT cdecl = nil; EVP_DecryptInit_ex: function(ctx: PEVP_CIPHER_CTX; const cipher: PEVP_CIPHER; impl: PENGINE; const key: PByte; const iv: PByte): TIdC_INT cdecl = nil; EVP_DecryptUpdate: function(ctx: PEVP_CIPHER_CTX; out_: PByte; out1: PIdC_INT; const in_: PByte; in_1: TIdC_INT): TIdC_INT cdecl = nil; EVP_DecryptFinal: function(ctx: PEVP_CIPHER_CTX; outm: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_DecryptFinal_ex: function(ctx: PEVP_MD_CTX; outm: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_CipherInit: function(ctx: PEVP_CIPHER_CTX; const cipher: PEVP_CIPHER; const key: PByte; const iv: PByte; enc: TIdC_INT): TIdC_INT cdecl = nil; EVP_CipherInit_ex: function(ctx: PEVP_CIPHER_CTX; const cipher: PEVP_CIPHER; impl: PENGINE; const key: PByte; const iv: PByte; enc: TidC_INT): TIdC_INT cdecl = nil; EVP_CipherUpdate: function(ctx: PEVP_CIPHER_CTX; out_: PByte; out1: PIdC_INT; const in_: PByte; in1: TIdC_INT): TIdC_INT cdecl = nil; EVP_CipherFinal: function(ctx: PEVP_CIPHER_CTX; outm: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_CipherFinal_ex: function(ctx: PEVP_CIPHER_CTX; outm: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_SignFinal: function(ctx: PEVP_CIPHER_CTX; md: PByte; s: PIdC_UINT; pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_DigestSign: function(ctx: PEVP_CIPHER_CTX; sigret: PByte; siglen: PIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_VerifyFinal: function(ctx: PEVP_MD_CTX; const sigbuf: PByte; siglen: TIdC_UINT; pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_DigestVerify: function(ctx: PEVP_CIPHER_CTX; const sigret: PByte; siglen: TIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_DigestSignInit: function(ctx: PEVP_MD_CTX; pctx: PPEVP_PKEY_CTX; const type_: PEVP_MD; e: PENGINE; pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_DigestSignFinal: function(ctx: PEVP_MD_CTX; sigret: PByte; siglen: PIdC_SIZET): TIdC_INT cdecl = nil; EVP_DigestVerifyInit: function(ctx: PEVP_MD_CTX; ppctx: PPEVP_PKEY_CTX; const type_: PEVP_MD; e: PENGINE; pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_DigestVerifyFinal: function(ctx: PEVP_MD_CTX; const sig: PByte; siglen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_OpenInit: function(ctx: PEVP_CIPHER_CTX; const type_: PEVP_CIPHER; const ek: PByte; ek1: TIdC_INT; const iv: PByte; priv: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_OpenFinal: function(ctx: PEVP_CIPHER_CTX; out_: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_SealInit: function(ctx: PEVP_CIPHER_CTX; const type_: EVP_CIPHER; ek: PPByte; ek1: PIdC_INT; iv: PByte; pubk: PPEVP_PKEY; npubk: TIdC_INT): TIdC_INT cdecl = nil; EVP_SealFinal: function(ctx: PEVP_CIPHER_CTX; out_: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_ENCODE_CTX_new: function: PEVP_ENCODE_CTX cdecl = nil; EVP_ENCODE_CTX_free: procedure(ctx: PEVP_ENCODE_CTX) cdecl = nil; EVP_ENCODE_CTX_copy: function(dctx: PEVP_ENCODE_CTX; sctx: PEVP_ENCODE_CTX): TIdC_INT cdecl = nil; EVP_ENCODE_CTX_num: function(ctx: PEVP_ENCODE_CTX): TIdC_INT cdecl = nil; EVP_EncodeInit: procedure(ctx: PEVP_ENCODE_CTX) cdecl = nil; EVP_EncodeUpdate: function(ctx: PEVP_ENCODE_CTX; out_: PByte; out1: PIdC_INT; const in_: PByte; in1: TIdC_INT): TIdC_INT cdecl = nil; EVP_EncodeFinal: procedure(ctx: PEVP_ENCODE_CTX; out_: PByte; out1: PIdC_INT) cdecl = nil; EVP_EncodeBlock: function(t: PByte; const f: PByte; n: TIdC_INT): TIdC_INT cdecl = nil; EVP_DecodeInit: procedure(ctx: PEVP_ENCODE_CTX) cdecl = nil; EVP_DecodeUpdate: function(ctx: PEVP_ENCODE_CTX; out_: PByte; out1: PIdC_INT; const in_: PByte; in1: TIdC_INT): TIdC_INT cdecl = nil; EVP_DecodeFinal: function(ctx: PEVP_ENCODE_CTX; out_: PByte; out1: PIdC_INT): TIdC_INT cdecl = nil; EVP_DecodeBlock: function(t: PByte; const f: PByte; n: TIdC_INT): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_new: function: PEVP_CIPHER_CTX cdecl = nil; EVP_CIPHER_CTX_reset: function(c: PEVP_CIPHER_CTX): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_free: procedure(c: PEVP_CIPHER_CTX) cdecl = nil; EVP_CIPHER_CTX_set_key_length: function(x: PEVP_CIPHER_CTX; keylen: TIdC_INT): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_set_padding: function(c: PEVP_CIPHER_CTX; pad: TIdC_INT): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_ctrl: function(ctx: PEVP_CIPHER_CTX; type_: TIdC_INT; arg: TIdC_INT; ptr: Pointer): TIdC_INT cdecl = nil; EVP_CIPHER_CTX_rand_key: function(ctx: PEVP_CIPHER_CTX; key: PByte): TIdC_INT cdecl = nil; BIO_f_md: function: PBIO_METHOD cdecl = nil; BIO_f_base64: function: PBIO_METHOD cdecl = nil; BIO_f_cipher: function: PBIO_METHOD cdecl = nil; BIO_f_reliable: function: PBIO_METHOD cdecl = nil; BIO_set_cipher: function(b: PBIO; c: PEVP_CIPHER; const k: PByte; const i: PByte; enc: TIdC_INT): TIdC_INT cdecl = nil; EVP_md_null: function: PEVP_MD cdecl = nil; EVP_md5: function: PEVP_MD cdecl = nil; EVP_md5_sha1: function: PEVP_MD cdecl = nil; EVP_sha1: function: PEVP_MD cdecl = nil; EVP_sha224: function: PEVP_MD cdecl = nil; EVP_sha256: function: PEVP_MD cdecl = nil; EVP_sha384: function: PEVP_MD cdecl = nil; EVP_sha512: function: PEVP_MD cdecl = nil; EVP_sha512_224: function: PEVP_MD cdecl = nil; EVP_sha512_256: function: PEVP_MD cdecl = nil; EVP_sha3_224: function: PEVP_MD cdecl = nil; EVP_sha3_256: function: PEVP_MD cdecl = nil; EVP_sha3_384: function: PEVP_MD cdecl = nil; EVP_sha3_512: function: PEVP_MD cdecl = nil; EVP_shake128: function: PEVP_MD cdecl = nil; EVP_shake256: function: PEVP_MD cdecl = nil; (* does nothing :-) *) EVP_enc_null: function: PEVP_CIPHER cdecl = nil; EVP_des_ecb: function: PEVP_CIPHER cdecl = nil; EVP_des_ede: function: PEVP_CIPHER cdecl = nil; EVP_des_ede3: function: PEVP_CIPHER cdecl = nil; EVP_des_ede_ecb: function: PEVP_CIPHER cdecl = nil; EVP_des_ede3_ecb: function: PEVP_CIPHER cdecl = nil; EVP_des_cfb64: function: PEVP_CIPHER cdecl = nil; //EVP_des_cfb EVP_des_cfb64 EVP_des_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_des_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_des_ede_cfb64: function: PEVP_CIPHER cdecl = nil; EVP_des_ede3_cfb64: function: PEVP_CIPHER cdecl = nil; //EVP_des_ede3_cfb EVP_des_ede3_cfb64 EVP_des_ede3_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_des_ede3_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_des_ofb: function: PEVP_CIPHER cdecl = nil; EVP_des_ede_ofb: function: PEVP_CIPHER cdecl = nil; EVP_des_ede3_ofb: function: PEVP_CIPHER cdecl = nil; EVP_des_cbc: function: PEVP_CIPHER cdecl = nil; EVP_des_ede_cbc: function: PEVP_CIPHER cdecl = nil; EVP_des_ede3_cbc: function: PEVP_CIPHER cdecl = nil; EVP_desx_cbc: function: PEVP_CIPHER cdecl = nil; EVP_des_ede3_wrap: function: PEVP_CIPHER cdecl = nil; // // This should now be supported through the dev_crypto ENGINE. But also, why // are rc4 and md5 declarations made here inside a "NO_DES" precompiler // branch? // EVP_rc4: function: PEVP_CIPHER cdecl = nil; EVP_rc4_40: function: PEVP_CIPHER cdecl = nil; EVP_idea_ecb: function: PEVP_CIPHER cdecl = nil; EVP_idea_cfb64: function: PEVP_CIPHER cdecl = nil; //EVP_idea_cfb EVP_idea_cfb64 EVP_idea_ofb: function: PEVP_CIPHER cdecl = nil; EVP_idea_cbc: function: PEVP_CIPHER cdecl = nil; EVP_rc2_ecb: function: PEVP_CIPHER cdecl = nil; EVP_rc2_cbc: function: PEVP_CIPHER cdecl = nil; EVP_rc2_40_cbc: function: PEVP_CIPHER cdecl = nil; EVP_rc2_64_cbc: function: PEVP_CIPHER cdecl = nil; EVP_rc2_cfb64: function: PEVP_CIPHER cdecl = nil; //EVP_rc2_cfb EVP_rc2_cfb64 EVP_rc2_ofb: function: PEVP_CIPHER cdecl = nil; EVP_bf_ecb: function: PEVP_CIPHER cdecl = nil; EVP_bf_cbc: function: PEVP_CIPHER cdecl = nil; EVP_bf_cfb64: function: PEVP_CIPHER cdecl = nil; //EVP_bf_cfb EVP_bf_cfb64 EVP_bf_ofb: function: PEVP_CIPHER cdecl = nil; EVP_cast5_ecb: function: PEVP_CIPHER cdecl = nil; EVP_cast5_cbc: function: PEVP_CIPHER cdecl = nil; EVP_cast5_cfb64: function: PEVP_CIPHER cdecl = nil; //EVP_cast5_cfb EVP_cast5_cfb64 EVP_cast5_ofb: function: PEVP_CIPHER cdecl = nil; EVP_rc5_32_12_16_cbc: function: PEVP_CIPHER cdecl = nil; EVP_rc5_32_12_16_ecb: function: PEVP_CIPHER cdecl = nil; EVP_rc5_32_12_16_cfb64: function: PEVP_CIPHER cdecl = nil; //EVP_rc5_32_12_16_cfb EVP_rc5_32_12_16_cfb64 EVP_rc5_32_12_16_ofb: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_ecb: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_cbc: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_aes_128_cfb EVP_aes_128_cfb128 EVP_aes_128_ofb: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_ctr: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_ccm: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_gcm: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_xts: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_wrap: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_wrap_pad: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_ocb: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_ecb: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_cbc: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_aes_192_cfb EVP_aes_192_cfb128 EVP_aes_192_ofb: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_ctr: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_ccm: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_gcm: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_wrap: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_wrap_pad: function: PEVP_CIPHER cdecl = nil; EVP_aes_192_ocb: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_ecb: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_cbc: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_aes_256_cfb EVP_aes_256_cfb128 EVP_aes_256_ofb: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_ctr: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_ccm: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_gcm: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_xts: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_wrap: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_wrap_pad: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_ocb: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_cbc_hmac_sha1: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_cbc_hmac_sha1: function: PEVP_CIPHER cdecl = nil; EVP_aes_128_cbc_hmac_sha256: function: PEVP_CIPHER cdecl = nil; EVP_aes_256_cbc_hmac_sha256: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_ecb: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_cbc: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_cfb128: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_ctr: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_ofb: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_gcm: function: PEVP_CIPHER cdecl = nil; EVP_aria_128_ccm: function: PEVP_CIPHER cdecl = nil; EVP_aria_192_ecb: function: PEVP_CIPHER cdecl = nil; EVP_aria_192_cbc: function: PEVP_CIPHER cdecl = nil; EVP_aria_192_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_aria_192_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_aria_192_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_aria_192_cfb EVP_aria_192_cfb128 EVP_aria_192_ctr: function: PEVP_CIPHER cdecl = nil; EVP_aria_192_ofb: function: PEVP_CIPHER cdecl = nil; EVP_aria_192_gcm: function: PEVP_CIPHER cdecl = nil; EVP_aria_192_ccm: function: PEVP_CIPHER cdecl = nil; EVP_aria_256_ecb: function: PEVP_CIPHER cdecl = nil; EVP_aria_256_cbc: function: PEVP_CIPHER cdecl = nil; EVP_aria_256_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_aria_256_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_aria_256_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_aria_256_cfb EVP_aria_256_cfb128 EVP_aria_256_ctr: function: PEVP_CIPHER cdecl = nil; EVP_aria_256_ofb: function: PEVP_CIPHER cdecl = nil; EVP_aria_256_gcm: function: PEVP_CIPHER cdecl = nil; EVP_aria_256_ccm: function: PEVP_CIPHER cdecl = nil; EVP_camellia_128_ecb: function: PEVP_CIPHER cdecl = nil; EVP_camellia_128_cbc: function: PEVP_CIPHER cdecl = nil; EVP_camellia_128_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_camellia_128_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_camellia_128_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_camellia_128_cfb EVP_camellia_128_cfb128 EVP_camellia_128_ofb: function: PEVP_CIPHER cdecl = nil; EVP_camellia_128_ctr: function: PEVP_CIPHER cdecl = nil; EVP_camellia_192_ecb: function: PEVP_CIPHER cdecl = nil; EVP_camellia_192_cbc: function: PEVP_CIPHER cdecl = nil; EVP_camellia_192_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_camellia_192_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_camellia_192_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_camellia_192_cfb EVP_camellia_192_cfb128 EVP_camellia_192_ofb: function: PEVP_CIPHER cdecl = nil; EVP_camellia_192_ctr: function: PEVP_CIPHER cdecl = nil; EVP_camellia_256_ecb: function: PEVP_CIPHER cdecl = nil; EVP_camellia_256_cbc: function: PEVP_CIPHER cdecl = nil; EVP_camellia_256_cfb1: function: PEVP_CIPHER cdecl = nil; EVP_camellia_256_cfb8: function: PEVP_CIPHER cdecl = nil; EVP_camellia_256_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_camellia_256_cfb EVP_camellia_256_cfb128 EVP_camellia_256_ofb: function: PEVP_CIPHER cdecl = nil; EVP_camellia_256_ctr: function: PEVP_CIPHER cdecl = nil; EVP_chacha20: function: PEVP_CIPHER cdecl = nil; EVP_chacha20_poly1305: function: PEVP_CIPHER cdecl = nil; EVP_seed_ecb: function: PEVP_CIPHER cdecl = nil; EVP_seed_cbc: function: PEVP_CIPHER cdecl = nil; EVP_seed_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_seed_cfb EVP_seed_cfb128 EVP_seed_ofb: function: PEVP_CIPHER cdecl = nil; EVP_sm4_ecb: function: PEVP_CIPHER cdecl = nil; EVP_sm4_cbc: function: PEVP_CIPHER cdecl = nil; EVP_sm4_cfb128: function: PEVP_CIPHER cdecl = nil; //EVP_sm4_cfb EVP_sm4_cfb128 EVP_sm4_ofb: function: PEVP_CIPHER cdecl = nil; EVP_sm4_ctr: function: PEVP_CIPHER cdecl = nil; EVP_add_cipher: function(const cipher: PEVP_CIPHER): TIdC_INT cdecl = nil; EVP_add_digest: function(const digest: PEVP_MD): TIdC_INT cdecl = nil; EVP_get_cipherbyname: function(const name: PIdAnsiChar): PEVP_CIPHER cdecl = nil; EVP_get_digestbyname: function(const name: PIdAnsiChar): PEVP_MD cdecl = nil; EVP_CIPHER_do_all: procedure(AFn: fn; arg: Pointer) cdecl = nil; EVP_CIPHER_do_all_sorted: procedure(AFn: fn; arg: Pointer) cdecl = nil; EVP_MD_do_all: procedure(AFn: fn; arg: Pointer) cdecl = nil; EVP_MD_do_all_sorted: procedure(AFn: fn; arg: Pointer) cdecl = nil; EVP_PKEY_decrypt_old: function(dec_key: PByte; const enc_key: PByte; enc_key_len: TIdC_INT; private_key: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_encrypt_old: function(dec_key: PByte; const enc_key: PByte; key_len: TIdC_INT; pub_key: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_type: function(type_: TIdC_INT): TIdC_INT cdecl = nil; EVP_PKEY_id: function(const pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_base_id: function(const pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_bits: function(const pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_security_bits: function(const pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_size: function(const pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_set_type: function(pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_set_type_str: function(pkey: PEVP_PKEY; const str: PIdAnsiChar; len: TIdC_INT): TIdC_INT cdecl = nil; EVP_PKEY_set_alias_type: function(pkey: PEVP_PKEY; type_: TIdC_INT): TIdC_INT cdecl = nil; EVP_PKEY_set1_engine: function(pkey: PEVP_PKEY; e: PENGINE): TIdC_INT cdecl = nil; EVP_PKEY_get0_engine: function(const pkey: PEVP_PKEY): PENGINE cdecl = nil; EVP_PKEY_assign: function(pkey: PEVP_PKEY; type_: TIdC_INT; key: Pointer): TIdC_INT cdecl = nil; EVP_PKEY_get0: function(const pkey: PEVP_PKEY): Pointer cdecl = nil; EVP_PKEY_get0_hmac: function(const pkey: PEVP_PKEY; len: PIdC_SIZET): PByte cdecl = nil; EVP_PKEY_get0_poly1305: function(const pkey: PEVP_PKEY; len: PIdC_SIZET): PByte cdecl = nil; EVP_PKEY_get0_siphash: function(const pkey: PEVP_PKEY; len: PIdC_SIZET): PByte cdecl = nil; EVP_PKEY_set1_RSA: function(pkey: PEVP_PKEY; key: PRSA): TIdC_INT cdecl = nil; EVP_PKEY_get0_RSA: function(pkey: PEVP_PKEY): PRSA cdecl = nil; EVP_PKEY_get1_RSA: function(pkey: PEVP_PKEY): PRSA cdecl = nil; EVP_PKEY_set1_DSA: function(pkey: PEVP_PKEY; key: PDSA): TIdC_INT cdecl = nil; EVP_PKEY_get0_DSA: function(pkey: PEVP_PKEY): PDSA cdecl = nil; EVP_PKEY_get1_DSA: function(pkey: PEVP_PKEY): PDSA cdecl = nil; EVP_PKEY_set1_DH: function(pkey: PEVP_PKEY; key: PDH): TIdC_INT cdecl = nil; EVP_PKEY_get0_DH: function(pkey: PEVP_PKEY): PDH cdecl = nil; EVP_PKEY_get1_DH: function(pkey: PEVP_PKEY): PDH cdecl = nil; EVP_PKEY_set1_EC_KEY: function(pkey: PEVP_PKEY; key: PEC_KEY): TIdC_INT cdecl = nil; EVP_PKEY_get0_EC_KEY: function(pkey: PEVP_PKEY): PEC_KEY cdecl = nil; EVP_PKEY_get1_EC_KEY: function(pkey: PEVP_PKEY): PEC_KEY cdecl = nil; EVP_PKEY_new: function: PEVP_PKEY cdecl = nil; EVP_PKEY_up_ref: function(pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_free: procedure(pkey: PEVP_PKEY) cdecl = nil; d2i_PublicKey: function(type_: TIdC_INT; a: PPEVP_PKEY; const pp: PPByte; length: TIdC_LONG): PEVP_PKEY cdecl = nil; i2d_PublicKey: function(a: PEVP_PKEY; pp: PPByte): TIdC_INT cdecl = nil; d2i_PrivateKey: function(type_: TIdC_INT; a: PEVP_PKEY; const pp: PPByte; length: TIdC_LONG): PEVP_PKEY cdecl = nil; d2i_AutoPrivateKey: function(a: PPEVP_PKEY; const pp: PPByte; length: TIdC_LONG): PEVP_PKEY cdecl = nil; i2d_PrivateKey: function(a: PEVP_PKEY; pp: PPByte): TIdC_INT cdecl = nil; EVP_PKEY_copy_parameters: function(to_: PEVP_PKEY; const from: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_missing_parameters: function(const pkey: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_save_parameters: function(pkey: PEVP_PKEY; mode: TIdC_INT): TIdC_INT cdecl = nil; EVP_PKEY_cmp_parameters: function(const a: PEVP_PKEY; const b: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_cmp: function(const a: PEVP_PKEY; const b: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_print_public: function(out_: PBIO; const pkey: PEVP_PKEY; indent: TIdC_INT; pctx: PASN1_PCTX): TIdC_INT cdecl = nil; EVP_PKEY_print_private: function(out_: PBIO; const pkey: PEVP_PKEY; indent: TIdC_INT; pctx: PASN1_PCTX): TIdC_INT cdecl = nil; EVP_PKEY_print_params: function(out_: PBIO; const pkey: PEVP_PKEY; indent: TIdC_INT; pctx: PASN1_PCTX): TIdC_INT cdecl = nil; EVP_PKEY_get_default_digest_nid: function(pkey: PEVP_PKEY; pnid: PIdC_INT): TIdC_INT cdecl = nil; EVP_PKEY_set1_tls_encodedpoint: function(pkey: PEVP_PKEY; const pt: PByte; ptlen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_get1_tls_encodedpoint: function(pkey: PEVP_PKEY; ppt: PPByte): TIdC_SIZET cdecl = nil; EVP_CIPHER_type: function(const ctx: PEVP_CIPHER): TIdC_INT cdecl = nil; (* calls methods *) EVP_CIPHER_param_to_asn1: function(c: PEVP_CIPHER_CTX; type_: PASN1_TYPE): TIdC_INT cdecl = nil; EVP_CIPHER_asn1_to_param: function(c: PEVP_CIPHER_CTX; type_: PASN1_TYPE): TIdC_INT cdecl = nil; (* These are used by EVP_CIPHER methods *) EVP_CIPHER_set_asn1_iv: function(c: PEVP_CIPHER_CTX; type_: PASN1_TYPE): TIdC_INT cdecl = nil; EVP_CIPHER_get_asn1_iv: function(c: PEVP_CIPHER_CTX; type_: PASN1_TYPE): TIdC_INT cdecl = nil; (* PKCS5 password based encryption *) PKCS5_PBE_keyivgen: function(ctx: PEVP_CIPHER_CTX; const pass: PIdAnsiChar; passlen: TIdC_INT; param: PASN1_TYPE; const cipher: PEVP_CIPHER; const md: PEVP_MD; en_de: TIdC_INT): TIdC_INT cdecl = nil; PKCS5_PBKDF2_HMAC_SHA1: function(const pass: PIdAnsiChar; passlen: TIdC_INT; const salt: PByte; saltlen: TIdC_INT; iter: TIdC_INT; keylen: TIdC_INT; out_: PByte): TIdC_INT cdecl = nil; PKCS5_PBKDF2_HMAC: function(const pass: PIdAnsiChar; passlen: TIdC_INT; const salt: PByte; saltlen: TIdC_INT; iter: TIdC_INT; const digest: PEVP_MD; keylen: TIdC_INT; out_: PByte): TIdC_INT cdecl = nil; PKCS5_v2_PBE_keyivgen: function(ctx: PEVP_CIPHER_CTX; const pass: PIdAnsiChar; passlen: TIdC_INT; param: PASN1_TYPE; const cipher: PEVP_CIPHER; const md: PEVP_MD; en_de: TIdC_INT): TIdC_INT cdecl = nil; EVP_PBE_scrypt: function(const pass: PIdAnsiChar; passlen: TIdC_SIZET; const salt: PByte; saltlen: TIdC_SIZET; N: TIdC_UINT64; r: TIdC_UINT64; p: TIdC_UINT64; maxmem: TIdC_UINT64; key: PByte; keylen: TIdC_SIZET): TIdC_INT cdecl = nil; PKCS5_v2_scrypt_keyivgen: function(ctx: PEVP_CIPHER_CTX; const pass: PIdAnsiChar; passlen: TIdC_INT; param: PASN1_TYPE; const c: PEVP_CIPHER; const md: PEVP_MD; en_de: TIdC_INT): TIdC_INT cdecl = nil; PKCS5_PBE_add: procedure cdecl = nil; EVP_PBE_CipherInit: function(pbe_obj: PASN1_OBJECT; const pass: PIdAnsiChar; passlen: TIdC_INT; param: PASN1_TYPE; ctx: PEVP_CIPHER_CTX; en_de: TIdC_INT): TIdC_INT cdecl = nil; (* PBE type *) EVP_PBE_alg_add_type: function(pbe_type: TIdC_INT; pbe_nid: TIdC_INT; cipher_nid: TIdC_INT; md_nid: TIdC_INT; keygen: PEVP_PBE_KEYGEN): TIdC_INT cdecl = nil; EVP_PBE_alg_add: function(nid: TIdC_INT; const cipher: PEVP_CIPHER; const md: PEVP_MD; keygen: PEVP_PBE_KEYGEN): TIdC_INT cdecl = nil; EVP_PBE_find: function(type_: TIdC_INT; pbe_nid: TIdC_INT; pcnid: PIdC_INT; pmnid: PIdC_INT; pkeygen: PPEVP_PBE_KEYGEN): TIdC_INT cdecl = nil; EVP_PBE_cleanup: procedure cdecl = nil; EVP_PBE_get: function(ptype: PIdC_INT; ppbe_nid: PIdC_INT; num: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_asn1_get_count: function: TIdC_INT cdecl = nil; EVP_PKEY_asn1_get0: function(idx: TIdC_INT): PEVP_PKEY_ASN1_METHOD cdecl = nil; EVP_PKEY_asn1_find: function(pe: PPENGINE; type_: TIdC_INT): PEVP_PKEY_ASN1_METHOD cdecl = nil; EVP_PKEY_asn1_find_str: function(pe: PPENGINE; const str: PIdAnsiChar; len: TIdC_INT): PEVP_PKEY_ASN1_METHOD cdecl = nil; EVP_PKEY_asn1_add0: function(const ameth: PEVP_PKEY_ASN1_METHOD): TIdC_INT cdecl = nil; EVP_PKEY_asn1_add_alias: function(to_: TIdC_INT; from: TIdC_INT): TIdC_INT cdecl = nil; EVP_PKEY_asn1_get0_info: function(ppkey_id: PIdC_INT; pkey_base_id: PIdC_INT; ppkey_flags: PIdC_INT; const pinfo: PPIdAnsiChar; const ppem_str: PPIdAnsiChar; const ameth: PEVP_PKEY_ASN1_METHOD): TIdC_INT cdecl = nil; EVP_PKEY_get0_asn1: function(const pkey: PEVP_PKEY): PEVP_PKEY_ASN1_METHOD cdecl = nil; EVP_PKEY_asn1_new: function(id: TIdC_INT; flags: TIdC_INT; const pem_str: PIdAnsiChar; const info: PIdAnsiChar): PEVP_PKEY_ASN1_METHOD cdecl = nil; EVP_PKEY_asn1_copy: procedure(dst: PEVP_PKEY_ASN1_METHOD; const src: PEVP_PKEY_ASN1_METHOD) cdecl = nil; EVP_PKEY_asn1_free: procedure(ameth: PEVP_PKEY_ASN1_METHOD) cdecl = nil; EVP_PKEY_asn1_set_public: procedure(ameth: PEVP_PKEY_ASN1_METHOD; APub_decode: pub_decode; APub_encode: pub_encode; APub_cmd: pub_cmd; APub_print: pub_print; APkey_size: pkey_size; APkey_bits: pkey_bits) cdecl = nil; EVP_PKEY_asn1_set_private: procedure(ameth: PEVP_PKEY_ASN1_METHOD; APriv_decode: priv_decode; APriv_encode: priv_encode; APriv_print: priv_print) cdecl = nil; EVP_PKEY_asn1_set_param: procedure(ameth: PEVP_PKEY_ASN1_METHOD; AParam_decode: param_decode; AParam_encode: param_encode; AParam_missing: param_missing; AParam_copy: param_copy; AParam_cmp: param_cmp; AParam_print: param_print) cdecl = nil; EVP_PKEY_asn1_set_free: procedure(ameth: PEVP_PKEY_ASN1_METHOD; APkey_free: pkey_free) cdecl = nil; EVP_PKEY_asn1_set_ctrl: procedure(ameth: PEVP_PKEY_ASN1_METHOD; APkey_ctrl: pkey_ctrl) cdecl = nil; EVP_PKEY_asn1_set_item: procedure(ameth: PEVP_PKEY_ASN1_METHOD; AItem_verify: item_verify; AItem_sign: item_sign) cdecl = nil; EVP_PKEY_asn1_set_siginf: procedure(ameth: PEVP_PKEY_ASN1_METHOD; ASiginf_set: siginf_set) cdecl = nil; EVP_PKEY_asn1_set_check: procedure(ameth: PEVP_PKEY_ASN1_METHOD; APkey_check: pkey_check) cdecl = nil; EVP_PKEY_asn1_set_public_check: procedure(ameth: PEVP_PKEY_ASN1_METHOD; APkey_pub_check: pkey_pub_check) cdecl = nil; EVP_PKEY_asn1_set_param_check: procedure(ameth: PEVP_PKEY_ASN1_METHOD; APkey_param_check: pkey_param_check) cdecl = nil; EVP_PKEY_asn1_set_set_priv_key: procedure(ameth: PEVP_PKEY_ASN1_METHOD; ASet_priv_key: set_priv_key) cdecl = nil; EVP_PKEY_asn1_set_set_pub_key: procedure(ameth: PEVP_PKEY_ASN1_METHOD; ASet_pub_key: set_pub_key) cdecl = nil; EVP_PKEY_asn1_set_get_priv_key: procedure(ameth: PEVP_PKEY_ASN1_METHOD; AGet_priv_key: get_priv_key) cdecl = nil; EVP_PKEY_asn1_set_get_pub_key: procedure(ameth: PEVP_PKEY_ASN1_METHOD; AGet_pub_key: get_pub_key) cdecl = nil; EVP_PKEY_asn1_set_security_bits: procedure(ameth: PEVP_PKEY_ASN1_METHOD; APkey_security_bits: pkey_security_bits) cdecl = nil; EVP_PKEY_meth_find: function(type_: TIdC_INT): PEVP_PKEY_METHOD cdecl = nil; EVP_PKEY_meth_new: function(id: TIdC_INT; flags: TIdC_INT): PEVP_PKEY_METHOD cdecl = nil; EVP_PKEY_meth_get0_info: procedure(ppkey_id: PIdC_INT; pflags: PIdC_INT; const meth: PEVP_PKEY_METHOD) cdecl = nil; EVP_PKEY_meth_copy: procedure(dst: PEVP_PKEY_METHOD; const src: PEVP_PKEY_METHOD) cdecl = nil; EVP_PKEY_meth_free: procedure(pmeth: PEVP_PKEY_METHOD) cdecl = nil; EVP_PKEY_meth_add0: function(const pmeth: PEVP_PKEY_METHOD): TIdC_INT cdecl = nil; EVP_PKEY_meth_remove: function(const pmeth: PEVP_PKEY_METHOD): TIdC_INT cdecl = nil; EVP_PKEY_meth_get_count: function: TIdC_SIZET cdecl = nil; EVP_PKEY_meth_get0: function(idx: TIdC_SIZET): PEVP_PKEY_METHOD cdecl = nil; EVP_PKEY_CTX_new: function(pkey: PEVP_PKEY; e: PENGINE): PEVP_PKEY_CTX cdecl = nil; EVP_PKEY_CTX_new_id: function(id: TIdC_INT; e: PENGINE): PEVP_PKEY_CTX cdecl = nil; EVP_PKEY_CTX_dup: function(ctx: PEVP_PKEY_CTX): PEVP_PKEY_CTX cdecl = nil; EVP_PKEY_CTX_free: procedure(ctx: PEVP_PKEY_CTX) cdecl = nil; EVP_PKEY_CTX_ctrl: function(ctx: PEVP_PKEY_CTX; keytype: TIdC_INT; optype: TIdC_INT; cmd: TIdC_INT; p1: TIdC_INT; p2: Pointer): TIdC_INT cdecl = nil; EVP_PKEY_CTX_ctrl_str: function(ctx: PEVP_PKEY_CTX; const type_: PIdAnsiChar; const value: PIdAnsiChar): TIdC_INT cdecl = nil; EVP_PKEY_CTX_ctrl_uint64: function(ctx: PEVP_PKEY_CTX; keytype: TIdC_INT; optype: TIdC_INT; cmd: TIdC_INT; value: TIdC_UINT64): TIdC_INT cdecl = nil; EVP_PKEY_CTX_str2ctrl: function(ctx: PEVP_PKEY_CTX; cmd: TIdC_INT; const str: PIdAnsiChar): TIdC_INT cdecl = nil; EVP_PKEY_CTX_hex2ctrl: function(ctx: PEVP_PKEY_CTX; cmd: TIdC_INT; const hex: PIdAnsiChar): TIdC_INT cdecl = nil; EVP_PKEY_CTX_md: function(ctx: PEVP_PKEY_CTX; optype: TIdC_INT; cmd: TIdC_INT; const md: PIdAnsiChar): TIdC_INT cdecl = nil; EVP_PKEY_CTX_get_operation: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_CTX_set0_keygen_info: procedure(ctx: PEVP_PKEY_CTX; dat: PIdC_INT; datlen: TIdC_INT) cdecl = nil; EVP_PKEY_new_mac_key: function(type_: TIdC_INT; e: PENGINE; const key: PByte; keylen: TIdC_INT): PEVP_PKEY cdecl = nil; EVP_PKEY_new_raw_private_key: function(type_: TIdC_INT; e: PENGINE; const priv: PByte; len: TIdC_SIZET): PEVP_PKEY cdecl = nil; EVP_PKEY_new_raw_public_key: function(type_: TIdC_INT; e: PENGINE; const pub: PByte; len: TIdC_SIZET): PEVP_PKEY cdecl = nil; EVP_PKEY_get_raw_private_key: function(const pkey: PEVP_PKEY; priv: PByte; len: PIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_get_raw_public_key: function(const pkey: PEVP_PKEY; pub: PByte; len: PIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_new_CMAC_key: function(e: PENGINE; const priv: PByte; len: TIdC_SIZET; const cipher: PEVP_CIPHER): PEVP_PKEY cdecl = nil; EVP_PKEY_CTX_set_data: procedure(ctx: PEVP_PKEY_CTX; data: Pointer) cdecl = nil; EVP_PKEY_CTX_get_data: function(ctx: PEVP_PKEY_CTX): Pointer cdecl = nil; EVP_PKEY_CTX_get0_pkey: function(ctx: PEVP_PKEY_CTX): PEVP_PKEY cdecl = nil; EVP_PKEY_CTX_get0_peerkey: function(ctx: PEVP_PKEY_CTX): PEVP_PKEY cdecl = nil; EVP_PKEY_CTX_set_app_data: procedure(ctx: PEVP_PKEY_CTX; data: Pointer) cdecl = nil; EVP_PKEY_CTX_get_app_data: function(ctx: PEVP_PKEY_CTX): Pointer cdecl = nil; EVP_PKEY_sign_init: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_sign: function(ctx: PEVP_PKEY_CTX; sig: PByte; siglen: PIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_verify_init: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_verify: function(ctx: PEVP_PKEY_CTX; const sig: PByte; siglen: TIdC_SIZET; const tbs: PByte; tbslen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_verify_recover_init: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_verify_recover: function(ctx: PEVP_PKEY_CTX; rout: PByte; routlen: PIdC_SIZET; const sig: PByte; siglen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_encrypt_init: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_encrypt: function(ctx: PEVP_PKEY_CTX; out_: PByte; outlen: PIdC_SIZET; const in_: PByte; inlen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_decrypt_init: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_decrypt: function(ctx: PEVP_PKEY_CTX; out_: PByte; outlen: PIdC_SIZET; const in_: PByte; inlen: TIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_derive_init: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_derive_set_peer: function(ctx: PEVP_PKEY_CTX; peer: PEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_derive: function(ctx: PEVP_PKEY_CTX; key: PByte; keylen: PIdC_SIZET): TIdC_INT cdecl = nil; EVP_PKEY_paramgen_init: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_paramgen: function(ctx: PEVP_PKEY_CTX; ppkey: PPEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_keygen_init: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_keygen: function(ctx: PEVP_PKEY_CTX; ppkey: PPEVP_PKEY): TIdC_INT cdecl = nil; EVP_PKEY_check: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_public_check: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_param_check: function(ctx: PEVP_PKEY_CTX): TIdC_INT cdecl = nil; EVP_PKEY_CTX_set_cb: procedure(ctx: PEVP_PKEY_CTX; cb: EVP_PKEY_gen_cb) cdecl = nil; EVP_PKEY_CTX_get_cb: function(ctx: PEVP_PKEY_CTX): EVP_PKEY_gen_cb cdecl = nil; EVP_PKEY_CTX_get_keygen_info: function(ctx: PEVP_PKEY_CTX; idx: TIdC_INT): TIdC_INT cdecl = nil; EVP_PKEY_meth_set_init: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_init: EVP_PKEY_meth_init) cdecl = nil; EVP_PKEY_meth_set_copy: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_copy_cb: EVP_PKEY_meth_copy_cb) cdecl = nil; EVP_PKEY_meth_set_cleanup: procedure(pmeth: PEVP_PKEY_METHOD; PEVP_PKEY_meth_cleanup: EVP_PKEY_meth_cleanup) cdecl = nil; EVP_PKEY_meth_set_paramgen: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_paramgen_init: EVP_PKEY_meth_paramgen_init; AEVP_PKEY_meth_paramgen: EVP_PKEY_meth_paramgen_init) cdecl = nil; EVP_PKEY_meth_set_keygen: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_keygen_init: EVP_PKEY_meth_keygen_init; AEVP_PKEY_meth_keygen: EVP_PKEY_meth_keygen) cdecl = nil; EVP_PKEY_meth_set_sign: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_sign_init: EVP_PKEY_meth_sign_init; AEVP_PKEY_meth_sign: EVP_PKEY_meth_sign) cdecl = nil; EVP_PKEY_meth_set_verify: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_verify_init: EVP_PKEY_meth_verify_init; AEVP_PKEY_meth_verify: EVP_PKEY_meth_verify_init) cdecl = nil; EVP_PKEY_meth_set_verify_recover: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_verify_recover_init: EVP_PKEY_meth_verify_recover_init; AEVP_PKEY_meth_verify_recover: EVP_PKEY_meth_verify_recover_init) cdecl = nil; EVP_PKEY_meth_set_signctx: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_signctx_init: EVP_PKEY_meth_signctx_init; AEVP_PKEY_meth_signctx: EVP_PKEY_meth_signctx) cdecl = nil; EVP_PKEY_meth_set_verifyctx: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_verifyctx_init: EVP_PKEY_meth_verifyctx_init; AEVP_PKEY_meth_verifyctx: EVP_PKEY_meth_verifyctx) cdecl = nil; EVP_PKEY_meth_set_encrypt: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_encrypt_init: EVP_PKEY_meth_encrypt_init; AEVP_PKEY_meth_encrypt: EVP_PKEY_meth_encrypt) cdecl = nil; EVP_PKEY_meth_set_decrypt: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_decrypt_init: EVP_PKEY_meth_decrypt_init; AEVP_PKEY_meth_decrypt: EVP_PKEY_meth_decrypt) cdecl = nil; EVP_PKEY_meth_set_derive: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_derive_init: EVP_PKEY_meth_derive_init; AEVP_PKEY_meth_derive: EVP_PKEY_meth_derive) cdecl = nil; EVP_PKEY_meth_set_ctrl: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_ctrl: EVP_PKEY_meth_ctrl; AEVP_PKEY_meth_ctrl_str: EVP_PKEY_meth_ctrl_str) cdecl = nil; EVP_PKEY_meth_set_digestsign: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_digestsign: EVP_PKEY_meth_digestsign) cdecl = nil; EVP_PKEY_meth_set_digestverify: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_digestverify: EVP_PKEY_meth_digestverify) cdecl = nil; EVP_PKEY_meth_set_check: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_check: EVP_PKEY_meth_check) cdecl = nil; EVP_PKEY_meth_set_public_check: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_public_check: EVP_PKEY_meth_public_check) cdecl = nil; EVP_PKEY_meth_set_param_check: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_param_check: EVP_PKEY_meth_param_check) cdecl = nil; EVP_PKEY_meth_set_digest_custom: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_digest_custom: EVP_PKEY_meth_digest_custom) cdecl = nil; EVP_PKEY_meth_get_init: procedure(const pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_init: PEVP_PKEY_meth_init) cdecl = nil; EVP_PKEY_meth_get_copy: procedure(const pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_copy: PEVP_PKEY_meth_copy) cdecl = nil; EVP_PKEY_meth_get_cleanup: procedure(const pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_cleanup: PEVP_PKEY_meth_cleanup) cdecl = nil; EVP_PKEY_meth_get_paramgen: procedure(const pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_paramgen_init: EVP_PKEY_meth_paramgen_init; AEVP_PKEY_meth_paramgen: PEVP_PKEY_meth_paramgen) cdecl = nil; EVP_PKEY_meth_get_keygen: procedure(const pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_keygen_init: EVP_PKEY_meth_keygen_init; AEVP_PKEY_meth_keygen: PEVP_PKEY_meth_keygen) cdecl = nil; EVP_PKEY_meth_get_sign: procedure(const pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_sign_init: PEVP_PKEY_meth_sign_init; AEVP_PKEY_meth_sign: PEVP_PKEY_meth_sign) cdecl = nil; EVP_PKEY_meth_get_verify: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_verify_init: PEVP_PKEY_meth_verify_init; AEVP_PKEY_meth_verify: PEVP_PKEY_meth_verify_init) cdecl = nil; EVP_PKEY_meth_get_verify_recover: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_verify_recover_init: PEVP_PKEY_meth_verify_recover_init; AEVP_PKEY_meth_verify_recover: PEVP_PKEY_meth_verify_recover_init) cdecl = nil; EVP_PKEY_meth_get_signctx: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_signctx_init: PEVP_PKEY_meth_signctx_init; AEVP_PKEY_meth_signctx: PEVP_PKEY_meth_signctx) cdecl = nil; EVP_PKEY_meth_get_verifyctx: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_verifyctx_init: PEVP_PKEY_meth_verifyctx_init; AEVP_PKEY_meth_verifyctx: PEVP_PKEY_meth_verifyctx) cdecl = nil; EVP_PKEY_meth_get_encrypt: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_encrypt_init: PEVP_PKEY_meth_encrypt_init; AEVP_PKEY_meth_encrypt: PEVP_PKEY_meth_encrypt) cdecl = nil; EVP_PKEY_meth_get_decrypt: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_decrypt_init: PEVP_PKEY_meth_decrypt_init; AEVP_PKEY_meth_decrypt: PEVP_PKEY_meth_decrypt) cdecl = nil; EVP_PKEY_meth_get_derive: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_derive_init: PEVP_PKEY_meth_derive_init; AEVP_PKEY_meth_derive: PEVP_PKEY_meth_derive) cdecl = nil; EVP_PKEY_meth_get_ctrl: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_ctrl: PEVP_PKEY_meth_ctrl; AEVP_PKEY_meth_ctrl_str: PEVP_PKEY_meth_ctrl_str) cdecl = nil; EVP_PKEY_meth_get_digestsign: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_digestsign: PEVP_PKEY_meth_digestsign) cdecl = nil; EVP_PKEY_meth_get_digestverify: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_digestverify: PEVP_PKEY_meth_digestverify) cdecl = nil; EVP_PKEY_meth_get_check: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_check: PEVP_PKEY_meth_check) cdecl = nil; EVP_PKEY_meth_get_public_check: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_public_check: PEVP_PKEY_meth_public_check) cdecl = nil; EVP_PKEY_meth_get_param_check: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_param_check: PEVP_PKEY_meth_param_check) cdecl = nil; EVP_PKEY_meth_get_digest_custom: procedure(pmeth: PEVP_PKEY_METHOD; AEVP_PKEY_meth_digest_custom: PEVP_PKEY_meth_digest_custom) cdecl = nil; EVP_add_alg_module: procedure cdecl = nil; implementation procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); function LoadFunction(const AMethodName: string; const AFailed: TStringList): Pointer; begin Result := LoadLibFunction(ADllHandle, AMethodName); if not Assigned(Result) then AFailed.Add(AMethodName); end; begin EVP_MD_meth_new := LoadFunction('EVP_MD_meth_new', AFailed); EVP_MD_meth_dup := LoadFunction('EVP_MD_meth_dup', AFailed); EVP_MD_meth_free := LoadFunction('EVP_MD_meth_free', AFailed); EVP_MD_meth_set_input_blocksize := LoadFunction('EVP_MD_meth_set_input_blocksize', AFailed); EVP_MD_meth_set_result_size := LoadFunction('EVP_MD_meth_set_result_size', AFailed); EVP_MD_meth_set_app_datasize := LoadFunction('EVP_MD_meth_set_app_datasize', AFailed); EVP_MD_meth_set_flags := LoadFunction('EVP_MD_meth_set_flags', AFailed); EVP_MD_meth_set_init := LoadFunction('EVP_MD_meth_set_init', AFailed); EVP_MD_meth_set_update := LoadFunction('EVP_MD_meth_set_update', AFailed); EVP_MD_meth_set_final := LoadFunction('EVP_MD_meth_set_final', AFailed); EVP_MD_meth_set_copy := LoadFunction('EVP_MD_meth_set_copy', AFailed); EVP_MD_meth_set_cleanup := LoadFunction('EVP_MD_meth_set_cleanup', AFailed); EVP_MD_meth_set_ctrl := LoadFunction('EVP_MD_meth_set_ctrl', AFailed); EVP_MD_meth_get_input_blocksize := LoadFunction('EVP_MD_meth_get_input_blocksize', AFailed); EVP_MD_meth_get_result_size := LoadFunction('EVP_MD_meth_get_result_size', AFailed); EVP_MD_meth_get_app_datasize := LoadFunction('EVP_MD_meth_get_app_datasize', AFailed); EVP_MD_meth_get_flags := LoadFunction('EVP_MD_meth_get_flags', AFailed); EVP_MD_meth_get_init := LoadFunction('EVP_MD_meth_get_init', AFailed); EVP_MD_meth_get_update := LoadFunction('EVP_MD_meth_get_update', AFailed); EVP_MD_meth_get_final := LoadFunction('EVP_MD_meth_get_final', AFailed); EVP_MD_meth_get_copy := LoadFunction('EVP_MD_meth_get_copy', AFailed); EVP_MD_meth_get_cleanup := LoadFunction('EVP_MD_meth_get_cleanup', AFailed); EVP_MD_meth_get_ctrl := LoadFunction('EVP_MD_meth_get_ctrl', AFailed); EVP_CIPHER_meth_new := LoadFunction('EVP_CIPHER_meth_new', AFailed); EVP_CIPHER_meth_dup := LoadFunction('EVP_CIPHER_meth_dup', AFailed); EVP_CIPHER_meth_free := LoadFunction('EVP_CIPHER_meth_free', AFailed); EVP_CIPHER_meth_set_iv_length := LoadFunction('EVP_CIPHER_meth_set_iv_length', AFailed); EVP_CIPHER_meth_set_flags := LoadFunction('EVP_CIPHER_meth_set_flags', AFailed); EVP_CIPHER_meth_set_impl_ctx_size := LoadFunction('EVP_CIPHER_meth_set_impl_ctx_size', AFailed); EVP_CIPHER_meth_set_init := LoadFunction('EVP_CIPHER_meth_set_init', AFailed); EVP_CIPHER_meth_set_do_cipher := LoadFunction('EVP_CIPHER_meth_set_do_cipher', AFailed); EVP_CIPHER_meth_set_cleanup := LoadFunction('EVP_CIPHER_meth_set_cleanup', AFailed); EVP_CIPHER_meth_set_set_asn1_params := LoadFunction('EVP_CIPHER_meth_set_set_asn1_params', AFailed); EVP_CIPHER_meth_set_get_asn1_params := LoadFunction('EVP_CIPHER_meth_set_get_asn1_params', AFailed); EVP_CIPHER_meth_set_ctrl := LoadFunction('EVP_CIPHER_meth_set_ctrl', AFailed); EVP_CIPHER_meth_get_init := LoadFunction('EVP_CIPHER_meth_get_init', AFailed); EVP_CIPHER_meth_get_do_cipher := LoadFunction('EVP_CIPHER_meth_get_do_cipher', AFailed); EVP_CIPHER_meth_get_cleanup := LoadFunction('EVP_CIPHER_meth_get_cleanup', AFailed); EVP_CIPHER_meth_get_set_asn1_params := LoadFunction('EVP_CIPHER_meth_get_set_asn1_params', AFailed); EVP_CIPHER_meth_get_get_asn1_params := LoadFunction('EVP_CIPHER_meth_get_get_asn1_params', AFailed); EVP_CIPHER_meth_get_ctrl := LoadFunction('EVP_CIPHER_meth_get_ctrl', AFailed); EVP_MD_type := LoadFunction('EVP_MD_type', AFailed); EVP_MD_pkey_type := LoadFunction('EVP_MD_pkey_type', AFailed); EVP_MD_size := LoadFunction('EVP_MD_size', AFailed); EVP_MD_block_size := LoadFunction('EVP_MD_block_size', AFailed); EVP_MD_flags := LoadFunction('EVP_MD_flags', AFailed); EVP_MD_CTX_md := LoadFunction('EVP_MD_CTX_md', AFailed); EVP_MD_CTX_update_fn := LoadFunction('EVP_MD_CTX_update_fn', AFailed); EVP_MD_CTX_set_update_fn := LoadFunction('EVP_MD_CTX_set_update_fn', AFailed); EVP_MD_CTX_pkey_ctx := LoadFunction('EVP_MD_CTX_pkey_ctx', AFailed); EVP_MD_CTX_set_pkey_ctx := LoadFunction('EVP_MD_CTX_set_pkey_ctx', AFailed); EVP_MD_CTX_md_data := LoadFunction('EVP_MD_CTX_md_data', AFailed); EVP_CIPHER_nid := LoadFunction('EVP_CIPHER_nid', AFailed); EVP_CIPHER_block_size := LoadFunction('EVP_CIPHER_block_size', AFailed); EVP_CIPHER_impl_ctx_size := LoadFunction('EVP_CIPHER_impl_ctx_size', AFailed); EVP_CIPHER_key_length := LoadFunction('EVP_CIPHER_key_length', AFailed); EVP_CIPHER_iv_length := LoadFunction('EVP_CIPHER_iv_length', AFailed); EVP_CIPHER_flags := LoadFunction('EVP_CIPHER_flags', AFailed); EVP_CIPHER_CTX_cipher := LoadFunction('EVP_CIPHER_CTX_cipher', AFailed); EVP_CIPHER_CTX_encrypting := LoadFunction('EVP_CIPHER_CTX_encrypting', AFailed); EVP_CIPHER_CTX_nid := LoadFunction('EVP_CIPHER_CTX_nid', AFailed); EVP_CIPHER_CTX_block_size := LoadFunction('EVP_CIPHER_CTX_block_size', AFailed); EVP_CIPHER_CTX_key_length := LoadFunction('EVP_CIPHER_CTX_key_length', AFailed); EVP_CIPHER_CTX_iv_length := LoadFunction('EVP_CIPHER_CTX_iv_length', AFailed); EVP_CIPHER_CTX_iv := LoadFunction('EVP_CIPHER_CTX_iv', AFailed); EVP_CIPHER_CTX_original_iv := LoadFunction('EVP_CIPHER_CTX_original_iv', AFailed); EVP_CIPHER_CTX_iv_noconst := LoadFunction('EVP_CIPHER_CTX_iv_noconst', AFailed); EVP_CIPHER_CTX_buf_noconst := LoadFunction('EVP_CIPHER_CTX_buf_noconst', AFailed); EVP_CIPHER_CTX_num := LoadFunction('EVP_CIPHER_CTX_num', AFailed); EVP_CIPHER_CTX_set_num := LoadFunction('EVP_CIPHER_CTX_set_num', AFailed); EVP_CIPHER_CTX_copy := LoadFunction('EVP_CIPHER_CTX_copy', AFailed); EVP_CIPHER_CTX_get_app_data := LoadFunction('EVP_CIPHER_CTX_get_app_data', AFailed); EVP_CIPHER_CTX_set_app_data := LoadFunction('EVP_CIPHER_CTX_set_app_data', AFailed); EVP_CIPHER_CTX_get_cipher_data := LoadFunction('EVP_CIPHER_CTX_get_cipher_data', AFailed); EVP_CIPHER_CTX_set_cipher_data := LoadFunction('EVP_CIPHER_CTX_set_cipher_data', AFailed); BIO_set_md := LoadFunction('BIO_set_md', AFailed); EVP_MD_CTX_ctrl := LoadFunction('EVP_MD_CTX_ctrl', AFailed); EVP_MD_CTX_new := LoadFunction('EVP_MD_CTX_new', AFailed); EVP_MD_CTX_reset := LoadFunction('EVP_MD_CTX_reset', AFailed); EVP_MD_CTX_free := LoadFunction('EVP_MD_CTX_free', AFailed); EVP_MD_CTX_copy_ex := LoadFunction('EVP_MD_CTX_copy_ex', AFailed); EVP_MD_CTX_set_flags := LoadFunction('EVP_MD_CTX_set_flags', AFailed); EVP_MD_CTX_clear_flags := LoadFunction('EVP_MD_CTX_clear_flags', AFailed); EVP_MD_CTX_test_flags := LoadFunction('EVP_MD_CTX_test_flags', AFailed); EVP_DigestInit_ex := LoadFunction('EVP_DigestInit_ex', AFailed); EVP_DigestUpdate := LoadFunction('EVP_DigestUpdate', AFailed); EVP_DigestFinal_ex := LoadFunction('EVP_DigestFinal_ex', AFailed); EVP_Digest := LoadFunction('EVP_Digest', AFailed); EVP_MD_CTX_copy := LoadFunction('EVP_MD_CTX_copy', AFailed); EVP_DigestInit := LoadFunction('EVP_DigestInit', AFailed); EVP_DigestFinal := LoadFunction('EVP_DigestFinal', AFailed); EVP_DigestFinalXOF := LoadFunction('EVP_DigestFinalXOF', AFailed); EVP_read_pw_string := LoadFunction('EVP_read_pw_string', AFailed); EVP_read_pw_string_min := LoadFunction('EVP_read_pw_string_min', AFailed); EVP_set_pw_prompt := LoadFunction('EVP_set_pw_prompt', AFailed); EVP_get_pw_prompt := LoadFunction('EVP_get_pw_prompt', AFailed); EVP_BytesToKey := LoadFunction('EVP_BytesToKey', AFailed); EVP_CIPHER_CTX_set_flags := LoadFunction('EVP_CIPHER_CTX_set_flags', AFailed); EVP_CIPHER_CTX_clear_flags := LoadFunction('EVP_CIPHER_CTX_clear_flags', AFailed); EVP_CIPHER_CTX_test_flags := LoadFunction('EVP_CIPHER_CTX_test_flags', AFailed); EVP_EncryptInit := LoadFunction('EVP_EncryptInit', AFailed); EVP_EncryptInit_ex := LoadFunction('EVP_EncryptInit_ex', AFailed); EVP_EncryptUpdate := LoadFunction('EVP_EncryptUpdate', AFailed); EVP_EncryptFinal_ex := LoadFunction('EVP_EncryptFinal_ex', AFailed); EVP_EncryptFinal := LoadFunction('EVP_EncryptFinal', AFailed); EVP_DecryptInit := LoadFunction('EVP_DecryptInit', AFailed); EVP_DecryptInit_ex := LoadFunction('EVP_DecryptInit_ex', AFailed); EVP_DecryptUpdate := LoadFunction('EVP_DecryptUpdate', AFailed); EVP_DecryptFinal := LoadFunction('EVP_DecryptFinal', AFailed); EVP_DecryptFinal_ex := LoadFunction('EVP_DecryptFinal_ex', AFailed); EVP_CipherInit := LoadFunction('EVP_CipherInit', AFailed); EVP_CipherInit_ex := LoadFunction('EVP_CipherInit_ex', AFailed); EVP_CipherUpdate := LoadFunction('EVP_CipherUpdate', AFailed); EVP_CipherFinal := LoadFunction('EVP_CipherFinal', AFailed); EVP_CipherFinal_ex := LoadFunction('EVP_CipherFinal_ex', AFailed); EVP_SignFinal := LoadFunction('EVP_SignFinal', AFailed); EVP_DigestSign := LoadFunction('EVP_DigestSign', AFailed); EVP_VerifyFinal := LoadFunction('EVP_VerifyFinal', AFailed); EVP_DigestVerify := LoadFunction('EVP_DigestVerify', AFailed); EVP_DigestSignInit := LoadFunction('EVP_DigestSignInit', AFailed); EVP_DigestSignFinal := LoadFunction('EVP_DigestSignFinal', AFailed); EVP_DigestVerifyInit := LoadFunction('EVP_DigestVerifyInit', AFailed); EVP_DigestVerifyFinal := LoadFunction('EVP_DigestVerifyFinal', AFailed); EVP_OpenInit := LoadFunction('EVP_OpenInit', AFailed); EVP_OpenFinal := LoadFunction('EVP_OpenFinal', AFailed); EVP_SealInit := LoadFunction('EVP_SealInit', AFailed); EVP_SealFinal := LoadFunction('EVP_SealFinal', AFailed); EVP_ENCODE_CTX_new := LoadFunction('EVP_ENCODE_CTX_new', AFailed); EVP_ENCODE_CTX_free := LoadFunction('EVP_ENCODE_CTX_free', AFailed); EVP_ENCODE_CTX_copy := LoadFunction('EVP_ENCODE_CTX_copy', AFailed); EVP_ENCODE_CTX_num := LoadFunction('EVP_ENCODE_CTX_num', AFailed); EVP_EncodeInit := LoadFunction('EVP_EncodeInit', AFailed); EVP_EncodeUpdate := LoadFunction('EVP_EncodeUpdate', AFailed); EVP_EncodeFinal := LoadFunction('EVP_EncodeFinal', AFailed); EVP_EncodeBlock := LoadFunction('EVP_EncodeBlock', AFailed); EVP_DecodeInit := LoadFunction('EVP_DecodeInit', AFailed); EVP_DecodeUpdate := LoadFunction('EVP_DecodeUpdate', AFailed); EVP_DecodeFinal := LoadFunction('EVP_DecodeFinal', AFailed); EVP_DecodeBlock := LoadFunction('EVP_DecodeBlock', AFailed); EVP_CIPHER_CTX_new := LoadFunction('EVP_CIPHER_CTX_new', AFailed); EVP_CIPHER_CTX_reset := LoadFunction('EVP_CIPHER_CTX_reset', AFailed); EVP_CIPHER_CTX_free := LoadFunction('EVP_CIPHER_CTX_free', AFailed); EVP_CIPHER_CTX_set_key_length := LoadFunction('EVP_CIPHER_CTX_set_key_length', AFailed); EVP_CIPHER_CTX_set_padding := LoadFunction('EVP_CIPHER_CTX_set_padding', AFailed); EVP_CIPHER_CTX_ctrl := LoadFunction('EVP_CIPHER_CTX_ctrl', AFailed); EVP_CIPHER_CTX_rand_key := LoadFunction('EVP_CIPHER_CTX_rand_key', AFailed); BIO_f_md := LoadFunction('BIO_f_md', AFailed); BIO_f_base64 := LoadFunction('BIO_f_base64', AFailed); BIO_f_cipher := LoadFunction('BIO_f_cipher', AFailed); BIO_f_reliable := LoadFunction('BIO_f_reliable', AFailed); BIO_set_cipher := LoadFunction('BIO_set_cipher', AFailed); EVP_md_null := LoadFunction('EVP_md_null', AFailed); EVP_md5 := LoadFunction('EVP_md5', AFailed); EVP_md5_sha1 := LoadFunction('EVP_md5_sha1', AFailed); EVP_sha1 := LoadFunction('EVP_sha1', AFailed); EVP_sha224 := LoadFunction('EVP_sha224', AFailed); EVP_sha256 := LoadFunction('EVP_sha256', AFailed); EVP_sha384 := LoadFunction('EVP_sha384', AFailed); EVP_sha512 := LoadFunction('EVP_sha512', AFailed); EVP_sha512_224 := LoadFunction('EVP_sha512_224', AFailed); EVP_sha512_256 := LoadFunction('EVP_sha512_256', AFailed); EVP_sha3_224 := LoadFunction('EVP_sha3_224', AFailed); EVP_sha3_256 := LoadFunction('EVP_sha3_256', AFailed); EVP_sha3_384 := LoadFunction('EVP_sha3_384', AFailed); EVP_sha3_512 := LoadFunction('EVP_sha3_512', AFailed); EVP_shake128 := LoadFunction('EVP_shake128', AFailed); EVP_shake256 := LoadFunction('EVP_shake256', AFailed); EVP_enc_null := LoadFunction('EVP_enc_null', AFailed); EVP_des_ecb := LoadFunction('EVP_des_ecb', AFailed); EVP_des_ede := LoadFunction('EVP_des_ede', AFailed); EVP_des_ede3 := LoadFunction('EVP_des_ede3', AFailed); EVP_des_ede_ecb := LoadFunction('EVP_des_ede_ecb', AFailed); EVP_des_ede3_ecb := LoadFunction('EVP_des_ede3_ecb', AFailed); EVP_des_cfb64 := LoadFunction('EVP_des_cfb64', AFailed); EVP_des_cfb1 := LoadFunction('EVP_des_cfb1', AFailed); EVP_des_cfb8 := LoadFunction('EVP_des_cfb8', AFailed); EVP_des_ede_cfb64 := LoadFunction('EVP_des_ede_cfb64', AFailed); EVP_des_ede3_cfb64 := LoadFunction('EVP_des_ede3_cfb64', AFailed); EVP_des_ede3_cfb1 := LoadFunction('EVP_des_ede3_cfb1', AFailed); EVP_des_ede3_cfb8 := LoadFunction('EVP_des_ede3_cfb8', AFailed); EVP_des_ofb := LoadFunction('EVP_des_ofb', AFailed); EVP_des_ede_ofb := LoadFunction('EVP_des_ede_ofb', AFailed); EVP_des_ede3_ofb := LoadFunction('EVP_des_ede3_ofb', AFailed); EVP_des_cbc := LoadFunction('EVP_des_cbc', AFailed); EVP_des_ede_cbc := LoadFunction('EVP_des_ede_cbc', AFailed); EVP_des_ede3_cbc := LoadFunction('EVP_des_ede3_cbc', AFailed); EVP_desx_cbc := LoadFunction('EVP_desx_cbc', AFailed); EVP_des_ede3_wrap := LoadFunction('EVP_des_ede3_wrap', AFailed); EVP_rc4 := LoadFunction('EVP_rc4', AFailed); EVP_rc4_40 := LoadFunction('EVP_rc4_40', AFailed); EVP_idea_ecb := LoadFunction('EVP_idea_ecb', AFailed); EVP_idea_cfb64 := LoadFunction('EVP_idea_cfb64', AFailed); EVP_idea_ofb := LoadFunction('EVP_idea_ofb', AFailed); EVP_idea_cbc := LoadFunction('EVP_idea_cbc', AFailed); EVP_rc2_ecb := LoadFunction('EVP_rc2_ecb', AFailed); EVP_rc2_cbc := LoadFunction('EVP_rc2_cbc', AFailed); EVP_rc2_40_cbc := LoadFunction('EVP_rc2_40_cbc', AFailed); EVP_rc2_64_cbc := LoadFunction('EVP_rc2_64_cbc', AFailed); EVP_rc2_cfb64 := LoadFunction('EVP_rc2_cfb64', AFailed); EVP_rc2_ofb := LoadFunction('EVP_rc2_ofb', AFailed); EVP_bf_ecb := LoadFunction('EVP_bf_ecb', AFailed); EVP_bf_cbc := LoadFunction('EVP_bf_cbc', AFailed); EVP_bf_cfb64 := LoadFunction('EVP_bf_cfb64', AFailed); EVP_bf_ofb := LoadFunction('EVP_bf_ofb', AFailed); EVP_cast5_ecb := LoadFunction('EVP_cast5_ecb', AFailed); EVP_cast5_cbc := LoadFunction('EVP_cast5_cbc', AFailed); EVP_cast5_cfb64 := LoadFunction('EVP_cast5_cfb64', AFailed); EVP_cast5_ofb := LoadFunction('EVP_cast5_ofb', AFailed); EVP_rc5_32_12_16_cbc := LoadFunction('EVP_rc5_32_12_16_cbc', AFailed); EVP_rc5_32_12_16_ecb := LoadFunction('EVP_rc5_32_12_16_ecb', AFailed); EVP_rc5_32_12_16_cfb64 := LoadFunction('EVP_rc5_32_12_16_cfb64', AFailed); EVP_rc5_32_12_16_ofb := LoadFunction('EVP_rc5_32_12_16_ofb', AFailed); EVP_aes_128_ecb := LoadFunction('EVP_aes_128_ecb', AFailed); EVP_aes_128_cbc := LoadFunction('EVP_aes_128_cbc', AFailed); EVP_aes_128_cfb1 := LoadFunction('EVP_aes_128_cfb1', AFailed); EVP_aes_128_cfb8 := LoadFunction('EVP_aes_128_cfb8', AFailed); EVP_aes_128_cfb128 := LoadFunction('EVP_aes_128_cfb128', AFailed); EVP_aes_128_ofb := LoadFunction('EVP_aes_128_ofb', AFailed); EVP_aes_128_ctr := LoadFunction('EVP_aes_128_ctr', AFailed); EVP_aes_128_ccm := LoadFunction('EVP_aes_128_ccm', AFailed); EVP_aes_128_gcm := LoadFunction('EVP_aes_128_gcm', AFailed); EVP_aes_128_xts := LoadFunction('EVP_aes_128_xts', AFailed); EVP_aes_128_wrap := LoadFunction('EVP_aes_128_wrap', AFailed); EVP_aes_128_wrap_pad := LoadFunction('EVP_aes_128_wrap_pad', AFailed); EVP_aes_128_ocb := LoadFunction('EVP_aes_128_ocb', AFailed); EVP_aes_192_ecb := LoadFunction('EVP_aes_192_ecb', AFailed); EVP_aes_192_cbc := LoadFunction('EVP_aes_192_cbc', AFailed); EVP_aes_192_cfb1 := LoadFunction('EVP_aes_192_cfb1', AFailed); EVP_aes_192_cfb8 := LoadFunction('EVP_aes_192_cfb8', AFailed); EVP_aes_192_cfb128 := LoadFunction('EVP_aes_192_cfb128', AFailed); EVP_aes_192_ofb := LoadFunction('EVP_aes_192_ofb', AFailed); EVP_aes_192_ctr := LoadFunction('EVP_aes_192_ctr', AFailed); EVP_aes_192_ccm := LoadFunction('EVP_aes_192_ccm', AFailed); EVP_aes_192_gcm := LoadFunction('EVP_aes_192_gcm', AFailed); EVP_aes_192_wrap := LoadFunction('EVP_aes_192_wrap', AFailed); EVP_aes_192_wrap_pad := LoadFunction('EVP_aes_192_wrap_pad', AFailed); EVP_aes_192_ocb := LoadFunction('EVP_aes_192_ocb', AFailed); EVP_aes_256_ecb := LoadFunction('EVP_aes_256_ecb', AFailed); EVP_aes_256_cbc := LoadFunction('EVP_aes_256_cbc', AFailed); EVP_aes_256_cfb1 := LoadFunction('EVP_aes_256_cfb1', AFailed); EVP_aes_256_cfb8 := LoadFunction('EVP_aes_256_cfb8', AFailed); EVP_aes_256_cfb128 := LoadFunction('EVP_aes_256_cfb128', AFailed); EVP_aes_256_ofb := LoadFunction('EVP_aes_256_ofb', AFailed); EVP_aes_256_ctr := LoadFunction('EVP_aes_256_ctr', AFailed); EVP_aes_256_ccm := LoadFunction('EVP_aes_256_ccm', AFailed); EVP_aes_256_gcm := LoadFunction('EVP_aes_256_gcm', AFailed); EVP_aes_256_xts := LoadFunction('EVP_aes_256_xts', AFailed); EVP_aes_256_wrap := LoadFunction('EVP_aes_256_wrap', AFailed); EVP_aes_256_wrap_pad := LoadFunction('EVP_aes_256_wrap_pad', AFailed); EVP_aes_256_ocb := LoadFunction('EVP_aes_256_ocb', AFailed); EVP_aes_128_cbc_hmac_sha1 := LoadFunction('EVP_aes_128_cbc_hmac_sha1', AFailed); EVP_aes_256_cbc_hmac_sha1 := LoadFunction('EVP_aes_256_cbc_hmac_sha1', AFailed); EVP_aes_128_cbc_hmac_sha256 := LoadFunction('EVP_aes_128_cbc_hmac_sha256', AFailed); EVP_aes_256_cbc_hmac_sha256 := LoadFunction('EVP_aes_256_cbc_hmac_sha256', AFailed); EVP_aria_128_ecb := LoadFunction('EVP_aria_128_ecb', AFailed); EVP_aria_128_cbc := LoadFunction('EVP_aria_128_cbc', AFailed); EVP_aria_128_cfb1 := LoadFunction('EVP_aria_128_cfb1', AFailed); EVP_aria_128_cfb8 := LoadFunction('EVP_aria_128_cfb8', AFailed); EVP_aria_128_cfb128 := LoadFunction('EVP_aria_128_cfb128', AFailed); EVP_aria_128_ctr := LoadFunction('EVP_aria_128_ctr', AFailed); EVP_aria_128_ofb := LoadFunction('EVP_aria_128_ofb', AFailed); EVP_aria_128_gcm := LoadFunction('EVP_aria_128_gcm', AFailed); EVP_aria_128_ccm := LoadFunction('EVP_aria_128_ccm', AFailed); EVP_aria_192_ecb := LoadFunction('EVP_aria_192_ecb', AFailed); EVP_aria_192_cbc := LoadFunction('EVP_aria_192_cbc', AFailed); EVP_aria_192_cfb1 := LoadFunction('EVP_aria_192_cfb1', AFailed); EVP_aria_192_cfb8 := LoadFunction('EVP_aria_192_cfb8', AFailed); EVP_aria_192_cfb128 := LoadFunction('EVP_aria_192_cfb128', AFailed); EVP_aria_192_ctr := LoadFunction('EVP_aria_192_ctr', AFailed); EVP_aria_192_ofb := LoadFunction('EVP_aria_192_ofb', AFailed); EVP_aria_192_gcm := LoadFunction('EVP_aria_192_gcm', AFailed); EVP_aria_192_ccm := LoadFunction('EVP_aria_192_ccm', AFailed); EVP_aria_256_ecb := LoadFunction('EVP_aria_256_ecb', AFailed); EVP_aria_256_cbc := LoadFunction('EVP_aria_256_cbc', AFailed); EVP_aria_256_cfb1 := LoadFunction('EVP_aria_256_cfb1', AFailed); EVP_aria_256_cfb8 := LoadFunction('EVP_aria_256_cfb8', AFailed); EVP_aria_256_cfb128 := LoadFunction('EVP_aria_256_cfb128', AFailed); EVP_aria_256_ctr := LoadFunction('EVP_aria_256_ctr', AFailed); EVP_aria_256_ofb := LoadFunction('EVP_aria_256_ofb', AFailed); EVP_aria_256_gcm := LoadFunction('EVP_aria_256_gcm', AFailed); EVP_aria_256_ccm := LoadFunction('EVP_aria_256_ccm', AFailed); EVP_camellia_128_ecb := LoadFunction('EVP_camellia_128_ecb', AFailed); EVP_camellia_128_cbc := LoadFunction('EVP_camellia_128_cbc', AFailed); EVP_camellia_128_cfb1 := LoadFunction('EVP_camellia_128_cfb1', AFailed); EVP_camellia_128_cfb8 := LoadFunction('EVP_camellia_128_cfb8', AFailed); EVP_camellia_128_cfb128 := LoadFunction('EVP_camellia_128_cfb128', AFailed); EVP_camellia_128_ofb := LoadFunction('EVP_camellia_128_ofb', AFailed); EVP_camellia_128_ctr := LoadFunction('EVP_camellia_128_ctr', AFailed); EVP_camellia_192_ecb := LoadFunction('EVP_camellia_192_ecb', AFailed); EVP_camellia_192_cbc := LoadFunction('EVP_camellia_192_cbc', AFailed); EVP_camellia_192_cfb1 := LoadFunction('EVP_camellia_192_cfb1', AFailed); EVP_camellia_192_cfb8 := LoadFunction('EVP_camellia_192_cfb8', AFailed); EVP_camellia_192_cfb128 := LoadFunction('EVP_camellia_192_cfb128', AFailed); EVP_camellia_192_ofb := LoadFunction('EVP_camellia_192_ofb', AFailed); EVP_camellia_192_ctr := LoadFunction('EVP_camellia_192_ctr', AFailed); EVP_camellia_256_ecb := LoadFunction('EVP_camellia_256_ecb', AFailed); EVP_camellia_256_cbc := LoadFunction('EVP_camellia_256_cbc', AFailed); EVP_camellia_256_cfb1 := LoadFunction('EVP_camellia_256_cfb1', AFailed); EVP_camellia_256_cfb8 := LoadFunction('EVP_camellia_256_cfb8', AFailed); EVP_camellia_256_cfb128 := LoadFunction('EVP_camellia_256_cfb128', AFailed); EVP_camellia_256_ofb := LoadFunction('EVP_camellia_256_ofb', AFailed); EVP_camellia_256_ctr := LoadFunction('EVP_camellia_256_ctr', AFailed); EVP_chacha20 := LoadFunction('EVP_chacha20', AFailed); EVP_chacha20_poly1305 := LoadFunction('EVP_chacha20_poly1305', AFailed); EVP_seed_ecb := LoadFunction('EVP_seed_ecb', AFailed); EVP_seed_cbc := LoadFunction('EVP_seed_cbc', AFailed); EVP_seed_cfb128 := LoadFunction('EVP_seed_cfb128', AFailed); EVP_seed_ofb := LoadFunction('EVP_seed_ofb', AFailed); EVP_sm4_ecb := LoadFunction('EVP_sm4_ecb', AFailed); EVP_sm4_cbc := LoadFunction('EVP_sm4_cbc', AFailed); EVP_sm4_cfb128 := LoadFunction('EVP_sm4_cfb128', AFailed); EVP_sm4_ofb := LoadFunction('EVP_sm4_ofb', AFailed); EVP_sm4_ctr := LoadFunction('EVP_sm4_ctr', AFailed); EVP_add_cipher := LoadFunction('EVP_add_cipher', AFailed); EVP_add_digest := LoadFunction('EVP_add_digest', AFailed); EVP_get_cipherbyname := LoadFunction('EVP_get_cipherbyname', AFailed); EVP_get_digestbyname := LoadFunction('EVP_get_digestbyname', AFailed); EVP_CIPHER_do_all := LoadFunction('EVP_CIPHER_do_all', AFailed); EVP_CIPHER_do_all_sorted := LoadFunction('EVP_CIPHER_do_all_sorted', AFailed); EVP_MD_do_all := LoadFunction('EVP_MD_do_all', AFailed); EVP_MD_do_all_sorted := LoadFunction('EVP_MD_do_all_sorted', AFailed); EVP_PKEY_decrypt_old := LoadFunction('EVP_PKEY_decrypt_old', AFailed); EVP_PKEY_encrypt_old := LoadFunction('EVP_PKEY_encrypt_old', AFailed); EVP_PKEY_type := LoadFunction('EVP_PKEY_type', AFailed); EVP_PKEY_id := LoadFunction('EVP_PKEY_id', AFailed); EVP_PKEY_base_id := LoadFunction('EVP_PKEY_base_id', AFailed); EVP_PKEY_bits := LoadFunction('EVP_PKEY_bits', AFailed); EVP_PKEY_security_bits := LoadFunction('EVP_PKEY_security_bits', AFailed); EVP_PKEY_size := LoadFunction('EVP_PKEY_size', AFailed); EVP_PKEY_set_type := LoadFunction('EVP_PKEY_set_type', AFailed); EVP_PKEY_set_type_str := LoadFunction('EVP_PKEY_set_type_str', AFailed); EVP_PKEY_set_alias_type := LoadFunction('EVP_PKEY_set_alias_type', AFailed); EVP_PKEY_set1_engine := LoadFunction('EVP_PKEY_set1_engine', AFailed); EVP_PKEY_get0_engine := LoadFunction('EVP_PKEY_get0_engine', AFailed); EVP_PKEY_assign := LoadFunction('EVP_PKEY_assign', AFailed); EVP_PKEY_get0 := LoadFunction('EVP_PKEY_get0', AFailed); EVP_PKEY_get0_hmac := LoadFunction('EVP_PKEY_get0_hmac', AFailed); EVP_PKEY_get0_poly1305 := LoadFunction('EVP_PKEY_get0_poly1305', AFailed); EVP_PKEY_get0_siphash := LoadFunction('EVP_PKEY_get0_siphash', AFailed); EVP_PKEY_set1_RSA := LoadFunction('EVP_PKEY_set1_RSA', AFailed); EVP_PKEY_get0_RSA := LoadFunction('EVP_PKEY_get0_RSA', AFailed); EVP_PKEY_get1_RSA := LoadFunction('EVP_PKEY_get1_RSA', AFailed); EVP_PKEY_set1_DSA := LoadFunction('EVP_PKEY_set1_DSA', AFailed); EVP_PKEY_get0_DSA := LoadFunction('EVP_PKEY_get0_DSA', AFailed); EVP_PKEY_get1_DSA := LoadFunction('EVP_PKEY_get1_DSA', AFailed); EVP_PKEY_set1_DH := LoadFunction('EVP_PKEY_set1_DH', AFailed); EVP_PKEY_get0_DH := LoadFunction('EVP_PKEY_get0_DH', AFailed); EVP_PKEY_get1_DH := LoadFunction('EVP_PKEY_get1_DH', AFailed); EVP_PKEY_set1_EC_KEY := LoadFunction('EVP_PKEY_set1_EC_KEY', AFailed); EVP_PKEY_get0_EC_KEY := LoadFunction('EVP_PKEY_get0_EC_KEY', AFailed); EVP_PKEY_get1_EC_KEY := LoadFunction('EVP_PKEY_get1_EC_KEY', AFailed); EVP_PKEY_new := LoadFunction('EVP_PKEY_new', AFailed); EVP_PKEY_up_ref := LoadFunction('EVP_PKEY_up_ref', AFailed); EVP_PKEY_free := LoadFunction('EVP_PKEY_free', AFailed); d2i_PublicKey := LoadFunction('d2i_PublicKey', AFailed); i2d_PublicKey := LoadFunction('i2d_PublicKey', AFailed); d2i_PrivateKey := LoadFunction('d2i_PrivateKey', AFailed); d2i_AutoPrivateKey := LoadFunction('d2i_AutoPrivateKey', AFailed); i2d_PrivateKey := LoadFunction('i2d_PrivateKey', AFailed); EVP_PKEY_copy_parameters := LoadFunction('EVP_PKEY_copy_parameters', AFailed); EVP_PKEY_missing_parameters := LoadFunction('EVP_PKEY_missing_parameters', AFailed); EVP_PKEY_save_parameters := LoadFunction('EVP_PKEY_save_parameters', AFailed); EVP_PKEY_cmp_parameters := LoadFunction('EVP_PKEY_cmp_parameters', AFailed); EVP_PKEY_cmp := LoadFunction('EVP_PKEY_cmp', AFailed); EVP_PKEY_print_public := LoadFunction('EVP_PKEY_print_public', AFailed); EVP_PKEY_print_private := LoadFunction('EVP_PKEY_print_private', AFailed); EVP_PKEY_print_params := LoadFunction('EVP_PKEY_print_params', AFailed); EVP_PKEY_get_default_digest_nid := LoadFunction('EVP_PKEY_get_default_digest_nid', AFailed); EVP_PKEY_set1_tls_encodedpoint := LoadFunction('EVP_PKEY_set1_tls_encodedpoint', AFailed); EVP_PKEY_get1_tls_encodedpoint := LoadFunction('EVP_PKEY_get1_tls_encodedpoint', AFailed); EVP_CIPHER_type := LoadFunction('EVP_CIPHER_type', AFailed); EVP_CIPHER_param_to_asn1 := LoadFunction('EVP_CIPHER_param_to_asn1', AFailed); EVP_CIPHER_asn1_to_param := LoadFunction('EVP_CIPHER_asn1_to_param', AFailed); EVP_CIPHER_set_asn1_iv := LoadFunction('EVP_CIPHER_set_asn1_iv', AFailed); EVP_CIPHER_get_asn1_iv := LoadFunction('EVP_CIPHER_get_asn1_iv', AFailed); PKCS5_PBE_keyivgen := LoadFunction('PKCS5_PBE_keyivgen', AFailed); PKCS5_PBKDF2_HMAC_SHA1 := LoadFunction('PKCS5_PBKDF2_HMAC_SHA1', AFailed); PKCS5_PBKDF2_HMAC := LoadFunction('PKCS5_PBKDF2_HMAC', AFailed); PKCS5_v2_PBE_keyivgen := LoadFunction('PKCS5_v2_PBE_keyivgen', AFailed); EVP_PBE_scrypt := LoadFunction('EVP_PBE_scrypt', AFailed); PKCS5_v2_scrypt_keyivgen := LoadFunction('PKCS5_v2_scrypt_keyivgen', AFailed); PKCS5_PBE_add := LoadFunction('PKCS5_PBE_add', AFailed); EVP_PBE_CipherInit := LoadFunction('EVP_PBE_CipherInit', AFailed); EVP_PBE_alg_add_type := LoadFunction('EVP_PBE_alg_add_type', AFailed); EVP_PBE_alg_add := LoadFunction('EVP_PBE_alg_add', AFailed); EVP_PBE_find := LoadFunction('EVP_PBE_find', AFailed); EVP_PBE_cleanup := LoadFunction('EVP_PBE_cleanup', AFailed); EVP_PBE_get := LoadFunction('EVP_PBE_get', AFailed); EVP_PKEY_asn1_get_count := LoadFunction('EVP_PKEY_asn1_get_count', AFailed); EVP_PKEY_asn1_get0 := LoadFunction('EVP_PKEY_asn1_get0', AFailed); EVP_PKEY_asn1_find := LoadFunction('EVP_PKEY_asn1_find', AFailed); EVP_PKEY_asn1_find_str := LoadFunction('EVP_PKEY_asn1_find_str', AFailed); EVP_PKEY_asn1_add0 := LoadFunction('EVP_PKEY_asn1_add0', AFailed); EVP_PKEY_asn1_add_alias := LoadFunction('EVP_PKEY_asn1_add_alias', AFailed); EVP_PKEY_asn1_get0_info := LoadFunction('EVP_PKEY_asn1_get0_info', AFailed); EVP_PKEY_get0_asn1 := LoadFunction('EVP_PKEY_get0_asn1', AFailed); EVP_PKEY_asn1_new := LoadFunction('EVP_PKEY_asn1_new', AFailed); EVP_PKEY_asn1_copy := LoadFunction('EVP_PKEY_asn1_copy', AFailed); EVP_PKEY_asn1_free := LoadFunction('EVP_PKEY_asn1_free', AFailed); EVP_PKEY_asn1_set_public := LoadFunction('EVP_PKEY_asn1_set_public', AFailed); EVP_PKEY_asn1_set_private := LoadFunction('EVP_PKEY_asn1_set_private', AFailed); EVP_PKEY_asn1_set_param := LoadFunction('EVP_PKEY_asn1_set_param', AFailed); EVP_PKEY_asn1_set_free := LoadFunction('EVP_PKEY_asn1_set_free', AFailed); EVP_PKEY_asn1_set_ctrl := LoadFunction('EVP_PKEY_asn1_set_ctrl', AFailed); EVP_PKEY_asn1_set_item := LoadFunction('EVP_PKEY_asn1_set_item', AFailed); EVP_PKEY_asn1_set_siginf := LoadFunction('EVP_PKEY_asn1_set_siginf', AFailed); EVP_PKEY_asn1_set_check := LoadFunction('EVP_PKEY_asn1_set_check', AFailed); EVP_PKEY_asn1_set_public_check := LoadFunction('EVP_PKEY_asn1_set_public_check', AFailed); EVP_PKEY_asn1_set_param_check := LoadFunction('EVP_PKEY_asn1_set_param_check', AFailed); EVP_PKEY_asn1_set_set_priv_key := LoadFunction('EVP_PKEY_asn1_set_set_priv_key', AFailed); EVP_PKEY_asn1_set_set_pub_key := LoadFunction('EVP_PKEY_asn1_set_set_pub_key', AFailed); EVP_PKEY_asn1_set_get_priv_key := LoadFunction('EVP_PKEY_asn1_set_get_priv_key', AFailed); EVP_PKEY_asn1_set_get_pub_key := LoadFunction('EVP_PKEY_asn1_set_get_pub_key', AFailed); EVP_PKEY_asn1_set_security_bits := LoadFunction('EVP_PKEY_asn1_set_security_bits', AFailed); EVP_PKEY_meth_find := LoadFunction('EVP_PKEY_meth_find', AFailed); EVP_PKEY_meth_new := LoadFunction('EVP_PKEY_meth_new', AFailed); EVP_PKEY_meth_get0_info := LoadFunction('EVP_PKEY_meth_get0_info', AFailed); EVP_PKEY_meth_copy := LoadFunction('EVP_PKEY_meth_copy', AFailed); EVP_PKEY_meth_free := LoadFunction('EVP_PKEY_meth_free', AFailed); EVP_PKEY_meth_add0 := LoadFunction('EVP_PKEY_meth_add0', AFailed); EVP_PKEY_meth_remove := LoadFunction('EVP_PKEY_meth_remove', AFailed); EVP_PKEY_meth_get_count := LoadFunction('EVP_PKEY_meth_get_count', AFailed); EVP_PKEY_meth_get0 := LoadFunction('EVP_PKEY_meth_get0', AFailed); EVP_PKEY_CTX_new := LoadFunction('EVP_PKEY_CTX_new', AFailed); EVP_PKEY_CTX_new_id := LoadFunction('EVP_PKEY_CTX_new_id', AFailed); EVP_PKEY_CTX_dup := LoadFunction('EVP_PKEY_CTX_dup', AFailed); EVP_PKEY_CTX_free := LoadFunction('EVP_PKEY_CTX_free', AFailed); EVP_PKEY_CTX_ctrl := LoadFunction('EVP_PKEY_CTX_ctrl', AFailed); EVP_PKEY_CTX_ctrl_str := LoadFunction('EVP_PKEY_CTX_ctrl_str', AFailed); EVP_PKEY_CTX_ctrl_uint64 := LoadFunction('EVP_PKEY_CTX_ctrl_uint64', AFailed); EVP_PKEY_CTX_str2ctrl := LoadFunction('EVP_PKEY_CTX_str2ctrl', AFailed); EVP_PKEY_CTX_hex2ctrl := LoadFunction('EVP_PKEY_CTX_hex2ctrl', AFailed); EVP_PKEY_CTX_md := LoadFunction('EVP_PKEY_CTX_md', AFailed); EVP_PKEY_CTX_get_operation := LoadFunction('EVP_PKEY_CTX_get_operation', AFailed); EVP_PKEY_CTX_set0_keygen_info := LoadFunction('EVP_PKEY_CTX_set0_keygen_info', AFailed); EVP_PKEY_new_mac_key := LoadFunction('EVP_PKEY_new_mac_key', AFailed); EVP_PKEY_new_raw_private_key := LoadFunction('EVP_PKEY_new_raw_private_key', AFailed); EVP_PKEY_new_raw_public_key := LoadFunction('EVP_PKEY_new_raw_public_key', AFailed); EVP_PKEY_get_raw_private_key := LoadFunction('EVP_PKEY_get_raw_private_key', AFailed); EVP_PKEY_get_raw_public_key := LoadFunction('EVP_PKEY_get_raw_public_key', AFailed); EVP_PKEY_new_CMAC_key := LoadFunction('EVP_PKEY_new_CMAC_key', AFailed); EVP_PKEY_CTX_set_data := LoadFunction('EVP_PKEY_CTX_set_data', AFailed); EVP_PKEY_CTX_get_data := LoadFunction('EVP_PKEY_CTX_get_data', AFailed); EVP_PKEY_CTX_get0_pkey := LoadFunction('EVP_PKEY_CTX_get0_pkey', AFailed); EVP_PKEY_CTX_get0_peerkey := LoadFunction('EVP_PKEY_CTX_get0_peerkey', AFailed); EVP_PKEY_CTX_set_app_data := LoadFunction('EVP_PKEY_CTX_set_app_data', AFailed); EVP_PKEY_CTX_get_app_data := LoadFunction('EVP_PKEY_CTX_get_app_data', AFailed); EVP_PKEY_sign_init := LoadFunction('EVP_PKEY_sign_init', AFailed); EVP_PKEY_sign := LoadFunction('EVP_PKEY_sign', AFailed); EVP_PKEY_verify_init := LoadFunction('EVP_PKEY_verify_init', AFailed); EVP_PKEY_verify := LoadFunction('EVP_PKEY_verify', AFailed); EVP_PKEY_verify_recover_init := LoadFunction('EVP_PKEY_verify_recover_init', AFailed); EVP_PKEY_verify_recover := LoadFunction('EVP_PKEY_verify_recover', AFailed); EVP_PKEY_encrypt_init := LoadFunction('EVP_PKEY_encrypt_init', AFailed); EVP_PKEY_encrypt := LoadFunction('EVP_PKEY_encrypt', AFailed); EVP_PKEY_decrypt_init := LoadFunction('EVP_PKEY_decrypt_init', AFailed); EVP_PKEY_decrypt := LoadFunction('EVP_PKEY_decrypt', AFailed); EVP_PKEY_derive_init := LoadFunction('EVP_PKEY_derive_init', AFailed); EVP_PKEY_derive_set_peer := LoadFunction('EVP_PKEY_derive_set_peer', AFailed); EVP_PKEY_derive := LoadFunction('EVP_PKEY_derive', AFailed); EVP_PKEY_paramgen_init := LoadFunction('EVP_PKEY_paramgen_init', AFailed); EVP_PKEY_paramgen := LoadFunction('EVP_PKEY_paramgen', AFailed); EVP_PKEY_keygen_init := LoadFunction('EVP_PKEY_keygen_init', AFailed); EVP_PKEY_keygen := LoadFunction('EVP_PKEY_keygen', AFailed); EVP_PKEY_check := LoadFunction('EVP_PKEY_check', AFailed); EVP_PKEY_public_check := LoadFunction('EVP_PKEY_public_check', AFailed); EVP_PKEY_param_check := LoadFunction('EVP_PKEY_param_check', AFailed); EVP_PKEY_CTX_set_cb := LoadFunction('EVP_PKEY_CTX_set_cb', AFailed); EVP_PKEY_CTX_get_cb := LoadFunction('EVP_PKEY_CTX_get_cb', AFailed); EVP_PKEY_CTX_get_keygen_info := LoadFunction('EVP_PKEY_CTX_get_keygen_info', AFailed); EVP_PKEY_meth_set_init := LoadFunction('EVP_PKEY_meth_set_init', AFailed); EVP_PKEY_meth_set_copy := LoadFunction('EVP_PKEY_meth_set_copy', AFailed); EVP_PKEY_meth_set_cleanup := LoadFunction('EVP_PKEY_meth_set_cleanup', AFailed); EVP_PKEY_meth_set_paramgen := LoadFunction('EVP_PKEY_meth_set_paramgen', AFailed); EVP_PKEY_meth_set_keygen := LoadFunction('EVP_PKEY_meth_set_keygen', AFailed); EVP_PKEY_meth_set_sign := LoadFunction('EVP_PKEY_meth_set_sign', AFailed); EVP_PKEY_meth_set_verify := LoadFunction('EVP_PKEY_meth_set_verify', AFailed); EVP_PKEY_meth_set_verify_recover := LoadFunction('EVP_PKEY_meth_set_verify_recover', AFailed); EVP_PKEY_meth_set_signctx := LoadFunction('EVP_PKEY_meth_set_signctx', AFailed); EVP_PKEY_meth_set_verifyctx := LoadFunction('EVP_PKEY_meth_set_verifyctx', AFailed); EVP_PKEY_meth_set_encrypt := LoadFunction('EVP_PKEY_meth_set_encrypt', AFailed); EVP_PKEY_meth_set_decrypt := LoadFunction('EVP_PKEY_meth_set_decrypt', AFailed); EVP_PKEY_meth_set_derive := LoadFunction('EVP_PKEY_meth_set_derive', AFailed); EVP_PKEY_meth_set_ctrl := LoadFunction('EVP_PKEY_meth_set_ctrl', AFailed); EVP_PKEY_meth_set_digestsign := LoadFunction('EVP_PKEY_meth_set_digestsign', AFailed); EVP_PKEY_meth_set_digestverify := LoadFunction('EVP_PKEY_meth_set_digestverify', AFailed); EVP_PKEY_meth_set_check := LoadFunction('EVP_PKEY_meth_set_check', AFailed); EVP_PKEY_meth_set_public_check := LoadFunction('EVP_PKEY_meth_set_public_check', AFailed); EVP_PKEY_meth_set_param_check := LoadFunction('EVP_PKEY_meth_set_param_check', AFailed); EVP_PKEY_meth_set_digest_custom := LoadFunction('EVP_PKEY_meth_set_digest_custom', AFailed); EVP_PKEY_meth_get_init := LoadFunction('EVP_PKEY_meth_get_init', AFailed); EVP_PKEY_meth_get_copy := LoadFunction('EVP_PKEY_meth_get_copy', AFailed); EVP_PKEY_meth_get_cleanup := LoadFunction('EVP_PKEY_meth_get_cleanup', AFailed); EVP_PKEY_meth_get_paramgen := LoadFunction('EVP_PKEY_meth_get_paramgen', AFailed); EVP_PKEY_meth_get_keygen := LoadFunction('EVP_PKEY_meth_get_keygen', AFailed); EVP_PKEY_meth_get_sign := LoadFunction('EVP_PKEY_meth_get_sign', AFailed); EVP_PKEY_meth_get_verify := LoadFunction('EVP_PKEY_meth_get_verify', AFailed); EVP_PKEY_meth_get_verify_recover := LoadFunction('EVP_PKEY_meth_get_verify_recover', AFailed); EVP_PKEY_meth_get_signctx := LoadFunction('EVP_PKEY_meth_get_signctx', AFailed); EVP_PKEY_meth_get_verifyctx := LoadFunction('EVP_PKEY_meth_get_verifyctx', AFailed); EVP_PKEY_meth_get_encrypt := LoadFunction('EVP_PKEY_meth_get_encrypt', AFailed); EVP_PKEY_meth_get_decrypt := LoadFunction('EVP_PKEY_meth_get_decrypt', AFailed); EVP_PKEY_meth_get_derive := LoadFunction('EVP_PKEY_meth_get_derive', AFailed); EVP_PKEY_meth_get_ctrl := LoadFunction('EVP_PKEY_meth_get_ctrl', AFailed); EVP_PKEY_meth_get_digestsign := LoadFunction('EVP_PKEY_meth_get_digestsign', AFailed); EVP_PKEY_meth_get_digestverify := LoadFunction('EVP_PKEY_meth_get_digestverify', AFailed); EVP_PKEY_meth_get_check := LoadFunction('EVP_PKEY_meth_get_check', AFailed); EVP_PKEY_meth_get_public_check := LoadFunction('EVP_PKEY_meth_get_public_check', AFailed); EVP_PKEY_meth_get_param_check := LoadFunction('EVP_PKEY_meth_get_param_check', AFailed); EVP_PKEY_meth_get_digest_custom := LoadFunction('EVP_PKEY_meth_get_digest_custom', AFailed); EVP_add_alg_module := LoadFunction('EVP_add_alg_module', AFailed); end; procedure UnLoad; begin EVP_MD_meth_new := nil; EVP_MD_meth_dup := nil; EVP_MD_meth_free := nil; EVP_MD_meth_set_input_blocksize := nil; EVP_MD_meth_set_result_size := nil; EVP_MD_meth_set_app_datasize := nil; EVP_MD_meth_set_flags := nil; EVP_MD_meth_set_init := nil; EVP_MD_meth_set_update := nil; EVP_MD_meth_set_final := nil; EVP_MD_meth_set_copy := nil; EVP_MD_meth_set_cleanup := nil; EVP_MD_meth_set_ctrl := nil; EVP_MD_meth_get_input_blocksize := nil; EVP_MD_meth_get_result_size := nil; EVP_MD_meth_get_app_datasize := nil; EVP_MD_meth_get_flags := nil; EVP_MD_meth_get_init := nil; EVP_MD_meth_get_update := nil; EVP_MD_meth_get_final := nil; EVP_MD_meth_get_copy := nil; EVP_MD_meth_get_cleanup := nil; EVP_MD_meth_get_ctrl := nil; EVP_CIPHER_meth_new := nil; EVP_CIPHER_meth_dup := nil; EVP_CIPHER_meth_free := nil; EVP_CIPHER_meth_set_iv_length := nil; EVP_CIPHER_meth_set_flags := nil; EVP_CIPHER_meth_set_impl_ctx_size := nil; EVP_CIPHER_meth_set_init := nil; EVP_CIPHER_meth_set_do_cipher := nil; EVP_CIPHER_meth_set_cleanup := nil; EVP_CIPHER_meth_set_set_asn1_params := nil; EVP_CIPHER_meth_set_get_asn1_params := nil; EVP_CIPHER_meth_set_ctrl := nil; EVP_CIPHER_meth_get_init := nil; EVP_CIPHER_meth_get_do_cipher := nil; EVP_CIPHER_meth_get_cleanup := nil; EVP_CIPHER_meth_get_set_asn1_params := nil; EVP_CIPHER_meth_get_get_asn1_params := nil; EVP_CIPHER_meth_get_ctrl := nil; EVP_MD_type := nil; EVP_MD_pkey_type := nil; EVP_MD_size := nil; EVP_MD_block_size := nil; EVP_MD_flags := nil; EVP_MD_CTX_md := nil; EVP_MD_CTX_update_fn := nil; EVP_MD_CTX_set_update_fn := nil; EVP_MD_CTX_pkey_ctx := nil; EVP_MD_CTX_set_pkey_ctx := nil; EVP_MD_CTX_md_data := nil; EVP_CIPHER_nid := nil; EVP_CIPHER_block_size := nil; EVP_CIPHER_impl_ctx_size := nil; EVP_CIPHER_key_length := nil; EVP_CIPHER_iv_length := nil; EVP_CIPHER_flags := nil; EVP_CIPHER_CTX_cipher := nil; EVP_CIPHER_CTX_encrypting := nil; EVP_CIPHER_CTX_nid := nil; EVP_CIPHER_CTX_block_size := nil; EVP_CIPHER_CTX_key_length := nil; EVP_CIPHER_CTX_iv_length := nil; EVP_CIPHER_CTX_iv := nil; EVP_CIPHER_CTX_original_iv := nil; EVP_CIPHER_CTX_iv_noconst := nil; EVP_CIPHER_CTX_buf_noconst := nil; EVP_CIPHER_CTX_num := nil; EVP_CIPHER_CTX_set_num := nil; EVP_CIPHER_CTX_copy := nil; EVP_CIPHER_CTX_get_app_data := nil; EVP_CIPHER_CTX_set_app_data := nil; EVP_CIPHER_CTX_get_cipher_data := nil; EVP_CIPHER_CTX_set_cipher_data := nil; BIO_set_md := nil; EVP_MD_CTX_ctrl := nil; EVP_MD_CTX_new := nil; EVP_MD_CTX_reset := nil; EVP_MD_CTX_free := nil; EVP_MD_CTX_copy_ex := nil; EVP_MD_CTX_set_flags := nil; EVP_MD_CTX_clear_flags := nil; EVP_MD_CTX_test_flags := nil; EVP_DigestInit_ex := nil; EVP_DigestUpdate := nil; EVP_DigestFinal_ex := nil; EVP_Digest := nil; EVP_MD_CTX_copy := nil; EVP_DigestInit := nil; EVP_DigestFinal := nil; EVP_DigestFinalXOF := nil; EVP_read_pw_string := nil; EVP_read_pw_string_min := nil; EVP_set_pw_prompt := nil; EVP_get_pw_prompt := nil; EVP_BytesToKey := nil; EVP_CIPHER_CTX_set_flags := nil; EVP_CIPHER_CTX_clear_flags := nil; EVP_CIPHER_CTX_test_flags := nil; EVP_EncryptInit := nil; EVP_EncryptInit_ex := nil; EVP_EncryptUpdate := nil; EVP_EncryptFinal_ex := nil; EVP_EncryptFinal := nil; EVP_DecryptInit := nil; EVP_DecryptInit_ex := nil; EVP_DecryptUpdate := nil; EVP_DecryptFinal := nil; EVP_DecryptFinal_ex := nil; EVP_CipherInit := nil; EVP_CipherInit_ex := nil; EVP_CipherUpdate := nil; EVP_CipherFinal := nil; EVP_CipherFinal_ex := nil; EVP_SignFinal := nil; EVP_DigestSign := nil; EVP_VerifyFinal := nil; EVP_DigestVerify := nil; EVP_DigestSignInit := nil; EVP_DigestSignFinal := nil; EVP_DigestVerifyInit := nil; EVP_DigestVerifyFinal := nil; EVP_OpenInit := nil; EVP_OpenFinal := nil; EVP_SealInit := nil; EVP_SealFinal := nil; EVP_ENCODE_CTX_new := nil; EVP_ENCODE_CTX_free := nil; EVP_ENCODE_CTX_copy := nil; EVP_ENCODE_CTX_num := nil; EVP_EncodeInit := nil; EVP_EncodeUpdate := nil; EVP_EncodeFinal := nil; EVP_EncodeBlock := nil; EVP_DecodeInit := nil; EVP_DecodeUpdate := nil; EVP_DecodeFinal := nil; EVP_DecodeBlock := nil; EVP_CIPHER_CTX_new := nil; EVP_CIPHER_CTX_reset := nil; EVP_CIPHER_CTX_free := nil; EVP_CIPHER_CTX_set_key_length := nil; EVP_CIPHER_CTX_set_padding := nil; EVP_CIPHER_CTX_ctrl := nil; EVP_CIPHER_CTX_rand_key := nil; BIO_f_md := nil; BIO_f_base64 := nil; BIO_f_cipher := nil; BIO_f_reliable := nil; BIO_set_cipher := nil; EVP_md_null := nil; EVP_md5 := nil; EVP_md5_sha1 := nil; EVP_sha1 := nil; EVP_sha224 := nil; EVP_sha256 := nil; EVP_sha384 := nil; EVP_sha512 := nil; EVP_sha512_224 := nil; EVP_sha512_256 := nil; EVP_sha3_224 := nil; EVP_sha3_256 := nil; EVP_sha3_384 := nil; EVP_sha3_512 := nil; EVP_shake128 := nil; EVP_shake256 := nil; EVP_enc_null := nil; EVP_des_ecb := nil; EVP_des_ede := nil; EVP_des_ede3 := nil; EVP_des_ede_ecb := nil; EVP_des_ede3_ecb := nil; EVP_des_cfb64 := nil; EVP_des_cfb1 := nil; EVP_des_cfb8 := nil; EVP_des_ede_cfb64 := nil; EVP_des_ede3_cfb64 := nil; EVP_des_ede3_cfb1 := nil; EVP_des_ede3_cfb8 := nil; EVP_des_ofb := nil; EVP_des_ede_ofb := nil; EVP_des_ede3_ofb := nil; EVP_des_cbc := nil; EVP_des_ede_cbc := nil; EVP_des_ede3_cbc := nil; EVP_desx_cbc := nil; EVP_des_ede3_wrap := nil; EVP_rc4 := nil; EVP_rc4_40 := nil; EVP_idea_ecb := nil; EVP_idea_cfb64 := nil; EVP_idea_ofb := nil; EVP_idea_cbc := nil; EVP_rc2_ecb := nil; EVP_rc2_cbc := nil; EVP_rc2_40_cbc := nil; EVP_rc2_64_cbc := nil; EVP_rc2_cfb64 := nil; EVP_rc2_ofb := nil; EVP_bf_ecb := nil; EVP_bf_cbc := nil; EVP_bf_cfb64 := nil; EVP_bf_ofb := nil; EVP_cast5_ecb := nil; EVP_cast5_cbc := nil; EVP_cast5_cfb64 := nil; EVP_cast5_ofb := nil; EVP_rc5_32_12_16_cbc := nil; EVP_rc5_32_12_16_ecb := nil; EVP_rc5_32_12_16_cfb64 := nil; EVP_rc5_32_12_16_ofb := nil; EVP_aes_128_ecb := nil; EVP_aes_128_cbc := nil; EVP_aes_128_cfb1 := nil; EVP_aes_128_cfb8 := nil; EVP_aes_128_cfb128 := nil; EVP_aes_128_ofb := nil; EVP_aes_128_ctr := nil; EVP_aes_128_ccm := nil; EVP_aes_128_gcm := nil; EVP_aes_128_xts := nil; EVP_aes_128_wrap := nil; EVP_aes_128_wrap_pad := nil; EVP_aes_128_ocb := nil; EVP_aes_192_ecb := nil; EVP_aes_192_cbc := nil; EVP_aes_192_cfb1 := nil; EVP_aes_192_cfb8 := nil; EVP_aes_192_cfb128 := nil; EVP_aes_192_ofb := nil; EVP_aes_192_ctr := nil; EVP_aes_192_ccm := nil; EVP_aes_192_gcm := nil; EVP_aes_192_wrap := nil; EVP_aes_192_wrap_pad := nil; EVP_aes_192_ocb := nil; EVP_aes_256_ecb := nil; EVP_aes_256_cbc := nil; EVP_aes_256_cfb1 := nil; EVP_aes_256_cfb8 := nil; EVP_aes_256_cfb128 := nil; EVP_aes_256_ofb := nil; EVP_aes_256_ctr := nil; EVP_aes_256_ccm := nil; EVP_aes_256_gcm := nil; EVP_aes_256_xts := nil; EVP_aes_256_wrap := nil; EVP_aes_256_wrap_pad := nil; EVP_aes_256_ocb := nil; EVP_aes_128_cbc_hmac_sha1 := nil; EVP_aes_256_cbc_hmac_sha1 := nil; EVP_aes_128_cbc_hmac_sha256 := nil; EVP_aes_256_cbc_hmac_sha256 := nil; EVP_aria_128_ecb := nil; EVP_aria_128_cbc := nil; EVP_aria_128_cfb1 := nil; EVP_aria_128_cfb8 := nil; EVP_aria_128_cfb128 := nil; EVP_aria_128_ctr := nil; EVP_aria_128_ofb := nil; EVP_aria_128_gcm := nil; EVP_aria_128_ccm := nil; EVP_aria_192_ecb := nil; EVP_aria_192_cbc := nil; EVP_aria_192_cfb1 := nil; EVP_aria_192_cfb8 := nil; EVP_aria_192_cfb128 := nil; EVP_aria_192_ctr := nil; EVP_aria_192_ofb := nil; EVP_aria_192_gcm := nil; EVP_aria_192_ccm := nil; EVP_aria_256_ecb := nil; EVP_aria_256_cbc := nil; EVP_aria_256_cfb1 := nil; EVP_aria_256_cfb8 := nil; EVP_aria_256_cfb128 := nil; EVP_aria_256_ctr := nil; EVP_aria_256_ofb := nil; EVP_aria_256_gcm := nil; EVP_aria_256_ccm := nil; EVP_camellia_128_ecb := nil; EVP_camellia_128_cbc := nil; EVP_camellia_128_cfb1 := nil; EVP_camellia_128_cfb8 := nil; EVP_camellia_128_cfb128 := nil; EVP_camellia_128_ofb := nil; EVP_camellia_128_ctr := nil; EVP_camellia_192_ecb := nil; EVP_camellia_192_cbc := nil; EVP_camellia_192_cfb1 := nil; EVP_camellia_192_cfb8 := nil; EVP_camellia_192_cfb128 := nil; EVP_camellia_192_ofb := nil; EVP_camellia_192_ctr := nil; EVP_camellia_256_ecb := nil; EVP_camellia_256_cbc := nil; EVP_camellia_256_cfb1 := nil; EVP_camellia_256_cfb8 := nil; EVP_camellia_256_cfb128 := nil; EVP_camellia_256_ofb := nil; EVP_camellia_256_ctr := nil; EVP_chacha20 := nil; EVP_chacha20_poly1305 := nil; EVP_seed_ecb := nil; EVP_seed_cbc := nil; EVP_seed_cfb128 := nil; EVP_seed_ofb := nil; EVP_sm4_ecb := nil; EVP_sm4_cbc := nil; EVP_sm4_cfb128 := nil; EVP_sm4_ofb := nil; EVP_sm4_ctr := nil; EVP_add_cipher := nil; EVP_add_digest := nil; EVP_get_cipherbyname := nil; EVP_get_digestbyname := nil; EVP_CIPHER_do_all := nil; EVP_CIPHER_do_all_sorted := nil; EVP_MD_do_all := nil; EVP_MD_do_all_sorted := nil; EVP_PKEY_decrypt_old := nil; EVP_PKEY_encrypt_old := nil; EVP_PKEY_type := nil; EVP_PKEY_id := nil; EVP_PKEY_base_id := nil; EVP_PKEY_bits := nil; EVP_PKEY_security_bits := nil; EVP_PKEY_size := nil; EVP_PKEY_set_type := nil; EVP_PKEY_set_type_str := nil; EVP_PKEY_set_alias_type := nil; EVP_PKEY_set1_engine := nil; EVP_PKEY_get0_engine := nil; EVP_PKEY_assign := nil; EVP_PKEY_get0 := nil; EVP_PKEY_get0_hmac := nil; EVP_PKEY_get0_poly1305 := nil; EVP_PKEY_get0_siphash := nil; EVP_PKEY_set1_RSA := nil; EVP_PKEY_get0_RSA := nil; EVP_PKEY_get1_RSA := nil; EVP_PKEY_set1_DSA := nil; EVP_PKEY_get0_DSA := nil; EVP_PKEY_get1_DSA := nil; EVP_PKEY_set1_DH := nil; EVP_PKEY_get0_DH := nil; EVP_PKEY_get1_DH := nil; EVP_PKEY_set1_EC_KEY := nil; EVP_PKEY_get0_EC_KEY := nil; EVP_PKEY_get1_EC_KEY := nil; EVP_PKEY_new := nil; EVP_PKEY_up_ref := nil; EVP_PKEY_free := nil; d2i_PublicKey := nil; i2d_PublicKey := nil; d2i_PrivateKey := nil; d2i_AutoPrivateKey := nil; i2d_PrivateKey := nil; EVP_PKEY_copy_parameters := nil; EVP_PKEY_missing_parameters := nil; EVP_PKEY_save_parameters := nil; EVP_PKEY_cmp_parameters := nil; EVP_PKEY_cmp := nil; EVP_PKEY_print_public := nil; EVP_PKEY_print_private := nil; EVP_PKEY_print_params := nil; EVP_PKEY_get_default_digest_nid := nil; EVP_PKEY_set1_tls_encodedpoint := nil; EVP_PKEY_get1_tls_encodedpoint := nil; EVP_CIPHER_type := nil; EVP_CIPHER_param_to_asn1 := nil; EVP_CIPHER_asn1_to_param := nil; EVP_CIPHER_set_asn1_iv := nil; EVP_CIPHER_get_asn1_iv := nil; PKCS5_PBE_keyivgen := nil; PKCS5_PBKDF2_HMAC_SHA1 := nil; PKCS5_PBKDF2_HMAC := nil; PKCS5_v2_PBE_keyivgen := nil; EVP_PBE_scrypt := nil; PKCS5_v2_scrypt_keyivgen := nil; PKCS5_PBE_add := nil; EVP_PBE_CipherInit := nil; EVP_PBE_alg_add_type := nil; EVP_PBE_alg_add := nil; EVP_PBE_find := nil; EVP_PBE_cleanup := nil; EVP_PBE_get := nil; EVP_PKEY_asn1_get_count := nil; EVP_PKEY_asn1_get0 := nil; EVP_PKEY_asn1_find := nil; EVP_PKEY_asn1_find_str := nil; EVP_PKEY_asn1_add0 := nil; EVP_PKEY_asn1_add_alias := nil; EVP_PKEY_asn1_get0_info := nil; EVP_PKEY_get0_asn1 := nil; EVP_PKEY_asn1_new := nil; EVP_PKEY_asn1_copy := nil; EVP_PKEY_asn1_free := nil; EVP_PKEY_asn1_set_public := nil; EVP_PKEY_asn1_set_private := nil; EVP_PKEY_asn1_set_param := nil; EVP_PKEY_asn1_set_free := nil; EVP_PKEY_asn1_set_ctrl := nil; EVP_PKEY_asn1_set_item := nil; EVP_PKEY_asn1_set_siginf := nil; EVP_PKEY_asn1_set_check := nil; EVP_PKEY_asn1_set_public_check := nil; EVP_PKEY_asn1_set_param_check := nil; EVP_PKEY_asn1_set_set_priv_key := nil; EVP_PKEY_asn1_set_set_pub_key := nil; EVP_PKEY_asn1_set_get_priv_key := nil; EVP_PKEY_asn1_set_get_pub_key := nil; EVP_PKEY_asn1_set_security_bits := nil; EVP_PKEY_meth_find := nil; EVP_PKEY_meth_new := nil; EVP_PKEY_meth_get0_info := nil; EVP_PKEY_meth_copy := nil; EVP_PKEY_meth_free := nil; EVP_PKEY_meth_add0 := nil; EVP_PKEY_meth_remove := nil; EVP_PKEY_meth_get_count := nil; EVP_PKEY_meth_get0 := nil; EVP_PKEY_CTX_new := nil; EVP_PKEY_CTX_new_id := nil; EVP_PKEY_CTX_dup := nil; EVP_PKEY_CTX_free := nil; EVP_PKEY_CTX_ctrl := nil; EVP_PKEY_CTX_ctrl_str := nil; EVP_PKEY_CTX_ctrl_uint64 := nil; EVP_PKEY_CTX_str2ctrl := nil; EVP_PKEY_CTX_hex2ctrl := nil; EVP_PKEY_CTX_md := nil; EVP_PKEY_CTX_get_operation := nil; EVP_PKEY_CTX_set0_keygen_info := nil; EVP_PKEY_new_mac_key := nil; EVP_PKEY_new_raw_private_key := nil; EVP_PKEY_new_raw_public_key := nil; EVP_PKEY_get_raw_private_key := nil; EVP_PKEY_get_raw_public_key := nil; EVP_PKEY_new_CMAC_key := nil; EVP_PKEY_CTX_set_data := nil; EVP_PKEY_CTX_get_data := nil; EVP_PKEY_CTX_get0_pkey := nil; EVP_PKEY_CTX_get0_peerkey := nil; EVP_PKEY_CTX_set_app_data := nil; EVP_PKEY_CTX_get_app_data := nil; EVP_PKEY_sign_init := nil; EVP_PKEY_sign := nil; EVP_PKEY_verify_init := nil; EVP_PKEY_verify := nil; EVP_PKEY_verify_recover_init := nil; EVP_PKEY_verify_recover := nil; EVP_PKEY_encrypt_init := nil; EVP_PKEY_encrypt := nil; EVP_PKEY_decrypt_init := nil; EVP_PKEY_decrypt := nil; EVP_PKEY_derive_init := nil; EVP_PKEY_derive_set_peer := nil; EVP_PKEY_derive := nil; EVP_PKEY_paramgen_init := nil; EVP_PKEY_paramgen := nil; EVP_PKEY_keygen_init := nil; EVP_PKEY_keygen := nil; EVP_PKEY_check := nil; EVP_PKEY_public_check := nil; EVP_PKEY_param_check := nil; EVP_PKEY_CTX_set_cb := nil; EVP_PKEY_CTX_get_cb := nil; EVP_PKEY_CTX_get_keygen_info := nil; EVP_PKEY_meth_set_init := nil; EVP_PKEY_meth_set_copy := nil; EVP_PKEY_meth_set_cleanup := nil; EVP_PKEY_meth_set_paramgen := nil; EVP_PKEY_meth_set_keygen := nil; EVP_PKEY_meth_set_sign := nil; EVP_PKEY_meth_set_verify := nil; EVP_PKEY_meth_set_verify_recover := nil; EVP_PKEY_meth_set_signctx := nil; EVP_PKEY_meth_set_verifyctx := nil; EVP_PKEY_meth_set_encrypt := nil; EVP_PKEY_meth_set_decrypt := nil; EVP_PKEY_meth_set_derive := nil; EVP_PKEY_meth_set_ctrl := nil; EVP_PKEY_meth_set_digestsign := nil; EVP_PKEY_meth_set_digestverify := nil; EVP_PKEY_meth_set_check := nil; EVP_PKEY_meth_set_public_check := nil; EVP_PKEY_meth_set_param_check := nil; EVP_PKEY_meth_set_digest_custom := nil; EVP_PKEY_meth_get_init := nil; EVP_PKEY_meth_get_copy := nil; EVP_PKEY_meth_get_cleanup := nil; EVP_PKEY_meth_get_paramgen := nil; EVP_PKEY_meth_get_keygen := nil; EVP_PKEY_meth_get_sign := nil; EVP_PKEY_meth_get_verify := nil; EVP_PKEY_meth_get_verify_recover := nil; EVP_PKEY_meth_get_signctx := nil; EVP_PKEY_meth_get_verifyctx := nil; EVP_PKEY_meth_get_encrypt := nil; EVP_PKEY_meth_get_decrypt := nil; EVP_PKEY_meth_get_derive := nil; EVP_PKEY_meth_get_ctrl := nil; EVP_PKEY_meth_get_digestsign := nil; EVP_PKEY_meth_get_digestverify := nil; EVP_PKEY_meth_get_check := nil; EVP_PKEY_meth_get_public_check := nil; EVP_PKEY_meth_get_param_check := nil; EVP_PKEY_meth_get_digest_custom := nil; EVP_add_alg_module := nil; end; //# define EVP_PKEY_assign_RSA(pkey,rsa) EVP_PKEY_assign((pkey),EVP_PKEY_RSA, (char *)(rsa)) function EVP_PKEY_assign_RSA(pkey: PEVP_PKEY; rsa: Pointer): TIdC_INT; begin Result := EVP_PKEY_assign(pkey, EVP_PKEY_RSA, rsa); end; //# define EVP_PKEY_assign_DSA(pkey,dsa) EVP_PKEY_assign((pkey),EVP_PKEY_DSA, (char *)(dsa)) function EVP_PKEY_assign_DSA(pkey: PEVP_PKEY; dsa: Pointer): TIdC_INT; begin Result := EVP_PKEY_assign(pkey, EVP_PKEY_DSA, dsa); end; //# define EVP_PKEY_assign_DH(pkey,dh) EVP_PKEY_assign((pkey),EVP_PKEY_DH, (char *)(dh)) function EVP_PKEY_assign_DH(pkey: PEVP_PKEY; dh: Pointer): TIdC_INT; begin Result := EVP_PKEY_assign(pkey, EVP_PKEY_DH, dh); end; //# define EVP_PKEY_assign_EC_KEY(pkey,eckey) EVP_PKEY_assign((pkey),EVP_PKEY_EC, (char *)(eckey)) function EVP_PKEY_assign_EC_KEY(pkey: PEVP_PKEY; eckey: Pointer): TIdC_INT; begin Result := EVP_PKEY_assign(pkey, EVP_PKEY_EC, eckey); end; //# define EVP_PKEY_assign_SIPHASH(pkey,shkey) EVP_PKEY_assign((pkey),EVP_PKEY_SIPHASH, (char *)(shkey)) function EVP_PKEY_assign_SIPHASH(pkey: PEVP_PKEY; shkey: Pointer): TIdC_INT; begin Result := EVP_PKEY_assign(pkey, EVP_PKEY_SIPHASH, shkey); end; //# define EVP_PKEY_assign_POLY1305(pkey,polykey) EVP_PKEY_assign((pkey),EVP_PKEY_POLY1305, (char *)(polykey)) function EVP_PKEY_assign_POLY1305(pkey: PEVP_PKEY; polykey: Pointer): TIdC_INT; begin Result := EVP_PKEY_assign(pkey, EVP_PKEY_POLY1305, polykey); end; end.
unit NtUiLib.Reflection.AccessMasks; { The module provides logic for representing access masks as strings via Runtime Type Information. } interface uses Ntapi.WinNt; // Prepare a textual representation of an access mask function FormatAccess( const Access: TAccessMask; MaskType: Pointer = nil; // Use TypeInfo(T) IncludePrefix: Boolean = False ): String; type TAccessMaskHelper = record helper for TAccessMask function Format<T>(IncludePrefix: Boolean = False): String; end; implementation uses DelphiApi.Reflection, DelphiUiLib.Strings, DelphiUiLib.Reflection.Numeric, System.Rtti, NtUtils; {$BOOLEVAL OFF} {$IFOPT R+}{$DEFINE R+}{$ENDIF} {$IFOPT Q+}{$DEFINE Q+}{$ENDIF} procedure ConcatFlags(var Result: String; NewFlags: String); begin if (Result <> '') and (NewFlags <> '') then Result := Result + ', ' + NewFlags else if NewFlags <> '' then Result := NewFlags; end; function FormatAccess; var UnmappedBits: TAccessMask; RttiContext: TRttiContext; RttiType: TRttiType; a: TCustomAttribute; FullAccess: TAccessMask; Reflection: TNumericReflection; begin if Access = 0 then Result := 'No access' else begin UnmappedBits := Access; Result := ''; if not Assigned(MaskType) then MaskType := TypeInfo(TAccessMask); RttiContext := TRttiContext.Create; RttiType := RttiContext.GetType(MaskType); // Determine which bits are necessary for having full access for a in RttiType.GetAttributes do if a is ValidMaskAttribute then begin FullAccess := ValidMaskAttribute(a).ValidMask; // Map and exclude if Access and FullAccess = FullAccess then begin Result := 'Full access'; UnmappedBits := UnmappedBits and not FullAccess; end; Break; end; // Custom access mask if HasAny(UnmappedBits) and (MaskType <> TypeInfo(TAccessMask)) then begin // Represent type-specific access, if any Reflection := GetNumericReflection(MaskType, UnmappedBits); if Reflection.UnknownBits <> UnmappedBits then begin // Some bits were mapped ConcatFlags(Result, Reflection.Text); UnmappedBits := Reflection.UnknownBits; end; end; // Map standard, generic, and other access rights, including unknown bits if HasAny(UnmappedBits) then ConcatFlags(Result, GetNumericReflection(TypeInfo(TAccessMask), UnmappedBits).Text); end; if IncludePrefix then Result := IntToHexEx(Access, 6) + ' (' + Result + ')'; end; { TAccessMaskHelper } function TAccessMaskHelper.Format<T>; begin Result := FormatAccess(Self, TypeInfo(T), IncludePrefix); end; end.
unit OAuth2.Grant.ClientCredentials; interface uses Web.HTTPApp, OAuth2.Contract.ResponseType, OAuth2.Contract.Grant.GrantType, OAuth2.Grant.AbstractAuthorize; type TOAuth2ClientCredentialsGrant = class(TAbstractAuthorizeGrant) private { private declarations } protected { protected declarations } public { public declarations } function GetIdentifier: string; override; function RespondToAccessTokenRequest(ARequest: TWebRequest; AResponseType: IOAuth2ResponseType; AAccessTokenTTL: Int64): IOAuth2ResponseType; override; class function New: IOAuth2GrantTypeGrant; end; implementation uses System.SysUtils, OAuth2.Contract.Entity.Client, OAuth2.Contract.Entity.Scope, OAuth2.Contract.Entity.AccessToken, OAuth2.Exception.ServerException; { TOAuth2ClientCredentialsGrant } function TOAuth2ClientCredentialsGrant.GetIdentifier: string; begin Result := 'client_credentials'; end; class function TOAuth2ClientCredentialsGrant.New: IOAuth2GrantTypeGrant; begin Result := TOAuth2ClientCredentialsGrant.Create; end; function TOAuth2ClientCredentialsGrant.RespondToAccessTokenRequest(ARequest: TWebRequest; AResponseType: IOAuth2ResponseType; AAccessTokenTTL: Int64): IOAuth2ResponseType; var LClientId: string; LClient: IOAuth2ClientEntity; LScopes: TArray<IOAuth2ScopeEntity>; LFinalizedScopes: TArray<IOAuth2ScopeEntity>; LAccessToken: IOAuth2AccessTokenEntity; begin Result := AResponseType; LClientId := GetClientCredentials(ARequest).GetClientId; LClient := GetClientEntityOrFail(LClientId, ARequest); if (not LClient.IsConfidential) then raise EOAuth2ServerException.InvalidClient(ARequest); ValidateClient(ARequest); LScopes := ValidateScopes(GetRequestParameter('scopes', ARequest, EmptyStr)); LFinalizedScopes := GetScopeRepository.FinalizeScopes( LScopes, GetIdentifier, LClient ); LAccessToken := IssueAccessToken(AAccessTokenTTL, LClient, EmptyStr, LFinalizedScopes); AResponseType.SetAccessToken(LAccessToken); end; end.
unit uWindows; interface uses Registry, Windows, SysUtils, Classes; function GetProgramFilesDir: string; function DeleteFolder(sDir: string): Boolean; function GetWidowScreenPosition: TPoint; function GetChildWidowScreenPosition: TPoint; implementation uses uConst; function GetProgramFilesDir: string; var r: TRegistry; begin r := TRegistry.Create; r.RootKey := HKEY_LOCAL_MACHINE; if r.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion', False) then result := r.ReadString('ProgramFilesDir') else result := NULL; r.CloseKey; r.Free; end; function DeleteFolder(sDir: string): Boolean; var oList: TStringList; iFindResult: integer; srSchRec : TSearchRec; cnt: integer; begin cnt := 0; oList := TStringList.Create; try iFindResult := FindFirst(sDir + '\*.*', faAnyFile - faDirectory, srSchRec); while iFindResult = 0 do begin oList.Add(sDir + '\' + srSchRec.Name); iFindResult := FindNext(srSchRec); end; while oList.Count > 0 do begin if not DeleteFile(oList.Strings[0]) then inc(cnt); oList.Delete(0); end; result := cnt = 0; except result := false; end; end; function GetWidowScreenPosition: TPoint; var X, Y: integer; begin X := GetSystemMetrics(SM_CYBORDER); Y := GetSystemMetrics(SM_CXBORDER); Y := Y + GetSystemMetrics(SM_CYCAPTION); Y := Y + GetSystemMetrics(SM_CYMENU); result := Point(X, Y); end; function GetChildWidowScreenPosition: TPoint; var X, Y: integer; begin X := GetSystemMetrics(SM_CYBORDER); Y := GetSystemMetrics(SM_CXBORDER); Y := Y + GetSystemMetrics(SM_CYCAPTION) * 2; Y := Y + GetSystemMetrics(SM_CYMENU); result := Point(X, Y); end; end.
unit Tasker.Plugin.Setting; interface type TDummy = class end; //// ----------------------------- SETTING PLUGIN ONLY --------------------------------- // // // public static class Setting { // // /** // * Variable name into which a description of any error that occurred can be placed // * for the user to process. // * // * Should *only* be set when the BroadcastReceiver result code indicates a failure. // * // * Note that the user needs to have configured the task to continue after failure of the plugin // * action otherwise they will not be able to make use of the error message. // * // * For use with #addRelevantVariableList(Intent, String[]) and #addVariableBundle(Bundle, Bundle) // * // */ // public final static String VARNAME_ERROR_MESSAGE = VARIABLE_PREFIX + "errmsg"; // // /** // * @see #setVariableReplaceKeys(Bundle, String[]) // */ // private final static String BUNDLE_KEY_VARIABLE_REPLACE_STRINGS = EXTRAS_PREFIX + "VARIABLE_REPLACE_KEYS"; // // /** // * @see #requestTimeoutMS(android.content.Intent, int) // */ // private final static String EXTRA_REQUESTED_TIMEOUT = EXTRAS_PREFIX + "REQUESTED_TIMEOUT"; // // /** // * @see #requestTimeoutMS(android.content.Intent, int) // */ // // public final static int REQUESTED_TIMEOUT_MS_NONE = 0; // // /** // * @see #requestTimeoutMS(android.content.Intent, int) // */ // // public final static int REQUESTED_TIMEOUT_MS_MAX = 3599000; // // /** // * @see #requestTimeoutMS(android.content.Intent, int) // */ // // public final static int REQUESTED_TIMEOUT_MS_NEVER = REQUESTED_TIMEOUT_MS_MAX + 1000; // // /** // * @see #signalFinish(Context, Intent, int, Bundle) // * @see Host#addCompletionIntent(Intent, Intent) // */ // private final static String EXTRA_PLUGIN_COMPLETION_INTENT = EXTRAS_PREFIX + "COMPLETION_INTENT"; // // /** // * @see #signalFinish(Context, Intent, int, Bundle) // * @see Host#getSettingResultCode(Intent) // */ // public final static String EXTRA_RESULT_CODE = EXTRAS_PREFIX + "RESULT_CODE"; // // /** // * @see #signalFinish(Context, Intent, int, Bundle) // * @see Host#getSettingResultCode(Intent) // */ // // public final static int RESULT_CODE_OK = Activity.RESULT_OK; // public final static int RESULT_CODE_OK_MINOR_FAILURES = Activity.RESULT_FIRST_USER; // public final static int RESULT_CODE_FAILED = Activity.RESULT_FIRST_USER + 1; // public final static int RESULT_CODE_PENDING = Activity.RESULT_FIRST_USER + 2; // public final static int RESULT_CODE_UNKNOWN = Activity.RESULT_FIRST_USER + 3; // // /** // * If a plugin wants to define it's own error codes, start numbering them here. // * The code will be placed in an error variable (%err in the case of Tasker) for // * the user to process after the plugin action. // */ // // public final static int RESULT_CODE_FAILED_PLUGIN_FIRST = Activity.RESULT_FIRST_USER + 9; // // /** // * Used by: plugin EditActivity. // * // * Indicates to plugin that host will replace variables in specified bundle keys. // * // * Replacement takes place every time the setting is fired, before the bundle is // * passed to the plugin FireReceiver. // * // * @param extrasFromHost intent extras from the intent received by the edit activity // * @see #setVariableReplaceKeys(Bundle, String[]) // */ // public static boolean hostSupportsOnFireVariableReplacement( Bundle extrasFromHost ) { // return hostSupports( extrasFromHost, EXTRA_HOST_CAPABILITY_SETTING_FIRE_VARIABLE_REPLACEMENT ); // } // // /** // * Used by: plugin EditActivity. // * // * Description as above. // * // * This version also includes backwards compatibility with pre 4.2 Tasker versions. // * At some point this function will be deprecated. // * // * @param editActivity the plugin edit activity, needed to test calling Tasker version // * @see #setVariableReplaceKeys(Bundle, String[]) // */ // // public static boolean hostSupportsOnFireVariableReplacement( Activity editActivity ) { // // boolean supportedFlag = hostSupportsOnFireVariableReplacement( editActivity.getIntent().getExtras() ); // // if ( ! supportedFlag ) { // // ComponentName callingActivity = editActivity.getCallingActivity(); // // if ( callingActivity == null ) // Log.w( TAG, "hostSupportsOnFireVariableReplacement: null callingActivity, defaulting to false" ); // else { // String callerPackage = callingActivity.getPackageName(); // // // Tasker only supporteed this from 1.0.10 // supportedFlag = // ( callerPackage.startsWith( BASE_KEY ) ) && // ( getPackageVersionCode( editActivity.getPackageManager(), callerPackage ) > FIRST_ON_FIRE_VARIABLES_TASKER_VERSION ) // ; // } // } // // return supportedFlag; // } // // public static boolean hostSupportsSynchronousExecution( Bundle extrasFromHost ) { // return hostSupports( extrasFromHost, EXTRA_HOST_CAPABILITY_SETTING_SYNCHRONOUS_EXECUTION ); // } // // /** // * Request the host to wait the specified number of milliseconds before continuing. // * Note that the host may choose to ignore the request. // * // * Maximum value is REQUESTED_TIMEOUT_MS_MAX. // * Also available are REQUESTED_TIMEOUT_MS_NONE (continue immediately without waiting // * for the plugin to finish) and REQUESTED_TIMEOUT_MS_NEVER (wait forever for // * a result). // * // * Used in EditActivity, before setResult(). // * // * @param intentToHost the intent being returned to the host // * @param timeoutMS // */ // public static void requestTimeoutMS( Intent intentToHost, int timeoutMS ) { // if ( timeoutMS < 0 ) // Log.w( TAG, "requestTimeoutMS: ignoring negative timeout (" + timeoutMS + ")" ); // else { // if ( // ( timeoutMS > REQUESTED_TIMEOUT_MS_MAX ) && // ( timeoutMS != REQUESTED_TIMEOUT_MS_NEVER ) // ) { // Log.w( TAG, "requestTimeoutMS: requested timeout " + timeoutMS + " exceeds maximum, setting to max (" + REQUESTED_TIMEOUT_MS_MAX + ")" ); // timeoutMS = REQUESTED_TIMEOUT_MS_MAX; // } // intentToHost.putExtra( EXTRA_REQUESTED_TIMEOUT, timeoutMS ); // } // } // // /** // * Used by: plugin EditActivity // * // * Indicates to host which bundle keys should be replaced. // * // * @param resultBundleToHost the bundle being returned to the host // * @param listOfKeyNames which bundle keys to replace variables in when setting fires // * @see #hostSupportsOnFireVariableReplacement(Bundle) // * @see #setKeyEncoding(Bundle,String[],Encoding) // */ // public static void setVariableReplaceKeys( Bundle resultBundleToHost, String [] listOfKeyNames ) { // addStringArrayToBundleAsString( // listOfKeyNames, resultBundleToHost, BUNDLE_KEY_VARIABLE_REPLACE_STRINGS, // "setVariableReplaceKeys" // ); // } // // /** // * Used by: plugin FireReceiver // * // * Indicates to plugin whether the host will process variables which it passes back // * // * @param extrasFromHost intent extras from the intent received by the FireReceiver // * @see #signalFinish(Context, Intent, int, Bundle) // */ // public static boolean hostSupportsVariableReturn( Bundle extrasFromHost ) { // return hostSupports( extrasFromHost, EXTRA_HOST_CAPABILITY_SETTING_RETURN_VARIABLES ); // } // // /** // * Used by: plugin FireReceiver // * // * Tell the host that the plugin has finished execution. // * // * This should only be used if RESULT_CODE_PENDING was returned by FireReceiver.onReceive(). // * // * @param originalFireIntent the intent received from the host (via onReceive()) // * @param resultCode level of success in performing the settings // * @param vars any variables that the plugin wants to set in the host // * @see #hostSupportsSynchronousExecution(Bundle) // */ // public static boolean signalFinish( Context context, Intent originalFireIntent, int resultCode, Bundle vars ) { // // String errorPrefix = "signalFinish: "; // // boolean okFlag = false; // // String completionIntentString = (String) getExtraValueSafe( originalFireIntent, Setting.EXTRA_PLUGIN_COMPLETION_INTENT, String.class, "signalFinish" ); // // if ( completionIntentString != null ) { // // Uri completionIntentUri = null; // try { // completionIntentUri = Uri.parse( completionIntentString ); // } // // should only throw NullPointer but don't particularly trust it // catch ( Exception e ) { // Log.w( TAG, errorPrefix + "couldn't parse " + completionIntentString ); // } // // if ( completionIntentUri != null ) { // try { // Intent completionIntent = Intent.parseUri( completionIntentString, Intent.URI_INTENT_SCHEME ); // // completionIntent.putExtra( EXTRA_RESULT_CODE, resultCode ); // // if ( vars != null ) // completionIntent.putExtra( EXTRA_VARIABLES_BUNDLE, vars ); // // context.sendBroadcast( completionIntent ); // // okFlag = true; // } // catch ( URISyntaxException e ) { // Log.w( TAG, errorPrefix + "bad URI: " + completionIntentUri ); // } // } // } // // return okFlag; // } // // /** // * Check for a hint on the timeout value the host is using. // * Used by: plugin FireReceiver. // * Requires Tasker 4.7+ // * // * @param extrasFromHost intent extras from the intent received by the FireReceiver // * @return timeoutMS the hosts timeout setting for the action or -1 if no hint is available. // * // * @see #REQUESTED_TIMEOUT_MS_NONE, REQUESTED_TIMEOUT_MS_MAX, REQUESTED_TIMEOUT_MS_NEVER // */ // public static int getHintTimeoutMS( Bundle extrasFromHost ) { // // int timeoutMS = -1; // // Bundle hintsBundle = (Bundle) TaskerPlugin.getBundleValueSafe( extrasFromHost, EXTRA_HINTS_BUNDLE, Bundle.class, "getHintTimeoutMS" ); // // if ( hintsBundle != null ) { // // Integer val = (Integer) getBundleValueSafe( hintsBundle, BUNDLE_KEY_HINT_TIMEOUT_MS, Integer.class, "getHintTimeoutMS" ); // // if ( val != null ) // timeoutMS = val; // } // // return timeoutMS; // } // } implementation end.
unit BDEInfoUnit; interface uses DBTables,Classes, SysUtils; type TBDEInfo=class private FDataBases:TStringList; function GetFDataBases:TStrings; protected public constructor Create; destructor Destroy; override; // function IBGetPathOfAlias(_alias:string):string; function IBAddAlias(_alias,_path:string):boolean; procedure IBDeleteAlias(_alias:string); function IsAlias(value:string):boolean; // property DataBases:TStrings read GetFDataBases; end; implementation function TBDEInfo.IsAlias(value:string):boolean; var _list:TStringList; begin _list:=TStringList.Create; try Session.GetAliasNames(_list); result:=_list.IndexOf(value)>-1; //result:=Session.GetFindDatabase(value)<>nil; finally _list.Free; end; end; procedure TBDEInfo.IBDeleteAlias(_alias:string); begin if Session.IsAlias(_alias) then begin Session.DeleteAlias(_alias); Session.SaveConfigFile; end; end; function TBDEInfo.IBAddAlias(_alias,_path:string):boolean; var MyList: TStringList; begin result:=true; IBDeleteAlias(_alias); MyList:=TStringList.Create; try with MyList do begin Add('ENABLE SCHEMA CACHE=FALSE'); //MyList.Add('LANGDRIVER=Pdox ANSI Cyrillic'); Add('SERVER NAME='+_path); Add('USER NAME=MYNAME'); end; try Session.AddAlias(_alias, 'INTRBASE', MyList); // {MyList.Clear; MyList.Add('LANGDRIVER=Pdox ANSI Cyrillic'); Session.ModifyDriver('INTRBASE', MyList);} // Session.SaveConfigFile; except result:=FALSE; end; finally MyList.Free; end; end; function TBDEInfo.GetFDataBases:TStrings; begin Result:=FDataBases; end; function TBDEInfo.IBGetPathOfAlias(_alias:string):string; var theStrList:TStringList; //GPath:String; begin theStrList:=TStringList.Create; try try Session.GetAliasParams(_alias,theStrList); result:=copy(theStrList[0],13,length(theStrList[0])); except on E:Exception do raise Exception.Create('Алиас ' + _alias + ' не зарегистрирован на копмьютере:'#13+ E.Message); end; finally theStrList.Free; end; end; constructor TBDEInfo.Create; begin FDataBases:=TStringList.Create; Session.ConfigMode:=cmAll; Session.GetDatabaseNames(FDataBases); end; destructor TBDEInfo.Destroy; begin FDataBases.Free; inherited Destroy; end; end.
unit TNsRemotePublish.Application.PublishController; interface uses {$IFNDEF FPC} System.Classes, System.SysUtils, System.JSON, System.Generics.Collections, System.NetEncoding, System.IOUtils, {$ELSE} Classes, sysutils, jsonparser, fpjson, fgl, base64, {$ENDIF} TNsRemotePublish.Infrastructure.CompressionFactory, TNSRemotePublish.Infrastructure.Interfaces.Compression, TNsRestFramework.Infrastructure.Services.Logger, TNsRestFramework.Infrastructure.HTTPControllerFactory, TNsRestFramework.Infrastructure.HTTPRestRequest, TNsRestFramework.Infrastructure.HTTPRouting, TNsRestFramework.Infrastructure.HTTPController; type TPublishJSON = class private FPublishFile: string; FDestination: string; FAction: string; FCleanup: Boolean; FBackup: Boolean; FFileType : string; procedure SetPublishFile(const Value: string); procedure SetAction(const Value: string); procedure SetDestination(const Value: string); procedure SetBackup(const Value: Boolean); procedure SetCleanup(const Value: Boolean); public property FileType : string read FFileType write FFileType; property PublishFile : string read FPublishFile write SetPublishFile; property Destination : string read FDestination write SetDestination; property Action : string read FAction write SetAction; property Cleanup : Boolean read FCleanup write SetCleanup; property Backup : Boolean read FBackup write SetBackup; end; { THTTPPublishController } THTTPPublishController = class(THTTPController) private procedure OnExtractFile(Sender : TObject; const Filename : string; Position: Int64); procedure PublishJob(Job : TPublishJSON); function GetJobFromJson(jsonObject : TJSONObject) : TPublishJSON; {$IFNDEF FPC} function GetJobsFromJSON(const Body : string) : TObjectList<TPublishJSON>; {$ELSE} function GetJobsFromJSON(const Body : string) : TFPGObjectList<TPublishJSON>; {$ENDIF} public constructor Create; function ProcessRequest(Request : THTTPRestRequest) : Cardinal; override; end; var PublishController : IController; implementation { TMVCDefaultController } constructor THTTPPublishController.Create; begin inherited; fisdefault := False; froute.Name := 'default'; froute.IsDefault := True; froute.RelativePath := 'publish'; froute.AddMethod('POST'); froute.needStaticController := False; end; function THTTPPublishController.GetJobFromJson(jsonObject: TJSONObject): TPublishJSON; begin try Result := TPublishJSON.Create; {$IFNDEF FPC} if jsonObject.GetValue('file') as TJSONString <> nil then Result.FPublishFile := TJSONString(jsonObject.GetValue('file')).ToString.Replace('"',''); if jsonObject.GetValue('destination') as TJSONString <> nil then Result.FDestination := TJSONString(jsonObject.GetValue('destination')).ToString.Replace('"',''); if jsonObject.GetValue('action') as TJSONString <> nil then Result.FAction := TJSONString(jsonObject.GetValue('action')).ToString.Replace('"',''); if jsonObject.GetValue('cleanup') as TJSONBool <> nil then Result.FCleanup := (jsonObject.GetValue('cleanup') as TJSONBool).AsBoolean; if jsonObject.GetValue('backup') as TJSONBool <> nil then Result.FBackup := (jsonObject.GetValue('backup') as TJSONBool).AsBoolean; if jsonObject.GetValue('filetype') as TJSONString <> nil then Result.FFileType := TJSONString(jsonObject.GetValue('filetype')).ToString.Replace('"',''); {$ELSE} if jsonObject.Get('file') <> '' then Result.FPublishFile := string(jsonObject.Get('file')).Replace('"',''); if jsonObject.Get('destination') <> '' then Result.FDestination := string(jsonObject.Get('destination')).Replace('"',''); if jsonObject.Get('action') <> '' then Result.FAction := string(jsonObject.Get('action')).Replace('"',''); if jsonObject.Get('cleanup') as TJSONBool <> nil then Result.FCleanup := (jsonObject.Get('cleanup') as TJSONBool).AsBoolean; if jsonObject.Get('backup') as TJSONBool <> nil then Result.FBackup := (jsonObject.Get('backup') as TJSONBool).AsBoolean; if jsonObject.Get('filetype') <> '' then Result.FFileType := string(jsonObject.Get('filetype')).Replace('"',''); {$ENDIF} except on E : Exception do raise Exception.CreateFmt('Not valid Json: %s',[e.Message]); //on E : Exception do Logger.Error('Exception: %s JSON Content: %s',[e.Message,JsonObject.ToJSON]); end; end; {$IFNDEF FPC} function THTTPPublishController.GetJobsFromJSON(const Body : string) : TObjectList<TPublishJSON>; var vJSONScenario: TJSONValue; vJSONValue: TJSONValue; begin Result := nil; vJSONScenario := TJSONObject.ParseJSONValue(Body, False); if vJSONScenario <> nil then begin try Result := TObjectList<TPublishJSON>.Create(True); if vJSONScenario is TJSONArray then begin Logger.Debug('JSON is an Array'); for vJSONValue in vJSONScenario as TJSONArray do begin if vJSONValue is TJSONObject then Result.Add(GetJobFromJson(TJSONObject(vJSONValue) as TJSONObject)); end; end else if vJSONScenario is TJSONObject then Result.Add(GetJobFromJson(TJSONObject(vJSONScenario) as TJSONObject)); finally vJSONScenario.Free; end; end; end; {$ELSE} function THTTPPublishController.GetJobsFromJSON(const Body: string): TFPGObjectList<TPublishJSON>; var vJSONScenario: TJSONData; I : integer; begin Result := nil; vJSONScenario := GetJSON(body); if vJSONScenario <> nil then begin try Result := TFPGObjectList<TPublishJSON>.Create(True); case vJSONScenario.JSONType of jtArray : begin Logger.Debug('JSON is an Array'); for I:=0 to vJSONScenario.Count -1 do begin Result.Add(GetJobFromJson(TJSONObject(vJSONScenario) as TJSONObject)); end; end; jtObject : begin Result.Add(GetJobFromJson(TJSONObject(vJSONScenario) as TJSONObject)); end; end; finally vJSONScenario.Free; end; end; end; {$ENDIF} procedure THTTPPublishController.OnExtractFile(Sender: TObject; const Filename: string; Position: Int64); begin Logger.Debug('Deflating : %s',[Filename]); end; function THTTPPublishController.ProcessRequest(Request: THTTPRestRequest): Cardinal; var job : TPublishJSON; {$IFNDEF FPC} jobs : TObjectList<TPublishJSON>; {$ELSE} jobs : TFPGObjectList<TPublishJSON>; {$ENDIF} begin if Request.RequestInfo.ContentType = 'application/json' then begin try jobs := GetJobsFromJSON(Request.InContent); try for job in jobs do begin Logger.Info('New publish JOB added'); PublishJob(job); end; Result := 200; except on e : Exception do begin Logger.Error(e.message); Result := 500; end; end; finally if jobs <> nil then jobs.Free; end; end else Result := 400; end; procedure THTTPPublishController.PublishJob(Job: TPublishJSON); var strstream : TStringStream; dest : string; destbak : string; compressor : ICompression; begin //Base 64 to stream {$IFNDEF FPC} strstream := TStringStream.Create(TNetEncoding.Base64.DecodeStringToBytes(Job.FPublishFile)); {$ELSE} strstream := TStringStream.Create(base64.DecodeStringBase64(Job.FPublishFile)); {$ENDIF} try if Job.FFileType = 'zip' then compressor := TCompressionFactory.GetInstance('zip') else raise Exception.Create('Filetype ' + Job.FFileType + ' Not supported '); compressor.SubscribeOnProcess(OnExtractFile); for dest in job.FDestination.Split([',']) do begin //if backup option, rename folder before publish if Job.Backup then begin destbak := dest + '_bak'; if DirectoryExists(destbak) then begin Logger.Info('Removing previous backup "%s" directory...',[dest]); TDirectory.Delete(destbak,True); end; TDirectory.Move(dest,destbak); Logger.Success('Renamed "%s" directory',[dest]); ForceDirectories(dest); end; //if cleanup option, delete all files before publish if Job.Cleanup then begin Logger.Info('Cleaning up "%s" directory...',[dest]); if DirectoryExists(dest) then TDirectory.Delete(dest,True); ForceDirectories(dest); Logger.Success('Cleaned "%s" directory',[dest]); if not DirectoryExists(dest) then raise Exception.CreateFmt('Destination folder "%s" not exists!',[dest]); end; //decompress files Logger.Info('Extracting files to %s...',[dest]); compressor.ExtractFromStreamToDisk(strstream, dest); Logger.Info('Files extracted to %s',[dest]); end; finally strstream.Free; end; end; { TPublishJSON } procedure TPublishJSON.SetAction(const Value: string); begin FAction := Value; end; procedure TPublishJSON.SetBackup(const Value: Boolean); begin FBackup := Value; end; procedure TPublishJSON.SetCleanup(const Value: Boolean); begin FCleanup := Value; end; procedure TPublishJSON.SetDestination(const Value: string); begin FDestination := Value; end; procedure TPublishJSON.SetPublishFile(const Value: string); begin FPublishFile := Value; end; initialization PublishController := THTTPPublishController.Create; THTTPControllerFactory.Init; THTTPControllerFactory.GetInstance.Add(PublishController); end.
unit UPagePanel; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2005 by Bradford Technologies, Inc. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TPagePanel = class; TPageContainer = class(TScrollBox) protected function CreatePage : TPagePanel ; virtual ; public //constructor Create(AOwner : TComponent); override; function AddPage : TPagePanel; end; // TPagePanel = class(TCustomControl) TPagePanel = class(TWinControl) private { Private declarations } FExpanded: boolean; FDefaultHeight : integer; FTitleRect : TRect; FExpandButtonArea : TRect; FExpanding : Boolean ; procedure SetExpanded(const Value: boolean); protected { Protected declarations } //procedure Paint ; override; procedure Loaded ; override; procedure WMNCHitTest(var message : TWMNCHitTest) ; message WM_NCHitTest; procedure WMNCLButtonDown(var message : TWMNCLButtonDown); message WM_NCLButtonDown; procedure WMNCPaint(var message : TWMNCPaint); message WM_NCPaint; procedure WMPAINT(var message: TWMPaint); message WM_Paint; procedure WMNCCalcSize(var message : TWMNCCalcSize); message WM_NCCalcSize; procedure CreateParams(var Params : TCreateParams); override; public { Public declarations } constructor Create(AOwner : TComponent) ; override; published { Published declarations } property Align; property Color; property Caption; property Expanded : boolean read FExpanded write SetExpanded ; end; implementation const colorPageTitle = $00A0FEFA; { TPagePanel } constructor TPagePanel.Create(AOwner: TComponent); begin inherited Create(AOwner); FExpanded := true; FExpandButtonArea := Rect(3,3,18,18); Height := 100 ; //Align := alTop; ControlStyle := [csSetCaption,csOpaque,csAcceptsControls]; end; procedure TPagePanel.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or WS_CHILD or WS_CLIPCHILDREN; Params.ExStyle := Params.ExStyle; Params.WindowClass.style := Params.WindowClass.style and not (CS_HREDRAW or CS_VREDRAW); end; procedure TPagePanel.Loaded; begin inherited Loaded ; FDefaultHeight := ClientHeight; SetExpanded(FExpanded); end; //procedure TPagePanel.Paint; //begin // inherited Paint ; //end; procedure TPagePanel.SetExpanded(const Value: boolean); begin // Clean this up later. if csLoading in ComponentState then begin FExpanded := Value end else begin if FExpanded = Value then exit ; FExpanded := Value; if not(Value) then begin FExpanding := true ; FDefaultHeight := ClientHeight; while ClientHeight > 0 do begin ClientHeight := ClientHeight - 10; repaint; end; ClientHeight := 0; FExpanding := false ; end; if (Value) then begin FExpanding := true ; while ClientHeight < FDefaultHeight do begin ClientHeight := ClientHeight + 10; repaint; end; ClientHeight := FDefaultHeight ; FExpanding := false ; end; end; end; procedure TPagePanel.WMNCCalcSize(var message: TWMNCCalcSize); begin inherited; with message.CalcSize_Params^ do begin rgrc[0].top := rgrc[0].top + 20; end; end; procedure TPagePanel.WMNCHitTest(var message: TWMNCHitTest); begin inherited; if not (csDesigning in ComponentState) then message.result := HTCAPTION; end; procedure TPagePanel.WMNCLButtonDown(var message: TWMNCLButtonDown); var WndRect : TRect; begin //inherited; GetWindowRect(handle,WndRect); // probably better way to do this ?? if ptInRect(Rect(WndRect.Left + FExpandButtonArea.Left,WndRect.Top + FExpandButtonArea.Top, WndRect.Left + FExpandButtonArea.Left + FExpandButtonArea.Right, WndRect.Top + FExpandButtonArea.Top + FExpandButtonArea.Bottom) ,point(message.xCursor,message.yCursor)) then begin Expanded := not FExpanded ; end; end; procedure TPagePanel.WMNCPaint(var message: TWMNCPaint); var dc : HDC ; NCCanvas : TCanvas ; Flags : integer; begin //inherited; // need to optimize this. dc := GetWindowDC(handle); NCCanvas := TCanvas.Create; try NCCanvas.Handle := dc ; FTitleRect := rect(0,0,NCCanvas.ClipRect.Right,20); // NCCanvas.FrameRect(FTitleRect); // NCCanvas.Brush.Color := clActiveCaption ; NCCanvas.Brush.Color := colorPageTitle; NCCanvas.FillRect(FTitleRect); NCCanvas.Brush.Color := clBlack; NCCanvas.FrameRect(FTitleRect); if FExpanded then flags := DFCS_SCROLLUP else flags := DFCS_SCROLLDOWN; DrawFrameControl(NCCanvas.Handle,FExpandButtonArea,DFC_SCROLL,flags); NCCanvas.Brush.Color := colorPageTitle; NCCanvas.Font.Color := clBlack; // NCCanvas.Font.Color := clCaptionText; NCCanvas.Font.Style := NCCanvas.Font.Style + [fsBold]; NCCanvas.TextOut(20,3,Caption); finally NCCanvas.Free; ReleaseDC(handle,dc); end; end; procedure TPagePanel.WMPAINT(var message: TWMPaint); var DC: HDC; R:TRect; PS: TPaintStruct; theCanvas : TCanvas; begin DC := Message.DC; if DC = 0 then DC := BeginPaint(Handle, PS); if dc <> 0 then begin theCanvas := TCanvas.Create; try with theCanvas do begin Handle := dc; Pen.width := 5; R := PS.rcPaint; FrameRect(R); FrameRect(ClipRect); MoveTo(0,0); Lineto(100,100); LineTo(100,10); LineTo(10,10); Handle := 0; end; finally theCanvas.free; // ReleaseDC(handle, dc); if Message.DC = 0 then EndPaint(Handle, PS); end; end; end; { TPageContainer } function TPageContainer.AddPage : TPagePanel; var NewPage : TPagePanel ; begin NewPage := CreatePage; NewPage.Parent := self; NewPage.Align := alTop ; result := NewPage; end; function TPageContainer.CreatePage: TPagePanel; begin Result := TPagePanel.Create(GetParentForm(self)); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC ODBC Bridge driver } { } { Copyright(c) 2004-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} {$I FireDAC.inc} {$IFDEF WIN32} {$HPPEMIT '#pragma link "FireDAC.Phys.ODBC.obj"'} {$ELSE} {$HPPEMIT '#pragma link "FireDAC.Phys.ODBC.o"'} {$ENDIF} unit FireDAC.Phys.ODBC; interface uses System.Classes, FireDAC.Phys, FireDAC.Phys.ODBCBase; type [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32)] TFDPhysODBCDriverLink = class(TFDPhysODBCBaseDriverLink) protected function GetBaseDriverID: String; override; end; {-------------------------------------------------------------------------------} implementation uses System.SysUtils, FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.Meta, FireDAC.Phys.ODBCCli, FireDAC.Phys.ODBCWrapper, FireDAC.Phys.ODBCMeta {$IFDEF FireDAC_ODBC_ALLMETA} , FireDAC.Phys.MSSQLMeta, FireDAC.Phys.MSAccMeta, FireDAC.Phys.DB2Meta, FireDAC.Phys.OracleMeta, FireDAC.Phys.ASAMeta, FireDAC.Phys.MySQLMeta, FireDAC.Phys.ADSMeta, FireDAC.Phys.IBMeta, FireDAC.Phys.PGMeta, FireDAC.Phys.SQLiteMeta, FireDAC.Phys.NexusMeta {$ENDIF} ; type TFDPhysODBCDriver = class; TFDPhysODBCConnection = class; TFDPhysODBCDriver = class(TFDPhysODBCDriverBase) protected class function GetBaseDriverID: String; override; function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override; procedure GetODBCConnectStringKeywords(AKeywords: TStrings); override; function GetConnParamCount(AKeys: TStrings): Integer; override; procedure GetConnParams(AKeys: TStrings; AIndex: Integer; var AName, AType, ADefVal, ACaption: String; var ALoginIndex: Integer); override; end; TFDPhysODBCConnection = class(TFDPhysODBCConnectionBase) private FRdbmsKind: TFDRDBMSKind; FNumericFormat: TFDDataType; procedure UpdateRDBMSKind; protected function InternalCreateCommandGenerator( const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override; function InternalCreateMetadata: TObject; override; procedure InternalConnect; override; function GetNumType: TFDDataType; override; public constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override; end; const S_FD_Binary = 'Binary'; S_FD_String = 'String'; {-------------------------------------------------------------------------------} { TFDPhysODBCDriverLink } {-------------------------------------------------------------------------------} function TFDPhysODBCDriverLink.GetBaseDriverID: String; begin Result := S_FD_ODBCId; end; {-------------------------------------------------------------------------------} { TFDPhysODBCDriver } {-------------------------------------------------------------------------------} class function TFDPhysODBCDriver.GetBaseDriverID: String; begin Result := S_FD_ODBCId; end; {-------------------------------------------------------------------------------} function TFDPhysODBCDriver.InternalCreateConnection( AConnHost: TFDPhysConnectionHost): TFDPhysConnection; begin Result := TFDPhysODBCConnection.Create(Self, AConnHost); end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCDriver.GetODBCConnectStringKeywords(AKeywords: TStrings); var i: Integer; begin inherited GetODBCConnectStringKeywords(AKeywords); i := AKeywords.IndexOf('=DRIVER'); if i >= 0 then AKeywords.Delete(i); i := AKeywords.IndexOf('DSN'); if i >= 0 then AKeywords.Delete(i); AKeywords.Add(S_FD_ConnParam_ODBC_Driver + '=DRIVER'); AKeywords.Add(S_FD_ConnParam_ODBC_DataSource + '=DSN'); AKeywords.Add(S_FD_ConnParam_Common_Database + '=DBQ'); AKeywords.Add(S_FD_ConnParam_Common_Database + '=DATABASE'); end; {-------------------------------------------------------------------------------} function TFDPhysODBCDriver.GetConnParamCount(AKeys: TStrings): Integer; begin Result := inherited GetConnParamCount(AKeys) + 8; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCDriver.GetConnParams(AKeys: TStrings; AIndex: Integer; var AName, AType, ADefVal, ACaption: String; var ALoginIndex: Integer); var j: TFDRDBMSKind; i: Integer; oList: TFDStringList; begin ALoginIndex := -1; ADefVal := ''; if AIndex < inherited GetConnParamCount(AKeys) then inherited GetConnParams(AKeys, AIndex, AName, AType, ADefVal, ACaption, ALoginIndex) else begin case AIndex - inherited GetConnParamCount(AKeys) of 0: begin Employ; oList := TFDStringList.Create; try AName := S_FD_ConnParam_ODBC_Driver; AType := ''; ODBCEnvironment.GetDrivers(oList, True); for i := 0 to oList.Count - 1 do begin if AType <> '' then AType := AType + ';'; AType := AType + oList[i]; end; finally FDFree(oList); Vacate; end; end; 1: begin Employ; oList := TFDStringList.Create; try AName := S_FD_ConnParam_ODBC_DataSource; AType := ''; ODBCEnvironment.GetDSNs(oList, False, True); for i := 0 to oList.Count - 1 do begin if AType <> '' then AType := AType + ';'; AType := AType + oList[i]; end; ALoginIndex := 2; finally FDFree(oList); Vacate; end; end; 2: begin AName := S_FD_ConnParam_ODBC_NumericFormat; AType := S_FD_Binary + ';' + S_FD_String; ADefVal := S_FD_Binary; end; 3: begin AName := S_FD_ConnParam_Common_MetaDefCatalog; AType := '@S'; end; 4: begin AName := S_FD_ConnParam_Common_MetaDefSchema; AType := '@S'; end; 5: begin AName := S_FD_ConnParam_Common_MetaCurCatalog; AType := '@S'; end; 6: begin AName := S_FD_ConnParam_Common_MetaCurSchema; AType := '@S'; end; 7: begin AName := S_FD_ConnParam_Common_RDBMSKind; AType := ''; for j := Low(TFDRDBMSKind) to High(TFDRDBMSKind) do begin if AType <> '' then AType := AType + ';'; AType := AType + C_FD_PhysRDBMSKinds[j]; end; end; end; ACaption := AName; end; end; {-------------------------------------------------------------------------------} { TFDPhysODBCConnection } {-------------------------------------------------------------------------------} constructor TFDPhysODBCConnection.Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); begin inherited Create(ADriverObj, AConnHost); UpdateRDBMSKind; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnection.UpdateRDBMSKind; var i: TFDRDBMSKind; s: string; function Match(const AName: String): Boolean; begin Result := Copy(s, 1, Length(AName)) = AName; end; begin if FRdbmsKind = mkUnknown then begin s := UpperCase(GetConnectionDef.AsString[S_FD_ConnParam_Common_RDBMSKind]); if s <> '' then for i := Low(TFDRDBMSKind) to High(TFDRDBMSKind) do if C_FD_PhysRDBMSKinds[i] = s then begin FRdbmsKind := i; Exit; end; end; if (FRdbmsKind = mkUnknown) and (ODBCConnection <> nil) then FRdbmsKind := ODBCConnection.RdbmsKind; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnection.InternalConnect; var sFmt: String; begin inherited InternalConnect; FRdbmsKind := mkUnknown; sFmt := GetConnectionDef.AsString[S_FD_ConnParam_ODBC_NumericFormat]; if CompareText(sFmt, S_FD_Binary) = 0 then FNumericFormat := dtBCD else FNumericFormat := dtAnsiString; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnection.GetNumType: TFDDataType; begin Result := FNumericFormat; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnection.InternalCreateCommandGenerator(const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; begin UpdateRDBMSKind; {$IFDEF FireDAC_ODBC_ALLMETA} if ACommand <> nil then case FRdbmsKind of mkOracle: Result := TFDPhysOraCommandGenerator.Create(ACommand, False); mkMSSQL: Result := TFDPhysMSSQLCommandGenerator.Create(ACommand); mkMSAccess: Result := TFDPhysMSAccCommandGenerator.Create(ACommand); mkMySQL: Result := TFDPhysMySQLCommandGenerator.Create(ACommand); mkDb2: Result := TFDPhysDb2CommandGenerator.Create(ACommand); mkASA: Result := TFDPhysASACommandGenerator.Create(ACommand); mkADS: Result := TFDPhysADSCommandGenerator.Create(ACommand); mkInterbase, mkFirebird: Result := TFDPhysIBCommandGenerator.Create(ACommand, 0, ecANSI); mkPostgreSQL:Result := TFDPhysPgCommandGenerator.Create(ACommand); mkSQLite: Result := TFDPhysSQLiteCommandGenerator.Create(ACommand); mkNexus: Result := TFDPhysNexusCommandGenerator.Create(ACommand); else Result := TFDPhysCommandGenerator.Create(ACommand); end else case FRdbmsKind of mkOracle: Result := TFDPhysOraCommandGenerator.Create(Self, False); mkMSSQL: Result := TFDPhysMSSQLCommandGenerator.Create(Self); mkMSAccess: Result := TFDPhysMSAccCommandGenerator.Create(Self); mkMySQL: Result := TFDPhysMySQLCommandGenerator.Create(Self); mkDb2: Result := TFDPhysDb2CommandGenerator.Create(Self); mkASA: Result := TFDPhysASACommandGenerator.Create(Self); mkADS: Result := TFDPhysADSCommandGenerator.Create(Self); mkInterbase, mkFirebird: Result := TFDPhysIBCommandGenerator.Create(Self, 0, ecANSI); mkPostgreSQL:Result := TFDPhysPgCommandGenerator.Create(Self); mkSQLite: Result := TFDPhysSQLiteCommandGenerator.Create(Self); mkNexus: Result := TFDPhysNexusCommandGenerator.Create(Self); else Result := TFDPhysCommandGenerator.Create(Self); end; {$ELSE} if ACommand <> nil then Result := TFDPhysCommandGenerator.Create(ACommand) else Result := TFDPhysCommandGenerator.Create(Self); {$ENDIF} end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnection.InternalCreateMetadata: TObject; var iSrvVer, iClntVer: TFDVersion; begin GetVersions(iSrvVer, iClntVer); UpdateRDBMSKind; {$IFDEF FireDAC_ODBC_ALLMETA} case FRdbmsKind of mkOracle: Result := TFDPhysOraMetadata.Create(Self, iSrvVer, iClntVer, False); mkMSSQL: Result := TFDPhysMSSQLMetadata.Create(Self, False, True, True, True, (ODBCConnection <> nil) and (ODBCConnection.DriverKind in [dkSQLSrv, dkSQLNC]), iSrvVer, iClntVer, GetKeywords, False); mkMSAccess: Result := TFDPhysMSAccMetadata.Create(Self, iSrvVer, iClntVer, GetKeywords); mkMySQL: Result := TFDPhysMySQLMetadata.Create(Self, False, iSrvVer, iClntVer, [nmCaseSens, nmDBApply], False); mkDb2: Result := TFDPhysDb2Metadata.Create(Self, iSrvVer, iClntVer, GetKeywords); mkASA: Result := TFDPhysASAMetadata.Create(Self, iSrvVer, iClntVer, GetKeywords); mkADS: Result := TFDPhysADSMetadata.Create(Self, iSrvVer, iClntVer); mkInterbase: Result := TFDPhysIBMetadata.Create(Self, ibInterbase, iSrvVer, iClntVer, 3, False); mkFirebird: Result := TFDPhysIBMetadata.Create(Self, ibFirebird, iSrvVer, iClntVer, 3, False); mkPostgreSQL:Result := TFDPhysPgMetadata.Create(Self, iSrvVer, iClntVer, False, False, False); mkSQLite: Result := TFDPhysSQLiteMetadata.Create(Self, sbSQLite, iSrvVer, iClntVer, False, False); mkNexus: Result := TFDPhysNexusMetadata.Create(Self, iSrvVer, iClntVer); else Result := nil; end; {$ELSE} Result := nil; {$ENDIF} if (ODBCConnection <> nil) and ODBCConnection.Connected then Result := TFDPhysODBCMetadata.Create(Self, iSrvVer, iClntVer, TFDPhysConnectionMetadata(Result)) else if Result = nil then Result := TFDPhysConnectionMetadata.Create(Self, iSrvVer, iClntVer, False); end; {-------------------------------------------------------------------------------} initialization FDPhysManager(); FDPhysManagerObj.RegisterDriverClass(TFDPhysODBCDriver); end.
{------------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is SynEditWordWrap.pas by Flávio Etrusco, released 2003-12-11. Unicode translation by Maël Hörz. All Rights Reserved. Contributors to the SynEdit and mwEdit projects are listed in the Contributors.txt file. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. -------------------------------------------------------------------------------} unit SynEditWordWrap; {$I SynEdit.inc} interface uses System.SysUtils, System.Classes, System.Generics.Collections, SynEditTypes, SynEditTextBuffer, SynEdit; const MaxIndex = MaxInt div 16; type TLineIndex = 0..MaxIndex; TRowIndex = 0..MaxIndex; // fLineOffsets[n] is the index of the first row of the [n+1]th line. // e.g. Starting row of first line (0) is 0. Starting row of second line (1) // is fLineOffsets[0]. Clear? TSynWordWrapPlugin = class(TInterfacedObject, ISynEditBufferPlugin) private fLineOffsets: TList<Integer>; fRowLengths: TList<Integer>; fLineCount: integer; fEditor: TCustomSynEdit; fMaxRowWidth: Integer; procedure SetEmpty; protected procedure WrapLine(const Index: Integer; out RowLengths: TArray<Integer>); procedure WrapLines; function ReWrapLine(aIndex: TLineIndex): integer; procedure TrimArrays; property Editor: TCustomSynEdit read fEditor; public constructor Create(aOwner: TCustomSynEdit); destructor Destroy; override; { ISynEditBufferPlugin } function BufferToDisplayPos(const aPos: TBufferCoord): TDisplayCoord; function DisplayToBufferPos(const aPos: TDisplayCoord): TBufferCoord; function RowCount: integer; function GetRowLength(aRow: integer): integer; function LinesInserted(aIndex: integer; aCount: integer): integer; function LinesDeleted(aIndex: integer; aCount: integer): integer; function LinePut(aIndex: integer; const OldLine: string): integer; procedure Reset; procedure DisplayChanged; end; implementation uses Winapi.Windows, Winapi.D2D1, System.RTLConsts, System.Math, System.Threading, SynUnicode, SynEditMiscProcs, SynDWrite; { TSynWordWrapPlugin } function TSynWordWrapPlugin.BufferToDisplayPos( const aPos: TBufferCoord): TDisplayCoord; var vStartRow: integer; // first row of the line cRow: integer; vRowLen: integer; begin Assert(aPos.Char > 0); Assert(aPos.Line > 0); if fLineCount < aPos.Line then begin // beyond EOF Result.Column := aPos.Char; Result.Row := RowCount + (aPos.Line - fLineCount); Exit; end; if aPos.Line = 1 then vStartRow := 0 else vStartRow := fLineOffsets[aPos.Line - 2]; vRowLen := 0; for cRow := vStartRow to fLineOffsets[aPos.Line - 1] - 1 do begin Inc(vRowLen, fRowLengths[cRow]); if aPos.Char <= vRowLen then begin Result.Column := aPos.Char - vRowLen + fRowLengths[cRow]; Result.Row := cRow + 1; Exit; end; end; // beyond EOL Result.Column := aPos.Char - vRowLen + fRowLengths[fLineOffsets[aPos.Line - 1] - 1]; Result.Row := fLineOffsets[aPos.Line - 1]; end; constructor TSynWordWrapPlugin.Create(aOwner: TCustomSynEdit); begin inherited Create; // just to work as reminder in case I revert it to a TComponent... if aOwner = nil then raise Exception.Create( 'Owner of TSynWordWrapPlugin must be a TCustomSynEdit' ); fEditor := aOwner; fLineCount := fEditor.Lines.Count; fLineOffsets := TList<Integer>.Create; fRowLengths := TList<Integer>.Create; Reset; end; destructor TSynWordWrapPlugin.Destroy; begin inherited; fLineOffsets.Free;; fRowLengths.Free; end; procedure TSynWordWrapPlugin.DisplayChanged; begin if Editor.WrapAreaWidth <> fMaxRowWidth then Reset; end; function TSynWordWrapPlugin.DisplayToBufferPos( const aPos: TDisplayCoord): TBufferCoord; var cLine: integer; cRow: integer; begin Assert(aPos.Column > 0); Assert(aPos.Row > 0); if aPos.Row > RowCount then begin // beyond EOF Result.Char := aPos.Column; Result.Line := aPos.Row - RowCount + fLineCount; Exit; end; //Optimized loop start point but could use binary search for cLine := Min(aPos.Row - 2, fLineCount - 2) downto 0 do if aPos.Row > fLineOffsets[cLine] then begin Result.Line := cLine + 2; if aPos.Row = fLineOffsets[cLine + 1] then //last row of line Result.Char := aPos.Column else Result.Char := Min(aPos.Column, fRowLengths[aPos.Row - 1] + 1); for cRow := fLineOffsets[cLine] to aPos.Row - 2 do Inc(Result.Char, fRowLengths[cRow]); Exit; end; // first line Result.Line := 1; if aPos.Row = fLineOffsets[0] then //last row of line Result.Char := aPos.Column else Result.Char := Min(aPos.Column, fRowLengths[aPos.Row - 1] + 1); for cRow := 0 to aPos.Row - 2 do Inc(Result.Char, fRowLengths[cRow]); end; function TSynWordWrapPlugin.GetRowLength(aRow: integer): integer; // aRow is 1-based... begin if (aRow <= 0) or (aRow > RowCount) then TList.Error(SListIndexError, aRow); Result := fRowLengths[aRow - 1]; end; function TSynWordWrapPlugin.LinesDeleted(aIndex: integer; aCount: integer): integer; // Returns the number of rows deleted var vStartRow: integer; vEndRow: integer; cLine: integer; begin if fMaxRowWidth < Editor.CharWidth then Exit(0); Assert(aIndex >= 0); Assert(aCount >= 1); Assert(aIndex + aCount <= fLineCount); if aIndex = 0 then vStartRow := 0 else vStartRow := fLineOffsets[aIndex - 1]; vEndRow := fLineOffsets[aIndex + aCount - 1]; Result := vEndRow - vStartRow; // resize fRowLengths if vStartRow < RowCount then fRowLengths.DeleteRange(vStartRow, Result); // resize fLineOffsets fLineOffsets.DeleteRange(aIndex, aCount); Dec(fLineCount, aCount); // update offsets for cLine := aIndex to fLineCount - 1 do Dec(fLineOffsets.List[cLine], Result); if fLineCount = 0 then SetEmpty; end; function TSynWordWrapPlugin.LinesInserted(aIndex: integer; aCount: integer): integer; // Returns the number of rows inserted var vPrevOffset: TRowIndex; cLine: integer; TempArray: TArray<Integer>; begin if fMaxRowWidth < Editor.CharWidth then Exit(0); Assert(aIndex >= 0); Assert(aCount >= 1); Assert(aIndex <= fLineCount); Inc(fLineCount, aCount); // set offset to same as previous line if aIndex = 0 then vPrevOffset := 0 else vPrevOffset := fLineOffsets[aIndex - 1]; // resize fLineOffsets SetLength(TempArray, aCount); fLineOffsets.InsertRange(aIndex, TempArray); // Rewrap Result := 0; for cLine := aIndex to aIndex + aCount - 1 do begin fLineOffsets[cLine] := vPrevOffset; ReWrapLine(cLine); Inc(Result, fLineOffsets[cLine] - vPrevOffset); vPrevOffset := fLineOffsets[cLine]; end; // Adjust lines below for cLine := aIndex + aCount to fLineCount - 1 do Inc(fLineOffsets.List[cLine], Result); end; function TSynWordWrapPlugin.LinePut(aIndex: integer; const OldLine: string): integer; var cLine: integer; begin if fMaxRowWidth < Editor.CharWidth then Exit(0); Assert(aIndex >= 0); Assert(aIndex < fLineCount); // Rewrap Result := ReWrapLine(aIndex); // Adjust lines below if Result <> 0 then for cLine := aIndex + 1 to fLineCount - 1 do Inc(fLineOffsets.List[cLine], Result); end; procedure TSynWordWrapPlugin.Reset; begin fMaxRowWidth := Editor.WrapAreaWidth; WrapLines; end; function TSynWordWrapPlugin.ReWrapLine(aIndex: TLineIndex): integer; // Returns RowCount delta (how many wrapped lines were added or removed by this change). var RowLengths: TArray<Integer>; PrevOffset: Integer; PrevRowCount: Integer; begin WrapLine(aIndex, RowLengths); if aIndex = 0 then PrevOffset := 0 else PrevOffset := fLineOffsets[aIndex - 1]; PrevRowCount := fLineOffsets[aIndex] - PrevOffset; if PrevRowCount > 0 then fRowLengths.DeleteRange(PrevOffset, PrevRowCount); fRowLengths.InsertRange(PrevOffset, RowLengths); fLineOffsets[aIndex] := PrevOffset + Length(RowLengths); Result := Length(RowLengths) - PrevRowCount; end; procedure TSynWordWrapPlugin.WrapLines; var cRow: Integer; cLine: Integer; RowLengths: TArray<TArray<Integer>>; begin fLineOffsets.Clear; fLineOffsets.Capacity := Editor.Lines.Count; fRowLengths.Clear; fRowLengths.Capacity := Editor.Lines.Count; if (Editor.Lines.Count = 0) or (fMaxRowWidth < Editor.CharWidth) then Exit; SetLength(RowLengths, Editor.Lines.Count); TParallel.&For(0, Editor.Lines.Count - 1, procedure(I: Integer) begin WrapLine(I, RowLengths[I]); end); cRow := 0; for cLine := 0 to Editor.Lines.Count - 1 do begin fRowLengths.AddRange(RowLengths[cLine]); Inc(cRow, Length(RowLengths[cLine])); fLineOffsets.Add(cRow); end; end; function TSynWordWrapPlugin.RowCount: integer; begin if fLineCount > 0 then Result := fLineOffsets[fLineCount - 1] else Result := 0; Assert(fRowLengths.Count = Result); end; procedure TSynWordWrapPlugin.SetEmpty; begin fLineCount := 0; // free unsused memory TrimArrays; end; procedure TSynWordWrapPlugin.TrimArrays; begin fLineOffsets.TrimExcess; fRowLengths.TrimExcess; end; procedure TSynWordWrapPlugin.WrapLine(const Index: Integer; out RowLengths: TArray<Integer>); var SLine: string; Layout: TSynTextLayout; W: Integer; P, P2, PStart, PEnd, PBreak: PChar; CW, TW, LW: Integer; IsTrailing, IsInside: BOOL; fWorkList: TList<Integer>; HTM: TDwriteHitTestMetrics; begin CW := Editor.CharWidth; TW := Editor.TabWidth * Editor.CharWidth; SLine := Editor.Lines[Index]; PStart := PChar(SLine); PEnd := PStart + SLine.Length; if (PEnd - PStart) * CW < fMaxRowWidth div 3 then // Optimization. Assume line will fit! RowLengths := [SLine.Length] else begin fWorkList := TList<Integer>.Create; try // Preallocation helps with very long lines fWorkList.Capacity := MulDiv(SLine.Length, CW + 1, fMaxRowWidth); P := PStart; PBreak := nil; W := 0; while (P < PEnd) do begin while (P < PEnd) and (W < fMaxRowWidth) do begin if (P > PStart) and Editor.IsWordBreakChar(P^) then PBreak := P + IfThen(P^ = #32, 1, 0); case P^ of #9: Inc(W, TW - W mod TW); #32..#126: Inc(W, CW); else break; end; Inc(P); end; if (P < PEnd) and (W < fMaxRowWidth) then begin // Just in case P is followed by combining characters if (P > PStart) and not (Word((P-1)^) in [9, 32]) then begin Dec(P); Dec(W, CW); end; // Measure non-ascii text code points P2 := P; while P2 < PEnd do begin Inc(P2); if Word(P2^) in [9, 32..126] then Break; end; Layout.Create(Editor.TextFormat, P, P2-P, MaxInt, Editor.LineHeight); LW := Round(Layout.TextMetrics.width); if W + LW >= fMaxRowWidth then begin CheckOSError(Layout.IDW.HitTestPoint(fMaxRowWidth - W, Editor.LineHeight div 2, IsTrailing, IsInside, HTM)); Inc(P, HTM.textPosition + 1); end else P := P2; Inc(W, LW); end; if W >= fMaxRowWidth then begin if Assigned(PBreak) then begin FWorkList.Add(PBreak - PStart); PStart := PBreak; P := PStart; PBreak := nil; end else begin // "emergency" wrapping FWorkList.Add(P - PStart); PStart := P; end; W := 0; end; end; if P > PStart then FWorkList.Add(P - PStart); RowLengths := fWorkList.ToArray; finally fWorkList.Free; end; end; end; end.
unit CalibrationCH2WSImpl; interface uses InvokeRegistry, Types, XSBuiltIns, CalibrationCH2WSIntf, CommunicationObj, Constants; type { TCalibrationCH2WS } TCalibrationCH2WS = class(TCommObj, ICalibrationCH2WS) public // ICalibration function Get_Potencia: Integer; safecall; function Get_CRadarPL: Single; safecall; function Get_CRadarPC: Single; safecall; function Get_PotMetPL: Single; safecall; function Get_PotMetPC: Single; safecall; function Get_MPS_Voltage: Double; safecall; function Get_Tx_Pulse_SP: Integer; safecall; function Get_Tx_Pulse_LP: Integer; safecall; function Get_Start_Sample_SP: Integer; safecall; function Get_Final_Sample_SP: Integer; safecall; function Get_Start_Sample_LP: Integer; safecall; function Get_Final_Sample_LP: Integer; safecall; function Get_Tx_Factor: Double; safecall; function Get_Stalo_Delay: Integer; safecall; function Get_Stalo_Step: Integer; safecall; function Get_Stalo_Width: Integer; safecall; function Get_Valid_tx_power: Double; safecall; function Get_Loop_Gain: Double; safecall; // ICalibrationControl procedure Set_Potencia(Value: Integer); safecall; procedure Set_CRadarPL(Value: Single); safecall; procedure Set_CRadarPC(Value: Single); safecall; procedure Set_MPS_Voltage(Value: Double); safecall; procedure Set_Tx_Pulse_SP(Value: Integer); safecall; procedure Set_Tx_Pulse_LP(Value: Integer); safecall; procedure Set_Start_Sample_SP(Value: Integer); safecall; procedure Set_Final_Sample_SP(Value: Integer); safecall; procedure Set_Start_Sample_LP(Value: Integer); safecall; procedure Set_Final_Sample_LP(Value: Integer); safecall; procedure Set_Tx_Factor(Value: Double); safecall; procedure Set_Stalo_Delay(Value: Integer); safecall; procedure Set_Stalo_Step(Value: Integer); safecall; procedure Set_Stalo_Width(Value: Integer); safecall; procedure Set_Valid_tx_power(Value: Double); safecall; procedure Set_Loop_Gain(Value: Double); safecall; procedure SaveDRX; safecall; function CheckCredentials : boolean; override; end; implementation uses Users, Calib, ActiveX, ElbrusTypes, ManagerDRX; { TCalibrationCH2WS } function TCalibrationCH2WS.CheckCredentials: boolean; begin result := CheckAuthHeader >= ul_Service; end; function TCalibrationCH2WS.Get_CRadarPC: Single; begin Result := theCalibration.CRadarPC2; end; function TCalibrationCH2WS.Get_CRadarPL: Single; begin Result := theCalibration.CRadarPL2; end; function TCalibrationCH2WS.Get_Final_Sample_LP: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Final_Sample_LP else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Final_Sample_SP: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Final_Sample_SP else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Loop_Gain: Double; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Loop_Gain else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_MPS_Voltage: Double; begin Result := theCalibration.MPS_Voltage2; end; function TCalibrationCH2WS.Get_Potencia: Integer; begin Result := theCalibration.Potencia2; end; function TCalibrationCH2WS.Get_PotMetPC: Single; begin Result := theCalibration.PotMetPC2; end; function TCalibrationCH2WS.Get_PotMetPL: Single; begin Result := theCalibration.PotMetPC2; end; function TCalibrationCH2WS.Get_Stalo_Delay: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Stalo_Delay else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Stalo_Step: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Stalo_Step else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Stalo_Width: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Stalo_Width else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Start_Sample_LP: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Start_Sample_LP else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Start_Sample_SP: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Start_Sample_SP else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Tx_Factor: Double; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Tx_Factor else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Tx_Pulse_LP: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Tx_Pulse_LP else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Tx_Pulse_SP: Integer; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Tx_Pulse_SP else result := 0; except result := 0; DRX2.Validate; end; end; function TCalibrationCH2WS.Get_Valid_tx_power: Double; begin try if DRX2.Ready then result := DRX2.AFC_WS.Get_Valid_Tx_Power else result := 0; except result := 0; DRX2.Validate; end; end; procedure TCalibrationCH2WS.SaveDRX; begin if InControl and DRX2.Ready then DRX2.AFC_WS.Save_Calibration; end; procedure TCalibrationCH2WS.Set_CRadarPC(Value: Single); begin if InControl then theCalibration.CRadarPC2 := Value; end; procedure TCalibrationCH2WS.Set_CRadarPL(Value: Single); begin if InControl then theCalibration.CRadarPL2 := Value; end; procedure TCalibrationCH2WS.Set_Final_Sample_LP(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Final_Sample_LP(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Final_Sample_SP(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Final_Sample_SP(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Loop_Gain(Value: Double); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Loop_Gain(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_MPS_Voltage(Value: Double); begin if InControl then theCalibration.MPS_Voltage2 := Value; end; procedure TCalibrationCH2WS.Set_Potencia(Value: Integer); begin if InControl then theCalibration.Potencia2 := Value; end; procedure TCalibrationCH2WS.Set_Stalo_Delay(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Stalo_Delay(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Stalo_Step(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Stalo_Step(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Stalo_Width(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Stalo_Width(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Start_Sample_LP(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Start_Sample_LP(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Start_Sample_SP(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Start_Sample_SP(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Tx_Factor(Value: Double); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Tx_Factor(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Tx_Pulse_LP(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Tx_Pulse_LP(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Tx_Pulse_SP(Value: Integer); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Tx_Pulse_SP(Value); except DRX2.Validate; end; end; procedure TCalibrationCH2WS.Set_Valid_tx_power(Value: Double); begin try if InControl and DRX2.Ready then DRX2.AFC_WS.Set_Valid_tx_power(Value); except DRX2.Validate; end; end; initialization { Invokable classes must be registered } InvRegistry.RegisterInvokableClass(TCalibrationCH2WS); end.
unit uNet; interface uses Classes, uConsts, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdBaseComponent, IdCookieManager, IdAntiFreeze, Dialogs; type TPostingNNM = class private FAuth: Boolean; FHTTP: TIdHTTP; FCoock: TIdCookieManager; FAntiFreeze: TIdAntiFreeze; FLogin, FPassword: string; FTimeout: Integer; function DoLogin: TResultPost; function PrepareHTTP: Boolean; function PrepareData(var APostData: TPostData; AShowProgress: TShowProgress = nil): Boolean; public constructor Create(Login, Password: string; Timeout: Integer; AProxy: TProxy); destructor Destroy; override; function PostImage(ASource, ADoc: string; out ANewSource: string; AShowProgress: TShowProgress = nil): TResultPost; function PostNews(APostData: TPostData; AShowProgress: TShowProgress = nil): TResultPost; end; implementation uses SysUtils, IdGlobal, uParser, frmuLoginDlg, IdMultiPartFormData, Controls, IdException; { TPostingNNM } constructor TPostingNNM.Create(Login, Password: string; Timeout: Integer; AProxy: TProxy); begin FAuth := False; FHTTP := TIdHTTP.Create(nil); FHTTP.Host := NNM_Adress; FHTTP.Port := 80; if AProxy.ProxyActive then begin FHTTP.ProxyParams.ProxyPort := AProxy.ProxyPort; FHTTP.ProxyParams.ProxyServer := AProxy.ProxyHost; FHTTP.ProxyParams.ProxyUsername := AProxy.ProxyLogin; FHTTP.ProxyParams.ProxyPassword := AProxy.ProxyPassword; end else begin FHTTP.ProxyParams.ProxyPort := 0; FHTTP.ProxyParams.ProxyServer := ''; FHTTP.ProxyParams.ProxyUsername := ''; FHTTP.ProxyParams.ProxyPassword := ''; end; FCoock := TIdCookieManager.Create(nil); FHTTP.CookieManager := FCoock; FHTTP.HandleRedirects := True; FHTTP.ReadTimeout := 1000 * Timeout; FHTTP.HTTPOptions := [hoForceEncodeParams]; FAntiFreeze := TIdAntiFreeze.Create(FHTTP); FLogin := Login; FPassword := Password; FTimeout := 1000 * Timeout; end; destructor TPostingNNM.Destroy; begin FAuth := False; FLogin := ''; FPassword := ''; if Assigned(FAntiFreeze) then FAntiFreeze.Free; if Assigned(FCoock) then FCoock.Free; if Assigned(FHTTP) then FHTTP.Free; FCoock := nil; FHTTP := nil; FAntiFreeze := nil; inherited; end; function TPostingNNM.DoLogin: TResultPost; var Data: TStringList; ResStr: string; FRepeat: Boolean; begin FRepeat := False; if FAuth then begin Result := postOk; Exit; end; Result := postNotLogin; if not PrepareHTTP then Exit; Data := TStringList.Create; try repeat try Data.Add(CFLogin + '=' + FLogin); Data.Add(CFPassword + '=' + FPassword); FHTTP.Connect(FTimeout); try try ResStr := FHTTP.Post(CPLogin, Data); if Pos(CSNoLogin, ResStr) <> 0 then Result := postNotLogin else Result := postOk; if Result <> postOk then begin frmLogin := TfrmLogin.Create(nil); try case frmLogin.ShowModal of mrOk: begin FLogin := frmLogin.Edit1.Text; FPassword := frmLogin.MaskEdit1.Text; FRepeat := True; end; mrCancel: FRepeat := False; else FRepeat := False; end; finally if Assigned(frmLogin) then frmLogin.Free; frmLogin := nil; end; end; except on E: EIdHTTPProtocolException do begin if E.ReplyErrorCode = 502 then Result := postNotServer else Result := postNotLogin; end else Result := postNotLogin; end; finally FHTTP.Disconnect; end; finally if Result = postOk then FAuth := True else FAuth := False; if Result = postOk then FRepeat := False; end; until not FRepeat; finally Data.Free; end; end; function TPostingNNM.PostImage(ASource, ADoc: string; out ANewSource: string; AShowProgress: TShowProgress): TResultPost; var Data: TIdMultiPartFormDataStream; ResStr: string; link: string; Index, SI: Integer; begin ANewSource := ''; if Assigned(AShowProgress) then AShowProgress('Подготовка изображения для отправки на сайт: ' + ASource); if not PrepareHTTP then begin Result := postNotHTTP; Exit; end; Result := postNotImage; if not FileExists(ASource) then Exit; if ADoc[Length(ADoc)] <> '/' then link := ADoc + '/' + CPImage else link := ADoc + CPImage; if DoLogin = postOk then begin Result := postOk; Data := TIdMultiPartFormDataStream.Create; FHTTP.Connect(FTimeout); try {if IsUrl(ASource) then Data.AddFormField(CFImageUrl, ASource) else} Data.AddFile(CFImageFile, ASource, GetMIMETypeFromFile(ASource)); Data.AddFormField('ap', 'post'); FHTTP.Request.ContentType := Data.RequestContentType; try if Assigned(AShowProgress) then AShowProgress('Отправка изображения на сайт: ' + ASource); ResStr := FHTTP.Post(link, Data); if Pos('[img=', ResStr) <> 0 then begin Index := Pos('[img=', ResStr) + 5; SI := Index; while Index <= Length(ResStr) do if ResStr[Index] <> ']' then Inc(Index) else begin ANewSource := Copy(ResStr, SI, Index - SI); Break; end; end; if Assigned(AShowProgress) then AShowProgress('Установка нового адреса изображения в новости'); except on E: EIdHTTPProtocolException do begin if E.ReplyErrorCode = 502 then Result := postNotServer else Result := postErrImage; end else Result := postErrImage; end; finally if Assigned(AShowProgress) then AShowProgress('Завершение отправки изображения на сайт'); FHTTP.Disconnect; Data.Free; end; end else Result := postNotLogin; if Assigned(AShowProgress) then AShowProgress(''); end; function TPostingNNM.PostNews(APostData: TPostData; AShowProgress: TShowProgress): TResultPost; var link: string; Data: TIdMultiPartFormDataStream; ResStr: String; Index: Integer; CodeStr: String; f: Boolean; Category, s: String; begin if Assigned(AShowProgress) then AShowProgress('Подготовка новости для отправки на сайт'); if not PrepareData(APostData, AShowProgress) then begin Result := postNotPrepare; Exit; end; if not PrepareHTTP then begin Result := postNotHTTP; Exit; end; if APostData.Doc.Adress[Length(APostData.Doc.Adress)] <> '/' then link := APostData.Doc.Adress + '/' + CPNews else link := APostData.Doc.Adress + CPNews; if DoLogin = postOk then begin Data := TIdMultiPartFormDataStream.Create; FHTTP.Connect(FTimeout); try try if Assigned(AShowProgress) then AShowProgress('Проверка существования дока для новости'); ResStr := FHTTP.Get(link); CodeStr := ''; f := false; APostData.IsCat := APostData.IsCat and (Pos('<input type=checkbox name=n_dalee', LowerCase(ResStr)) <> 0); Index := Pos('<form method=''post'' name=''form_add_new_std''', ResStr); if Index <> 0 then while Index <= Length(ResStr) do begin if f and (ResStr[Index] = '''') then Break; if f then CodeStr := CodeStr + ResStr[Index]; if LowerCase(Copy(ResStr, Index, 7)) = 'value=''' then begin f := true; Inc(Index, 6); end; Inc(Index); end; if CodeStr = '' then begin Result := postNotDoc; Exit; end; if Assigned(AShowProgress) then AShowProgress('Заполнение формы данными'); Data.AddFormField('doc', CodeStr); Data.AddFormField(CFTitleNews, APostData.Title); Data.AddFormField(CFTextNews, APostData.Text); Data.AddFormField(CFLinkNews, APostData.InLink); if APostData.IsCat then begin Data.AddFormField(CFIsRazdel, '1'); Category := ''; s := LowerCase(APostData.Category); if s = 'Новости' then Category := '1' else if s = 'Железо' then Category := '13' else if s = 'Файлы' then Category := '2' else if s = 'Обзоры' then Category := '14' else if s = 'Мобилы' then Category := '3' else if s = 'Творчество' then Category := '15' else if s = 'Музыка' then Category := '9' else if s = 'Фильмы' then Category := '16' else if s = 'PDA' then Category := '10' else if s = 'Юмор' then Category := '17'else if s = 'Игры' then Category := '12' else if s = 'Другое' then Category := '18'; Data.AddFormField(CFRazdel, Category); end else begin Data.AddFormField(CFIsRazdel, ''); Data.AddFormField(CFRazdel, ''); end; Data.AddFormField('vopr', ''); Data.AddFormField('otv1', ''); Data.AddFormField('otv2', ''); Data.AddFormField('otv3', ''); Data.AddFormField('otv4', ''); Data.AddFormField('otv5', ''); Data.AddFormField('otv6', ''); Data.AddFormField('otv7', ''); Data.AddFormField('otv8', ''); Data.AddFormField('otv9', ''); Data.AddFormField('postn', 'Запостить новость'); if Assigned(AShowProgress) then AShowProgress('Отправка новости на сайт'); ResStr := FHTTP.Post(CPPost, Data); if Pos('<title> NoNaMe - скачать программы</title>', ResStr) <> 0 then Result := postNotPost else Result := postOk; except on E: EIdHTTPProtocolException do begin if E.ReplyErrorCode = 502 then Result := postNotServer else Result := postNotPost; end else Result := postNotPost; end; finally if Assigned(AShowProgress) then AShowProgress(''); FHTTP.Disconnect; Data.Free; end; end else Result := postNotLogin; end; function TPostingNNM.PrepareData(var APostData: TPostData; AShowProgress: TShowProgress): Boolean; var Text, ImgTxt, NewImg: string; Index: Integer; fimg: Boolean; begin // Подготовка новости к отправке // В частности, отправка изображений и получение нового адреса Result := False; if APostData.Text = '' then Exit; Text := ''; Index := 1; fimg := False; ImgTxt := ''; while Index <= Length(APostData.Text) do begin if fimg then ImgTxt := ImgTxt + APostData.Text[Index] else Text := Text + APostData.Text[Index]; if fimg and (LowerCase(Copy(APostData.Text, Index, 2)) = '"]') then begin fimg := False; ImgTxt := StringReplace(ImgTxt, '"', '', [rfreplaceAll, rfIgnoreCase]); if PostImage(ImgTxt, APostData.Doc.Adress, NewImg, AShowProgress) <> postOk then Exit; Text := Text + NewImg + ']'; Inc(Index); ImgTxt := ''; end; if LowerCase(Copy(APostData.Text, Index, 6)) = '[img="' then begin fimg := True; Text := Text + 'img='; Inc(Index, 5); end; Inc(Index); end; APostData.Text := Text; Result := True; end; function TPostingNNM.PrepareHTTP: Boolean; begin Result := Assigned(FHTTP); end; end.
unit core_game; {$mode objfpc}{$H+} interface uses Classes, SysUtils, core_types, core_terrain_generator, VectorGeometry, core_player, core_actor, core_orders, core_render,core_atmosphere, ui_main_menu, core_orders_manager; type { TGame } TGame = class public aliens:TPlayer; procedure setEnemies(p,pp:tplayer); //loads actors when map is loaded. //also sets controlledActorID for player1 if one of actors has name=player1 procedure loadActorsFromFile(const filename: string); procedure loadKnownItems(const path:string); procedure saveGame(const path: string); procedure loadGame(path: string); //procedure constructor create(playersCount:byte); destructor destroy;override; end; var game:tgame; implementation { TGame } procedure TGame.setEnemies(p, pp: tplayer); begin p.enemies+=[pp.playerID]; pp.enemies+=[p.playerID]; p.friends-=[pp.playerID]; pp.friends-=[p.playerID]; p.neutrals-=[pp.playerID]; pp.neutrals-=[p.playerID]; end; procedure TGame.saveGame(const path:string); begin terrain.saveMap(path+'map.terrain'); renderer.saveLights(path+'map.terrain'); end; procedure TGame.loadGame(path: string); var i:integer; begin log(format('loading map: %s',[ExtractFileName(path)])); //maybe here we can tell if it's single or multiplayer mode? //difference being that in multi, client shouldn't load map actors? //only terrain //multiPlayerMode could be simpy set when selectig it in main menu multiPlayerMode:=false;//multiMode; terrain.loadMap(path); renderer.loadLights(path); //dont load in multi client. actors will be spawned with commands from server path:=ChangeFileExt(path,'.actors'); if multiPlayerMode=false then begin loadActorsFromFile(path); //oM.addOrder(orToggleBrain,player1.actorID,0); //camera follow actor //oM.addCameraMode(player1.actorID,cmEdge); end else begin //in multiplayer there is no default player1 actor as we didn't load him from file //so we need to first login to remote server and get him or he needs to be already assigned when we get here om.addOrder(orLogin,0,0); end; //camera.setAboveGround(40); //loadKnownItems(extractfilepath(path)+'knownItems.txt'); //get control over actor0 end; procedure TGame.loadActorsFromFile(const filename: string); var i,j,actorID,faction,typ:integer; position:TAffineVector; str:tstringlist; a:tactor; o:rorder; key,value,name:string; begin if not fileexists(filename) then begin log('achtung! TGame.loadActorsFromFile:: file doesn''t exist: '+filename); exit; end; str:=TStringList.create; str.LoadFromFile(filename); i:=0;actorID:=-1;typ:=-1;faction:=0;name:='noname'; //reset id counter //lastActorID:=0; while i<str.Count do begin str.GetNameValue(i,key,value); if key='actorID' then begin actorID:=strtoint(value); end else if key='name' then begin Name:=value; end else if key='posX' then begin position[0]:=strtofloat(value); end else if key='posY' then begin position[1]:=strtofloat(value); end else if key='posZ' then begin position[2]:=strtofloat(value); end else if key='faction' then begin faction:=strtoint(value); end else if key='rotY' then begin faction:=strtoint(value); end else if key='typ' then begin typ:=strtoint(value); end else //u.position[0]:=f1;u.position[1]:=f2;u.position[2]:=f3; if value='[/actor]' then begin //actors.Add(a.actorID,a); //retain id links //if lastActorID<a.actorID then lastActorID:=a.actorID; //add an order and mark it as processed by logic j:=oM.addOrder; o:=om.queue[j]; //skip second create on logic update //o.eatenLogic:=true; o.order:=orCreateActor; o.int1:=actorID; o.int2:=typ; o.int3:=faction; o.v1:=position; om.queue[j]:=o; if name=player1.name then player1.actorID:=actorID; end; inc(i); end; str.free; end; procedure TGame.loadKnownItems(const path: string); var str:TStringList; i:integer; begin str:=TStringList.create; str.LoadFromFile(path); for i:=0 to str.count-1 do begin // alembik.getBlueprint(eItemTypes(GetEnumValue(typeinfo(eItemTypes),str[i]))).known:=true; end; str.free; end; constructor TGame.create(playersCount: byte); var i:integer; begin setlength(players,playersCount); for i:=0 to length(players)-1 do players[i]:=TPlayer.create(i); //if single player? player1:=players[0]; aliens:=players[1]; setEnemies(player1,aliens); player1.resources[byte(btStone)]:=100; player1.resources[byte(btRedSlab)]:=128; player1.resources[byte(btIron)]:=13; player1.resources[byte(btCopper)]:=25; oM.addOrder(orCameraMode,-1,integer(eCameraModes.cmEdge)); end; destructor TGame.destroy; var i:integer; begin for i:=0 to length(players)-1 do players[i].destroy; inherited; end; end.
unit uF16_tambahResep; {unit ini berguna untuk menambah resep masakan baru} //INTERFACE interface uses uP1_tipeBentukan, uF1_load; procedure mainTambahResep(ID : integer; var dataBahanMentah : tabelBahanMentah; var dataBahanOlahan : tabelBahanOlahan; var dataResep : tabelResep; var dataSimulasi : tabelSimulasi; var dataInventoriBahanMentah : tabelBahanMentah); function isResepExist(nama:string; var dataResep : tabelResep):boolean; //IMPLEMENTATION implementation //Prosedur Pembantu (1) function isResepExist(nama : string; var dataResep : tabelResep):boolean; {I.S : Menerima input sebuah nama resep F.S : Jikalai ternyata nama resep itu telah ada, maka fungsi ini akan mengeluarkan TRUE Kalau nama resep itu belum ada, keluarannya akan FALSE} {Kamus Lokal} var i : integer; found : boolean; {Algoritma} begin i:=1; found:=false; while (found=false) and ( i<=dataResep.banyakItem) do begin if dataResep.itemKe[i].nama=nama then begin found:=true; end else i:=i+1; end; if (found=true) then begin isResepExist:=true; end else isResepExist:=false; end; //Prosedur Pembantu (2) function hitungHargaModalResep(ID : integer; var dataBahanMentah : tabelBahanMentah; var dataBahanOlahan : tabelBahanOlahan; var dataResep : tabelResep; var dataInventoriBahanMentah : tabelBahanMentah):Integer; {Fungsi ini berguna untuk menghitung harga modal dari sebuah resep I.S : Menerima masukan berupa ID F.S : Mengeluarkan output berupa Integer yang adalah harga modal resep yang telah dikalkulasikan sedemikian rupa} {Kamus Lokal} var i, j : integer; {Algoritma} begin hitungHargaModalResep:=0; {inisialisai harga modal resep tersebut} for i:=1 to dataResep.banyakItem do begin for j:=1 to dataBahanMentah.banyakItem do begin if dataResep.itemKe[i].nama=dataBahanMentah.itemKe[j].nama then begin hitungHargaModalResep:=hitungHargaModalResep+dataBahanMentah.itemKe[j].hargaBeli; end; end; for j:=1 to dataBahanOlahan.banyakItem do begin if dataResep.itemKe[i].nama=dataBahanOlahan.itemKe[j].nama then begin hitungHargaModalResep:=hitungHargaModalResep+dataBahanOlahan.itemKe[j].hargaJual; end; end; end; end; //////////////////// // PROSEDUR UTAMA // //////////////////// procedure mainTambahResep(ID : integer; var dataBahanMentah : tabelBahanMentah; var dataBahanOlahan : tabelBahanOlahan; var dataResep : tabelResep; var dataSimulasi : tabelSimulasi; var dataInventoriBahanMentah : tabelBahanMentah); {I.S : Menerima masukan ID dan data-data lainnya F.S : Hasil nama resep dan bahan-bahan penyusunnya akan disimpan di dalam array-array} {Kamus Lokal} var nama : string; {nama resep baru yg dimasukin} found : boolean; i , j ,k : integer; {pencacah} n : integer; {jumlah bahan resep} {Algoritma} begin repeat write('Nama resep :'); readln(nama); if (isResepExist(nama,dataResep)=true) then {menggunakan fungsi isResepExist untuk mengecek apakah sudah ada resep dengan nama yang sama} begin writeln('Nama resep telah ada, masukan nama yang lain!'); {validasi nama resep} end; until (isResepExist(nama,dataResep)=false); repeat writeln('Masukkan jumlah bahan resep'); readln(n); if n<2 then begin writeln('Jumlah bahan resep tidak boleh kurang dari 2!'); end; until (n>=2); for k:=1 to n do i:=1; begin writeln('Masukkan nama bahan ke ',k); repeat readln(nama); found := false; {lalu dilakukan validasi apakah nama bahan resep ada di tabel nama inventori bahan mentah/olahan} while (found=false) do begin for j:=1 to dataBahanMentah.banyakItem do begin {dicek dulu, siapa tau nama bahan terbut ada di data inventori bahan mentah} if dataBahanMentah.itemKe[ID].nama[j]=nama then found:=true; end; for j:=1 to dataBahanOlahan.banyakItem do begin if dataBahanOlahan.itemKe[ID].nama[j]=nama then found:=true; end; writeln('Bahan tersebut tidak ada, silahkan masukkan nama bahan lain!'); end; until (found=true); dataResep.itemKe[ID].bahan[i]:=nama; i:=i+1; end; repeat write('Harga jual resep :'); read(dataResep.itemKe[ID].hargaJual); if (dataResep.itemKe[ID].hargaJual < (0.125 * hitungHargaModalResep(ID,dataBahanMentah,dataBahanOlahan,dataResep,dataInventoriBahanMentah))) then begin writeln('Harga jual minimum harus 12,5% lebih tinggi dari harga modal!'); {proses validasi harga jual resep tersebut} end; until ((dataResep.itemKe[ID].hargaJual >= (0.125 * hitungHargaModalResep(ID,dataBahanMentah,dataBahanOlahan,dataResep,dataInventoriBahanMentah)))); end; end.
unit uFramework; interface type // Abstract Class TCorrecao = class abstract procedure Iniciar(); virtual; abstract; procedure Corrigir(); virtual; abstract; procedure Finalizar(); virtual; abstract; procedure Processar(); end; // Concrete Class TCorrecaoProva = class(TCorrecao) procedure Iniciar(); override; procedure Corrigir(); override; procedure Finalizar(); override; end; // Concrete Class TCorrecaoRedacao = class(TCorrecao) procedure Iniciar(); override; procedure Corrigir(); override; procedure Finalizar(); override; end; implementation { TCorrecao } procedure TCorrecao.Processar(); begin // chamo métodos virtuais de mim mesmo // sobrescritos nas subclasses Iniciar(); // aqui posso colocar um passo adicional // como um factory method Corrigir(); Finalizar(); end; { TCorrecaoProva } procedure TCorrecaoProva.Corrigir(); begin WriteLn('Corrigindo Prova'); end; procedure TCorrecaoProva.Finalizar(); begin WriteLn('Finalizando correção da Prova'); end; procedure TCorrecaoProva.Iniciar(); begin WriteLn('Iniciando correção da Prova'); end; { TCorrecaoRedacao } procedure TCorrecaoRedacao.Corrigir(); begin WriteLn('Corrigindo Redação'); end; procedure TCorrecaoRedacao.Finalizar(); begin WriteLn('Finalizando correção da Redação'); end; procedure TCorrecaoRedacao.Iniciar(); begin WriteLn('Iniciando correção da Redação'); end; end.
unit uPedidoItemModel; interface type TPedidoItemModel = class private FIDPed: Integer; FIDItem: Integer; FIDItemSeq: Integer; FQuantidade: Double; FValorUnitario: Double; FDescricao: String; public function ValidarDadosObrigatorios(out sMsg: String) : Integer; published property IDPed: Integer read FIDPed write FIDPed; property IDItem: Integer read FIDItem write FIDItem; property IDItemSeq: Integer read FIDItemSeq write FIDItemSeq; property Quantidade: Double read FQuantidade write FQuantidade; property ValorUnitario: Double read FValorUnitario write FValorUnitario; property Descricao: String read FDescricao write FDescricao; end; implementation { TPedidoItemModel } function TPedidoItemModel.ValidarDadosObrigatorios(out sMsg: String): Integer; begin if (FQuantidade <= 0) then begin sMsg := 'A quantidade deve ser maior que zero!'; Result := -1; Exit; end; if (FValorUnitario <= 0) then begin sMsg := 'O valor unitário deve ser maior que zero!'; Result := -1; Exit; end; Result := 1; end; end.
unit ufrmCadCargo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmModeloCad, Data.DB, IBCustomDataSet, IBQuery, Vcl.ComCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls; type TfrmCadCargo = class(TfrmModeloCad) EDTPESCARGO: TEdit; Label3: TLabel; CKTODOS: TCheckBox; pFundoCargo: TPanel; Label1: TLabel; EdtCargo: TEdit; Label2: TLabel; EdtTipo: TEdit; qrySelectID_CARGO: TIntegerField; qrySelectDESCRICAO: TIBStringField; qrySelectTIPO: TIBStringField; procedure pAtualizaCargo; procedure pCarregarEdit(vID_cargo : Integer); procedure pGravarAtualizarDeletar(vStatus : String; vID_CARGO: Integer); procedure btnNovoClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CKTODOSClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnFiltrarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure gGridPesquisaDblClick(Sender: TObject); procedure gGridPesquisaCellClick(Column: TColumn); procedure btnPrimeiroClick(Sender: TObject); procedure btnAnteriorClick(Sender: TObject); procedure btnProximoClick(Sender: TObject); procedure btnUltimoClick(Sender: TObject); procedure gGridPesquisaKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); private { Private declarations } vStatus : string; public { Public declarations } end; var frmCadCargo: TfrmCadCargo; implementation {$R *.dfm} uses ufrmPrincipal, uModule; procedure TfrmCadCargo.btnAnteriorClick(Sender: TObject); begin inherited; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); end; procedure TfrmCadCargo.btnEditarClick(Sender: TObject); begin inherited; vStatus :='EDITAR'; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); EdtCargo.SetFocus; end; procedure TfrmCadCargo.btnExcluirClick(Sender: TObject); var vPergunta : Integer; begin inherited; vPergunta := MessageBox(Handle, pchar('Deseja excluir esse registro ?') , pchar(NomeSistema), 36); if vPergunta = 6 then begin pGravarAtualizarDeletar('DELETAR',qrySelect.FieldByName('ID_CARGO').AsInteger); pAtualizaCargo; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); end; end; procedure TfrmCadCargo.btnFiltrarClick(Sender: TObject); begin inherited; pAtualizaCargo; end; procedure TfrmCadCargo.btnGravarClick(Sender: TObject); var vPergunta :Integer; begin vPergunta := MessageBox(Handle, pchar('Deseja gravar esse registro ?') , pchar(NomeSistema), 36); if vPergunta = 6 then begin pGravarAtualizarDeletar(vStatus,qrySelect.FieldByName('ID_CARGO').AsInteger); Module.IBTransaction.CommitRetaining; end; inherited; pAtualizacargo; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); end; procedure TfrmCadCargo.btnNovoClick(Sender: TObject); begin inherited; vStatus := 'NOVO'; EdtCargo.SetFocus; end; procedure TfrmCadCargo.btnPrimeiroClick(Sender: TObject); begin inherited; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); end; procedure TfrmCadCargo.btnProximoClick(Sender: TObject); begin inherited; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); end; procedure TfrmCadCargo.btnUltimoClick(Sender: TObject); begin inherited; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); end; procedure TfrmCadCargo.CKTODOSClick(Sender: TObject); begin inherited; if CKTODOS.State = cbChecked then begin EDTPESCARGO.Enabled := false; EDTPESCARGO.Text := ''; end else begin EDTPESCARGO.Enabled := true; EDTPESCARGO.SetFocus; end; end; procedure TfrmCadCargo.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; frmCadCargo := nil; end; procedure TfrmCadCargo.FormShow(Sender: TObject); begin inherited; pAtualizaCargo; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); end; procedure TfrmCadCargo.gGridPesquisaCellClick(Column: TColumn); begin inherited; pCarregarEdit(qrySelect.FieldByName('ID_CARGO').AsInteger); end; procedure TfrmCadCargo.gGridPesquisaDblClick(Sender: TObject); begin inherited; pFundoCargo.Enabled := true; pcGuia.TabIndex := 1; pCarregarEdit(qrySelect.FieldByName('ID_cargo').AsInteger); end; procedure TfrmCadCargo.gGridPesquisaKeyPress(Sender: TObject; var Key: Char); begin inherited; if (key = #13) and (pcGuia.TabIndex = 0) then begin pCarregarEdit(qrySelect.FieldByName('ID_cargo').AsInteger); pcGuia.TabIndex := 1; pFundoCargo.Enabled := True; end; end; procedure TfrmCadcargo.pCarregarEdit(vID_cargo : Integer); var qryCarregar : TIBQuery; begin qryCarregar := TIBQuery.Create(Self); with qryCarregar do begin Database := Module.IBLOJAHS; Transaction := Module.IBTransaction; Close; SQL.Clear; SQL.Add('SELECT * FROM CARGO '); SQL.Add('WHERE ID_CARGO = :ID_CARGO '); ParamByName('ID_CARGO').AsInteger := vID_CARGO; Open; EdtCargo.Text := FieldByName('DESCRICAO').AsString; EdtTipo.Text := FieldByName('TIPO').AsString; end; FreeAndNil(qryCarregar); end; procedure TfrmCadcargo.pGravarAtualizarDeletar(vStatus: String; vID_cargo: Integer); begin qryGravar.Database := Module.IBLOJAHS; qryGravar.Transaction := Module.IBTransaction; if vStatus = 'NOVO' then begin with qryGravar do begin Close; SQL.Clear; SQL.Add(' INSERT INTO CARGO '); SQL.Add(' ( '); SQL.Add(' ID_CARGO, DESCRICAO, TIPO '); SQL.Add(' ) '); SQL.Add(' VALUES '); SQL.Add(' ( '); SQL.Add(' :ID_CARGO, :DESCRICAO, :TIPO '); SQL.Add(' ) '); ParamByName('ID_CARGO').AsInteger := 0; end; end else if vStatus = 'EDITAR' then begin with qryGravar do begin Close; SQL.Clear; SQL.Add(' UPDATE CARGO SET DESCRICAO = :DESCRICAO, TIPO = :TIPO '); SQL.Add(' WHERE ID_CARGO = :ID_CARGO '); ParamByName('ID_CARGO').Value := vID_CARGO; end; end else begin with qryGravar do begin Close; SQL.Clear; SQL.Add(' DELETE FROM CARGO '); SQL.Add(' WHERE ID_CARGO = :ID_CARGO '); ParamByName('ID_CARGO').Value := vID_CARGO; end; end; if vStatus <> 'DELETAR' then begin with qryGravar do begin ParamByName('DESCRICAO').AsString := EdtCargo.Text; ParamByName('TIPO').AsString := EdtTipo.Text; end; end; qryGravar.ExecSQL; Module.IBTransaction.CommitRetaining; end; procedure TfrmCadcargo.pAtualizaCargo; begin with qrySelect do begin Close; SQL.Clear; sql.Add('SELECT ID_CARGO, DESCRICAO, TIPO'); sql.Add('FROM CARGO '); SQL.Add('WHERE (1 = 1) '); if CKTODOS.Checked = FALSE then begin SQL.Add('AND upper(DESCRICAO) LIKE upper(:CARGO)'); ParamByName('CARGO').AsString := '%'+EDTPESCARGO.TEXT+'%'; end; Open; end; end; end.
{******************************************************************************} { } { Delphi SwagDoc Library } { Copyright (c) 2018 Marcelo Jaloto } { https://github.com/marcelojaloto/SwagDoc } { } {******************************************************************************} { } { 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 Sample.Main; 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.ScrollBox, FMX.Memo; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses Sample.SwagDoc; procedure TForm1.Button1Click(Sender: TObject); var vSampleDocApi: TSampleApiSwagDocBuilder; begin vSampleDocApi := TSampleApiSwagDocBuilder.Create; try vSampleDocApi.DeployFolder := ExtractFilePath(ParamStr(0)); memo1.Lines.Text := vSampleDocApi.Generate; finally vSampleDocApi.Free; end; end; initialization ReportMemoryLeaksOnShutdown := True; end.
unit SendDebtTest; interface uses dbTest, dbMovementTest, ObjectTest; type TSendDebtTest = class (TdbMovementTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TSendDebt = class(TMovementTest) private function InsertDefault: integer; override; public function InsertUpdateSendDebt(const Id: integer): integer; constructor Create; override; end; implementation uses UtilConst, JuridicalTest, dbObjectTest, SysUtils, Db, TestFramework; { TSendDebt } constructor TSendDebt.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Movement_SendDebt'; spSelect := 'gpSelect_Movement_SendDebt'; spGet := 'gpGet_Movement_SendDebt'; end; function TSendDebt.InsertDefault: integer; var Id: Integer; begin Id:=0; result := InsertUpdateSendDebt(Id); end; function TSendDebt.InsertUpdateSendDebt(const Id: integer): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); { FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber); FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate); FParams.AddParam('inStartRunPlan', ftDateTime, ptInput, StartRunPlan); FParams.AddParam('inEndRunPlan', ftDateTime, ptInput, EndRunPlan); FParams.AddParam('inStartRun', ftDateTime, ptInput, StartRun); FParams.AddParam('inEndRun', ftDateTime, ptInput, EndRun); FParams.AddParam('inHoursAdd', ftFloat, ptInput, HoursAdd); FParams.AddParam('inComment', ftString, ptInput, Comment); FParams.AddParam('inCarId', ftInteger, ptInput, CarId); FParams.AddParam('inCarTrailerId', ftInteger, ptInput, CarTrailerId); FParams.AddParam('inPersonalDriverId', ftInteger, ptInput, PersonalDriverId); FParams.AddParam('inPersonalDriverMoreId', ftInteger, ptInput, PersonalDriverMoreId); FParams.AddParam('inUnitForwardingId', ftInteger, ptInput, UnitForwardingId); result := InsertUpdate(FParams); } end; { TSendDebtTest } procedure TSendDebtTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'Movement\SendDebt\'; inherited; ScriptDirectory := ProcedurePath + 'MovementItem\SendDebt\'; inherited; ScriptDirectory := ProcedurePath + 'MovementItemContainer\SendDebt\'; inherited; end; procedure TSendDebtTest.Test; var MovementSendDebt: TSendDebt; Id: Integer; begin inherited; // Создаем документ MovementSendDebt := TSendDebt.Create; Id := MovementSendDebt.InsertDefault; // создание документа try // редактирование finally end; end; initialization TestFramework.RegisterTest('Документы', TSendDebtTest.Suite); end.
unit DSharp.Core.Times.Tests; interface implementation uses DSharp.Core.Times, TestFramework; type TTimesTestCase = class(TTestCase) private FTimes: Times; published procedure Verify_AtLeastOnce_One_True; procedure Verify_AtLeastOnce_Two_True; procedure Verify_AtLeastOnce_Zero_False; procedure Verify_AtLeastZero_One_True; procedure Verify_AtLeastZero_Zero_True; procedure Verify_AtMostOnce_One_True; procedure Verify_AtMostOnce_Two_True; procedure Verify_AtMostOnce_Zero_True; procedure Verify_AtMostZero_One_False; procedure Verify_AtMostZero_Zero_True; procedure Verify_BetweenOneAndTwo_One_True; procedure Verify_BetweenOneAndTwo_Three_False; procedure Verify_BetweenOneAndTwo_Two_True; procedure Verify_BetweenOneAndTwo_Zero_False; procedure Verify_ExactlyOnce_One_True; procedure Verify_ExactlyOnce_Two_False; procedure Verify_ExactlyOnce_Zero_False; procedure Verify_ExactlyZero_One_False; procedure Verify_ExactlyZero_Zero_True; end; { TTimesTestCase } procedure TTimesTestCase.Verify_AtLeastOnce_One_True; begin FTimes := Times.AtLeastOnce; CheckTrue(FTimes.Verify(1)); end; procedure TTimesTestCase.Verify_AtLeastOnce_Two_True; begin FTimes := Times.AtLeastOnce; CheckTrue(FTimes.Verify(2)); end; procedure TTimesTestCase.Verify_AtLeastOnce_Zero_False; begin FTimes := Times.AtLeastOnce; CheckFalse(FTimes.Verify(0)); end; procedure TTimesTestCase.Verify_AtLeastZero_One_True; begin FTimes := Times.AtLeast(0); CheckTrue(FTimes.Verify(1)); end; procedure TTimesTestCase.Verify_AtLeastZero_Zero_True; begin FTimes := Times.AtLeast(0); CheckTrue(FTimes.Verify(0)); end; procedure TTimesTestCase.Verify_AtMostOnce_One_True; begin FTimes := Times.AtMostOnce; CheckTrue(FTimes.Verify(1)); end; procedure TTimesTestCase.Verify_AtMostOnce_Two_True; begin FTimes := Times.AtMostOnce; CheckFalse(FTimes.Verify(2)); end; procedure TTimesTestCase.Verify_AtMostOnce_Zero_True; begin FTimes := Times.AtMostOnce; CheckTrue(FTimes.Verify(0)); end; procedure TTimesTestCase.Verify_AtMostZero_One_False; begin FTimes := Times.AtMost(0); CheckFalse(FTimes.Verify(1)); end; procedure TTimesTestCase.Verify_AtMostZero_Zero_True; begin FTimes := Times.AtMost(0); CheckTrue(FTimes.Verify(0)); end; procedure TTimesTestCase.Verify_BetweenOneAndTwo_One_True; begin FTimes := Times.Between(1, 2); CheckTrue(FTimes.Verify(1)); end; procedure TTimesTestCase.Verify_BetweenOneAndTwo_Three_False; begin FTimes := Times.Between(1, 2); CheckFalse(FTimes.Verify(3)); end; procedure TTimesTestCase.Verify_BetweenOneAndTwo_Two_True; begin FTimes := Times.Between(1, 2); CheckTrue(FTimes.Verify(2)); end; procedure TTimesTestCase.Verify_BetweenOneAndTwo_Zero_False; begin FTimes := Times.Between(1, 2); CheckFalse(FTimes.Verify(0)); end; procedure TTimesTestCase.Verify_ExactlyOnce_One_True; begin FTimes := Times.Exactly(1); CheckTrue(FTimes.Verify(1)); end; procedure TTimesTestCase.Verify_ExactlyOnce_Two_False; begin FTimes := Times.Exactly(1); CheckFalse(FTimes.Verify(2)); end; procedure TTimesTestCase.Verify_ExactlyOnce_Zero_False; begin FTimes := Times.Exactly(1); CheckFalse(FTimes.Verify(0)); end; procedure TTimesTestCase.Verify_ExactlyZero_One_False; begin FTimes := Times.Exactly(0); CheckFalse(FTimes.Verify(1)); end; procedure TTimesTestCase.Verify_ExactlyZero_Zero_True; begin FTimes := Times.Exactly(0); CheckTrue(FTimes.Verify(0)); end; initialization RegisterTest('DSharp.Core.Times', TTimesTestCase.Suite); end.
unit FormUtama; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, ComCtrls; type { TFormMorphology } TFormMorphology = class(TForm) btnLoad: TButton; btnMorphAND: TButton; btnMorphAND3: TButton; btnMorphOR: TButton; btnSave: TButton; btnGray: TButton; btnBiner: TButton; btnMorph: TButton; editBiner: TEdit; imgMorphAND3: TImage; imgMorphOR: TImage; imgMorphAND: TImage; imgBiner: TImage; imgGray: TImage; imgOri: TImage; txtMorphAND: TLabel; txtMorphAND3: TLabel; txtMorphOR: TLabel; txtBiner: TLabel; txtGray: TLabel; txtOriginal: TLabel; openDialog: TOpenDialog; saveDialog: TSaveDialog; tBarBiner: TTrackBar; procedure btnBinerClick(Sender: TObject); procedure btnGrayClick(Sender: TObject); procedure btnLoadClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure editBinerChange(Sender: TObject); private public end; var FormMorphology: TFormMorphology; implementation {$R *.lfm} { TFormMorphology } uses Windows; var bmpR, bmpG, bmpB: array[0..1000, 0..1000] of byte; procedure TFormMorphology.btnLoadClick(Sender: TObject); var x, y: integer; begin if openDialog.Execute then begin imgOri.Picture.LoadFromFile(openDialog.FileName); for y:=0 to imgOri.Height-1 do begin for x:=0 to imgOri.Width-1 do begin bmpR[x,y] := getRValue(imgOri.Canvas.Pixels[x,y]); bmpG[x,y] := getGValue(imgOri.Canvas.Pixels[x,y]); bmpB[x,y] := getBValue(imgOri.Canvas.Pixels[x,y]); end; end; end; end; procedure TFormMorphology.btnGrayClick(Sender: TObject); var x, y: integer; gray: byte; begin for y:=0 to imgGray.Height-1 do begin for x:=0 to imgGray.Width-1 do begin gray := (bmpR[x,y] + bmpG[x,y] + bmpB[x,y]) div 3; imgGray.Canvas.Pixels[x,y] := RGB(gray, gray, gray); end; end; end; procedure TFormMorphology.btnBinerClick(Sender: TObject); var x, y: integer; gray: byte; begin for y:=0 to imgBiner.Height-1 do begin for x:=0 to imgBiner.Width-1 do begin gray := (bmpR[x,y] + bmpG[x,y] + bmpB[x,y]) div 3; if (gray <= tBarBiner.Position) then begin imgBiner.Canvas.Pixels[x,y] := RGB(0, 0, 0); end else begin imgBiner.Canvas.Pixels[x,y] := RGB(255, 255, 255); end; end; end; end; procedure TFormMorphology.btnSaveClick(Sender: TObject); var x, y: integer; begin if saveDialog.Execute then begin imgMorphAND.Picture.SaveToFile(SaveDialog.FileName); end; end; procedure TFormMorphology.editBinerChange(Sender: TObject); begin editBiner.Text := IntToStr(tBarBiner.Position); end; end.
unit dmIntuit; interface uses System.SysUtils , System.Classes , System.JSON , System.IOUtils , REST.Types , REST.Client , REST.Authenticator.OAuth , System.Net.URLClient , Data.Bind.Components , Data.Bind.ObjectScope , JSON.InvoiceList , JSON.AttachableList , OAuth2.Intuit , fmLogin ; type TOnLogStatus = procedure(inText: string) of object; TdmIntuitAPI = class(TDataModule) RESTResponse1: TRESTResponse; RESTRequest1: TRESTRequest; RESTClient1: TRESTClient; procedure DataModuleDestroy(Sender: TObject); procedure DataModuleCreate(Sender: TObject); strict private FrealmId : String; FOnLog : TOnLogStatus; FfrmLogin: TfrmLogin; procedure doLog(inText: string); private { Private declarations } public { Public declarations } OAuth2Authenticator1: TIntuitOAuth2; function CreateInvoice(invoice: TInvoiceClass): TInvoiceClass; procedure SetupInvoice(invoice: TInvoiceClass; TxnDate: TDate; invoiceID: String); procedure UploadAttachment(inFilename, inInvoiceID: string); procedure ChangeRefreshTokenToAccessToken; procedure ShowLoginForm; published property RealmId : string read FrealmId write FrealmId; end; var dmIntuitAPI: TdmIntuitAPI; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses secrets ; procedure TdmIntuitAPI.DataModuleDestroy(Sender: TObject); begin FreeAndNil(OAuth2Authenticator1); FreeAndNil(FfrmLogin); end; procedure TdmIntuitAPI.DataModuleCreate(Sender: TObject); begin OAuth2Authenticator1 := TIntuitOAuth2.Create(nil); OAuth2Authenticator1.AuthorizationEndpoint := 'https://appcenter.intuit.com/connect/oauth2'; OAuth2Authenticator1.AccessTokenEndpoint := 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer'; OAuth2Authenticator1.RedirectionEndpoint := 'https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl'; OAuth2Authenticator1.Scope := 'com.intuit.quickbooks.accounting openid profile email phone address'; OAuth2Authenticator1.ClientID := SECRET_INTUIT_CLIENTID; OAuth2Authenticator1.ClientSecret := SECRET_INTUIT_CLIENTSECRET; OAuth2Authenticator1.ResponseType := TOAuth2ResponseType.rtCODE; RESTClient1.Authenticator := OAuth2Authenticator1; FfrmLogin := TfrmLogin.Create(nil); end; procedure TdmIntuitAPI.ChangeRefreshTokenToAccessToken; begin OAuth2Authenticator1.RefreshToken := FfrmLogin.GetRefreshToken; RealmId := SECRET_REALMID; OAuth2Authenticator1.ChangeRefreshTokenToAccesToken; end; function TdmIntuitAPI.CreateInvoice(invoice: TInvoiceClass): TInvoiceClass; var invoiceJSON: TJSONObject; invoiceText: string; retJSON : TJSONObject; begin RESTRequest1.ResetToDefaults; RESTResponse1.ResetToDefaults; invoiceJSON := TJSONObject.ParseJSONValue(invoice.ToJsonString) as TJSONObject; invoiceJSON.RemovePair('allowIPNPayment'); invoiceJSON.RemovePair('allowOnlineACHPayment'); invoiceJSON.RemovePair('allowOnlinePayment'); invoiceJSON.RemovePair('allowOnlineCreditCardPayment'); invoiceJSON.RemovePair('CreditCardPayment'); invoiceJSON.RemovePair('EmailStatus'); invoiceJSON.RemovePair('Balance'); invoiceJSON.RemovePair('Deposit'); invoiceJSON.RemovePair('DocNumber'); invoiceJSON.RemovePair('Id'); invoiceJSON.RemovePair('DueDate'); invoiceJSON.RemovePair('TxnSource'); invoiceJSON.RemovePair('GlobalTaxCalculation'); invoiceJSON.RemovePair('MetaData'); invoiceJSON.RemovePair('TotalAmt'); invoiceJSON.RemovePair('domain'); invoiceJSON.RemovePair('sparse'); invoiceText := invoiceJSON.ToJSON; doLog(invoiceText); RESTRequest1.Method := rmPost; FrealmID := SECRET_REALMID; RESTRequest1.Resource := '/v3/company/' + FrealmId + '/invoice?minorversion=38'; RESTRequest1.AddBody(invoiceText, ctAPPLICATION_JSON); RESTRequest1.Execute; doLog(RESTResponse1.Content); retJSON := TJSONObject.ParseJSONValue(RESTResponse1.Content) as TJSONObject; try Result := TInvoiceClass.FromJsonString(retJSON.Values['Invoice'].ToJSON); finally FreeAndNil(retJSON); end; end; procedure TdmIntuitAPI.SetupInvoice(invoice: TInvoiceClass; TxnDate:TDate; invoiceID:String); begin invoice.CurrencyRef.name := 'Australian Dollar'; invoice.CurrencyRef.value := 'AUD'; invoice.CustomerRef.name := SECRET_CUSTOMER_NAME; invoice.CustomerRef.value := SECRET_CUSTOMER_ID; invoice.EmailStatus := 'NotSet'; invoice.GlobalTaxCalculation := 'NotApplicable'; invoice.PrintStatus := 'NotSet'; invoice.SyncToken := '0'; invoice.domain := 'QBO'; invoice.TxnDate := FormatDatetime('yyyy-mm-dd', TxnDate); //'2019-05-30'; invoice.CustomerMemo.value := invoiceID; invoice.TrackingNum := invoiceID; end; procedure TdmIntuitAPI.doLog(inText: string); begin if Assigned(FOnLog) then FOnLog(inText); end; procedure TdmIntuitAPI.ShowLoginForm; var uri : TURI; begin uri := TURI.Create('https://appcenter.intuit.com/connect/oauth2'); uri.AddParameter('client_id', SECRET_INTUIT_CLIENTID); uri.AddParameter('client_secret', SECRET_INTUIT_CLIENTSECRET); uri.AddParameter('scope', 'com.intuit.quickbooks.accounting'); uri.AddParameter('redirect_uri', SECRET_REDIRECT_URL); uri.AddParameter('state', '2342342323'); uri.AddParameter('response_type', 'code'); FfrmLogin.Login(uri.ToString); end; procedure TdmIntuitAPI.UploadAttachment(inFilename:string; inInvoiceID:string); var attachable : TAttachableClass; attachableRefArr : TArray<TAttachableRefClass>; attachableRef : TAttachableRefClass; attachJSON : TJSONObject; RequestStream : TStringStream; param : TRESTRequestParameter; begin if not TFile.Exists(inFilename) then begin raise Exception.Create('File Does not exist - ' + inFilename); end; attachable := TAttachableClass.Create; attachable.ContentType := 'application/pdf'; attachable.FileName := ExtractFileName(inFilename); attachableRefArr := TArray<TAttachableRefClass>.Create(); SetLength(attachableRefArr, 1); attachableRef := TAttachableRefClass.Create; attachableRefArr[0] := attachableRef; attachableRef.EntityRef.&type := 'Invoice'; attachableRef.EntityRef.value := inInvoiceID; attachableRef.IncludeOnSend := False; attachable.AttachableRef := attachableRefArr; RESTRequest1.Method := rmPOST; RESTRequest1.Resource := '/v3/company/' + RealmId + '/upload'; DoLog(attachable.ToJsonString); DoLog('--------'); attachJSON := TJSONObject.ParseJSONValue(attachable.ToJsonString) as TJSONObject; attachJSON.RemovePair('MetaData'); attachJSON.RemovePair('Id'); attachJSON.RemovePair('Size'); attachJSON.RemovePair('TempDownloadUri'); attachJSON.RemovePair('domain'); attachJSON.RemovePair('sparse'); attachJSON.RemovePair('SyncToken'); RESTRequest1.ClearBody; // This workaround is required to get around a bug in the Delphi REST Components param := RESTRequest1.Params.AddItem('file_metadata_01', '', TRESTRequestParameterKind.pkREQUESTBODY, [], TRESTContentType.ctAPPLICATION_JSON); RequestStream := TStringStream.Create; try RequestStream.WriteString(attachjson.ToJSON); param.SetStream(RequestStream); finally FreeAndNil(RequestStream); end; // End workaround RESTRequest1.AddFile('file_content_01', inFilename, TRESTContentType.ctAPPLICATION_PDF); RESTRequest1.Execute; DoLog(attachJSON.ToJSON); DoLog('--------'); DoLog(RESTResponse1.Content); end; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Core.Exceptions; interface uses System.SysUtils, System.Rtti, WiRL.Core.JSON, WiRL.Core.Context, WiRL.http.Response; type Pair = record public Name: string; Value: TValue; class function S(const AName: string; const AValue: string): Pair; static; class function B(const AName: string; AValue: Boolean): Pair; static; class function N(const AName: string; AValue: Integer): Pair; static; class function F(const AName: string; AValue: Currency): Pair; static; class function D(const AName: string; AValue: TDateTime): Pair; static; function ToJSONValue: TJSONValue; function ToJSONPair: TJSONPair; end; TExceptionValues = array of Pair; TValuesUtil = class class function MakeValueArray(APair1: Pair): TExceptionValues; overload; static; class function MakeValueArray(APair1, APair2: Pair): TExceptionValues; overload; static; class function MakeValueArray(APair1, APair2, APair3: Pair): TExceptionValues; overload; static; end; EWiRLException = class(Exception); /// <summary> /// This exception may be thrown by a resource method if a specific HTTP error response needs to be produced. /// </summary> EWiRLWebApplicationException = class(EWiRLException) private FValues: TJSONObject; FStatus: Integer; procedure CreateAndFillValues; public /// <summary> /// Construct an exception with a blank message and default HTTP status code of 500. /// </summary> constructor Create; overload; /// <summary> /// Construct an exception with specified message and default HTTP status code of 500. /// </summary> constructor Create(const AMessage: string); overload; /// <summary> /// Construct an exception with specified message and specified HTTP status code. /// </summary> constructor Create(const AMessage: string; AStatus: Integer); overload; /// <summary> /// Construct a web exception with optional values /// </summary> /// <param name="AMessage">The exception's message</param> /// <param name="AStatus">The HTTP status</param> /// <param name="AValues">Optional values that will go in the data part</param> constructor Create(const AMessage: string; AStatus: Integer; AValues: TExceptionValues); overload; /// <summary> /// Construct a web exception with an inner exception already trapped /// </summary> /// <param name="AInnerException">The inner exception object</param> /// <param name="AStatus">The HTTP status</param> /// <param name="AValues">Optional values (will be put in "data" sub-section)</param> constructor Create(AInnerException: Exception; AStatus: Integer; AValues: TExceptionValues); overload; /// <summary> /// Construct a web exception with optional values /// </summary> /// <param name="AMessage">The exception's message</param> /// <param name="AStatus">The HTTP status</param> /// <param name="AJObject">Optional JSON object (will be put in "data" sub-section)</param> constructor Create(const AMessage: string; AStatus: Integer; AJObject: TJSONObject); overload; destructor Destroy; override; class function ExceptionToJSON(E: Exception): string; class procedure HandleException(AContext: TWiRLContext; E: Exception); static; function ToJSON: string; property Status: Integer read FStatus write FStatus; end; // Client errors (400) EWiRLNotFoundException = class(EWiRLWebApplicationException) public constructor Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); end; EWiRLNotAuthorizedException = class(EWiRLWebApplicationException) public constructor Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); end; EWiRLNotAcceptableException = class(EWiRLWebApplicationException) public constructor Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); end; EWiRLUnsupportedMediaTypeException = class(EWiRLWebApplicationException) public constructor Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); end; // Server errors (500) EWiRLServerException = class(EWiRLWebApplicationException) public constructor Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); end; EWiRLNotImplementedException = class(EWiRLWebApplicationException) public constructor Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); end; implementation uses System.TypInfo, WiRL.http.Accept.MediaType, WiRL.Core.Application; { Pair } class function Pair.B(const AName: string; AValue: Boolean): Pair; begin Result.Name := AName; Result.Value := TValue.From<Boolean>(AValue); end; class function Pair.D(const AName: string; AValue: TDateTime): Pair; begin Result.Name := AName; Result.Value := TValue.From<TDateTime>(AValue); end; class function Pair.F(const AName: string; AValue: Currency): Pair; begin Result.Name := AName; Result.Value := TValue.From<Currency>(AValue); end; class function Pair.N(const AName: string; AValue: Integer): Pair; begin Result.Name := AName; Result.Value := TValue.From<Integer>(AValue); end; class function Pair.S(const AName: string; const AValue: string): Pair; begin Result.Name := AName; Result.Value := TValue.From<string>(AValue); end; function Pair.ToJSONPair: TJSONPair; begin Result := TJSONPair.Create(Name, ToJSONValue); end; function Pair.ToJSONValue: TJSONValue; var LDate: Double; begin Result := nil; if Value.IsType<TDateTime> then begin LDate := Value.AsCurrency; if Trunc(LDate) = 0 then Result := TJSONString.Create(FormatDateTime('hh:nn:ss:zzz', LDate)) else if Frac(LDate) = 0 then Result := TJSONString.Create(FormatDateTime('yyyy-mm-dd', LDate)) else Result := TJSONString.Create(FormatDateTime('yyyy-mm-dd hh:nn:ss:zzz', LDate)) end else if Value.IsType<Boolean> then begin if Value.AsBoolean then Result := TJSONTrue.Create else Result := TJSONFalse.Create end else case Value.Kind of tkUnknown: Result := TJSONString.Create('type:unknown'); tkInteger: Result := TJSONNumber.Create(Value.AsCurrency); tkChar: Result := TJSONString.Create(Value.AsString); tkEnumeration: Result := TJSONString.Create('type:enumeration'); tkFloat: Result := TJSONNumber.Create(Value.AsCurrency); tkString: Result := TJSONString.Create(Value.AsString); tkSet: Result := TJSONString.Create(Value.AsString); tkClass: Result := TJSONString.Create(Value.AsObject.ToString); tkMethod: Result := TJSONString.Create('type:method'); tkWChar: Result := TJSONString.Create(Value.AsString); tkLString: Result := TJSONString.Create(Value.AsString); tkWString: Result := TJSONString.Create(Value.AsString); tkVariant: Result := TJSONString.Create(Value.AsString); tkArray: Result := TJSONString.Create('type:array'); tkRecord: Result := TJSONString.Create('type:record'); tkInterface: Result := TJSONString.Create('type:interface'); tkInt64: Result := TJSONNumber.Create(Value.AsInt64); tkDynArray: Result := TJSONString.Create('type:dynarray'); tkUString: Result := TJSONString.Create(Value.AsString); tkClassRef: Result := TJSONString.Create(Value.AsClass.ClassName); tkPointer: Result := TJSONNumber.Create(Value.AsInteger); tkProcedure: Result := TJSONString.Create('type:procedure'); end; end; { EWiRLWebApplicationException } constructor EWiRLWebApplicationException.Create; begin Create('', 500); end; constructor EWiRLWebApplicationException.Create(const AMessage: string); begin Create(AMessage, 500); end; constructor EWiRLWebApplicationException.Create(const AMessage: string; AStatus: Integer); begin inherited Create(AMessage); FStatus := AStatus; CreateAndFillValues; end; constructor EWiRLWebApplicationException.Create(const AMessage: string; AStatus: Integer; AValues: TExceptionValues); var LPair: Pair; LData: TJSONObject; begin Create(AMessage, AStatus); if Length(AValues) > 0 then begin LData := TJSONObject.Create; FValues.AddPair('data', LData); for LPair in AValues do if not LPair.Value.IsEmpty then LData.AddPair(LPair.ToJSONPair); end; end; constructor EWiRLWebApplicationException.Create(const AMessage: string; AStatus: Integer; AJObject: TJSONObject); var LData: TJSONObject; begin Create(AMessage, AStatus); if Assigned(AJObject) then begin LData := (AJObject.Clone as TJSONObject); FValues.AddPair('data', LData); end; end; constructor EWiRLWebApplicationException.Create(AInnerException: Exception; AStatus: Integer; AValues: TExceptionValues); begin Create(AInnerException.Message, AStatus, AValues); end; destructor EWiRLWebApplicationException.Destroy; begin FValues.Free; inherited; end; class function EWiRLWebApplicationException.ExceptionToJSON(E: Exception): string; var LJSON: TJSONObject; begin LJSON := TJSONObject.Create; try LJSON.AddPair(TJSONPair.Create('status', TJSONNumber.Create(500))); LJSON.AddPair(TJSONPair.Create('exception', TJSONString.Create(E.ClassName))); LJSON.AddPair(TJSONPair.Create('message', TJSONString.Create(E.Message))); Result := TJSONHelper.ToJSON(LJSON); finally LJSON.Free; end; end; class procedure EWiRLWebApplicationException.HandleException(AContext: TWiRLContext; E: Exception); var LWebException: EWiRLWebApplicationException; LAuthChallengeHeader: string; begin if Assigned(AContext.Application) and (AContext.Application is TWiRLApplication) then LAuthChallengeHeader := TWiRLApplication(AContext.Application).AuthChallengeHeader else LAuthChallengeHeader := ''; if E is EWiRLWebApplicationException then begin LWebException := E as EWiRLWebApplicationException; AContext.Response.StatusCode := LWebException.Status; AContext.Response.SetNonStandardReasonString(LWebException.Message); AContext.Response.Content := LWebException.ToJSON; AContext.Response.ContentType := TMediaType.APPLICATION_JSON; // Set the Authorization challenge if (LWebException.Status = 401) and (LAuthChallengeHeader <> '') then AContext.Response.HeaderFields['WWW-Authenticate'] := LAuthChallengeHeader; end else if E is Exception then begin AContext.Response.StatusCode := 500; AContext.Response.SetNonStandardReasonString(E.Message); AContext.Response.Content := EWiRLWebApplicationException.ExceptionToJSON(E); AContext.Response.ContentType := TMediaType.APPLICATION_JSON; end; end; procedure EWiRLWebApplicationException.CreateAndFillValues; begin FValues := TJSONObject.Create; FValues.AddPair(TJSONPair.Create('status', TJSONNumber.Create(FStatus))); FValues.AddPair(TJSONPair.Create('exception', TJSONString.Create(Self.ClassName))); FValues.AddPair(TJSONPair.Create('message', TJSONString.Create(Self.Message))); end; function EWiRLWebApplicationException.ToJSON: string; begin if not Assigned(FValues) then CreateAndFillValues; Result := TJSONHelper.ToJSON(FValues) end; { EWiRLNotFoundException } constructor EWiRLNotFoundException.Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); var LPairArray: TExceptionValues; begin if not AIssuer.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('issuer', AIssuer); end; if not AMethod.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('method', AMethod); end; inherited Create(AMessage, 404, LPairArray); end; { EWiRLServerException } constructor EWiRLServerException.Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); var LPairArray: TExceptionValues; begin if not AIssuer.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('issuer', AIssuer); end; if not AMethod.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('method', AMethod); end; inherited Create(AMessage, 500, LPairArray); end; { EWiRLNotAuthorizedException } constructor EWiRLNotAuthorizedException.Create(const AMessage: string; const AIssuer: string = ''; const AMethod: string = ''); var LPairArray: TExceptionValues; begin if not AIssuer.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('issuer', AIssuer); end; if not AMethod.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('method', AMethod); end; inherited Create(AMessage, 401, LPairArray); end; { EWiRLNotImplementedException } constructor EWiRLNotImplementedException.Create( const AMessage, AIssuer, AMethod: string); var LPairArray: TExceptionValues; begin if not AIssuer.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('issuer', AIssuer); end; if not AMethod.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('method', AMethod); end; inherited Create(AMessage, 501, LPairArray); end; { EWiRLUnsupportedMediaTypeException } constructor EWiRLUnsupportedMediaTypeException.Create( const AMessage, AIssuer, AMethod: string); var LPairArray: TExceptionValues; begin if not AIssuer.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('issuer', AIssuer); end; if not AMethod.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('method', AMethod); end; inherited Create(AMessage, 415, LPairArray); end; { TValuesUtil } class function TValuesUtil.MakeValueArray(APair1: Pair): TExceptionValues; begin SetLength(Result, 1); Result[0] := APair1; end; class function TValuesUtil.MakeValueArray(APair1, APair2: Pair): TExceptionValues; begin SetLength(Result, 2); Result[0] := APair1; Result[1] := APair2; end; class function TValuesUtil.MakeValueArray(APair1, APair2, APair3: Pair): TExceptionValues; begin SetLength(Result, 3); Result[0] := APair1; Result[1] := APair2; Result[2] := APair3; end; { EWiRLNotAcceptableException } constructor EWiRLNotAcceptableException.Create(const AMessage, AIssuer, AMethod: string); var LPairArray: TExceptionValues; begin if not AIssuer.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('issuer', AIssuer); end; if not AMethod.IsEmpty then begin SetLength(LPairArray, Length(LPairArray) + 1); LPairArray[Length(LPairArray) - 1] := Pair.S('method', AMethod); end; inherited Create(AMessage, 406, LPairArray); end; end.
// ****************************************************************** // // Program Name : Angelic Tech Components // Program Version: 1.00 // Platform(s) : Android, iOS, OSX, Win32, Win64 // Framework : FireMonkey // // Filenames : AT.FMX.Dialog.Message.pas/.fmx // File Version : 1.00 // Date Created : 12-OCT-2015 // Author : Matthew S. Vesperman // // Description: // // Message dialog for FireMonkey. // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © 2015 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** /// <summary> /// Defines classes, types, constants, variables and functions to /// display a custom FireMonkey message dialog. /// </summary> unit AT.FMX.Dialog.Message; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.Effects, FMX.Controls.Presentation; type /// <summary> /// Defines an enumeration to identify the message box buttons. /// </summary> TATFMXMsgDlgBtn = ( /// <summary> /// OK button. /// </summary> fmbOK, /// <summary> /// Yes button. /// </summary> fmbYes, /// <summary> /// No button. /// </summary> fmbNo, /// <summary> /// Cancel button. /// </summary> fmbCancel, /// <summary> /// Retry button. /// </summary> fmbRetry, /// <summary> /// Close button. /// </summary> fmbClose); /// <summary> /// Defines a set of <see cref="TATFMXMsgDlgBtn" /> to display in /// the message dialog. /// </summary> TATFMXMsgDlgBtns = set of TATFMXMsgDlgBtn; /// <summary> /// Defines an enumeration to indicate which icon to show in the /// message dialog. /// </summary> TATFMXMsgDlgIcon = ( /// <summary> /// Don't display an icon. /// </summary> miNone, /// <summary> /// <img src="E:\Components\XE8\AngelicTech\Images\error.png" /> /// Display an error icon. /// </summary> miError, /// <summary> /// <img src="E:\Components\XE8\AngelicTech\Images\info.png" /> /// Display an info icon. /// </summary> miInfo, /// <summary> /// <img src="E:\Components\XE8\AngelicTech\Images\question.png" /> /// Display a question icon. /// </summary> miQuestion, /// <summary> /// <img src="E:\Components\XE8\AngelicTech\Images\shield.png" /> /// Display a shield icon. /// </summary> miShield, /// <summary> /// <img src="E:\Components\XE8\AngelicTech\Images\warning.png" /> /// Display a warning icon. /// </summary> miWarning); /// <summary> /// Defines a custom FireMonkey message dialog class. /// </summary> /// <remarks> /// The calling code is responsible for freeing the message /// dialog. /// </remarks> TfrmATFMXMessageDlg = class(TForm) /// <summary> /// Cancel button object. /// </summary> btnCancel: TButton; /// <summary> /// Close button object. /// </summary> btnClose: TButton; /// <summary> /// No button object. /// </summary> btnNo: TButton; /// <summary> /// OK button object. /// </summary> btnOK: TButton; /// <summary> /// Retry button object. /// </summary> btnRetry: TButton; /// <summary> /// Yes button object. /// </summary> btnYes: TButton; /// <summary> /// Error icon image object. /// </summary> imgError: TImage; /// <summary> /// Info icon image object. /// </summary> imgInfo: TImage; /// <summary> /// Question icon image object. /// </summary> imgQuestion: TImage; /// <summary> /// Shield icon image object. /// </summary> imgShield: TImage; /// <summary> /// Warning icon image object. /// </summary> imgWarning: TImage; /// <summary> /// Button flow layout object. /// </summary> layButtons: TFlowLayout; /// <summary> /// Contents layout object. /// </summary> layContent: TLayout; /// <summary> /// Left layout object. /// </summary> layLeft: TLayout; /// <summary> /// Content label object. /// </summary> lblContentText: TLabel; /// <summary> /// Instruction label object. /// </summary> lblInstruct: TLabel; /// <summary> /// Reflection effect for error icon. /// </summary> reffError: TReflectionEffect; /// <summary> /// Reflection effect for info icon. /// </summary> reffInfo: TReflectionEffect; /// <summary> /// Reflection effect for instruction label. /// </summary> reffInstruct: TReflectionEffect; /// <summary> /// Reflection effect for question icon. /// </summary> reffQuestion: TReflectionEffect; /// <summary> /// Reflection effect for shield icon. /// </summary> reffShield: TReflectionEffect; /// <summary> /// Reflection effect for warning icon. /// </summary> reffWarn: TReflectionEffect; strict private /// <summary> /// Set containing buttons to display. /// </summary> FButtons: TATFMXMsgDlgBtns; /// <summary> /// Flag indicating which button is default. /// </summary> FDefaultButton: TATFMXMsgDlgBtn; /// <summary> /// Which icon should be displayed. /// </summary> FIcon: TATFMXMsgDlgIcon; /// <summary> /// Returns the number of visible buttons in the message /// dialog. /// </summary> function _GetVisibleButtonCount: Byte; /// <summary> /// Ensures the message dialog's width can display all visible /// buttons. /// </summary> procedure _UpdateDialogWidth; strict protected /// <summary> /// Getter for ContentText property. /// </summary> function GetContentText: string; /// <summary> /// Getter for instruction property. /// </summary> function GetInstruct: string; /// <summary> /// Getter for reflections property. /// </summary> function GetReflect: Boolean; /// <summary> /// Getter for dialog title property. /// </summary> function GetTitle: string; /// <summary> /// Setter for the Buttons property. /// </summary> /// <param name="Value"> /// The set of buttons to display. /// </param> procedure SetButtons(const Value: TATFMXMsgDlgBtns); /// <summary> /// Setter for the ContentText property. /// </summary> /// <param name="Value"> /// The content text to display. /// </param> procedure SetContentText(const Value: string); /// <summary> /// Setter for the DefaultButton property. /// </summary> procedure SetDefaultButton(const Value: TATFMXMsgDlgBtn); /// <summary> /// Setter for the icon property. /// </summary> procedure SetIcon(const Value: TATFMXMsgDlgIcon); /// <summary> /// Setter for the instruction property. /// </summary> procedure SetInstruct(const Value: string); /// <summary> /// Setter for the reflection property. /// </summary> procedure SetReflect(const Value: Boolean); /// <summary> /// Setter for the title property. /// </summary> procedure SetTitle(const Value: string); public /// <summary> /// Message dialog Create constructor. /// </summary> /// <param name="AOwner"> /// The message dialog's owner. /// </param> constructor Create(AOwner: TComponent); override; published /// <summary> /// Indicates which buttons to display. /// </summary> property Buttons: TATFMXMsgDlgBtns read FButtons write SetButtons; /// <summary> /// The main content text to display. /// </summary> property ContentText: string read GetContentText write SetContentText; /// <summary> /// Indicates which button is the default one. /// </summary> property DefaultButton: TATFMXMsgDlgBtn read FDefaultButton write SetDefaultButton; /// <summary> /// Indicates which icon to display. /// </summary> property Icon: TATFMXMsgDlgIcon read FIcon write SetIcon; /// <summary> /// The instruction text to display. /// </summary> property Instruction: string read GetInstruct write SetInstruct; /// <summary> /// Should reflections be used? /// </summary> /// <remarks> /// Set this property to True to use reflections, False /// otherwise. /// </remarks> property Reflections: Boolean read GetReflect write SetReflect; /// <summary> /// The title of the message dialog. /// </summary> property Title: string read GetTitle write SetTitle; end; /// <summary> /// Displays a FMX message dialog to the user. /// </summary> /// <param name="AOwner"> /// The owner form for the message dialog. ( <i>If you pass NIL, /// the application main form, if one exists, will be used.</i>) /// </param> /// <param name="AContent"> /// The content text for the message dialog. /// </param> /// <param name="AInstruct"> /// The instruction text for the message dialog. <i>Default: empty /// string</i> /// </param> /// <param name="ATitle"> /// The title of the message dialog.Default: empty string /// </param> /// <param name="AIcon"> /// The icon to display in the message dialog. <i>Default: miNone</i> /// </param> /// <param name="AButtons"> /// The set of buttons to display in the message dialog. <i> /// Default: [fmbOK]</i> /// </param> /// <param name="ADefault"> /// The default button for the message dialog. <i>Default: fmbOK</i> /// </param> /// <param name="AReflections"> /// Display reflections in the message dialog? <i>Default: True</i> /// </param> /// <returns> /// The modal result of the message dialog. /// </returns> function FMXMessageDlg(AOwner: TCustomForm; AContent: String; AInstruct: String = ''; ATitle: String = ''; AIcon: TATFMXMsgDlgIcon = miNone; AButtons: TATFMXMsgDlgBtns = [fmbOK]; ADefault: TATFMXMsgDlgBtn = fmbOK; AReflections: Boolean = True): TModalResult; overload; /// <summary> /// Displays a FMX message dialog to the user. /// </summary> /// <param name="AContent"> /// The content text for the message dialog. /// </param> /// <param name="AInstruct"> /// The instruction text for the message dialog. <i>Default: empty /// string</i> /// </param> /// <param name="ATitle"> /// The title of the message dialog.Default: empty string /// </param> /// <param name="AIcon"> /// The icon to display in the message dialog. <i>Default: miNone</i> /// </param> /// <param name="AButtons"> /// The set of buttons to display in the message dialog. <i> /// Default: [fmbOK]</i> /// </param> /// <param name="ADefault"> /// The default button for the message dialog. <i>Default: fmbOK</i> /// </param> /// <param name="AReflections"> /// Display reflections in the message dialog? <i>Default: True</i> /// </param> /// <returns> /// The modal result of the message dialog. /// </returns> /// <remarks> /// This version of the FMXMessageDlg function is provided for /// backwards compatibility. /// </remarks> function FMXMessageDlg(AContent: String; AInstruct: String = ''; ATitle: String = ''; AIcon: TATFMXMsgDlgIcon = miNone; AButtons: TATFMXMsgDlgBtns = [fmbOK]; ADefault: TATFMXMsgDlgBtn = fmbOK; AReflections: Boolean = True): TModalResult; overload; var frmATFMXMessageDlg: TfrmATFMXMessageDlg; implementation uses Math, AT.GarbageCollector; {$R *.fmx} function FMXMessageDlg(AOwner: TCustomForm; AContent: String; AInstruct: String = ''; ATitle: String = ''; AIcon: TATFMXMsgDlgIcon = miNone; AButtons: TATFMXMsgDlgBtns = [fmbOK]; ADefault: TATFMXMsgDlgBtn = fmbOK; AReflections: Boolean = True): TModalResult; var ACaption: String; //Caption text... AGC : IATGarbageCollector; //Local garbage collector... AFrm : TfrmATFMXMessageDlg; //Dialog form reference... AOwnerObj: TCommonCustomForm; //Owner object for msg dialog... begin //Is the ATitle param empty??? if (ATitle.IsEmpty) then ACaption := Application.Title //Yes, use application's title... else ACaption := ATitle; //No, use the ATitle parameter... //Did an owner get passed in??? if (Assigned(AOwner)) then //Yes, assign it as our owner... AOwnerObj := AOwner else //No, assign app main form as our owner form... AOwnerObj := Application.MainForm; //Create message dialog object and add to local gc... AFrm := TATGC.Collect(TfrmATFMXMessageDlg.Create(AOwnerObj), AGC); //Did we assign an owner object??? if (Assigned(AOwnerObj)) then //Yes, set position to owner form center AFrm.Position := TFormPosition.OwnerFormCenter else //No, set form position to screen center... AFrm.Position := TFormPosition.ScreenCenter; AFrm.Buttons := AButtons; //Set buttons to display... AFrm.ContentText := AContent; //Set content text... AFrm.DefaultButton := ADefault; //Set default button... AFrm.Icon := AIcon; //Set icon... AFrm.Instruction := AInstruct; //Set instruction text... AFrm.Reflections := AReflections; //Set reflections... AFrm.Title := ACaption; //Set title... //Display message dialog and return ModalResult... Result := AFrm.ShowModal; end; function FMXMessageDlg(AContent: String; AInstruct: String = ''; ATitle: String = ''; AIcon: TATFMXMsgDlgIcon = miNone; AButtons: TATFMXMsgDlgBtns = [fmbOK]; ADefault: TATFMXMsgDlgBtn = fmbOK; AReflections: Boolean = True): TModalResult; begin //Call other function to display, pass NIL as owner... Result := FMXMessageDlg(NIL, AContent, AInstruct, ATitle, AIcon, AButtons, ADefault, AReflections); end; { TfrmATFMXMessageDlg } constructor TfrmATFMXMessageDlg.Create(AOwner: TComponent); begin //Call inherited method... inherited Create(AOwner); Buttons := [fmbOK]; //Init button set... ContentText := EmptyStr; //Init content text... DefaultButton := fmbOK; //Init default button... Icon := miNone; //Init message icon... Instruction := EmptyStr; //Init instruction text... Reflections := False; //Init reflection display... Title := Application.Title; //Init dialog title... end; function TfrmATFMXMessageDlg.GetContentText: string; begin //Return content text... Result := lblContentText.Text; end; function TfrmATFMXMessageDlg.GetInstruct: string; begin //Return instruction text... Result := lblInstruct.Text; end; function TfrmATFMXMessageDlg.GetReflect: Boolean; begin //Return reflection value... Result := reffInstruct.Enabled; end; function TfrmATFMXMessageDlg.GetTitle: string; begin //Return dialog caption... Result := Self.Caption; end; function TfrmATFMXMessageDlg._GetVisibleButtonCount: Byte; begin //Init result to zero... Result := 0; //Is OK button visible??? if (btnOK.Visible) then Inc(Result); //Yes, increment count... //Is Yes button visible??? if (btnYes.Visible) then Inc(Result); //Yes, increment count... //Is No button visible??? if (btnNo.Visible) then Inc(Result); //Yes, increment count... //Is Retry button visible??? if (btnRetry.Visible) then Inc(Result); //Yes, increment count... //Is Cancel button visible??? if (btnCancel.Visible) then Inc(Result); //Yes, increment count... //Is Close button visible??? if (btnClose.Visible) then Inc(Result); //Yes, increment count... end; procedure TfrmATFMXMessageDlg.SetButtons(const Value: TATFMXMsgDlgBtns); begin //Save the set into the field... FButtons := Value; //Update button visibility... btnOK.Visible := (fmbOK IN FButtons); btnYes.Visible := (fmbYes IN FButtons); btnNo.Visible := (fmbNo IN FButtons); btnRetry.Visible := (fmbRetry IN FButtons); btnCancel.Visible := (fmbCancel IN FButtons); btnClose.Visible := (fmbClose IN FButtons); //Update the dialog box width... _UpdateDialogWidth; end; procedure TfrmATFMXMessageDlg.SetContentText(const Value: string); begin //Set the content text... lblContentText.Text := Value; end; procedure TfrmATFMXMessageDlg.SetDefaultButton(const Value: TATFMXMsgDlgBtn); begin //Save the default button... FDefaultButton := Value; //Set the default value of all buttons... btnOK.Default := (Value = fmbOK); btnYes.Default := (Value = fmbYes); btnNo.Default := (Value = fmbNo); btnRetry.Default := (Value = fmbRetry); btnCancel.Default := (Value = fmbCancel); btnClose.Default := (Value = fmbClose); end; procedure TfrmATFMXMessageDlg.SetIcon(const Value: TATFMXMsgDlgIcon); begin //Save the icon value... FIcon := Value; //Set the correct icon as visible... imgError.Visible := (Value = miError); imgInfo.Visible := (Value = miInfo); imgQuestion.Visible := (Value = miQuestion); imgShield.Visible := (Value = miShield); imgWarning.Visible := (Value = miWarning); end; procedure TfrmATFMXMessageDlg.SetInstruct(const Value: string); begin //Save the instruction text value... lblInstruct.Text := Value; end; procedure TfrmATFMXMessageDlg.SetReflect(const Value: Boolean); begin //Set the enabled property of the reflection effects... reffInstruct.Enabled := Value; reffError.Enabled := Value; reffInfo.Enabled := Value; reffQuestion.Enabled := Value; reffShield.Enabled := Value; reffWarn.Enabled := Value; end; procedure TfrmATFMXMessageDlg.SetTitle(const Value: string); begin //Save the title... Self.Caption := Value; end; procedure TfrmATFMXMessageDlg._UpdateDialogWidth; var ABtnCnt : Byte; //Number of visible buttons... AHGap : Integer; //Distance between buttons... AHMargin: Integer; //Total left/right margin distance... AWid : Integer; //Calculated width of buttons... begin //Get number of visible buttons... ABtnCnt := _GetVisibleButtonCount; //Get distance between buttons... AHGap := Trunc(layButtons.HorizontalGap); //Get total of left/right layout margins... AHMargin := Trunc(layButtons.Margins.Left + layButtons.Margins.Right); //Calculate minumum width needed by buttons... AWid := Trunc((btnOK.Width * ABtnCnt) + ((ABtnCnt - 1) * AHGap) + AHMargin); //Add an additional 20px space... AWid := AWid + 20; //Set width to calculated width or 350, whichever is bigger... Self.Width := Max(350, AWid); end; end.
unit SORM.Model.Conexao.Firedac.Query; interface uses SORM.Model.Conexao.Interfaces, Data.DB, 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; Type TModelConexaoFiredacQuery = class(TInterfacedObject, ImodelQuery) private FQuery: TFDQuery; FConn : iModelConexao; public constructor Create(Value: iModelConexao); destructor Destroy; override; class function New(Value: iModelConexao): ImodelQuery; function Query: TObject; function OpenTable(Table: string): ImodelQuery; end; implementation uses System.SysUtils; { TModelConexaoFiredacQuery } constructor TModelConexaoFiredacQuery.Create(Value: iModelConexao); begin FConn := Value; FQuery := TFdQuery.Create(nil); FQuery.Connection := TFDConnection(FConn.Connection); end; destructor TModelConexaoFiredacQuery.Destroy; begin FreeAndNil(FQuery); inherited; end; class function TModelConexaoFiredacQuery.New(Value: iModelConexao): ImodelQuery; begin result := Self.Create(Value); end; function TModelConexaoFiredacQuery.OpenTable(Table: string): ImodelQuery; var SQL : string; begin result := Self; SQL := 'SELECT * FROM '+ Table; FQuery.SQL.Add(SQL); FQuery.Open; end; function TModelConexaoFiredacQuery.Query: TObject; begin result := FQuery; end; end.
unit Un_Principal; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, Un_Contagem; type TForm1 = class(TForm) Label1: TLabel; btReiniciar: TButton; btContar: TButton; LbQuantidade: TLabel; LbTempoMedio: TLabel; LbTempo: TLabel; procedure btReiniciarClick(Sender: TObject); procedure btContarClick(Sender: TObject); private { Private declarations } FContador: TContagem; procedure AtualizarDados; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation {$R *.fmx} { TForm1 } procedure TForm1.AtualizarDados; begin LbQuantidade.Text := 'Quantidade: ' + FContador.Quantidade.ToString; LbTempoMedio.Text := 'Tempo Médio: ' + FormatDateTime( 'hh:nn:ss', FContador.TempoMedio ); LbTempo.Text := 'Tempo decorrido: ' + FormatDateTime( 'hh:nn:ss', Now - FContador.Primeiro ); end; // ***************************************************************************** procedure TForm1.btContarClick(Sender: TObject); begin FContador.Adicionar; AtualizarDados; end; // ***************************************************************************** procedure TForm1.btReiniciarClick(Sender: TObject); begin FContador.Reiniciar; AtualizarDados; end; // ***************************************************************************** constructor TForm1.Create(AOwner: TComponent); begin inherited; FContador := TContagem.Create( Self ); end; // ***************************************************************************** destructor TForm1.Destroy; begin FContador.Free; inherited; end; // ***************************************************************************** end.
unit SG_CheckBox; interface uses stdctrls; function getCheckBoxSQLValue(checkBox:TCheckBox):string; implementation function getCheckBoxSQLValue(checkBox:TCheckBox):string; begin if checkBox.Checked then Result:='1' else Result:='0'; end; end.
unit AqDrop.Core.FileLog; interface uses AqDrop.Core.Types, AqDrop.Core.Log; type TAqFileLog = class strict private FLogsPath: string; FFileNameMask: string; FLog: TAqLog; FObserverID: TAqID; public constructor Create(const pLogsPath: string; const pLog: TAqLog; const pFileNameMask: string = 'YYYYMMDD'); destructor Destroy; override; procedure SaveLog(const pMessage: TAqLogMessage); end; implementation uses System.SysUtils, System.Classes, System.IOUtils; { TAqFileLog } constructor TAqFileLog.Create(const pLogsPath: string; const pLog: TAqLog; const pFileNameMask: string); begin FLogsPath := pLogsPath; FFileNameMask := pFileNameMask; TDirectory.CreateDirectory(FLogsPath); FLog := pLog; FObserverID := pLog.RegisterObserver( procedure(pMessage: TAqLogMessage) begin SaveLog(pMessage); end); end; destructor TAqFileLog.Destroy; begin FLog.UnregisterObserver(FObserverID); inherited; end; procedure TAqFileLog.SaveLog(const pMessage: TAqLogMessage); var lFilePath: string; lMessage: string; begin lFilePath := TPath.Combine(FLogsPath, FormatDateTime(FFileNameMask, pMessage.DateTime) + '.log'); lMessage := pMessage.GetDefaultFormatMessage; TThread.Queue(nil, procedure begin TFile.AppendAllText(lFilePath, lMessage + sLineBreak, TEncoding.Unicode); end); end; end.
unit PedidoMVPIntf; interface uses Pedido, PedidoIntf, Controls, Generics.Collections; type IPedidoPresenter = interface; IPedidoView = interface ['{D45F2B80-7CF9-4CC3-A29F-E585A51C7FAC}'] function GetPedido: TPedido; procedure SetPedido(Value: TPedido); function GetPresenter: IPedidoPresenter; procedure SetPresenter(const Value: IPedidoPresenter); function ShowView: TModalResult; property Pedido: TPedido read GetPedido write SetPedido; property Presenter: IPedidoPresenter read GetPresenter write SetPresenter; end; IPedidoPresenter = interface ['{7C74346C-E2C3-44DE-966B-9770D872ECB4}'] function GetModel: IPedido; procedure SetModel(const Value: IPedido); function GetView: IPedidoView; procedure SetView(const Value: IPedidoView); function Add: Integer; function Get: TPedido; function ListAll: TList<TPedido>; property Model: IPedido read GetModel write SetModel; property View: IPedidoView read GetView write SetView; end; implementation end.
unit uPerformance; interface uses Data.DB, Datasnap.DBClient, System.Generics.Collections; type IPerformanceCheck = interface(IInterface) ['{8A7EC44F-CF9A-44E1-A43A-981650F5BCA8}'] procedure IniciarContagemParaOMetodo(const NomeDoMetodo: string); procedure PararContagemParaOMetodo(const NomeDoMetodo: string); function PegarDataSetInterno: TDataSet; end; TPerformanceMetodo = class Nome: string; Profundidade: integer; Inicio: int64; Fim: int64; end; TPerformanceCheck = class(TInterfacedObject, IPerformanceCheck) private FcdsPerformance: TClientDataSet; FNomeMetodo: TField; FTempoExecucao: TField; FPilhaProfundidade: integer; FContagem: TDictionary<string, TPerformanceMetodo>; FCampoProfundidade: TField; procedure ConfigurarDataSet; procedure RegistrarPerformance(const Metodo: TPerformanceMetodo); public constructor Create; destructor Destroy; override; procedure IniciarContagemParaOMetodo(const NomeDoMetodo: string); procedure PararContagemParaOMetodo(const NomeDoMetodo: string); function PegarDataSetInterno: TDataSet; end; function PegarPerformanceCheck: IPerformanceCheck; implementation uses Winapi.Windows, System.SysUtils; var _performanceCheck: IPerformanceCheck; function PegarPerformanceCheck: IPerformanceCheck; begin if not Assigned(_performanceCheck) then _performanceCheck := TPerformanceCheck.Create; result := _performanceCheck; end; constructor TPerformanceCheck.Create; var _frequency64: int64; begin inherited; QueryPerformanceFrequency(_frequency64); if _frequency64 = 0 then raise Exception.Create('O sistema operacional não suporta análise de performance'); FContagem := TDictionary<string, TPerformanceMetodo>.Create; FcdsPerformance := TClientDataSet.Create(nil); ConfigurarDataSet; FPilhaProfundidade := 0; end; procedure TPerformanceCheck.ConfigurarDataSet; const SEM_TAMANHO_DEFINIDO = 0; CAMPO_OBRIGATORIO = True; TAMANHO_MAXIMO_NOME_METODO = 500; begin FcdsPerformance.FieldDefs.Add('id', ftAutoInc, SEM_TAMANHO_DEFINIDO, not CAMPO_OBRIGATORIO); FcdsPerformance.FieldDefs.Add('NOME_METODO', ftString, TAMANHO_MAXIMO_NOME_METODO, CAMPO_OBRIGATORIO); FcdsPerformance.FieldDefs.Add('TEMPO_EXECUCAO', ftInteger, SEM_TAMANHO_DEFINIDO, CAMPO_OBRIGATORIO); FcdsPerformance.FieldDefs.Add('PROFUNDIDADE', ftInteger, SEM_TAMANHO_DEFINIDO, CAMPO_OBRIGATORIO); FcdsPerformance.CreateDataSet; FNomeMetodo := FcdsPerformance.FieldByName('NOME_METODO'); FTempoExecucao := FcdsPerformance.FindField('TEMPO_EXECUCAO'); FCampoProfundidade := FcdsPerformance.FindField('PROFUNDIDADE'); end; destructor TPerformanceCheck.Destroy; begin FcdsPerformance.Close; FcdsPerformance.Free; inherited; end; procedure TPerformanceCheck.IniciarContagemParaOMetodo(const NomeDoMetodo: string); var _metodo: TPerformanceMetodo; _inicio: int64; begin _metodo := TPerformanceMetodo.Create; _metodo.Nome := NomeDoMetodo; _metodo.Profundidade := FPilhaProfundidade; QueryPerformanceCounter(_inicio); _metodo.Inicio := _inicio; FContagem.Add(NomeDoMetodo, _metodo); inc(FPilhaProfundidade); end; procedure TPerformanceCheck.PararContagemParaOMetodo(const NomeDoMetodo: string); var _metodo: TPerformanceMetodo; _fim: int64; begin _metodo := FContagem.Items[NomeDoMetodo]; try QueryPerformanceCounter(_fim); _metodo.Fim := _fim; RegistrarPerformance(_metodo); finally Dec(FPilhaProfundidade); _metodo.Free; end; end; procedure TPerformanceCheck.RegistrarPerformance(const Metodo: TPerformanceMetodo); begin FcdsPerformance.Insert; FNomeMetodo.AsString := Metodo.Nome; FTempoExecucao.AsInteger := Metodo.Fim - Metodo.Inicio; FCampoProfundidade.AsInteger := FPilhaProfundidade; FcdsPerformance.Post; end; function TPerformanceCheck.PegarDataSetInterno: TDataSet; begin result := FcdsPerformance; end; end.
unit RocketFirstStage; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ThrustInfo, BaseModel; type IBaseRocketFirstStage = interface(IBaseModel) ['{3FC10254-BC67-4C3C-95A4-05AEAD6F79AB}'] function GetBurnTimeSeconds: LongWord; function GetEngines: LongWord; function GetFuelAmountTons: LongWord; function GetReusable: Boolean; function GetThrustSeaLevel: IThrustInfo; function GetThrustVacuum: IThrustInfo; procedure SetBurnTimeSeconds(AValue: LongWord); procedure SetEngines(AValue: LongWord); procedure SetFuelAmountTons(AValue: LongWord); procedure SetReusable(AValue: Boolean); procedure SetThrustSeaLevel(AValue: IThrustInfo); procedure SetThrustVacuum(AValue: IThrustInfo); end; IRocketFirstStage = interface(IBaseRocketFirstStage) ['{C968F9BB-D955-4AD0-8722-5B83A8A8FBB1}'] property BurnTimeSeconds: LongWord read GetBurnTimeSeconds write SetBurnTimeSeconds; property Engines: LongWord read GetEngines write SetEngines; property FuelAmountTons: LongWord read GetFuelAmountTons write SetFuelAmountTons; property Reusable: Boolean read GetReusable write SetReusable; property ThrustSeaLevel: IThrustInfo read GetThrustSeaLevel write SetThrustSeaLevel; property ThrustVacuum: IThrustInfo read GetThrustVacuum write SetThrustVacuum; end; function NewRocketFirstStage: IRocketFirstStage; implementation uses JSON_Helper, Variants; type { TRocketFirstStage } TRocketFirstStage = class(TBaseModel, IRocketFirstStage) private FBurnTimeSeconds: LongWord; FEngines: LongWord; FFuelAmountTons: LongWord; FReusable: Boolean; FThrustSeaLevel: IThrustInfo; FThrustVacuum: IThrustInfo; private function GetBurnTimeSeconds: LongWord; function GetEngines: LongWord; function GetFuelAmountTons: LongWord; function GetReusable: Boolean; function GetThrustSeaLevel: IThrustInfo; function GetThrustVacuum: IThrustInfo; private procedure SetBurnTimeSeconds(AValue: LongWord); procedure SetBurnTimeSeconds(AValue: Variant); procedure SetEngines(AValue: LongWord); procedure SetEngines(AValue: Variant); procedure SetFuelAmountTons(AValue: LongWord); procedure SetFuelAmountTons(AValue: Variant); procedure SetReusable(AValue: Boolean); procedure SetReusable(AValue: Variant); procedure SetThrustSeaLevel(AValue: IThrustInfo); procedure SetThrustVacuum(AValue: IThrustInfo); public function ToString: string; override; procedure BuildSubObjects(const JSONData: IJSONData); override; published property burn_time_sec: Variant write SetBurnTimeSeconds; property engines: Variant write SetEngines; property fuel_amount_tons: Variant write SetFuelAmountTons; property reusable: Variant write SetReusable; end; function NewRocketFirstStage: IRocketFirstStage; begin Result := TRocketFirstStage.Create; end; { TRocketFirstStage } function TRocketFirstStage.GetBurnTimeSeconds: LongWord; begin Result := FBurnTimeSeconds; end; function TRocketFirstStage.GetEngines: LongWord; begin Result := FEngines; end; function TRocketFirstStage.GetFuelAmountTons: LongWord; begin Result := FFuelAmountTons; end; function TRocketFirstStage.GetReusable: Boolean; begin Result := FReusable; end; function TRocketFirstStage.GetThrustSeaLevel: IThrustInfo; begin Result := FThrustSeaLevel; end; function TRocketFirstStage.GetThrustVacuum: IThrustInfo; begin Result := FThrustVacuum; end; procedure TRocketFirstStage.SetBurnTimeSeconds(AValue: LongWord); begin FBurnTimeSeconds := AValue; end; procedure TRocketFirstStage.SetBurnTimeSeconds(AValue: Variant); begin if VarIsNull(AValue) then AValue := -1; FBurnTimeSeconds := AValue; end; procedure TRocketFirstStage.SetEngines(AValue: LongWord); begin FEngines := AValue; end; procedure TRocketFirstStage.SetEngines(AValue: Variant); begin if VarIsNull(AValue) then begin FEngines := -0; end else if VarIsNumeric(AValue) then FEngines := AValue; end; procedure TRocketFirstStage.SetFuelAmountTons(AValue: LongWord); begin FFuelAmountTons := AValue; end; procedure TRocketFirstStage.SetFuelAmountTons(AValue: Variant); begin if VarIsNull(AValue) then begin FFuelAmountTons := -0; end else if VarIsNumeric(AValue) then FFuelAmountTons := AValue; end; procedure TRocketFirstStage.SetReusable(AValue: Boolean); begin FReusable := AValue; end; procedure TRocketFirstStage.SetReusable(AValue: Variant); begin if VarIsNull(AValue) then begin FReusable := False; end else if VarIsBool(AValue) then FReusable := AValue; end; procedure TRocketFirstStage.SetThrustSeaLevel(AValue: IThrustInfo); begin FThrustSeaLevel := AValue; end; procedure TRocketFirstStage.SetThrustVacuum(AValue: IThrustInfo); begin FThrustVacuum := AValue; end; function TRocketFirstStage.ToString: string; begin Result := Format('' + 'Burn Time Seconds: %u' + LineEnding + 'Engines: %u' + LineEnding + 'Fuel Amount Tons: %u' + LineEnding + 'Reusable: %s' + LineEnding + 'Thrust Sea Level: %s' + LineEnding + 'Thrust Vacuum: %s' , [ GetBurnTimeSeconds, GetEngines, GetFuelAmountTons, BoolToStr(GetReusable, True), GetThrustSeaLevel.ToString, GetThrustVacuum.ToString ]); end; procedure TRocketFirstStage.BuildSubObjects(const JSONData: IJSONData); var SubJSONData: IJSONData; ThrustSealLevel, ThrustVacuum: IThrustInfo; begin inherited BuildSubObjects(JSONData); SubJSONData := JSONData.GetPath('thrust_sea_level'); ThrustSealLevel := NewThrustInfo; JSONToModel(SubJSONData.GetJSONData, ThrustSealLevel); Self.FThrustSeaLevel := ThrustSealLevel; SubJSONData := JSONData.GetPath('thrust_vacuum'); ThrustVacuum := NewThrustInfo; JSONToModel(SubJSONData.GetJSONData, ThrustVacuum); Self.FThrustVacuum := ThrustVacuum; end; end.
unit TestBandSVG; interface uses Spring ,Spring.Collections ,StrUtils ,SysUtils ,AnsiStrings ; type ISVGTester = interface(IInvokable) ['{4EB381E9-48C1-43B6-B847-50569DE5822A}'] function ExtractUsedPolygonKindsFromSVG(SVG: string): IList<integer>; procedure SubtractUsedCases(TotalListOfUsedCases: IList<integer>; const ListofCasesToSubtract: IList<integer>); end; TSVGTester = class(TInterfacedObject, ISVGTester) private class function ExtractListOfCommentsFromSVG(SVG: string): IList<string>; class function CommentsToPolygonKinds(Comments: IList<string>): IList<integer>; protected function ExtractUsedPolygonKindsFromSVG(SVG: string): IList<integer>; procedure SubtractUsedCases(TotalListOfUsedCases: IList<integer>; const ListofCasesToSubtract: IList<integer>); end; implementation { TSVGTester } function TSVGTester.ExtractUsedPolygonKindsFromSVG( SVG: string): IList<integer>; var ExtractedSVGComments: IList<string>; begin ExtractedSVGComments := ExtractListOfCommentsFromSVG(SVG); Result := CommentsToPolygonKinds(ExtractedSVGComments); end; procedure TSVGTester.SubtractUsedCases(TotalListOfUsedCases: IList<integer>; const ListOfCasesToSubtract: IList<integer>); var MarkAsUsedInTotalList: TAction<integer>; begin MarkAsUsedInTotalList := procedure( const Index: integer) begin TotalListOfUsedCases.items[Index] := -1; end; ListOfCasesToSubtract.ForEach(MarkAsUsedInTotalList); end; class function TSVGTester.CommentsToPolygonKinds( Comments: IList<string>): IList<integer>; var AppendToOutputList: TAction<string>; CaseTail: string ; LocalCaseList: IList<integer>; begin LocalCaseList := TCollections.CreateList<integer>; AppendToOutputList := procedure( const Comment: string) var iStartCommentPos: integer; begin iStartCommentPos := Pos('Polygon variation Case ', Comment); if iStartCommentPos > 0 then begin CaseTail := Copy(Comment, iStartCommentPos + Length('Polygon variation Case '), 2); LocalCaseList.Add(StrToInt(Trim(CaseTail))); end; end; Comments.ForEach(AppendToOutputList); Result := LocalCaseList; end; class function TSVGTester.ExtractListOfCommentsFromSVG(SVG: string): IList<string>; var CommentHeadPlace, CommentTailPlace: integer; CommentLength: integer; CommentStart: integer; begin CommentStart := 0; CommentHeadPlace := 1; Result := TCollections.CreateList<string>; while CommentHeadPlace > 0 do begin CommentHeadPlace := Posex('<!--', SVG, CommentHeadPlace); if CommentHeadPlace > 0 then begin CommentTailPlace := Posex('-->', SVG, CommentHeadPlace); if (CommentTailPlace > 0) and (CommentTailPlace > 0) then CommentStart := CommentHeadPlace + Length('<!--'); CommentLength := CommentTailPlace - CommentHeadPlace - Length('<!--'); Result.Add(Copy(SVG, CommentStart, CommentLength ) ); CommentHeadPlace := CommentTailplace; end; end; end; end.
unit ViewModel.TownList; interface uses Model.Interfaces; function CreateTownListViewModelClass: ITownListViewModelInterface; implementation uses Model.Town, Model.FormDeclarations, Model.ProSu.Interfaces, Model.ProSu.InterfaceActions, Model.ProSu.Provider, Model.ProSu.Subscriber; type TTownListViewModel = class(TInterfacedObject, ITownListViewModelInterface) private fModel: ITownModelInterface; fProvider : IProviderInterface; fSubscriberToEdit : ISubscriberInterface; function GetModel: ITownModelInterface; procedure SetModel(const newModel: ITownModelInterface); //function GetLabelsText: TTownListFormLabelsText; function GetProvider: IProviderInterface; function GetSubscriberToEdit: ISubscriberInterface; procedure SendNotification(const actions : TInterfaceActions); procedure SendErrorNotification (const errorType: TInterfaceErrors; const errorMessage: string); procedure NotificationFromProvider(const notifyClass : INotificationClass); public property Model: ITownModelInterface read GetModel write SetModel; property Provider: IProviderInterface read GetProvider; property SubscriberToEdit: ISubscriberInterface read GetSubscriberToEdit; constructor Create; end; { TTownViewModel } constructor TTownListViewModel.Create; begin fProvider:=CreateProSuProviderClass; fModel := CreateTownModelClass; end; function TTownListViewModel.GetModel: ITownModelInterface; begin result:=fModel; end; function TTownListViewModel.GetProvider: IProviderInterface; begin result:=fProvider; end; function TTownListViewModel.GetSubscriberToEdit: ISubscriberInterface; begin if not Assigned(fSubscriberToEdit) then fSubscriberToEdit := CreateProSuSubscriberClass; Result := fSubscriberToEdit; end; procedure TTownListViewModel.NotificationFromProvider( const notifyClass: INotificationClass); begin end; procedure TTownListViewModel.SendErrorNotification( const errorType: TInterfaceErrors; const errorMessage: string); var tmpErrorNotificationClass: TErrorNotificationClass; begin tmpErrorNotificationClass:=TErrorNotificationClass.Create; try tmpErrorNotificationClass.Actions:=errorType; tmpErrorNotificationClass.ActionMessage:=errorMessage; fProvider.NotifySubscribers(tmpErrorNotificationClass); finally tmpErrorNotificationClass.Free; end; end; procedure TTownListViewModel.SendNotification(const actions: TInterfaceActions); var tmpNotification : TNotificationClass; begin tmpNotification := TNotificationClass.Create; try tmpNotification.Actions := actions; fProvider.NotifySubscribers(tmpNotification); finally tmpNotification.Free; end; end; procedure TTownListViewModel.SetModel(const newModel: ITownModelInterface); begin fModel:=newModel; end; function CreateTownListViewModelClass: ITownListViewModelInterface; begin result:=TTownListViewModel.Create; end; end.
{============} Unit F_Text; {=============} {+---------------------------------------------+ | В этот модуль входят подпрограммы поддержки | | многостраничного вывода в текстовом режиме | +---------------------------------------------+} INTERFACE {-----------------------------------------------} Uses CRT, DOS; { Следующие константы используются для указания типа рамки при обращении к процедурам BORDER, SETWINDOW и PUTWINDOW. } const EmptyBorder = 0; {Стереть рамку} SingleBorder = 1; {Рамка из одинарных линий} DoubleBorder = 2; {Рамка из двойных линий} { Следующий массив определяет символы псевдографики для вычерчивания рамок (альтернативная кодировка) } BorderChar: array [0..2,1..6] of Char = ((#32, #32, #32, #32, #32, #32), (#218, #196, #191, #179, #192, #217), (#201, #205, #187, #186, #200, #188)); type PageType = record {Описатель страницы} case Byte of 0:(Attrib : Byte; {Атрибут символов} CLineUp : Byte; {Верхняя строка курсора} CLineDown: Byte; {Нижняя строка курсора} CVisible : Boolean; {Признаквидимого курсора} WBondUp : Word; {Левый верхнийугол окна} WBondDown: Word); {Правый нижний угол} 1:(PagePar: array [1..8] of Byte) end; const Pages: array [0..7] of PageType = ((PagePar:(7,6,7,1,0,0,79,24)), (PagePar:(7,6,7,1,0,0,79,24)), (PagePar:(7,6,7,1,0,0,79,24)), (PagePar:(7,6,7,1,0,0,79,24)), (PagePar:(7,6,7,1,0,0,79,24)), (PagePar:(7,6,7,1,0,0,79,24)), (PagePar:(7,6,7,1,0,0,79,24)), (PagePar:(7,6,7,1,0,0,79,24))); { Адрес регистра статуса адаптера CGA } PortCGA = $3DA; { Начало видеопамяти для CGA/EGA/VGA } BegVideo = $B800; { Следующие константы зависят от режима работы и типа адаптера. Значения по умолчанию соответствуют CGA/EGA/VGA в режиме CO80. Эти значения можно переопределить с помощью процедуры InitText } const MaxPage : Byte = 3; {Максимальный номер страницы} MaxChar : Byte = 80; {Количество символов в строке} MaxLine : Byte = 25; {Количество строк на экране} PageSize: Word = 4000; {Размер видимой страницы} VSize : Word = 4096; {Полный размер страницы} VMemory : Word = BegVideo; {Адрес видеопамяти} VMW: array [0..15] of Word = ($0000,BegVideo,$1000,BegVideo,$2000,BegVideo, $3000,BegVideo,$4000,BegVideo,$5000,BegVideo, $6000,BegVideo,$7000,BegVideo); { Массив VMP содержит адреса всех видеостраниц. Значения по умолчанию соответствуют адаптерам CGA/EGA/VGA в режиме CO80. Эти значения можно переопределить с помощью процедуры InitText } var VMP: array [0..7] of Pointer absolute VMW; { *-----------------------------------------------* | Подпрограммы управления цветом | *-----------------------------------------------* } PROCEDURE ChangeAttribute(Page,X1,Y1,X2,Y2,OldAtt,NewAtt: Byte); {Меняет атрибут OLDATT на значение NEWATT в прямоугольнике X1...Y2 страницы PAGE} PROCEDURE Colors(Text,Back: Byte); {Устанавливает цвет текста TEXT и фона BACK в текущей странице} PROCEDURE PageColors (Page,Text,Back: Byte); {Устанавливает цвет текста TEXT и фона BACK в странице PAGE} FUNCTION PackAttribute(Text,Back: Byte): Byte; {Упаковывает два цвета в байт атрибута} PROCEDURE SetAttribute(Page,X1,Y1,X2,Y2,Attr: Byte); {Заменяет атрибут всех символов в прямоугольнике X1...Y2 страницы PAGE на значение Attr} PROCEDURE UnPackAttribute(Attr: Byte; var Text,Back: Byte); {Распаковывает байт атрибутаи возвращает два цвета} { *----------------------------------------------* | Подпрограммы управления курсором | *----------------------------------------------* } PROCEDURE CursorOff; {Отключает курсор в активной странице} PROCEDURE CursorOn; {Включает курсор в активной странице} PROCEDURE CursorOnOff (Page: Byte; Vis: Boolean); {Устанавливает признак видимости курсора: PAGE - номер страницы; VIS - признак видимости} PROCEDURE GetCursor (Page: Byte; var X,Y,Up,Down: Byte); {Возвращает координаты курсора: PAGE - номер страницы; X,Y - возвращаемые координаты (отсчет от 1,1); Up, Down - размер курсора в строках развертки} FUNCTION GetCursorVisible(Page: Byte): Boolean; {Возвращает признак видимости курсора} PROCEDURE PutCursor(Page,X,Y: Byte); {Устанавливает требуемое положение курсора. PAGE - номер страницы; X,Y - координаты курсора (отсчет от 1,1)} PROCEDURE SetCursorLine(Page,Up,Down: Byte); {Устанавливает размер курсора} { *----------------------------------------------* | Подпрограммы управления текстовым выводом | *----------------------------------------------* } PROCEDURE Border (Page,X1,Y1,X2,Y2,Bord: Byte); {Обводит рамкой заданную прямоугольную область страницы PAGE: X1..Y2 - координаты окна; BORD - константа 0..2, указывающая тип рамки. Символы рамки выводятся c текущими атрибутами} PROCEDURE CopyChar (Page: Byte; Cr: Char; Attr: Byte; Count: Word); {Записывает несколько копий символа, начиная с позиции, на которую указывает курсор : PAGE - номер 0..MaxPage страницы; CR - копируемый символ; ATTR - его атрибуты; COUNT - количество копий символа. Символ записывается с указанными атрибутами, курсор не меняет своего положения} PROCEDURE GetChar (Page: Byte;var Cr: Char; var Attr: Byte); {Читает символ и его атрибуты: PAGE - номер 0..MaxPage страницы, откуда нужно прочитать символ; CR - прочитанный символ; ATTR - его атрибуты} PROCEDURE InitText; {Переопределяет константы, зависящие от адаптера и режима его работы. Содержимое экрана не меняется} PROCEDURE MoveFromScreen (var Source, Destin;Count: Word); {Читает данные из видеопамяти : SOURCE - адрес считываемой видеопамяти; DESTIN - имя переменной,куда будут прочитаны данные; COUNT - объем считываемой информации в байтах} PROCEDURE MoveToScreen (var Source, Destin;Count: Word); {Записывает данные в видеопамять : SOURCE - переменная, содержащая записываемую информацию; DESTIN - адрес фрагмента видеопамяти; COUNT - объем записываемой информации} PROCEDURE PageWriteOn; {Переназначает стандартный канал вывода на процедуру PAGEWRITE, поддерживающую вывод в любую страницу} PROCEDURE PageWriteOff; {Восстанавливает стандартный канал вывода} PROCEDURE PutChar (Page: Byte; Cr: Char); {Записывает символ на место,указываемое курсором: PAGE - номер 0..MaxPage страницы; CR - записываемый символ; Символ записывается с текущими атрибутами, курсор не меняет своего положения} PROCEDURE WriteChar (Page: Byte; Cr: Char); {Выводит символ и сдвигает курсор. Используются текущие атрибуты} {*-----------------------------------------------* |Многостраничные варианты подпрограмм модуля CRT| *-----------------------------------------------*} PROCEDURE ClrEOL; {Удаляет остаток строки справа от курсора в активной странице} PROCEDURE ClrScr; {Очищает текущее окно (страницу)} PROCEDURE DelLine; {Удаляет строку в активной странице} PROCEDURE GotoXY(X,Y: Byte); {Устанавливает курсор в активной странице} PROCEDURE InsLine; {Вставляет пустую строку в активной странице} PROCEDURE TextBackGround(Color: Byte); {Устанавливает цвет фонав активной странице} PROCEDURE TextColor(Color: Byte); {Устанавливает цвет символовв активной странице} FUNCTION WhereX: Byte; {Возвращает горизонтальную координату курсора в активной странице} FUNCTION WhereY: Byte; {Возвращает вертикальную координату курсора в активной странице} PROCEDURE Window(X1,Y1,X2,Y2: Byte); {Устанавливает окно в активной странице} {*----------------------------------------------* | Подпрограммы управления страницами | *----------------------------------------------*} FUNCTION GetActivePage: Byte; {Возвращает номер активной текстовой страницы} PROCEDURE GetPage (Page: Byte; var Destin); {Копирует текстовую страницу в оперативную память: PAGE - номер копируемой страницы; DESTIN - переменная, куда будет копироваться страница} PROCEDURE SwapPage (Source, Destin: Byte); {Копирует одну текстовую страницу в другую: SOURCE - номер страницы-источника информации; DESTIN - номер страницы-приемника} FUNCTION PageSaveSize: Word; {Возвращает размер буфера, необходимый для сохранения текущего состояния видеостраницы} PROCEDURE PutPage (var Source; Page: Byte); {Пересылает копию текстовой страницы из оперативной памяти в видеопамять: SOURCE - имя переменной, хранящей копию страницы; PAGE - номер страницы-приемника информации} PROCEDURE RestorePage(Page: Byte; var Buf); {Восстанавливает текущее состояние страницы PAGE по содержимому буфера BUF} PROCEDURE SetActivePage(Page: Byte); {Устанавливает активной заданную текстовую страницу. PAGE - номер страницы} PROCEDURE SavePage(Page: Byte; var Buf); {Сохраняет текущее состояние страницы PAGE в буфере BUF} {*----------------------------------------------* | Подпрограммы управления окнами | *----------------------------------------------*} PROCEDURE ChangeWindAttribute(Page,OldAtt,NewAtt: Byte); {Заменяет в окне PAGE атрибут OLDATT на значение NEWATT} PROCEDURE CopyWind(Page,X,Y: Byte;var Buf; LX,LY: Byte); {Переносит копию окна из памяти на страницу} PROCEDURE GetWindow (Page: Byte); {Восстанавливает состояние экрана, бывшее перед обращением к процедуре PUTWINDOW: PAGE - номер страницы, куда была скопирована активная} PROCEDURE PutWindow(X1,Y1,X2,Y2,Text,Back,Bord,Page: Byte; Header: String;Clip,Build,Play: Boolean); {Сохраняет активную страницу в заданной текстовой странице, создает в активной странице окно с заданными атрибутами, очищает его и обводит рамкой: X1...Y2 - координаты окна; TEXT - цвет символов; BACK - цвет фона; BORD - константа, указывающая тип рамки; PAGE - номер 0..MaxPage страницы, куда будет скопирована активная страница; HEADER - заголовок окна; CLIP - признак границ (TRUE - исключая X1...Y2, FALSE - включая границы X1...Y2); BUILD- признак развертывания окна; PLAY - надо ли сопровождать звуком} PROCEDURE SaveWind(Page: Byte; var Buf; var LX,LY: Byte); {Сохраняет копию окна в буфере BUF} PROCEDURE SetPageWindow (Page,X1,Y1,X2,Y2,Bord: Byte; Header: String; Clip: Boolean); {Создает окно в странице PAGEи обводит его рамкой: PAGE - номер страницы; X1...Y2 - координаты окна; BORD - константа, указывающая тип рамки; HEADER - заголовок окна; CLIP - признак границ (TRUE - внутри X1...Y2, FALSE - включая границы X1...Y2). Символы рамки выводятся с текущими атрибутами, окно очищается} PROCEDURE SetWindAttribute(Page,Attr: Byte); {Устанавливает новый атрибут окна} PROCEDURE SetWindow (X1,Y1,X2,Y2,Bord: Byte; Header: String; Clip,Build,Play: Boolean); {Создает окно в активной страницеи обводит его рамкой: X1...Y2 - координаты окна; BORD - константа, указывающая тип рамки; HEADER - заголовок окна; CLIP - признак границ (TRUE - внутри X1...Y2, FALSE - включая границы X1...Y2); BUILD- признак развертывания окна; PLAY - надо ли сопровождать звуком. Символы рамки выводятся с текущими атрибутами, окно очищается} PROCEDURE WindMoveTo(Page,X,Y: Byte;var Buf; ClipW: Boolean); {Перемещает окно в новое положение: PAGE - номер страницы; X,Y - новые координаты левого верхнего угла; BUF - вид экрана без окна; CLIPW- признак отсечки изображения} PROCEDURE WindMoveRel(Page: Byte; DX,DY: Integer; var Buf; ClipW: Boolean); {Смещает окно относительно прежнего положения: PAGE - номер страницы; DX,DY- приращения координат левого верхнего угла; BUF - вид экрана без окна; CLIPW- признак отсечки изображения} FUNCTION WindSize(Page: Byte): Word; {Возвращает размер буфера для сохранения окна} {-----------------------------------------------} IMPLEMENTATION {-----------------------------------------------} var Reg: registers; const ActivePage: Byte = 0; {Номер активной страницы} { *----------------------------------------------* | Подпрограммы управления цветом | *----------------------------------------------* } PROCEDURE ChangeAttribute(Page,X1,Y1,X2,Y2, OldAtt,NewAtt: Byte); {Меняет атрибут OLDATT на значение NEWATT в прямоугольнике X1...Y2 страницы PAGE} var Buf: array [1..80,1..2] of Byte; k,j,Size: Byte; BEGIN {Проверяем параметры обращения} if (Page<=MaxPage) and (X1 in [1..MaxChar]) and (Y1 in [1..MaxLine])and (X2 in [1..MaxChar]) and (Y2 in [1..MaxLine])and (X2>X1) and (Y2>Y1) then begin Size := (X2-X1+1)*2; {Размер строкивидеобуфера} for k := Y1 to Y2 do {Цикл по строкам} begin {Получаем копию видеопамяти} MoveFromScreen(Mem[VMemory:Page*VSize+ (pred(k)*MaxChar+X1-1)*2],Buf,Size); {Меняем атрибут} for j := 1 to Size div 2 do if Buf[j,2] = OldAtt then Buf[j,2] := NewAtt; {Возвращаем в видеопамять} MoveToScreen(Buf,Mem[VMemory:Page*VSize+ (pred(k)*MaxChar+X1-1)*2],Size) end end END; {ChangeAttribute} {------------------------} PROCEDURE Colors (Text,Back: Byte); {Устанавливает цвет текста TEXT и цвет фона BACK для активной страницы} BEGIN PageColors(ActivePage,Text,Back) END; PROCEDURE PageColors (Page,Text,Back: Byte); {Устанавливает цвет текста TEXT и цвет фона BACK для страницы PAGE} BEGIN if Page<=MaxPage then begin Pages[Page].Attrib := (Text and $8F) or ((Back and $7) shl 4) or (Back and $80); if Page=0 then begin CRT.TextColor(Text); CRT.TextBackGround(Back) end end END {Colors}; {------------------------} PROCEDURE SetAttribute(Page,X1,Y1,X2,Y2,Attr: Byte); {Заменяет атрибут всех символовв прямоугольнике X1...Y2 страницы PAGE на значение Attr} var Buf: array [1..80,1..2] of Byte; k,j,Size: Byte; BEGIN {Проверяем параметры обращения} if (Page<=MaxPage) and (X1 in [1..MaxChar]) and (Y1 in [1..MaxLine])and (X2 in [1..MaxChar]) and (Y2 in [1..MaxLine])and (X2>X1) and (Y2>Y1) then begin Size := (X2-X1+1)*2; for k := Y1 to Y2 do begin MoveFromScreen(Mem[VMemory:Page*VSize+ (pred(k)*MaxChar+X1-1)*2],Buf,Size); for j := 1 to Size div 2 do Buf[j,2] := Attr; MoveToScreen(Buf,Mem[VMemory:Page*VSize+ (pred(k)*MaxChar+X1-1)*2],Size) end end END; {SetAttribute} {--------------------} FUNCTION PackAttribute(Text,Back: Byte): Byte; {Упаковывает два цвета в байт атрибута} BEGIN PackAttribute := (Text and $8F) or ((Back and 7) shl 4) or (Back and $80) END; {PackAttrinute} {--------------------} PROCEDURE UnPackAttribute(Attr: Byte; var Text,Back: Byte); {Распаковывает байт атрибута и возвращает два цвета} BEGIN Text := Attr and $8F; Back := (Attr shr 4) and 7 END; {UnPackAttribute} {*----------------------------------------------* | Подпрограммы управления курсором | *----------------------------------------------*} PROCEDURE CursorOff; {Отключает курсор в активной странице} BEGIN with Reg do begin AH := 1; {Управление курсором} CH := $20 {Убрать курсор} end; Intr($10,Reg); Pages[ActivePage].CVisible := False END {CursorOff}; {------------------------} PROCEDURE CursorON; {Включает курсор в активной странице} BEGIN with Reg,Pages[ActivePage] do begin AH := 1; {Управление курсором} CH := CLineUp; {Верхняя строка развертки} CL := CLineDown {Нижняя строка} end; Intr($10,Reg); Pages[ActivePage].CVisible := True END {CursorOn}; {---------------------------} PROCEDURE CursorOnOff(Page: Byte; Vis: Boolean); {Устанавливает признак видимости курсора} BEGIN if Page<=MaxPage then if Page=ActivePage then case Vis of True : CursorOff; False: CursorOn end else Pages[Page].CVisible := Vis END; {CursorOnOff} {-------------------------} PROCEDURE GetCursor (Page: Byte;var X,Y,Up,Down: Byte); {Возвращает координаты и размер курсора: PAGE - номер страницы; X, Y - координаты (отсчет от 1,1); Up, Down - размер курсора} BEGIN if Page<=MaxPage then with Reg,Pages[Page] do begin AH := 3; {Получаем положение курсора} BH := Page; {Номер страницы} Intr($10,Reg); X := succ(DL); {Преобразуем координаты} Y := succ(DH); {к началу в 1,1} Up := CLineUp; {Верхняя строка развертки} Down := CLineDown {Нижняя строка} end END {GetCursor}; {------------------------} FUNCTION GetCursorVisible(Page: Byte): Boolean; {Возвращает признак видимости курсора} BEGIN GetCursorVisible := Pages[Page].CVisible END; {GetCursorVisible} {-----------------------} PROCEDURE PutCursor(Page,X,Y: Byte); {Устанавливает требуемое положение курсора. PAGE - номер страницы; X, Y - координаты курсора (отсчет от 1,1)} BEGIN {Проверяем параметры обращения} if (Page<=MaxPage) and (X in [1..MaxChar]) and (Y in [1..MaxLine]) then with Reg do begin AH := 2; {Установить курсор} DH := pred(Y); {Преобразуем координаты} DL := pred(X); {к началу в 0,0} BH := Page; {Страница} Intr($10,Reg) end END {PutCursor}; {--------------------------} PROCEDURE SetCursorLine(Page,Up,Down: Byte); {Устанавливает размер курсора} BEGIN if Page in [0..MaxPage] then with Pages[Page] do begin CLineUp := Up; CLineDown := Down; if Page=ActivePage then SetActivePage(Page) end END; {SetCursorLine} {*----------------------------------------------* | Подпрограммы управления текстовым выводом | *----------------------------------------------*} var OldOutput: Text; {Сохраняетстандартный канал вывода} const ChangeOut: Boolean = False; {Флаг замены канала вывода} PROCEDURE WriteCharXY(Page,X,Y: Byte; Cr: Char); {Выводит символ на указанное место.Атрибуты берутся из массива Attrib.Курсор остается на месте} var Loc: Word; {Старое положение курсора} BEGIN Loc := MemW[$0040:$0050+Page]; with Reg do begin AH := 2; DL := X-1; DH := Y-1; BH := Page; Intr($10,Reg); {Переводим курсор} AH := $9; AL := ord(Cr); BL := Pages[Page].Attrib; BH := Page; CX := 1; Intr($10,Reg); {Выводим символ} AH := 2; DX := Loc; BH := Page; Intr($10,Reg) {Курсор - на старое место} end; MemW[$0040:$0050+Page] := Loc END; {WriteCharXY} {--------------------------} FUNCTION ZeroFunc(var F: TextRec): Integer; Far; {Пустая процедура для операций OPEN/CLOSE} BEGIN ZeroFunc := 0 END; {ZeroFunc} {--------------------------} PROCEDURE Border (Page,X1,Y1,X2,Y2,Bord: Byte); {Обводит рамкойзаданную прямоугольную область экрана} var i : Integer; BEGIN {Проверяем параметры обращения} if not ((Page>MaxPage) or (X1<1) or (X2<=X1) or (Y1<1) or (Y2<=Y1) or (X2>MaxChar) or (Y2>MaxLine) or (Bord>2)) then begin WriteCharXY(Page,X1,Y1,BorderChar[Bord,1]); for i := 1 to X2-X1-1 do {Верхняя рамка} WriteCharXY(Page,X1+i,Y1,BorderChar[Bord,2]); WriteCharXY(Page,X2,Y1,BorderChar[Bord,3]); for i := 1 to Y2-Y1-1 do {Боковые стороны} begin WriteCharXY(Page,X1,Y1+i,BorderChar[Bord,4]); WriteCharXY(Page,X2,Y1+i,BorderChar[Bord,4]) end; WriteCharXY(Page,X1,Y2,BorderChar[Bord,5]); for i := 1 to x2-x1-1 do {Нижняя рамка} WriteCharXY(Page,X1+i,Y2,BorderChar[Bord,2]); WriteCharXY(Page,X2,Y2,BorderChar[Bord,6]) end END {Border}; {--------------------------} PROCEDURE CopyChar(Page:Byte; Cr:Char;Attr:Byte; Count:Word); {Выводит несколько копий символа} BEGIN if (Count>0) and (Page<=MaxPage) then with Reg do begin AH := 9; {Вывод символа} AL := ord(Cr); {Код символа} BL := Attr; {Атрибут} BH := Page; {Страница} CX := Count; {Количество копий} Intr($10,Reg) end END {CopyChar}; {--------------------------} PROCEDURE GetChar (Page: Byte;var Cr: Char; var Attr: Byte); {Читает символ, на который указывает курсор,и его атрибуты} BEGIN if Page<=MaxPage then with Reg do begin AH := 8; {Читать символ} BH := Page; {Страница} Intr($10,Reg); Cr := chr(AL); {Символ} Attr := AH {Его атрибут} end else {Неверная страница} begin Cr := chr(0); Attr := 0 end END {GetChar}; PROCEDURE InitText; {Переопределяет константы, зависящие от адаптера и режима его работы. Содержимоеэкрана не меняется} var k: Byte; Size: Word; Page: Byte; BEGIN {Определяем тип адаптера по байту оборудования ДОС} case (MemW[$0040:$0010] and $30) shr 4 of 3: begin {MDA} MaxPage := 0; VMemory := $B000 end; else begin {Остальные адаптеры} MaxPage := 3; VMemory := $B800 end; end; {Определяем режим работы адаптера} case Mem[$0040:$0049] of 0,1: MaxChar := 40; {40x25} 2,3: MaxChar := 80; {80x25} 7 : begin {MDA} MaxChar := 80; VMemory := $B000 end; else MaxChar := 80 end; {Вычисляем остальные константы} MaxLine := 25; PageSize := MaxLine*MaxChar*2; Page := ActivePage; for k := 0 to 7 do begin SetActivePage(k); VMW[2*k] := MemW[$0040:$004E] end; VSize := VMW[2]-VMW[0]; SetActivePage(Page) END; {InitText} {--------------------------} PROCEDURE MoveFromScreen (var Source,Destin;Count: Word); {Читает данные из видеопамяти} BEGIN if Count>0 then if not CheckSnow then Move(Source,Destin,Count) else {Синхронизация переноса для адаптера CGA} asm lds si,[Source] {DS:SI = адрес источника} les di,[Destin] {ES:DI = адрес приемника} mov cx,Count {Загружаем счетчик в CX} cld {Направление передачи} shr cx,1 {Заменяем байты на слова} mov dx,PortCGA {Загружаем в DXадрес CGA-пopтa} { Отсюда начинается цикл чтения из видеопамяти, который продолжается во время обратного хода луча при горизонтальной развертке. } @1: cli {Закрываем прерывания} @2: in al,dx {В начале очередного цикла} test al,1 {проверяем наличие обратного хода} jne @2 {Ждем обратный ход} lodsw {Получаем видеослово} sti {Открываем прерывания} stosw {Пишем видеослово в приемник} loop @1 {Продолжаем цикл} end END; {MoveFromScreen} {------------------------} PROCEDURE MoveToScreen (var Source, Destin;Count: Word); {Записывает данные в видеопамять} BEGIN if Count>0 then if not CheckSnow then Move (Source,Destin,Count) else {Синхронизация переноса для адаптера CGA} asm lds si,[Source] {DS:SI = адрес источника} les di,[Destin] {ES:DI = адрес приемник} mov cx,Count {Грузим в CX счетчик} cld {Направление передачи} shr cx,1 {Переводим байты в слова} mov dx,PortCGA {Получаем в DXстатус CGA-пopтa} mov bl,9 {Готовим в BL маску проверкиготовности} {Отсюда начинается цикл записи в видеопамять, который продолжается во время обратного хода луча при горизонтальной развертке. Запись проходит при закрытых прерываниях.} @3: lodsw {Получаем в BP} mov bp,ax {очередное видеослово} cli {Закрываем прерывания} @4: in al,dx {Получаем статус видеопорта} test al,1 {Конец горизонтального хода?} jne @4 {Нет - ждем} mov ax,bp {Переносим в AX видеослово} stosw {Пишем его в видеопамять} sti {Открываем прерывания} loop @3 {Продолжаем цикл} end END; {MoveToScreen} {--------------------------} FUNCTION PageWrite(var F: TextRec): Integer; Far; {Осуществляет вывод строки, подготовленнойпроцедурами WRITE/WRITELN, в активнуювидеостраницу} var k: Integer; BEGIN with F,Pages[ActivePage] do if (Mode=fmOutput) and (BufPos>0) then begin for k := 0 to BufPos-1 do with Reg do WriteChar(ActivePage,BufPtr^[k]); BufPos := 0 {Обнуляем буфер вывода} end; PageWrite := 0 END; {PageWrite} {--------------------------} PROCEDURE PageWriteOff; {Восстанавливает стандартный канал вывода} BEGIN if ChangeOut then begin move(OldOutput,Output,SizeOf(Output)); ChangeOut := False end END; {PageWriteOff} {------------------------} PROCEDURE PageWriteOn; {Переназначает стандартный канал выводана процедуру PAGEWRITE, поддерживающуювывод в любую страницу} BEGIN if ChangeOut then Exit; {Блокируем повторную установку} ChangeOut := True; {Сохраняем старый драйвер:} move(Output,OldOutput,SizeOf(Output)); with TextRec(Output) do begin {Назначаем новый драйвер:} OpenFunc := @ZeroFunc; InOutFunc := @PageWrite; FlushFunc := @PageWrite; CloseFunc := @ZeroFunc; end END; {PageWriteOn} {--------------------------} PROCEDURE PutChar (Page: Byte; Cr: Char); {Записывает символ на место, указываемое курсором в заданной странице. Курсорне меняет положения.Атрибуты берутся из массива Attrib} BEGIN if Page<=MaxPage then with Reg do begin AH := $9; AL := ord(Cr); BH := Page; BL := Pages[Page].Attrib; CX := 1; Intr($10,Reg) end END {PutChar}; {--------------------------} PROCEDURE WriteChar (Page: Byte; Cr: Char); {Выводит символ и сдвигает курсор. Используются атрибуты из массива Attrib} var X,Y,X1,Y1,X2,Y2,Size: Byte; Buf: array [1..80,1..2] of Char; VW,k: Word; P: Pointer; BEGIN if Page<=MaxPage then with Reg,Pages[Page] do begin GetCursor(Page,X,Y,X1,Y1); {Смещение в странице} k := (Pred(Y)*MaxChar+Pred(X))*2; P := ptr(VMemory,VMW[Page*2]+k); VW := Pages[Page].Attrib shl 8+ord(Cr); case Cr of {Обрабатываем спецсимволы} #7: begin {Звук} Sound(900); Delay(150); NoSound; Exit end; #8: if X>Lo(WBondUp)+2 then {Back Space} dec(X,2) else if Y>Hi(WBondUp)+2 then begin X := Lo(WBondDown); dec(Y) end; #10: inc(X,80); {LF} #13: X := Lo(WBondUp); {CR} else MoveToScreen(VW,P^,2); end; Inc(X); {Сдвигаем в строке} if X-1>Lo(WBondDown) then {Достигнута правая граница окна} begin X := Lo(WBondUp)+1; {Возвращаем к левой} inc(Y); {границе на новой строке} if Y-1>Hi(WBondDown) then begin {Достигли нижнюю границу} {Делаем прокрутку с помощью прямого обращенияк видеопамяти, т.к. функция 6 работает толькос активной страницей} dec(Y); X1 := Lo(WBondUp); Y1 := Hi(WBondUp); X2 := Lo(WBondDown); Y2 := Hi(WBondDown); Size := 2*(X2-X1+1); for k := Y1+1 to Y2 do begin MoveFromScreen(Mem[VMemory:Page* VSize+(k*MaxChar+X1)*2],Buf,Size); MoveToScreen(Buf,Mem[VMemory:Page* VSize+((k-1)*MaxChar+X1)*2],Size) end; for k := 1 to 1+X2-X1 do Buf[k,1] := ' '; MoveToScreen(Buf,Mem[VMemory:Page* VSize+(Y2*MaxChar+X1)*2],Size) end end; PutCursor(Page,X,Y) end END; {WriteChar} {*-------------------------------------------------* | Многостраничные варианты подпрограмм модуля CRT | *-------------------------------------------------*} PROCEDURE ClrEOL; {Удаляет остаток строки справа от курсорав активной странице} var X1,X2: Byte; P: Pointer; X,Y: Byte; Buf: array [1..80] of Word; BEGIN GetCursor(ActivePage,X,Y,X1,X2); with Pages[ActivePage] do begin P := Ptr(VMemory,VMW[ActivePage*2]+ (Pred(Y)*MaxChar+Pred(X))*2); X2 := PagePar[7]-X+2; for X := 1 to X2 do Buf[X] := 32+Attrib shl 8; MoveToScreen(Buf,P^,X*2) end END; {ClrEOL} {--------------------------} PROCEDURE ClrScr; {Очищает текущее окно (страницу)} BEGIN with Pages[ActivePage],Reg do begin AH := 6; {С помощью прокрутки} AL := 0; {очищаем все окно} BH := Attrib; CL := Lo(WBondUp); CH := Hi(WBondUp); DL := Lo(WBondDown); DH := Hi(WBondDown); Intr($10,Reg); AH := 2; {Устанавливаем курсор} BH := ActivePage; {в левый верхний угол} DX := WBondUp; Intr($10,Reg) end END; {ClrScr} {--------------------------} PROCEDURE DelLine; {Удаляет строку в активной странице} var k, S, {Длина строки окна} Y: Byte; {Номер строки с курсором} C: Word; {Смещение в памяти для левой границы окна} Buf: array [1..80,1..2] of Char; {Буфер строк} P: Pointer; BEGIN {Стираем строку прокруткой окна вверх} with Pages[ActivePage] do begin {Определяем положение в видеопамяти левой верхней границы окна} C := VMW[ActivePage*2]+PagePar[5]*2; Y := PagePar[6]+Pred(WhereY); S := (PagePar[7]-PagePar[5]+1)*2; {Переносим по строкам} for K := Y+1 to PagePar[8] do begin P := Ptr(VMemory,C+K*MaxChar*2); MoveFromScreen(P^,Buf,s); P := Ptr(VMemory,C+(K-1)*MaxChar*2); MoveToScreen(Buf,P^,s) end; {Готовим пустую строку} for K := 1 to 80 do begin Buf[k,1] := ' '; Buf[k,2] := chr(Attrib) end; {Выводим ее} P := Ptr(VMemory,C+PagePar[8]*MaxChar*2); MoveToScreen(Buf,P^,s) end END; {DelLine} PROCEDURE GotoXY(X,Y: Byte); {Устанавливает курсор в активной странице} BEGIN with Pages[ActivePage] do PutCursor(ActivePage,Lo(WBondUp)+X,Hi(WBondUp)+Y) END; {GotoXY} {-------------------------} PROCEDURE InsLine; {Вставляет пустую строку в активной странице} var k, S, {Длина строки окна} Y: Byte; {Номер строки с курсором} C: Word; {Смещение в памятидля левой границы окна} Buf: array [1..80,1..2] of Char; {Буфер строк} P: Pointer; BEGIN with Pages[ActivePage] do begin {Определяем положение в видеопамяти левой верхней границы окна} C := VMW[ActivePage*2]+PagePar[5]*2; Y := PagePar[6]+Pred(WhereY); S := (PagePar[7]-PagePar[5]+1)*2; {Переносим по строкам} for K := PagePar[8]-1 downto Y do begin P := Ptr(VMemory,C+K*MaxChar*2); MoveFromScreen(P^,Buf,s); P := Ptr(VMemory,C+(K+1)*MaxChar*2); MoveToScreen(Buf,P^,s) end; {Готовим пустую строку} for K := 1 to 80 do begin Buf[k,1] := ' '; Buf[k,2] := chr(Attrib) end; {Выводим ее} P := Ptr(VMemory,C+Y*MaxChar*2); MoveToScreen(Buf,P^,s) end END; {InsLine} {--------------------------} PROCEDURE TextBackGround(Color: Byte); {Устанавливает цвет фонав активной странице} BEGIN Pages[ActivePage].Attrib := (Pages[ActivePage].Attrib and $8F) or ((Color and $7) shl 4); if ActivePage=0 then CRT.TextBackGround(Color) END; {PageTextBackGround} {--------------------------} PROCEDURE TextColor(Color: Byte); {Устанавливает цвет символов в активной странице} BEGIN Pages[ActivePage].Attrib := (Pages[ActivePage].Attrib and $70) or (Color and $8F); if ActivePage=0 then CRT.TextColor(Color) END; {PageTextColor} FUNCTION WhereX: Byte; {Возвращает горизонтальную координату курсора в активной странице} var X,Y,U,D: Byte; BEGIN GetCursor(ActivePage,X,Y,U,D); WhereX := X-Lo(Pages[ActivePage].WBondUp) END; {WhereX} {--------------------------} FUNCTION WhereY: Byte; {Возвращает вертикальную координату курсора в активной странице} var X,Y,U,D: Byte; BEGIN GetCursor(ActivePage,X,Y,U,D); WhereY := Y-Hi(Pages[ActivePage].WBondUp) END; {WhereY} {--------------------------} PROCEDURE Window(X1,Y1,X2,Y2: Byte); {Устанавливает окно в активной странице} BEGIN {Проверяем параметры обращения} if (X1 in [1..MaxChar]) and (X2 in [1..MaxChar]) and (X2>X1) and (Y1 in [1..MaxLine]) and (Y2 in [1..MaxLine]) and (Y2>Y1) then with Pages[ActivePage] do begin WBondUp := pred(X1)+pred(Y1) shl 8; WBondDown := pred(X2)+pred(Y2) shl 8; PutCursor(ActivePage,X1,Y1); if ActivePage=0 then CRT.Window(X1,Y1,X2,Y2) end END; {*----------------------------------------------* | Подпрограммы управления страницами | *----------------------------------------------*} FUNCTION GetActivePage: Byte; {Возвращает номер активной текстовой страницы} BEGIN GetActivePage := ActivePage END {GetActivePage}; {---------------------------} PROCEDURE GetPage (Page: Byte; var Destin); {Копирует текстовую страницу в оперативную память} BEGIN if Page<=MaxPage then MoveFromScreen(Mem[VMemory:VSize*page], Destin,MaxChar*MaxLine*2) END {GetPage}; {------------------------} FUNCTION PageSaveSize: Word; {Возвращает размер буфера, необходимый для сохранения текущего состояния видеостраницы} BEGIN PageSaveSize := PageSize+SizeOf(PageType) END; {PageSaveSize} {------------------------} PROCEDURE PutPage (var Source; Page: Byte); {Пересылает содержимое оперативной памяти в страницу видеопамяти} BEGIN if Page<=MaxPage then MoveToScreen(Source,Mem[VMemory:VSize*Page], MaxChar*MaxLine*2) END {PutPage}; {--------------------------} PROCEDURE RestorePage(Page: Byte; var Buf); {Восстанавливает текущее состояние страницы PAGE по содержимому буфера BUF} var B: array [0..MaxInt] of Byte absolute Buf; BEGIN if Page>MaxPage then Exit; MoveToScreen(B,VMP[Page]^,PageSize); Move(B[PageSize],Pages[Page],SizeOf(PageType)); if Page=ActivePage then SetActivePage(ActivePage) END; {RestorePage} {--------------------------} PROCEDURE SavePage(Page: Byte; var Buf); {Сохраняет текущее состояниестраницы PAGE в буфере BUF} var B: array [0..MaxInt] of Byte absolute Buf; BEGIN if Page>MaxPage then Exit; MoveFromScreen(VMP[Page]^,B,PageSize); Move(Pages[Page],B[PageSize],SizeOf(PageType)) END; {SavePage} {------------------------} PROCEDURE SetActivePage (Page : Byte); {Активизирует заданную текстовую страницу} BEGIN if Page<=MaxPage then with Reg,Pages[Page] do begin AH := 5; {Установить страницу} AL := Page; {Номер страницы} ActivePage := Page; {КорректируемActivePage} Intr ($10,Reg); if CVisible then {Включаем/отключаем} CursorOn {курсор} else CursorOff; TextAttr := Attrib; {Устанавливаем атрибут} WindMin := WBondUp; {Текущее окно} WindMax := WBondDown end; END {SetActivePage}; {------------------------} PROCEDURE SwapPage (Source, Destin: Byte); { Копирует одну текстовую страницу в другую } var buf : array [1..2, 1..80] of Byte; i : Integer; BEGIN if (Source<=MaxPage) and (Destin<=MaxPage) then for i := 0 to MaxLine-1 do begin MoveFromScreen(Mem[VMemory:VSize* Source+i*MaxChar*2],buf,MaxChar*2); MoveToScreen(buf,Mem[VMemory:VSize* Destin+i*MaxChar*2],MaxChar*2) end END {SwapPage}; {*----------------------------------------------* | Подпрограммы управления окнами | *----------------------------------------------*} PROCEDURE ChangeWindAttribute(Page,OldAtt,NewAtt: Byte); {Заменяет в окне атрибут OLDATTна значение NEWATT} var X1,Y1,X2,Y2: Byte; BEGIN if Page<=MaxPage then with Pages[Page] do begin X1 := Lo(WBondUp); Y1 := Hi(WBondUp); X2 := Lo(WBondDown)+2; Y2 := Hi(WBondDown)+2; ChangeAttribute(Page,X1,Y1,X2,Y2,OldAtt,NewAtt) end END; {ChangeWindAttribute} {-----------------------} PROCEDURE CopyWind(Page,X,Y: Byte; var Buf; LX,LY: Byte); {Переносит копию окна из памяти на страницу} var X2,Y2,k: Byte; Size: Word; B: array [0..MaxInt] of Byte absolute Buf; BEGIN if (X in [1..MaxChar]) and (Y in [1..MaxLine]) and (Page<=MaxPage) then with Pages[Page] do begin X2 := X+LX-1; if X2>MaxChar then X2 := MaxChar; Y2 := Y+LY-1; if Y2>MaxLine then Y2 := MaxLine; Size := (X2-X+1)*2; for k := Y to Y2 do MoveToScreen(B[(k-Y)*LX*2],Mem[VMemory:Page*VSize+ (pred(k)*MaxChar+X-1)*2],Size); WBondUp := X+Y shl 8; WBondDown := X2-2+(Y2-2) shl 8; if Page=ActivePage then SetActivePage(Page) end END; {CopyWind} {------------------------} PROCEDURE GetWindow (Page: Byte); {Восстанавливает состояние экрана, бывшее перед обращением к процедуре PUTWINDOW} var X,Y,U,D: Byte; BEGIN if (Page<=MaxPage) and (Page<>ActivePage) then begin SwapPage(Page,ActivePage); Move(Pages[Page],Pages[ActivePage],SizeOf(PageType)); GetCursor(Page,X,Y,U,D); PutCursor(ActivePage,X,Y); SetCursorLine(ActivePage,U,D); SetActivePage(ActivePage) end END {GetWindow}; PROCEDURE PutWindow(X1,Y1,X2,Y2,Text,Back,Bord,Page: Byte; Header: String;Clip,Build,Play: Boolean); {Сохраняет текущий экран в текстовой странице PAGE и организует окно с заданными атрибутами и рамкой} var X,Y,U,D: Byte; BEGIN if not ((Page>MaxPage) or (X1<1) or (X2<=X1) or(Y1<1) or (Y2<=Y1) or (X2>MaxChar) or(Y2>MaxLine) or (Bord>2)) then begin SwapPage(ActivePage,Page); Move(Pages[ActivePage],Pages[Page],SizeOf(PageType)); GetCursor(ActivePage,X,Y,U,D); PutCursor(Page,X,Y); SetCursorLine(Page,U,D); Colors(Text,Back); SetWindow(X1,Y1,X2,Y2,Bord,Header,Clip,Build,Play) end; END {PutWindow}; {------------------------} PROCEDURE SaveWind(Page: Byte; var Buf; var LX,LY: Byte); {Сохраняет копию окна в буфере BUF} var X1,Y1,X2,Y2: Byte; B: array [0..MaxInt] of Byte absolute Buf; k: Byte; BEGIN if Page<=MaxPage then with Pages[Page] do begin X1 := Lo(WBondUp); Y1 := Hi(WBondUp); X2 := Lo(WBondDown)+2; Y2 := Hi(WBondDown)+2; LX := X2-X1+1; LY := Y2-Y1+1; for k := Y1 to Y2 do MoveFromScreen(Mem[VMemory:Page*VSize+ (pred(k)*MaxChar+X1-1)*2],B[(k-Y1)*LX*2],LX*2) end END; {SaveWind} {------------------------} PROCEDURE SetPageWindow (Page,X1,Y1,X2,Y2,Bord: Byte; Header: String;Clip: Boolean); {Создает окно в странице PAGEи обводит его рамкой} var buf: array [1..80,1..2] of Byte; X,Y,Size,k: Byte; BEGIN if not ((Page>MaxPage) or (X1<1) or (X2<=X1) or(Y1<1) or (Y2<=Y1) or (X2>MaxChar) or(Y2>MaxLine) or (Bord>2)) then begin {Очищаем прямоугольное окно на экране} Size := X2-X1+1; for Y := 1 to Size do begin buf[Y,1] := ord(' '); buf[Y,2] := Pages[Page].Attrib end; Size := Size+Size; for Y := Y1 to Y2 do MoveToScreen(Buf,Mem[VMemory:Page*VSize+ (pred(Y)*MaxChar+pred(X1))*2],Size); {Обводим его рамкой и выводим заголовок} if Bord<>EmptyBorder then Border(Page,X1,Y1,X2,Y2,Bord); if Length(Header)>0 then begin if Length(Header)>X2-X1-2 then Header[0] := chr(X2-X1-2); X := X1+(X2-X1-Length(Header)) div 2; for k := 1 to Length(Header) do WriteCharXY(Page,X+k,Y1,Header[k]); end; {Корректируем границы внутрь прямоугольника X1...Y2, если признак Clip равен True} if Clip then begin inc(X1); inc(Y1); dec(X2); dec(Y2) end; {Устанавливаем курсор в левую вершину и запоминаем координаты} dec(X1); {Преобразуем координаты} dec(Y1); {к началу в точке 0,0} dec(X2); dec(Y2); PutCursor(Page,X1+1,Y1+1); Pages[Page].WBondUp :=X1+Y1 shl 8; Pages[Page].WBondDown :=X2+Y2 shl 8; if Page=ActivePage then SetActivePage(Page) end END {SetPageWindow}; {------------------------} PROCEDURE SetWindAttribute(Page,Attr: Byte); {Устанавливает новый атрибут окна} var X1,Y1,X2,Y2: Byte; BEGIN if Page<=MaxPage then with Pages[Page] do begin X1 := Lo(WBondUp); Y1 := Hi(WBondUp); X2 := Lo(WBondDown)+2; Y2 := Hi(WBondDown)+2; SetAttribute(Page,X1,Y1,X2,Y2,Attr) end END; {SetWindAttribute} {------------------------} PROCEDURE SetWindow (X1,Y1,X2,Y2,Bord: Byte; Header: String; Clip,Build,Play: Boolean); {Создает окно в активной страницеи обводит его рамкой} var xx1,yy1,xx2,yy2,x,y,dx,dy,k: Byte; dt: Integer; const TonBeg = 400; {Начальный тон} TonEnd = 800; {Конечный тон} Pause = 5; N = 10; BEGIN if Build and ((x2-x1>=4) or (y2-y1>=4)) then begin {Начальное положение левого верхнего угла окна} x := (x2-x1) div 2; y := (y2-y1) div 2; {Количество промежуточных окон} dx := ((x2-x1) div 2) div N; dy := ((y2-y1) div 2) div N; if dx=0 then inc(dx); if dy=0 then inc(dy); if x>1 then begin xx1 := x1+x-1; xx2 := x2-x+1 end else begin xx1 := x1; xx2 := x2 end; if y>1 then begin yy1 := y1+y-1; yy2 := y2-y+1 end else begin yy1 := y1; yy2 := y2 end; {Изменение тона} dt := (TonEnd-TonBeg) div N; for k := 0 to N-1 do {Цикл построения} begin if Play then Sound(TonBeg+dt*k); {Включаем звук} SetPageWindow(ActivePage, xx1,yy1,xx2,yy2,Bord,Header,Clip); {Увеличиваем границы окна} if xx1>x1 then dec(xx1,dx); if xx2<x2 then inc(xx2,dx); if yy1>y1 then dec(yy1,dy); if yy2<y2 then inc(yy2,dy); Delay(Pause) end; if Play then NoSound; end; SetPageWindow(ActivePage,X1,Y1,X2,Y2,Bord,Header,Clip) END; {SetWindow} {------------------------} PROCEDURE WindMoveRel(Page: Byte; DX,DY: Integer; var Buf; ClipW: Boolean); {Смещает окно относительно прежнего положения: PAGE - номер страницы; DX,DY- приращения координатлевого верхнего угла; BUF - вид экрана без окна; CLIPW- признак отсечки изображения} var X,Y: Byte; BEGIN if Page<=MaxPage then with Pages[Page] do begin X := Lo(WBondUp); Y := Hi(WBondUp); if X+DX<1 then X := 1 else if X+DX>MaxChar then X := MaxChar else X := X+DX; if Y+DY<1 then Y := 1 else if Y+DY>MaxLine then Y := MaxLine else Y := Y+DY; WindMoveTo(Page,X,Y,Buf,ClipW) end END; {WindMovRel} {------------------------} PROCEDURE WindMoveTo(Page,X,Y: Byte;var Buf; ClipW: Boolean); {Перемещает окно в новое положение: PAGE - номер страницы; X,Y - новые координаты левого верхнего угла; BUF - вид экрана без окна; CLIPW- признак отсечки изображения} var X2,Y2,LX,LY: Byte; Cop: array [1..4000] of Byte; BEGIN if (X in [1..MaxChar]) and (Y in [1..MaxLine]) and (Page<=MaxPage) then with Pages[Page] do begin {Копируем окно в буфер Cop} SaveWind(Page,Cop,LX,LY); {Восстанавливаем вид страницы} MoveToScreen(Buf,VMP[Page]^,PageSize); if not ClipW then {Корректируем положение} begin while X+LX-1>MaxChar do dec(X); while Y+LY-1>MaxLine do dec(Y) end; {Переносим окно на новое место} CopyWind(Page,X,Y,Cop,LX,LY); {Запоминаем новые границы окна} if Page=ActivePage then SetActivePage(Page) end END; {WindMoveTo} {--------------------------} FUNCTION WindSize(Page: Byte): Word; {Возвращает размер буфера для сохранения окна} var X1,Y1,X2,Y2: Byte; BEGIN if Page<=MaxPage then with Pages[Page] do begin X1 := Lo(WBondUp); Y1 := Hi(WBondUp); X2 := Lo(WBondDown)+2; Y2 := Hi(WBondDown)+2; WindSize := (X2-X1+1)*(Y2-Y1+1)*2 end else WindSize := 0 END; {WindSize} {============} END. {TextCRT} {=============}
{******************************************************************************* * * * TksImageViewer - Enhanced image viewer component * * * * https://github.com/gmurt/KernowSoftwareFMX * * * * Copyright 2015 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * 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 ksImageViewer; interface {$I ksComponents.inc} uses Classes, Types, ksTypes, FMX.InertialMovement, System.UITypes, FMX.Graphics, FMX.Layouts, FMX.Types; type [ComponentPlatformsAttribute(pidWin32 or pidWin64 or {$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)] TksImageViewer = class(TksControl) private FAniCalc: TksAniCalc; FBitmap: TBitmap; FZoom: integer; FStartZoom: integer; FStartDistance: Integer; FOnZoom: TNotifyEvent; FMaxXPos: single; FMaxYPos: single; procedure AniCalcStart(Sender: TObject); procedure AniCalcStop(Sender: TObject); procedure AniCalcChange(Sender: TObject); procedure SetBitmap(const Value: TBitmap); procedure UpdateScrollLimits; procedure SetZoom(const Value: integer); protected procedure MouseDown(Button: TMouseButton; Shift: TShiftState; x, y: single); override; procedure MouseMove(Shift: TShiftState; x, y: single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; x, y: single); override; procedure DoMouseLeave; override; procedure Paint; override; procedure Resize; override; procedure CMGesture(var EventInfo: TGestureEventInfo); override; public procedure UpdateLabel(ADistance: integer); constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure MultiTouch(const Touches: TTouches; const Action: TTouchAction); published property Align; property Bitmap: TBitmap read FBitmap write SetBitmap; property Zoom: integer read FZoom write SetZoom default 100; property OnGesture; property OnZoom: TNotifyEvent read FOnZoom write FOnZoom; end; procedure Register; implementation uses System.UIConsts, SysUtils, Math, FMX.Controls; procedure Register; begin RegisterComponents('Kernow Software FMX', [TksImageViewer]); end; { TksImageViewer } procedure TksImageViewer.AniCalcStart(Sender: TObject); begin if Scene <> nil then Scene.ChangeScrollingState(Self, True); end; procedure TksImageViewer.AniCalcStop(Sender: TObject); begin if Scene <> nil then Scene.ChangeScrollingState(nil, False); end; procedure TksImageViewer.CMGesture(var EventInfo: TGestureEventInfo); {$IFDEF IOS} var APercent: integer; ANewZoom: integer; {$ENDIF} begin inherited; {$IFDEF IOS} if FStartDistance = 0 then APercent := 100 else APercent := Round((EventInfo.Distance / FStartDistance) * 100); ANewZoom := Round(FStartZoom * (APercent / 100)); if Max(FZoom, ANewZoom) - Min(FZoom, ANewZoom) > 10 then begin FStartZoom := FZoom; FStartDistance := 0; Exit; end; Zoom := ANewZoom; FStartZoom := Zoom; FStartDistance := EventInfo.Distance; {$ENDIF} end; constructor TksImageViewer.Create(AOwner: TComponent); begin inherited; FBitmap := TBitmap.Create; FAniCalc := TksAniCalc.Create(nil); FAniCalc.OnChanged := AniCalcChange; FAniCalc.ViewportPositionF := PointF(0, 0); FAniCalc.Animation := True; FAniCalc.Averaging := True; FAniCalc.Interval := 8; FAniCalc.BoundsAnimation := True; FAniCalc.TouchTracking := [ttHorizontal, ttVertical]; FAniCalc.OnChanged := AniCalcChange; FAniCalc.OnStart := AniCalcStart; FAniCalc.OnStop := AniCalcStop; FZoom := 100; FMaxXPos := 0; FMaxYPos := 0; Touch.InteractiveGestures := [TInteractiveGesture.Zoom, TInteractiveGesture.Pan]; end; destructor TksImageViewer.Destroy; begin FreeAndNil(FBitmap); FreeAndNil(FAniCalc); inherited; end; procedure TksImageViewer.MouseDown(Button: TMouseButton; Shift: TShiftState; x, y: single); begin inherited; //Form73.ListBox1.Items.Insert(0, 'MouseDown'); FAniCalc.MouseDown(x, y); end; procedure TksImageViewer.DoMouseLeave; begin inherited; if (FAniCalc <> nil) then FAniCalc.MouseLeave; FStartDistance := 0; FStartZoom := 0; //updatelabel(EventInfo.Distance); //updatelabel(); end; procedure TksImageViewer.MouseMove(Shift: TShiftState; x, y: single); begin inherited; FAniCalc.MouseMove(x, y); end; procedure TksImageViewer.MouseUp(Button: TMouseButton; Shift: TShiftState; x, y: single); begin inherited; FAniCalc.MouseUp(x, y); //Form73.ListBox1.Items.Insert(0, 'MouseUp'); FStartZoom := 0; FStartDistance := 0; UpdateScrollLimits; end; procedure TksImageViewer.MultiTouch(const Touches: TTouches; const Action: TTouchAction); begin // still working this out. end; procedure TksImageViewer.Paint; var ASourceRect: TRectF; ADestRect: TRectF; ASaveState: TCanvasSaveState; begin inherited; if (csDesigning in ComponentState) then DrawDesignBorder(claDimgray, claDimgray); ASaveState := Canvas.SaveState; try Canvas.IntersectClipRect(ClipRect); Canvas.Clear(claBlack); ASourceRect := RectF(0, 0, FBitmap.Width, FBitmap.Height); ADestRect := ASourceRect; ADestRect.Width := (FBitmap.Width/100)*FZoom; ADestRect.Height := (FBitmap.Height/100)*FZoom; //{$IFDEF ANDROID} ADestRect := ClipRect; //{$ENDIF} OffsetRect(ADestRect, 0-FAniCalc.ViewportPosition.X, 0-FAniCalc.ViewportPosition.Y); if ADestRect.Width < Width then OffsetRect(ADestRect, (Width - ADestRect.Width) /2, 0); if ADestRect.Height < Height then OffsetRect(ADestRect, 0, (Height - ADestRect.Height) /2); Canvas.DrawBitmap(FBitmap, ASourceRect, ADestRect, 1, True); finally Canvas.RestoreState(ASaveState); end; end; procedure TksImageViewer.Resize; begin inherited; UpdateScrollLimits; end; procedure TksImageViewer.SetBitmap(const Value: TBitmap); begin FBitmap.Assign(Value); UpdateScrollLimits; end; procedure TksImageViewer.SetZoom(const Value: integer); var xpercent, ypercent: single; begin if (Value > 10) and (Value < 200) then begin if FZoom <> Value then begin FZoom := Value; FAniCalc.UpdatePosImmediately; FAniCalc.MouseLeave; if FMaxXPos = 0 then XPercent := 0 else xpercent := (FAniCalc.ViewportPositionF.X / FMaxXPos) * 100; if FMaxYPos = 0 then ypercent := 0 else ypercent := (FAniCalc.ViewportPositionF.Y / FMaxYPos) * 100; UpdateScrollLimits; FAniCalc.ViewportPositionF := PointF((FMaxXPos / 100) * xpercent, (FMaxYPos / 100) * ypercent); InvalidateRect(ClipRect); if Assigned(FOnZoom) then FOnZoom(Self); end; end; end; procedure TksImageViewer.AniCalcChange(Sender: TObject); begin InvalidateRect(ClipRect); end; procedure TksImageViewer.UpdateLabel(ADistance: integer); begin end; procedure TksImageViewer.UpdateScrollLimits; var Targets: array of TAniCalculations.TTarget; w, h: single; begin if FAniCalc <> nil then begin //w := (FBitmap.Width / 100) * FZoom; //h := (FBitmap.Height / 100) * FZoom; //w := w - Width; //h := h - Height; w := 0; h := 0; SetLength(Targets, 2); Targets[0].TargetType := TAniCalculations.TTargetType.Min; Targets[0].Point := TPointD.Create(0, 0); Targets[1].TargetType := TAniCalculations.TTargetType.Max; Targets[1].Point := TPointD.Create(Max(0,w), Max(0, h)); FAniCalc.SetTargets(Targets); FMaxXPos := Targets[1].Point.X; FMaxYPos := Targets[1].Point.Y; end; end; end.
program PN (input, output); function isPrime (i : integer) : boolean; {returns True when PN, false if not} var laufzahl : integer; begin if i < 2 then isPrime := false else begin isPrime := true; for laufzahl := 2 to i -1 do if i mod laufzahl = 0 then isPrime := false end end; begin end .
unit Ntapi.appmodel; { This module includes definitions for inspecting packaged applocations. } interface {$WARN SYMBOL_PLATFORM OFF} {$MINENUMSIZE 4} uses Ntapi.WinNt, Ntapi.ntdef, Ntapi.ntseapi, Ntapi.ntpebteb, Ntapi.Versions, Ntapi.WinUser, DelphiApi.Reflection; const // SDK::appmodel.h - information flags PACKAGE_INFORMATION_BASIC = $00000000; PACKAGE_INFORMATION_FULL = $00000100; // SDK::appmodel.h - filter flags PACKAGE_FILTER_HEAD = $00000010; PACKAGE_FILTER_DIRECT = $00000020; PACKAGE_FILTER_RESOURCE = $00000040; PACKAGE_FILTER_BUNDLE = $00000080; PACKAGE_FILTER_OPTIONAL = $00020000; PACKAGE_FILTER_IS_IN_RELATED_SET = $00040000; PACKAGE_FILTER_STATIC = $00080000; PACKAGE_FILTER_DYNAMIC = $00100000; PACKAGE_FILTER_HOSTRUNTIME = $00200000; // Win 10 20H2+ // SDK::appmodel.h - package properties PACKAGE_PROPERTY_FRAMEWORK = $00000001; PACKAGE_PROPERTY_RESOURCE = $00000002; PACKAGE_PROPERTY_BUNDLE = $00000004; PACKAGE_PROPERTY_OPTIONAL = $00000008; PACKAGE_PROPERTY_HEAD = $00000010; // rev PACKAGE_PROPERTY_DIRECT = $00000020; // rev PACKAGE_PROPERTY_DEVELOPMENT_MODE = $00010000; PACKAGE_PROPERTY_IS_IN_RELATED_SET = $00040000; PACKAGE_PROPERTY_STATIC = $00080000; PACKAGE_PROPERTY_DYNAMIC = $00100000; PACKAGE_PROPERTY_HOSTRUNTIME = $00200000; // Win 10 20H2+ // Windows Internals book - package claim flags PSM_ACTIVATION_TOKEN_PACKAGED_APPLICATION = $0001; PSM_ACTIVATION_TOKEN_SHARED_ENTITY = $0002; PSM_ACTIVATION_TOKEN_FULL_TRUST = $0004; PSM_ACTIVATION_TOKEN_NATIVE_SERVICE = $0008; PSM_ACTIVATION_TOKEN_DEVELOPMENT_APP = $0010; PSM_ACTIVATION_TOKEN_BREAKAWAY_INHIBITED = $0020; PSM_ACTIVATION_TOKEN_RUNTIME_BROKER = $0040; // rev PSM_ACTIVATION_TOKEN_WIN32ALACARTE_PROCESS = $00010000; // rev // rev - attributes for RtlQueryPackageClaims PACKAGE_ATTRIBUTE_SYSAPPID_PRESENT = $0001; PACKAGE_ATTRIBUTE_PKG_CLAIM_PRESENT = $0002; PACKAGE_ATTRIBUTE_SKUID_PRESENT = $0004; PACKAGE_ATTRIBUTE_XBOX_LI_PRESENT = $0008; // rev - helpers for TAppModelPolicy_PolicyValue APP_MODEL_POLICY_TYPE_SHIFT = 16; APP_MODEL_POLICY_TYPE_MASK = $FFFF0000; APP_MODEL_POLICY_VALUE_MASK = $0000FFFF; // Desktop AppX activation options DAXAO_ELEVATE = $00000001; DAXAO_NONPACKAGED_EXE = $00000002; DAXAO_NONPACKAGED_EXE_PROCESS_TREE = $00000004; // Win 10 RS2+ DAXAO_NO_ERROR_UI = $00000008; // Win 10 20H1+ DAXAO_CHECK_FOR_APPINSTALLER_UPDATES = $00000010; // Win 10 20H1+ (was 0x40 in 19H1 & 19H2) DAXAO_CENTENNIAL_PROCESS = $00000020; // Win 10 20H1+ DAXAO_UNIVERSAL_PROCESS = $00000040; // Win 10 20H1+ DAXAO_WIN32ALACARTE_PROCESS = $00000080; // Win 10 20H1+ DAXAO_PARTIAL_TRUST = $00000100; // Win 10 20H1+ DAXAO_UNIVERSAL_CONSOLE = $00000200; // Win 10 20H1+ CLSID_DesktopAppXActivator: TGuid = '{168EB462-775F-42AE-9111-D714B2306C2E}'; type // SDK::appmodel.h [MinOSVersion(OsWin8)] [SDKName('PACKAGE_VERSION')] TPackageVersion = record Revision: Word; Build: Word; Minor: Word; Major: Word; end; // SDK::appmodel.h [MinOSVersion(OsWin8)] [SDKName('PACKAGE_ID')] TPackageId = record [Unlisted] Reserved: Cardinal; ProcessorArchitecture: TProcessorArchitecture; [Unlisted] Padding: Word; Version: TPackageVersion; Name: PWideChar; Publisher: PWideChar; ResourceID: PWideChar; PublisherID: PWideChar; end; PPackageId = ^TPackageId; // SDK::appmodel.h [MinOSVersion(OsWin1019H1)] [SDKName('PackagePathType')] [NamingStyle(nsCamelCase, 'PackagePathType_')] TPackagePathType = ( PackagePathType_Install = 0, PackagePathType_Mutable = 1, PackagePathType_Effective = 2, [MinOSVersion(OsWin1020H1)] PackagePathType_MachineExternal = 3, [MinOSVersion(OsWin1020H1)] PackagePathType_UserExternal = 4, [MinOSVersion(OsWin1020H1)] PackagePathType_EffectiveExternal = 5 ); [FlagName(PACKAGE_INFORMATION_BASIC, 'Basic')] [FlagName(PACKAGE_INFORMATION_FULL, 'Full')] TPackageInformationFlags = type Cardinal; TPackageFullNames = TAnysizeArray<PWideChar>; PPackageFullNames = ^TPackageFullNames; [FlagName(PACKAGE_FILTER_HEAD, 'Head Package')] [FlagName(PACKAGE_FILTER_DIRECT, 'Directly Dependent')] [FlagName(PACKAGE_FILTER_RESOURCE, 'Resource')] [FlagName(PACKAGE_FILTER_BUNDLE, 'Bundle')] [FlagName(PACKAGE_FILTER_OPTIONAL, 'Optional')] [FlagName(PACKAGE_FILTER_IS_IN_RELATED_SET, 'In Related Set')] [FlagName(PACKAGE_FILTER_STATIC, 'Static')] [FlagName(PACKAGE_FILTER_DYNAMIC, 'Dynamic')] [FlagName(PACKAGE_FILTER_HOSTRUNTIME, 'Host Runtime')] TPackageFilters = type Cardinal; [FlagName(PACKAGE_PROPERTY_FRAMEWORK, 'Framework')] [FlagName(PACKAGE_PROPERTY_RESOURCE, 'Resource')] [FlagName(PACKAGE_PROPERTY_BUNDLE, 'Bundle')] [FlagName(PACKAGE_PROPERTY_OPTIONAL, 'Optional')] [FlagName(PACKAGE_PROPERTY_HEAD, 'Head Package')] [FlagName(PACKAGE_PROPERTY_DIRECT, 'Directly Dependent')] [FlagName(PACKAGE_PROPERTY_DEVELOPMENT_MODE, 'Development Mode')] [FlagName(PACKAGE_PROPERTY_IS_IN_RELATED_SET, 'In Related Set')] [FlagName(PACKAGE_PROPERTY_STATIC, 'Static')] [FlagName(PACKAGE_PROPERTY_DYNAMIC, 'Dynamic')] [FlagName(PACKAGE_PROPERTY_HOSTRUNTIME, 'Host Runtime')] TPackageProperties = type Cardinal; TPackagePropertiesArray = TAnysizeArray<TPackageProperties>; PPackagePropertiesArray = ^TPackagePropertiesArray; // SDK::appmodel.h [SDKName('PackageOrigin')] [NamingStyle(nsCamelCase, 'PackageOrigin_')] TPackageOrigin = ( PackageOrigin_Unknown = 0, PackageOrigin_Unsigned = 1, PackageOrigin_Inbox = 2, PackageOrigin_Store = 3, PackageOrigin_DeveloperUnsigned = 4, PackageOrigin_DeveloperSigned = 5, PackageOrigin_LineOfBusiness = 6 ); [FlagName(PSM_ACTIVATION_TOKEN_PACKAGED_APPLICATION, 'Packaged Application')] [FlagName(PSM_ACTIVATION_TOKEN_SHARED_ENTITY, 'Shared Entity')] [FlagName(PSM_ACTIVATION_TOKEN_FULL_TRUST, 'Full Trust')] [FlagName(PSM_ACTIVATION_TOKEN_NATIVE_SERVICE, 'Native Service')] [FlagName(PSM_ACTIVATION_TOKEN_DEVELOPMENT_APP, 'Development App')] [FlagName(PSM_ACTIVATION_TOKEN_BREAKAWAY_INHIBITED, 'Breakaway Inhibited')] [FlagName(PSM_ACTIVATION_TOKEN_RUNTIME_BROKER, 'Runtime Broker')] [FlagName(PSM_ACTIVATION_TOKEN_WIN32ALACARTE_PROCESS, 'Win32 A-La-Carte Process')] TPackageClaimFlags = type Cardinal; // PHNT::ntrtl.h [SDKName('PS_PKG_CLAIM')] TPsPkgClaim = record Flags: TPackageClaimFlags; Origin: TPackageOrigin; end; PPsPkgClaim = ^TPsPkgClaim; [FlagName(PACKAGE_ATTRIBUTE_SYSAPPID_PRESENT, 'WIN://SYSAPPID')] [FlagName(PACKAGE_ATTRIBUTE_PKG_CLAIM_PRESENT, 'WIN://PKG')] [FlagName(PACKAGE_ATTRIBUTE_SKUID_PRESENT, 'WP://SKUID')] [FlagName(PACKAGE_ATTRIBUTE_XBOX_LI_PRESENT, 'XBOX://LI')] TPackagePresentAttributes = type UInt64; PPackagePresentAttributes = ^TPackagePresentAttributes; // SDK::appmodel.h [MinOSVersion(OsWin8)] [SDKName('PACKAGE_INFO')] TPackageInfo = record Reserved: Cardinal; Flags: TPackageProperties; Path: PWideChar; PackageFullName: PWideChar; PackageFamilyName: PWideChar; [Aggregate] PackageId: TPackageId; end; PPackageInfo = ^TPackageInfo; TPackageInfoArray = TAnysizeArray<TPackageInfo>; PPackageInfoArray = ^TPackageInfoArray; // SDK::appmodel.h [SDKName('PACKAGE_INFO_REFERENCE')] TPackageInfoReference = type THandle; // private - app model policy info classes [MinOSVersion(OsWin10RS1)] [SDKName('AppModelPolicy_Type')] [NamingStyle(nsCamelCase, 'AppModelPolicy_Type_'), Range(1)] TAppModelPolicyType = ( [Reserved] AppModelPolicy_Type_Unspecified = $0, AppModelPolicy_Type_LifecycleManager = $1, AppModelPolicy_Type_AppdataAccess = $2, AppModelPolicy_Type_WindowingModel = $3, AppModelPolicy_Type_DLLSearchOrder = $4, AppModelPolicy_Type_Fusion = $5, AppModelPolicy_Type_NonWindowsCodecLoading = $6, AppModelPolicy_Type_ProcessEnd = $7, AppModelPolicy_Type_BeginThreadInit = $8, AppModelPolicy_Type_DeveloperInformation = $9, AppModelPolicy_Type_CreateFileAccess = $A, AppModelPolicy_Type_ImplicitPackageBreakaway = $B, AppModelPolicy_Type_ProcessActivationShim = $C, AppModelPolicy_Type_AppKnownToStateRepository = $D, AppModelPolicy_Type_AudioManagement = $E, AppModelPolicy_Type_PackageMayContainPublicCOMRegistrations = $F, AppModelPolicy_Type_PackageMayContainPrivateCOMRegistrations = $10, AppModelPolicy_Type_LaunchCreateProcessExtensions = $11, AppModelPolicy_Type_CLRCompat = $12, AppModelPolicy_Type_LoaderIgnoreAlteredSearchForRelativePath = $13, AppModelPolicy_Type_ImplicitlyActivateClassicAAAServersAsIU = $14, AppModelPolicy_Type_COMClassicCatalog = $15, AppModelPolicy_Type_COMUnmarshaling = $16, AppModelPolicy_Type_COMAppLaunchPerfEnhancements = $17, AppModelPolicy_Type_COMSecurityInitialization = $18, AppModelPolicy_Type_ROInitializeSingleThreadedBehavior = $19, AppModelPolicy_Type_COMDefaultExceptionHandling = $1A, AppModelPolicy_Type_COMOopProxyAgility = $1B, AppModelPolicy_Type_AppServiceLifetime = $1C, AppModelPolicy_Type_WebPlatform = $1D, AppModelPolicy_Type_WinInetStoragePartitioning = $1E, AppModelPolicy_Type_IndexerProtocolHandlerHost = $1F, // Win 10 RS2+ AppModelPolicy_Type_LoaderIncludeUserDirectories = $20, // Win 10 RS2+ AppModelPolicy_Type_ConvertAppContainerToRestrictedAppContainer = $21, // Win 10 RS2+ AppModelPolicy_Type_PackageMayContainPrivateMapiProvider = $22, // Win 10 RS2+ AppModelPolicy_Type_AdminProcessPackageClaims = $23, // Win 10 RS3+ AppModelPolicy_Type_RegistryRedirectionBehavior = $24, // Win 10 RS3+ AppModelPolicy_Type_BypassCreateProcessAppxExtension = $25, // Win 10 RS3+ AppModelPolicy_Type_KnownFolderRedirection = $26, // Win 10 RS3+ AppModelPolicy_Type_PrivateActivateAsPackageWinrtClasses = $27, // Win 10 RS3+ AppModelPolicy_Type_AppPrivateFolderRedirection = $28, // Win 10 RS3+ AppModelPolicy_Type_GlobalSystemAppdataAccess = $29, // Win 10 RS3+ AppModelPolicy_Type_ConsoleHandleInheritance = $2A, // Win 10 RS4+ AppModelPolicy_Type_ConsoleBufferAccess = $2B, // Win 10 RS4+ AppModelPolicy_Type_ConvertCallerTokenToUserTokenForDeployment = $2C, // Win 10 RS4+ AppModelPolicy_Type_ShellExecuteRetrieveIdentityFromCurrentProcess = $2D, // Win 10 RS5+ AppModelPolicy_Type_CodeIntegritySigning = $2E, // Win 10 19H1+ AppModelPolicy_Type_PTCActivation = $2F, // Win 10 19H1+ AppModelPolicy_Type_COMIntraPackageRPCCall = $30, // Win 10 20H1+ AppModelPolicy_Type_LoadUser32ShimOnWindowsCoreOS = $31, // Win 10 20H1+ AppModelPolicy_Type_SecurityCapabilitiesOverride = $32, // Win 10 20H1+ AppModelPolicy_Type_CurrentDirectoryOverride = $33, // Win 10 20H1+ AppModelPolicy_Type_COMTokenMatchingForAAAServers = $34, // Win 10 20H1+ AppModelPolicy_Type_UseOriginalFileNameInTokenFQBNAttribute = $35, // Win 10 20H1+ AppModelPolicy_Type_LoaderIncludeAlternateForwarders = $36, // Win 10 20H1+ AppModelPolicy_Type_PullPackageDependencyData = $37, // Win 10 20H1+ AppModelPolicy_Type_AppInstancingErrorBehavior = $38, // Win 11+ AppModelPolicy_Type_BackgroundTaskRegistrationType = $39, // Win 11+ AppModelPolicy_Type_ModsPowerNotifification = $3A // Win 11+ ); // private - includes both type and value as 0xTTTTVVVV [MinOSVersion(OsWin10RS1)] [SDKName('AppModelPolicy_PolicyValue')] TAppModelPolicyValue = type Cardinal; // Info class 0x1 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_LifecycleManager_')] TAppModelPolicy_LifecycleManager = ( AppModelPolicy_LifecycleManager_Unmanaged = 0, AppModelPolicy_LifecycleManager_ManagedByPLM = 1, AppModelPolicy_LifecycleManager_ManagedByEM = 2 ); // Info class 0x2 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_AppdataAccess_')] TAppModelPolicy_AppdataAccess = ( AppModelPolicy_AppdataAccess_Allowed = 0, AppModelPolicy_AppdataAccess_Denied = 1 ); // Info class 0x3 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_WindowingModel_')] TAppModelPolicy_WindowingModel = ( AppModelPolicy_WindowingModel_HWND = 0, AppModelPolicy_WindowingModel_CoreWindow = 1, AppModelPolicy_WindowingModel_LegacyPhone = 2, AppModelPolicy_WindowingModel_None = 3 ); // Info class 0x4 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_DLLSearchOrder_')] TAppModelPolicy_DLLSearchOrder = ( AppModelPolicy_DLLSearchOrder_Traditional = 0, AppModelPolicy_DLLSearchOrder_PackageGraphBased = 1 ); // Info class 0x5 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_Fusion_')] TAppModelPolicy_Fusion = ( AppModelPolicy_Fusion_Full = 0, AppModelPolicy_Fusion_Limited = 1 ); // Info class 0x6 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_NonWindowsCodecLoading_')] TAppModelPolicy_NonWindowsCodecLoading = ( AppModelPolicy_NonWindowsCodecLoading_Allowed = 0, AppModelPolicy_NonWindowsCodecLoading_Denied = 1 ); // Info class 0x7 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ProcessEnd_')] TAppModelPolicy_ProcessEnd = ( AppModelPolicy_ProcessEnd_TerminateProcess = 0, AppModelPolicy_ProcessEnd_ExitProcess = 1 ); // Info class 0x8 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_BeginThreadInit_')] TAppModelPolicy_BeginThreadInit = ( AppModelPolicy_BeginThreadInit_ROInitialize = 0, AppModelPolicy_BeginThreadInit_None = 1 ); // Info class 0x9 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_DeveloperInformation_')] TAppModelPolicy_DeveloperInformation = ( AppModelPolicy_DeveloperInformation_UI = 0, AppModelPolicy_DeveloperInformation_None = 1 ); // Info class 0xA [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_CreateFileAccess_')] TAppModelPolicy_CreateFileAccess = ( AppModelPolicy_CreateFileAccess_Full = 0, AppModelPolicy_CreateFileAccess_Limited = 1 ); // Info class 0xB [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ImplicitPackageBreakaway_')] TAppModelPolicy_ImplicitPackageBreakaway = ( AppModelPolicy_ImplicitPackageBreakaway_Allowed = 0, AppModelPolicy_ImplicitPackageBreakaway_Denied = 1, AppModelPolicy_ImplicitPackageBreakaway_DeniedByApp = 2 // Win 10 RS2+ ); // Info class 0xC [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ProcessActivationShim_')] TAppModelPolicy_ProcessActivationShim = ( AppModelPolicy_ProcessActivationShim_None = 0, AppModelPolicy_ProcessActivationShim_PackagedCWALauncher = 1 ); // Info class 0xD [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_AppKnownToStateRepository_')] TAppModelPolicy_AppKnownToStateRepository = ( AppModelPolicy_AppKnownToStateRepository_Known = 0, AppModelPolicy_AppKnownToStateRepository_Unknown = 1 ); // Info class 0xE [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_AudioManagement_')] TAppModelPolicy_AudioManagement = ( AppModelPolicy_AudioManagement_Unmanaged = 0, AppModelPolicy_AudioManagement_ManagedByPBM = 1 ); // Info class 0xF [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_PackageMayContainPublicCOMRegistrations_')] TAppModelPolicy_PackageMayContainPublicCOMRegistrations = ( AppModelPolicy_PackageMayContainPublicCOMRegistrations_Yes = 0, AppModelPolicy_PackageMayContainPublicCOMRegistrations_No = 1 ); // Info class 0x10 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_PackageMayContainPrivateCOMRegistrations_')] TAppModelPolicy_PackageMayContainPrivateCOMRegistrations = ( AppModelPolicy_PackageMayContainPrivateCOMRegistrations_None = 0, AppModelPolicy_PackageMayContainPrivateCOMRegistrations_PrivateHive = 1 ); // Info class 0x11 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_LaunchCreateProcessExtensions_')] TAppModelPolicy_LaunchCreateProcessExtensions = ( AppModelPolicy_LaunchCreateProcessExtensions_None = 0, AppModelPolicy_LaunchCreateProcessExtensions_RegisterWithPSM = 1, AppModelPolicy_LaunchCreateProcessExtensions_RegisterWithDesktopAppx = 2, AppModelPolicy_LaunchCreateProcessExtensions_RegisterWithDesktopAppxNoHeliumContainer = 3 // Win 10 20H1+ ); // Info class 0x12 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_CLRCompat_')] TAppModelPolicy_CLRCompat = ( AppModelPolicy_CLRCompat_Others = 0, AppModelPolicy_CLRCompat_ClassicDesktop = 1, AppModelPolicy_CLRCompat_Universal = 2, AppModelPolicy_CLRCompat_PackagedDesktop = 3 ); // Info class 0x13 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_LoaderIgnoreAlteredSearchForRelativePath_')] TAppModelPolicy_LoaderIgnoreAlteredSearchForRelativePath = ( AppModelPolicy_LoaderIgnoreAlteredSearchForRelativePath_False = 0, AppModelPolicy_LoaderIgnoreAlteredSearchForRelativePath_True = 1 ); // Info class 0x14 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ImplicitlyActivateClassicAAAServersAsIU_')] TAppModelPolicy_ImplicitlyActivateClassicAAAServersAsIU = ( AppModelPolicy_ImplicitlyActivateClassicAAAServersAsIU_Yes = 0, AppModelPolicy_ImplicitlyActivateClassicAAAServersAsIU_No = 1 ); // Info class 0x15 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_COMClassicCatalog_')] TAppModelPolicy_COMClassicCatalog = ( AppModelPolicy_COMClassicCatalog_MachineHiveAndUserHive = 0, AppModelPolicy_COMClassicCatalog_MachineHiveOnly = 1 ); // Info class 0x16 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_COMUnmarshaling_')] TAppModelPolicy_COMUnmarshaling = ( AppModelPolicy_COMUnmarshaling_ForceStrongUnmarshaling = 0, AppModelPolicy_COMUnmarshaling_ApplicationManaged = 1 ); // Info class 0x17 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_COMAppLaunchPerfEnhancements_')] TAppModelPolicy_COMAppLaunchPerfEnhancements = ( AppModelPolicy_COMAppLaunchPerfEnhancements_Enabled = 0, AppModelPolicy_COMAppLaunchPerfEnhancements_Disabled = 1 ); // Info class 0x18 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_COMSecurityInitialization_')] TAppModelPolicy_COMSecurityInitialization = ( AppModelPolicy_COMSecurityInitialization_ApplicationManaged = 0, AppModelPolicy_COMSecurityInitialization_SystemManaged = 1 ); // Info class 0x19 [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ROInitializeSingleThreadedBehavior_')] TAppModelPolicy_ROInitializeSingleThreadedBehavior = ( AppModelPolicy_ROInitializeSingleThreadedBehavior_ASTA = 0, AppModelPolicy_ROInitializeSingleThreadedBehavior_STA = 1 ); // Info class 0x1A [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_COMDefaultExceptionHandling_')] TAppModelPolicy_COMDefaultExceptionHandling = ( AppModelPolicy_COMDefaultExceptionHandling_HandleAll = 0, AppModelPolicy_COMDefaultExceptionHandling_HandleNone = 1 ); // Info class 0x1B [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_COMOopProxyAgility_')] TAppModelPolicy_COMOopProxyAgility = ( AppModelPolicy_COMOopProxyAgility_Agile = 0, AppModelPolicy_COMOopProxyAgility_NonAgile = 1 ); // Info class 0x1C [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_AppServiceLifetime_')] TAppModelPolicy_AppServiceLifetime = ( AppModelPolicy_AppServiceLifetime_StandardTimeout = 0, AppModelPolicy_AppServiceLifetime_ExtensibleTimeout = 1, // Win RS5+ AppModelPolicy_AppServiceLifetime_ExtendedForSamePackage = 2 // Had diff value before Win 10 RS5 ); // Info class 0x1D [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_WebPlatform_')] TAppModelPolicy_WebPlatform = ( AppModelPolicy_WebPlatform_Edge = 0, AppModelPolicy_WebPlatform_Legacy = 1 ); // Info class 0x1E [MinOSVersion(OsWin10RS1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_WinInetStoragePartitioning_')] TAppModelPolicy_WinInetStoragePartitioning = ( AppModelPolicy_WinInetStoragePartitioning_Isolated = 0, AppModelPolicy_WinInetStoragePartitioning_SharedWithAppContainer = 1 ); // Info class 0x1F [MinOSVersion(OsWin10RS2)] [NamingStyle(nsCamelCase, 'AppModelPolicy_IndexerProtocolHandlerHost_')] TAppModelPolicy_IndexerProtocolHandlerHost = ( AppModelPolicy_IndexerProtocolHandlerHost_PerUser = 0, AppModelPolicy_IndexerProtocolHandlerHost_PerApp = 1 ); // Info class 0x20 [MinOSVersion(OsWin10RS2)] [NamingStyle(nsCamelCase, 'AppModelPolicy_LoaderIncludeUserDirectories_')] TAppModelPolicy_LoaderIncludeUserDirectories = ( AppModelPolicy_LoaderIncludeUserDirectories_False = 0, AppModelPolicy_LoaderIncludeUserDirectories_True = 1 ); // Info class 0x21 [MinOSVersion(OsWin10RS2)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ConvertAppContainerToRestrictedAppContainer_')] TAppModelPolicy_ConvertAppContainerToRestrictedAppContainer = ( AppModelPolicy_ConvertAppContainerToRestrictedAppContainer_False = 0, AppModelPolicy_ConvertAppContainerToRestrictedAppContainer_True = 1 ); // Info class 0x22 [MinOSVersion(OsWin10RS2)] [NamingStyle(nsCamelCase, 'AppModelPolicy_PackageMayContainPrivateMapiProvider_')] TAppModelPolicy_PackageMayContainPrivateMapiProvider = ( AppModelPolicy_PackageMayContainPrivateMapiProvider_None = 0, AppModelPolicy_PackageMayContainPrivateMapiProvider_PrivateHive = 1 ); // Info class 0x23 [MinOSVersion(OsWin10RS3)] [NamingStyle(nsCamelCase, 'AppModelPolicy_AdminProcessPackageClaims_')] TAppModelPolicy_AdminProcessPackageClaims = ( AppModelPolicy_AdminProcessPackageClaims_None = 0, AppModelPolicy_AdminProcessPackageClaims_Caller = 1 ); // Info class 0x24 [MinOSVersion(OsWin10RS3)] [NamingStyle(nsCamelCase, 'AppModelPolicy_RegistryRedirectionBehavior_')] TAppModelPolicy_RegistryRedirectionBehavior = ( AppModelPolicy_RegistryRedirectionBehavior_None = 0, AppModelPolicy_RegistryRedirectionBehavior_CopyOnWrite = 1 ); // Info class 0x25 [MinOSVersion(OsWin10RS3)] [NamingStyle(nsCamelCase, 'AppModelPolicy_BypassCreateProcessAppxExtension_')] TAppModelPolicy_BypassCreateProcessAppxExtension = ( AppModelPolicy_BypassCreateProcessAppxExtension_False = 0, AppModelPolicy_BypassCreateProcessAppxExtension_True = 1 ); // Info class 0x26 [MinOSVersion(OsWin10RS3)] [NamingStyle(nsCamelCase, 'AppModelPolicy_KnownFolderRedirection_')] TAppModelPolicy_KnownFolderRedirection = ( AppModelPolicy_KnownFolderRedirection_Isolated = 0, AppModelPolicy_KnownFolderRedirection_RedirectToPackage = 1 ); // Info class 0x27 [MinOSVersion(OsWin10RS3)] [NamingStyle(nsCamelCase, 'AppModelPolicy_PrivateActivateAsPackageWinrtClasses_')] TAppModelPolicy_PrivateActivateAsPackageWinrtClasses = ( AppModelPolicy_PrivateActivateAsPackageWinrtClasses_AllowNone = 0, AppModelPolicy_PrivateActivateAsPackageWinrtClasses_AllowFullTrust = 1, AppModelPolicy_PrivateActivateAsPackageWinrtClasses_AllowNonFullTrust = 2 ); // Info class 0x28 [MinOSVersion(OsWin10RS3)] [NamingStyle(nsCamelCase, 'AppModelPolicy_AppPrivateFolderRedirection_')] TAppModelPolicy_AppPrivateFolderRedirection = ( AppModelPolicy_AppPrivateFolderRedirection_None = 0, AppModelPolicy_AppPrivateFolderRedirection_AppPrivate = 1 ); // Info class 0x29 [MinOSVersion(OsWin10RS3)] [NamingStyle(nsCamelCase, 'AppModelPolicy_GlobalSystemAppdataAccess_')] TAppModelPolicy_GlobalSystemAppdataAccess = ( AppModelPolicy_GlobalSystemAppdataAccess_Normal = 0, AppModelPolicy_GlobalSystemAppdataAccess_Virtualized = 1 ); // Info class 0x2A [MinOSVersion(OsWin10RS4)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ConsoleHandleInheritance_')] TAppModelPolicy_ConsoleHandleInheritance = ( AppModelPolicy_ConsoleHandleInheritance_ConsoleOnly = 0, AppModelPolicy_ConsoleHandleInheritance_All = 1 ); // Info class 0x2B [MinOSVersion(OsWin10RS4)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ConsoleBufferAccess_')] TAppModelPolicy_ConsoleBufferAccess = ( AppModelPolicy_ConsoleBufferAccess_RestrictedUnidirectional = 0, AppModelPolicy_ConsoleBufferAccess_Unrestricted = 1 ); // Info class 0x2C [MinOSVersion(OsWin10RS4)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ConvertCallerTokenToUserTokenForDeployment_')] TAppModelPolicy_ConvertCallerTokenToUserTokenForDeployment = ( AppModelPolicy_ConvertCallerTokenToUserTokenForDeployment_UserCallerToken = 0, AppModelPolicy_ConvertCallerTokenToUserTokenForDeployment_ConvertTokenToUserToken = 1 ); // Info class 0x2D [MinOSVersion(OsWin10RS5)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ShellExecuteRetrieveIdentityFromCurrentProcess_')] TAppModelPolicy_ShellExecuteRetrieveIdentityFromCurrentProcess = ( AppModelPolicy_ShellExecuteRetrieveIdentityFromCurrentProcess_False = 0, AppModelPolicy_ShellExecuteRetrieveIdentityFromCurrentProcess_True = 1 ); // Info class 0x2E [MinOSVersion(OsWin1019H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_CodeIntegritySigning_')] TAppModelPolicy_CodeIntegritySigning = ( AppModelPolicy_CodeIntegritySigning_Default = 0, AppModelPolicy_CodeIntegritySigning_OriginBased = 1, AppModelPolicy_CodeIntegritySigning_OriginBasedForDev = 2 ); // Info class 0x2F [MinOSVersion(OsWin1019H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_PTCActivation_')] TAppModelPolicy_PTCActivation = ( AppModelPolicy_PTCActivation_Default = 0, AppModelPolicy_PTCActivation_AllowActivationInBrokerForMediumILContainer = 1 ); // Info class 0x30 [MinOSVersion(OsWin1020H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_COMIntraPackageRPCCall_')] TAppModelPolicy_COMIntraPackageRPCCall = ( AppModelPolicy_COMIntraPackageRPCCall_NoWake = 0, AppModelPolicy_COMIntraPackageRPCCall_Wake = 1 ); // Info class 0x31 [MinOSVersion(OsWin1020H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_LoadUser32ShimOnWindowsCoreOS_')] TAppModelPolicy_LoadUser32ShimOnWindowsCoreOS = ( AppModelPolicy_LoadUser32ShimOnWindowsCoreOS_True = 0, AppModelPolicy_LoadUser32ShimOnWindowsCoreOS_False = 1 ); // Info class 0x32 [MinOSVersion(OsWin1020H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_SecurityCapabilitiesOverride_')] TAppModelPolicy_SecurityCapabilitiesOverride = ( AppModelPolicy_SecurityCapabilitiesOverride_None = 0, AppModelPolicy_SecurityCapabilitiesOverride_PackageCapabilities = 1 ); // Info class 0x33 [MinOSVersion(OsWin1020H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_CurrentDirectoryOverride_')] TAppModelPolicy_CurrentDirectoryOverride = ( AppModelPolicy_CurrentDirectoryOverride_None = 0, AppModelPolicy_CurrentDirectoryOverride_PackageInstallDirectory = 1 ); // Info class 0x34 [MinOSVersion(OsWin1020H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_COMTokenMatchingForAAAServers_')] TAppModelPolicy_COMTokenMatchingForAAAServers = ( AppModelPolicy_COMTokenMatchingForAAAServers_DontUseNtCompareTokens = 0, AppModelPolicy_COMTokenMatchingForAAAServers_UseNtCompareTokens = 1 ); // Info class 0x35 [MinOSVersion(OsWin1020H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_UseOriginalFileNameInTokenFQBNAttribute_')] TAppModelPolicy_UseOriginalFileNameInTokenFQBNAttribute = ( AppModelPolicy_UseOriginalFileNameInTokenFQBNAttribute_False = 0, AppModelPolicy_UseOriginalFileNameInTokenFQBNAttribute_True = 1 ); // Info class 0x36 [MinOSVersion(OsWin1020H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_LoaderIncludeAlternateForwarders_')] TAppModelPolicy_LoaderIncludeAlternateForwarders = ( AppModelPolicy_LoaderIncludeAlternateForwarders_False = 0, AppModelPolicy_LoaderIncludeAlternateForwarders_True = 1 ); // Info class 0x37 [MinOSVersion(OsWin1020H1)] [NamingStyle(nsCamelCase, 'AppModelPolicy_PullPackageDependencyData_')] TAppModelPolicy_PullPackageDependencyData = ( AppModelPolicy_PullPackageDependencyData_False = 0, AppModelPolicy_PullPackageDependencyData_True = 1 ); // Info class 0x38 [MinOSVersion(OsWin11)] [NamingStyle(nsCamelCase, 'AppModelPolicy_AppInstancingErrorBehavior_')] TAppModelPolicy_AppInstancingErrorBehavior = ( AppModelPolicy_AppInstancingErrorBehavior_SuppressErrors = 0, AppModelPolicy_AppInstancingErrorBehavior_RaiseErrors = 1 ); // Info class 0x39 [MinOSVersion(OsWin11)] [NamingStyle(nsCamelCase, 'AppModelPolicy_BackgroundTaskRegistrationType_')] TAppModelPolicy_BackgroundTaskRegistrationType = ( AppModelPolicy_BackgroundTaskRegistrationType_Unsupported = 0, AppModelPolicy_BackgroundTaskRegistrationType_Manifested = 1, AppModelPolicy_BackgroundTaskRegistrationType_Win32CLSID = 2 ); // Info class 0x3A [MinOSVersion(OsWin11)] [NamingStyle(nsCamelCase, 'AppModelPolicy_ModsPowerNotifification_')] TAppModelPolicy_ModsPowerNotifification = ( AppModelPolicy_ModsPowerNotifification_Disabled = 0, AppModelPolicy_ModsPowerNotifification_Enabled = 1 ); { AppX } [SDKName('DESKTOPAPPXACTIVATEOPTIONS')] [FlagName(DAXAO_ELEVATE, 'Elavate')] [FlagName(DAXAO_NONPACKAGED_EXE, 'Non-packaged EXE')] [FlagName(DAXAO_NONPACKAGED_EXE_PROCESS_TREE, 'Non-packaged EXE Process Tree')] [FlagName(DAXAO_NO_ERROR_UI, 'No Error UI')] [FlagName(DAXAO_CHECK_FOR_APPINSTALLER_UPDATES, 'Check For AppInstaller Updates')] [FlagName(DAXAO_CENTENNIAL_PROCESS, 'Centennial Process')] [FlagName(DAXAO_UNIVERSAL_PROCESS, 'Universal Process')] [FlagName(DAXAO_WIN32ALACARTE_PROCESS, 'Win32Alacarte Process')] [FlagName(DAXAO_PARTIAL_TRUST, 'Partial Trust')] [FlagName(DAXAO_UNIVERSAL_CONSOLE, 'Universal Console')] TDesktopAppxActivateOptions = type Cardinal; [MinOSVersion(OsWin10RS1)] [SDKName('IDesktopAppXActivator')] IDesktopAppXActivatorV1 = interface (IUnknown) ['{B81F98D4-6F57-401A-8FCC-B66014CA80BB}'] function Activate( [in] applicationUserModelId: PWideChar; [in] packageRelativeExecutable: PWideChar; [in, opt] arguments: PWideChar; [out, ReleaseWith('NtClose')] out processHandle: THandle32 ): HResult; stdcall; function ActivateWithOptions( [in] applicationUserModelId: PWideChar; [in] executable: PWideChar; [in, opt] arguments: PWideChar; [in] activationOptions: TDesktopAppxActivateOptions; [out, ReleaseWith('NtClose')] out processHandle: THandle32 ): HResult; stdcall; end; [MinOSVersion(OsWin10RS2)] [SDKName('IDesktopAppXActivator')] IDesktopAppXActivatorV2 = interface (IUnknown) ['{72E3A5B0-8FEA-485C-9F8B-822B16DBA17F}'] function Activate( [in] applicationUserModelId: PWideChar; [in] packageRelativeExecutable: PWideChar; [in, opt] arguments: PWideChar; [out, ReleaseWith('NtClose')] out processHandle: THandle32 ): HResult; stdcall; function ActivateWithOptions( [in] applicationUserModelId: PWideChar; [in] executable: PWideChar; [in, opt] arguments: PWideChar; [in] activationOptions: TDesktopAppxActivateOptions; [in, opt] parentProcessId: TProcessId32; [out, ReleaseWith('NtClose')] out processHandle: THandle32 ): HResult; stdcall; end; [MinOSVersion(OsWin11)] [SDKName('IDesktopAppXActivator')] IDesktopAppXActivatorV3 = interface (IUnknown) ['{F158268A-D5A5-45CE-99CF-00D6C3F3FC0A}'] function Activate( [in] applicationUserModelId: PWideChar; [in] packageRelativeExecutable: PWideChar; [in, opt] arguments: PWideChar; [out, ReleaseWith('NtClose')] out processHandle: THandle32 ): HResult; stdcall; function ActivateWithOptions( [in] applicationUserModelId: PWideChar; [in] executable: PWideChar; [in, opt] arguments: PWideChar; [in] activationOptions: TDesktopAppxActivateOptions; [in, opt] parentProcessId: TProcessId32; [out, ReleaseWith('NtClose')] out processHandle: THandle32 ): HResult; stdcall; function ActivateWithOptionsAndArgs( [in] applicationUserModelId: PWideChar; [in] executable: PWideChar; [in, opt] arguments: PWideChar; [in] activationOptions: TDesktopAppxActivateOptions; [in, opt] parentProcessId: TProcessId32; [in, opt] activatedEventArgs: IInterface; [out, ReleaseWith('NtClose')] out processHandle: THandle32 ): HResult; stdcall; function ActivateWithOptionsArgsWorkingDirectoryShowWindow( [in] applicationUserModelId: PWideChar; [in] executable: PWideChar; [in, opt] arguments: PWideChar; [in] activationOptions: TDesktopAppxActivateOptions; [in, opt] parentProcessId: TProcessId32; [in, opt] activatedEventArgs: IInterface; [in, opt] workingDirectory: PWideChar; [in] showWindow: TShowMode32; [out, ReleaseWith('NtClose')] out processHandle: THandle32 ): HResult; stdcall; end; // SDK::appmodel.h [MinOSVersion(OsWin81)] function GetPackagePathByFullName( [in] packageFullName: PWideChar; [in, out, NumberOfElements] var pathLength: Cardinal; [out, WritesTo] path: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin81)] function GetStagedPackagePathByFullName( [in] packageFullName: PWideChar; [in, out, NumberOfElements] var pathLength: Cardinal; [out, WritesTo] path: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin1019H1)] function GetPackagePathByFullName2( [in] packageFullName: PWideChar; [in] packagePathType: TPackagePathType; [in, out, NumberOfElements] var pathLength: Cardinal; [out, WritesTo] path: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin1019H1)] function GetStagedPackagePathByFullName2( [in] packageFullName: PWideChar; [in] packagePathType: TPackagePathType; [in, out, NumberOfElements] var pathLength: Cardinal; [out, WritesTo] path: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin10TH1)] function GetApplicationUserModelIdFromToken( [in, Access(TOKEN_QUERY)] token: THandle; [in, out, NumberOfElements] var applicationUserModelIdLength: Cardinal; [out, WritesTo] applicationUserModelId: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function PackageIdFromFullName( [in] packageFullName: PWideChar; [in] flags: TPackageInformationFlags; [in, out, NumberOfBytes] var bufferLength: Cardinal; [out, WritesTo] buffer: PPackageId ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function PackageFullNameFromId( [in] const packageId: TPackageId; [in, out, NumberOfElements] var packageFullNameLength: Cardinal; [out, WritesTo] packageFullName: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function PackageFamilyNameFromId( [in] const packageId: TPackageId; [in, out, NumberOfElements] var packageFamilyNameLength: Cardinal; [out, WritesTo] packageFamilyName: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function PackageFamilyNameFromFullName( [in] packageFullName: PWideChar; [in, out, NumberOfElements] var packageFamilyNameLength: Cardinal; [out, WritesTo] packageFamilyName: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function PackageNameAndPublisherIdFromFamilyName( [in] packageFamilyName: PWideChar; [in, out, NumberOfElements] var packageNameLength: Cardinal; [out, WritesTo] packageName: PWideChar; [in, out, NumberOfElements] var packagePublisherIdLength: Cardinal; [out, WritesTo] packagePublisherId: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin81)] function FormatApplicationUserModelId( [in] packageFamilyName: PWideChar; [in] packageRelativeApplicationId: PWideChar; [in, out, NumberOfElements] var applicationUserModelIdLength: Cardinal; [out, WritesTo] applicationUserModelId: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin81)] function ParseApplicationUserModelId( [in] applicationUserModelId: PWideChar; [in, out, NumberOfElements] var packageFamilyNameLength: Cardinal; [out, WritesTo] packageFamilyName: PWideChar; [in, out, NumberOfElements] var packageRelativeApplicationIdLength: Cardinal; [out, WritesTo] packageRelativeApplicationId: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function GetPackagesByPackageFamily( [in] packageFamilyName: PWideChar; [in, out, NumberOfElements] var count: Cardinal; [out, WritesTo] packageFullNames: PPackageFullNames; [in, out, NumberOfElements] var bufferLength: Cardinal; [out, WritesTo] buffer: PWideChar ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin81)] function FindPackagesByPackageFamily( [in] packageFamilyName: PWideChar; [in] packageFilters: TPackageFilters; [in, out, NumberOfElements] var count: Cardinal; [out, WritesTo] packageFullNames: PPackageFullNames; [in, out, NumberOfElements] var bufferLength: Cardinal; [out, WritesTo] buffer: PWideChar; [out, WritesTo] packageProperties: PPackagePropertiesArray ): TWin32Error; stdcall; external kernelbase delayed; // PHNT::ntrtl.h [MinOSVersion(OsWin10TH1)] function RtlQueryPackageClaims( [in, Access(TOKEN_QUERY)] TokenHandle: THandle; [out, opt, WritesTo] PackageFullName: PWideChar; [in, out, opt, NumberOfBytes] PackageSize: PNativeUInt; [out, opt, WritesTo] AppId: PWideChar; [in, out, opt, NumberOfBytes] AppIdSize: PNativeUInt; [out, opt] DynamicId: PGuid; [out, opt] PkgClaim: PPsPkgClaim; [out, opt] AttributesPresent: PPackagePresentAttributes ): NTSTATUS; stdcall; external ntdll delayed; // SDK::appmodel.h [MinOSVersion(OsWin81)] function GetStagedPackageOrigin( [in] packageFullName: PWideChar; [out] out origin: TPackageOrigin ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function OpenPackageInfoByFullName( [in] packageFullName: PWideChar; [Reserved] reserved: Cardinal; [out, ReleaseWith('ClosePackageInfo')] out packageInfoReference: TPackageInfoReference ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin10TH1)] function OpenPackageInfoByFullNameForUser( [in, opt] userSid: PSid; [in] packageFullName: PWideChar; [Reserved] reserved: Cardinal; [out, ReleaseWith('ClosePackageInfo')] out packageInfoReference: TPackageInfoReference ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function ClosePackageInfo( [in] packageInfoReference: TPackageInfoReference ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin8)] function GetPackageInfo( [in] packageInfoReference: TPackageInfoReference; [in] flags: TPackageFilters; [in, out, NumberOfBytes] var bufferLength: Cardinal; [out, opt, WritesTo] buffer: PPackageInfoArray; [out, opt] count: PCardinal ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin1019H1)] function GetPackageInfo2( [in] packageInfoReference: TPackageInfoReference; [in] flags: TPackageFilters; [in] packagePathType: TPackagePathType; [in, out, NumberOfBytes] var bufferLength: Cardinal; [out, opt, WritesTo] buffer: PPackageInfoArray; [out, opt] count: PCardinal ): TWin32Error; stdcall; external kernelbase delayed; // SDK::appmodel.h [MinOSVersion(OsWin1021H1)] function CheckIsMSIXPackage( [in] packageFullName: PWideChar; [out] out isMSIXPackage: LongBool ): HRESULT; stdcall; external kernelbase delayed; implementation {$BOOLEVAL OFF} {$IFOPT R+}{$DEFINE R+}{$ENDIF} {$IFOPT Q+}{$DEFINE Q+}{$ENDIF} end.
unit Flyweight.Factory.FlyweightFactory; interface uses Flyweight.Flyweight, System.Generics.Collections, Flyweight.Car, Flyweight.Util.Types; type TFlyweightFactory = class private FPairsCarList: TDictionaryCarList; public constructor Create(ACarList: TCarList); function GetKey(AKey: TCar): string; function GetFlyweight(ASharedState: TCar): TFlyweight; procedure ListFlyweights; destructor Destroy; override; end; implementation uses System.Classes, System.SysUtils, Flyweight.Util.Helper, Flyweight.Util.Utils; { TFlyweightFactory } constructor TFlyweightFactory.Create(ACarList: TCarList); var oCar: TCar; begin if not Assigned(FPairsCarList) then FPairsCarList := TList < TPair < TFlyweight, string >>.Create; for oCar in ACarList do FPairsCarList.Add(TPair<TFlyweight, string>.Create(TFlyweight.Create(oCar), GetKey(oCar))); end; destructor TFlyweightFactory.Destroy; var I: Integer; begin for I := 0 to Pred(FPairsCarList.Count) do FPairsCarList.Items[I].Key.Free; FreeAndNil(FPairsCarList); inherited; end; // Returns a Flyweight's string hash for a given state. function TFlyweightFactory.GetKey(AKey: TCar): string; var oStringList: TList<string>; begin oStringList := TList<string>.Create; oStringList.Add(AKey.Model); oStringList.Add(AKey.Color); oStringList.Add(AKey.Company); if ((AKey.Owner <> '') and (AKey.Number <> '')) then begin oStringList.Add(AKey.Number); oStringList.Add(AKey.Owner); end; oStringList.Sort(); Result := String.Join('_', oStringList); FreeAndNil(oStringList); end; // Returns an existing Flyweight with a given state or creates a new one. function TFlyweightFactory.GetFlyweight(ASharedState: TCar): TFlyweight; var sKey: string; I: Integer; iIndex: Integer; begin sKey := GetKey(ASharedState); iIndex := -1; for I := 0 to Pred(FPairsCarList.Count) do begin if FPairsCarList.Items[I].Value = sKey then begin iIndex := I; Break; end; end; if iIndex = -1 then begin TUtilsSingleton.WriteLog ('FlyweightFactory: Cannot find a flyweight, creating new one.'); FPairsCarList.Add(TPair<TFlyweight, string>.Create (TFlyweight.Create(ASharedState), sKey)); Result := FPairsCarList[FPairsCarList.Count - 1].Key; end else begin TUtilsSingleton.WriteLog('FlyweightFactory: Reusing existing flyweight.'); FreeAndNil(ASharedState); Result := FPairsCarList[iIndex].Key; end; end; procedure TFlyweightFactory.ListFlyweights; var oItem: TPair<TFlyweight, string>; begin TUtilsSingleton.WriteLog('FlyweightFactory: I have ' + FPairsCarList.Count.ToString + ' flyweights:'); for oItem in FPairsCarList do TUtilsSingleton.WriteLog(oItem.Value); TUtilsSingleton.WriteLog(' '); end; end.
unit Gauge; interface uses Windows, Messages, SysUtils, Graphics, Controls, StdCtrls, ExtCtrls, Classes; type TMGauge = class(TCustomControl) public OKColor, FailColor, BackColor, TxtColor: TColor; Max: Single; constructor Create(AOwner: TWinControl); destructor Destroy; override; private fText: String; fPosition: Single; fOKLength: Word; procedure Paint; override; procedure SetPosition (const Value: Single); published property Canvas; property Position: Single read fPosition write SetPosition; end; implementation { TGauge } constructor TMGauge.Create(AOwner: TWinControl); begin inherited Create(AOwner); Parent := AOwner; OKColor := clLime; FailColor := clRed; BackColor := clWhite; TxtColor := clBlack; Position := -1; Max := 100; Canvas.Font.Size := 10; end; destructor TMGauge.Destroy; begin // inherited; end; /////////////////////////////////////////////////////////////// procedure TMGauge.Paint; // begin // inherited Paint; // // with Canvas do // begin // if fPosition < 0 then // begin // Pen.Color := clBlack; // Brush.Color := BackColor; // Rectangle(0, 0, Width, Height); // end // else // begin // Pen.Color := OKColor; // Brush.Color := OKColor; // Rectangle(0, 0, fOKLength, Height); // Pen.Color := FailColor; // Brush.Color := FailColor; // Rectangle(fOKLength, 0, Width, Height); // // Canvas.Font.Color := TxtColor; // SetBkMode(self.Canvas.Handle, 1); // Canvas.TextOut(Width div 2-20, Height div 2-8, fText); // end; // end; // // // end; // /////////////////////////////////////////////////////////////// procedure TMGauge.SetPosition(const Value: Single); begin fPosition := Value; if Value >= 0.0 then begin fOKLength := Round(Width*Value/Max); fText := FormatFloat('0.00', Value)+'%'; end; Repaint; end; end.
unit dxffileutils; interface uses Types, SysUtils, Classes, dxftypes, dxfclasses, HashStrings; const DEFAULT_LAYER = '0'; // this is Layer Name DEFAULT_LINESTYLE = 'CONTINUOUS'; procedure AddDefaultObjects(dxf: TDxfFile); procedure AddDefaultBlocks(dxf: TDxfFile); procedure NormalizeBlocks(dxf : TDxfFile); procedure AddDefaultTables(dxf: TDxfFile); procedure AddDefaultClasses(dxf: TDxfFile); // UpdateHeader indicates if "HandleSeed" of the dxf file should be updated // to include the latest "filled" handle procedure FillHandles(dxf: TDxfFile; UpdateHeader: Boolean = true); function AddLine(afile: TDxfFile; const p1, p2: TPoint; const ALayerName: string = DEFAULT_LAYER): TDxfLine; function AddPolyLine(afile: TDxfFile; const p: array of TPoint; const ALayerName: string = DEFAULT_LAYER): TDxfPolyLine; function AddEndSeq(afile : TDxfFile; const ALayerName: string = DEFAULT_LAYER): TDxfSeqEnd; function AddLine2d(afile: TDxfFile; const p1, p2: TDxfPoint; const ALayerName: string = DEFAULT_LAYER): TDxfLine; procedure PointToDfxPoint(const src: TPoint; var dst: TDxfPoint; z: double = 0); // updates "_Owner" and "_RefId" to the actual reference // based on Handle and Owner values. // Should be used after loading file procedure HandlesToLinks(dxf: TDxfFile); // updates "Owner" and "RefID" based on the r // Should be used before saving a file (after manual manipulation) // Handles must be populated prior to calling this procedure // FillHandles() can be used! procedure LinksToHandles(dxf: TDxfFile); procedure GatherDxfBase(dxf: TDxfFile; dst: TList); const ZERO_HANDLE = '0'; function FindByHandle(dxf: TDxfFile; const h: string): TDxfBase; function FindTableByHandle(dxf: TDxfFile; const h: string): TDxfTable; function FindTableByName(dxf: TDxfFile; const n: string): TDxfTable; function FindDictByHandle(dxf: TDxfFile; const h: string): TDxfDictionary; procedure DeleteObject(dxf: TDxfFile; const h: string); procedure DefaultHeader(var h: TDxfHeader); function IntToHandle(it: integer): string; function AllocLayer(dst: TDxfTable; const Name: string; const DefLineType: string; ColorNum: Integer = 7): TDxfLayerEntry; procedure InitFingerPrintId(var h: TDxfHeader); procedure InitVersionId(var h: TDxfHeader); procedure UpdateVersionIds(var h: TDxfHeader); implementation procedure AddDefaultBlocks(dxf: TDxfFile); var b : TDxfFileBlock; begin b := dxf.AddBlock; b.BlockName := '*Model_Space'; b.BlockName2 := '*Model_Space'; b.LayerName := '0'; b._blockEnd.LayerName := '0'; b := dxf.AddBlock; b.BlockName := '*Paper_Space'; b.BlockName2 := '*Paper_Space'; b.LayerName := '0'; b._blockEnd.LayerName := '0'; end; procedure NormalizeBlocks(dxf : TDxfFile); var i : integer; bf : TDxfFileBlock; begin for i:=0 to dxf.blocks.Count-1 do begin bf := TDxfFileBlock(dxf.blocks[i]); // block end is owned by the stating block bf._blockEnd.Owner := bf.Handle; end; end; procedure AddDefaultClasses(dxf: TDxfFile); var c : TDxfClass; begin if not Assigned(dxf) then Exit; c := dxf.AddClass; c.recName := 'ACDBDICTIONARYWDFLT'; c.cppName := 'AcDbDictionaryWithDefault'; c.appName := APPName_ObjectDBX_Cls; c := dxf.AddClass; c.recName := 'DICTIONARYVAR'; c.cppName := 'AcDbDictionaryVar'; c.appName := APPName_ObjectDBX_Cls; c.ProxyFlags := 2047; c := dxf.AddClass; c.recName := 'ACDBPLACEHOLDER'; c.cppName := 'AcDbPlaceHolder'; c.appName := APPName_ObjectDBX_Cls; c := dxf.AddClass; c.recName := 'LAYOUT'; c.cppName := 'AcDbLayout'; c.appName := APPName_ObjectDBX_Cls; c := dxf.AddClass; c.recName := 'TABLESTYLE'; c.cppName := 'AcDbTableStyle'; c.appName := APPName_ObjectDBX_Cls; c.ProxyFlags := 4095; end; function AddLine(afile: TDxfFile; const p1, p2: TPoint; const ALayerName: string): TDxfLine; begin Result:=TDxfLine.Create; PointToDfxPoint(p1, Result.StartPoint); PointToDfxPoint(p2, Result.EndPoint); Result.LayerName := ALayerName; Result.ColorNumber := CECOLOR_BYLAYER; afile.AddEntity(Result); end; function AddLine2d(afile: TDxfFile; const p1, p2: TDxfPoint; const ALayerName: string = DEFAULT_LAYER): TDxfLine; begin Result:=TDxfLine.Create; Result.StartPoint := p1; Result.EndPoint := p2; Result.LayerName := ALayerName; Result.ColorNumber := CECOLOR_BYLAYER; afile.AddEntity(Result); end; function AddPolyLine(afile: TDxfFile; const p: array of TPoint; const ALayerName: string = DEFAULT_LAYER): TDxfPolyLine; var i : integer; v : TDxfVertex; begin Result := TDxfPolyLine.Create; Result.LayerName := ALayerName; afile.AddEntity(Result); for i:=0 to length(p)-1 do begin v := TDxfVertex.Create; v.LayerName := AlayerName; PointToDfxPoint(p[i], v.Location); afile.AddEntity(v); end; AddEndSeq(afile, ALayerName); end; function AddEndSeq(afile : TDxfFile; const ALayerName: string = DEFAULT_LAYER): TDxfSeqEnd; begin Result := TDxfSeqEnd.Create; Result.LayerName := ALayerName; afile.AddEntity( Result ); end; procedure PointToDfxPoint(const src: TPoint; var dst: TDxfPoint; z: double); begin dst.x := src.X; dst.y := src.Y; dst.z := z; end; function HandleToInt(const it: string): Integer; var err : integer; begin err := 0; Result := 0; Val('$'+it, Result, err); if err <> 0 then Result := 0; end; function IntToHandle(it: integer): string; var i : integer; begin if it = 0 then begin Result := ZERO_HANDLE; Exit; end; Result := IntToHex(it, 16); i:=1; while (i <= length(Result)) and (Result[i]='0') do inc(i); Result := Copy(Result, i, length(Result)); end; procedure FillHandles(dxf: TDxfFile; UpdateHeader: Boolean); var i : integer; e : TDxfBase; h : integer; h2 : integer; l : TList; begin h:=32; l:=TList.Create; try GatherDxfBase(dxf, l); // making sure the seed is the latest handle for i:=0 to l.Count-1 do begin e := TDxfBase(l[i]); if e.Handle<>'' then begin h2 := HandleToInt(e.Handle); if h2 > h then h:=h2+1; // try the next! end; end; for i:=0 to l.Count-1 do begin e := TDxfBase(l[i]); if e.Handle = '' then begin e.Handle:=IntToHandle(h); inc(h); end; end; if UpdateHeader then dxf.header.Base.NextHandle := IntToHandle(h); finally l.Free; end; end; procedure AddDefaultObjects(dxf: TDxfFile); var root : TDxfDictionary; function AllocEntryDictionary(const EntryName: string): TDxfDictionary; var e : TDxfDictionaryEntry; d : TDxfDictionary; begin e:=root.AddEntry; e.EntryName := EntryName; d := TDxfDictionary.Create; d._Owner := root; dxf.objects.Add(d); e._Ref := d; Result := d; end; begin root := TDxfDictionary.Create; dxf.objects.Add(root); AllocEntryDictionary('ACAD_COLOR'); AllocEntryDictionary('ACAD_GROUP'); // mandatory AllocEntryDictionary('ACAD_LAYOUT'); AllocEntryDictionary('ACAD_MATERIAL'); AllocEntryDictionary('ACAD_MLINESTYLE'); AllocEntryDictionary('ACAD_PLOTSETTINGS'); AllocEntryDictionary('ACAD_PLOTSTYLENAME'); // ACDBDICTIONARYWDFLT (D4) "" ACDBPLACEHOLDER (D5) AllocEntryDictionary('ACAD_TABLESTYLE'); AllocEntryDictionary('ACDBHEADERROUNDTRIPXREC'); AllocEntryDictionary('AcDbVariableDictionary'); end; procedure HandlesToLinks(dxf: TDxfFile); var h : THashedStringList; i : integer; j : integer; b : TDxfBase; own : TDxfBase; begin h := THashedStringList.Create; try for i:=0 to dxf.objects.Count-1 do begin b := TDxfBase(dxf.objects[i]); h.AddObject(b.Handle, b); end; for i:=0 to dxf.entities.Count-1 do begin b := TDxfBase(dxf.objects[i]); h.AddObject(b.Handle, b); end; for i:=0 to h.Count-1 do begin b := TDxfBase(h.Objects[i]); if (b._Owner = nil) then begin j := h.IndexOf(b.Owner); if j>=0 then b._Owner := TDxfBase(h.Objects[j]); end; end; finally h.Free; end; end; procedure LinksToHandles(dxf: TDxfFile); var i, j : integer; blist : TList; b : TDxfBase; d : TDxfDictionary; e : TDxfDictionaryEntry; begin blist := TList.Create; try GatherDxfBase(dxf, blist); for i := 0 to blist.Count-1 do begin b := TDxfBase(blist[i]); if Assigned(b._Owner) and (b.Owner = '') then b.Owner := b._Owner.Handle else if not Assigned(b._Owner) and (b.Owner = '') then b.Owner := ZERO_HANDLE; if (b is TDxfDictionary) then begin d := TDxfDictionary(b); for j:=0 to d.Entries.Count-1 do begin e := TDxfDictionaryEntry(d.Entries[j]); if Assigned(e._Ref) and (e.RefId = '') then e.refId := e._Ref.Handle; end; end; end; finally blist.Free; end; end; procedure GatherDxfBase(dxf: TDxfFile; dst: TList); var i : integer; b : TDxfBase; j : integer; t : TDxfTable; begin if not Assigned(dxf) or not Assigned(dst) then Exit; for i:=0 to dxf.tables.Count-1 do begin b := TDxfBase(dxf.tables[i]); dst.Add(b); t := TDxfTable(b); for j := 0 to t.Count-1 do dst.Add(t.Entry[j]); end; for i:=0 to dxf.objects.Count-1 do begin b := TDxfBase(dxf.objects[i]); dst.Add(b); end; for i:=0 to dxf.entities.Count-1 do begin b := TDxfBase(dxf.entities[i]); dst.Add(b); end; for i:=0 to dxf.blocks.Count-1 do begin b := TDxfBase(dxf.blocks[i]); dst.Add(b); dst.Add(TDxfFileBlock(b)._blockEnd); end; end; function AllocLType(dst: TDxfTable; const Name: string; const Desc: string): TDxfLTypeEntry; const DEF_ALIGN_CODE = 65; begin Result := TDxfLTypeEntry.Create; Result.EntryType := TE_LTYPE; Result.SubClass := 'AcDbSymbolTableRecord'; Result.SubClass2 := 'AcDbLinetypeTableRecord'; Result._Owner := dst; dst.AddItem(Result); Result.LineType := Name; Result.Descr := Desc; Result.AlignCode := DEF_ALIGN_CODE; end; function AllocLayer(dst: TDxfTable; const Name: string; const DefLineType: string; ColorNum: Integer = 7): TDxfLayerEntry; begin Result := TDxfLayerEntry.Create; Result.EntryType := TE_LAYER; Result.SubClass := 'AcDbSymbolTableRecord'; Result.SubClass2 := 'AcDbLayerTableRecord'; Result._Owner := dst; dst.AddItem(Result); Result.LayerName := Name; Result.LineType := DefLineType; Result.ColorNum := ColorNum; Result.Lineweight := Lineweight_Standard; end; function AllocVPort(owner: TDxfTable; const VPortName: string): TDxfVPortEntry; begin Result := TDxfVPortEntry.Create; Result.EntryType := TE_VPORT; Result.SubClass := CLS_AcDbSymbolTableRecord; Result.SubClass2 := CLS_AcDbViewportTableRecord; Result.ViewName := VPortName; Result.LeftLow := DxfPoint(0,0); Result.UpRight := DxfPoint(1,1); Result.ViewCenter := DxfPoint(355,50); Result.SnapBase := DxfPoint(0,0); Result.SnapSpace := DxfPoint(1,1); Result.GridSpace := DxfPoint(0,0); Result.ViewDir := DxfPoint(0,0,1); Result.ViewTarget:= DxfPoint(0,0,0); Result._40 := 455; Result._41 := 2.5; Result.LensLen := 50; Result.FrontClipOfs := 0; Result.BackClipOfs := 0; Result.RotateAngle := 0; Result.TwistAngle := 0; Result.ViewMode := 0; Result.CircleSides := 10000; Result._73 := 0; Result._75 := 0; Result._76 := 0; Result._77 := 0; Result._78 := 0; Result._65 := 1; Result.UCSOrigin := DxfPoint(0,0,0); Result.UCSXAxis := DxfPoint(1,0,0); Result.UCSYAxis := DxfPoint(0,1,0); Result.OrthType := 0; if Assigned(Owner) then Owner.AddItem(Result); end; procedure AddDefaultTables(dxf: TDxfFile); var t : TDxfTable; ap : TDxfAppIdEntry; br : TDxfBlockRecordEntry; begin t := TDxfTable.Create; t.Name := 'VPORT'; AllocVPort(t, '*Active'); dxf.tables.Add(t); t := TDxfTable.Create; t.Name := 'LTYPE'; t.SubClass := 'AcDbSymbolTable'; dxf.tables.Add(t); AllocLType(t, 'ByBlock',''); AllocLType(t, 'ByLayer',''); AllocLType(t, DEFAULT_LINESTYLE,'Solid line'); t := TDxfTable.Create; t.Name := 'LAYER'; t.SubClass := 'AcDbSymbolTable'; dxf.tables.Add(t); AllocLayer(t, '0', 'CONTINUOUS'); t := TDxfTable.Create; t.Name := 'STYLE'; t.SubClass := 'AcDbSymbolTable'; dxf.tables.Add(t); t := TDxfTable.Create; t.Name := 'VIEW'; t.SubClass := 'AcDbSymbolTable'; dxf.tables.Add(t); t := TDxfTable.Create; t.Name := 'UCS'; t.SubClass := 'AcDbSymbolTable'; dxf.tables.Add(t); t := TDxfTable.Create; t.Name := 'APPID'; t.SubClass := 'AcDbSymbolTable'; dxf.tables.Add(t); ap := TDxfAppIdEntry.Create; ap.EntryType :='APPID'; ap.SubClass := 'AcDbSymbolTableRecord'; ap.AppData:='ACAD'; ap.Flags:=0; ap.SubClass2 := 'AcDbRegAppTableRecord'; ap._Owner := t; t.AddItem(ap); t := TDxfTable.Create; t.Name := 'DIMSTYLE'; t.SubClass := 'AcDbSymbolTable'; t.SubClass2 := 'AcDbDimStyleTable'; dxf.tables.Add(t); t := TDxfTable.Create; t.Name := 'BLOCK_RECORD'; t.SubClass := 'AcDbSymbolTable'; dxf.tables.Add(t); br := TDxfBlockRecordEntry.Create; br.EntryType := 'BLOCK_RECORD'; br.SubClass := 'AcDbSymbolTableRecord'; br.BlockName := '*Model_Space'; br.SubClass2 := 'AcDbBlockTableRecord'; br.LayoutId := '0'; br._Owner := t; t.AddItem(br); br := TDxfBlockRecordEntry.Create; br.EntryType := 'BLOCK_RECORD'; br.SubClass := 'AcDbSymbolTableRecord'; br.BlockName := '*Paper_Space'; br.SubClass2 := 'AcDbBlockTableRecord'; br.LayoutId := '0'; // layer name br._Owner := t; t.AddItem(br); end; function FindByHandle(dxf: TDxfFile; const h: string): TDxfBase; var f : TList; i : integer; begin f := TList.Create; try writeln('search start: ', h); GatherDxfBase(dxf, f); for i:=0 to f.Count-1 do begin Result := TDxfBase(f[i]); writeln('compare: ', Result.Handle ,' / ', h); if Result.Handle = h then Exit; end; Result := nil; finally f.Free; end; end; function FindTableByHandle(dxf: TDxfFile; const h: string): TDxfTable; var b : TDxfBase; begin b := FindByHandle(dxf, h); if not (b is TDxfTable) then Result := nil else Result := TDxfTable(b); end; function FindTableByName(dxf: TDxfFile; const n: string): TDxfTable; var i : integer; begin for i := 0 to dxf.tables.Count-1 do if TDxfTable(dxf.tables[i]).Name = n then begin Result := TDxfTable(dxf.tables[i]); Exit; end; Result := nil; end; function FindDictByHandle(dxf: TDxfFile; const h: string): TDxfDictionary; var b : TDxfBase; begin b := FindByHandle(dxf, h); if not (b is TDxfDictionary) then begin writeln('lame lame: ', h); Result := nil end else Result := TDxfDictionary(b); end; procedure DeleteObject(dxf: TDxfFile; const h: string); var i : integer; ob : TDxfObject; begin for i:=dxf.objects.Count-1 downto 0 do begin ob := TDxfObject(dxf.objects[i]); if ob.Handle = h then begin ob.Free; writeln('deleting: ' ,i,' ',h); dxf.objects.Delete(i); end; end; end; procedure DefaultHeader(var h: TDxfHeader); begin h.acad.Version := ACAD_VER_2000; h.acad.MaintVer := 20; // default maintenance version h.acad.isExtNames := 1; h.Base.CodePage := DEFAULT_CODEPAGE; H.BASE.ExtLowLeft.x:=-2.5; H.BASE.ExtLowLeft.Y:=-2.5; H.BASE.ExtUpRight.x:=+2.5; H.BASE.ExtUpRight.Y:=+2.5; H.BASE.LimUpRight.x:=420; H.BASE.LimUpRight.Y:=297; h.base.isRegen := 1; h.base.isFill := 1; h.base.LineTypeScale := 1; h.base.AttrVisMode := 1; h.Sel.TextStyle := DEFAULT_TEXTSTYLE; // this must be non-empty valid style! h.sel.Layer := '0'; h.Base.TextHeight := 0.2; h.Base.TraceWidth := 0.05; h.Sel.EntLineType := 'ByLayer'; h.Sel.EntLineTypeScale := 1; h.Sel.EntColor := CECOLOR_BYLAYER; h.Dim.Scale := 1; // $DIMSCALE h.Dim.ArrowSize := 0.18; // $DIMASZ h.Dim.ExtLineOfs := 0.0625; // $DIMEXO h.Dim.DimLineInc := 0.38; // ($DIMDLI) h.Dim.ExtLineExt := 0.18; // ($DIMEXE) h.Dim.TextHeight := 0.18; // ($DIMTXT) h.Dim.CenterSize := 0.09; // ($DIMCEN) h.Dim.isTextIns := 1; h.Dim.isTextOut := 1; h.Dim.isAssocDim := 1; // ($DIMASO) h.Dim.isRecompDim := 1; // ($DIMSHO) h.Dim.AltDec := 2; // ($DIMALTD) h.Dim.AltScale := 25.4; // ($DIMALTF) h.Dim.LinearScale := 1.0; // $DIMLFAC h.Dim.StyleName := DEFAULT_TEXTSTYLE; h.Dim.DispTolerance := 1.0; // $DIMTFAC h.Dim.LineGap := 0.09; // $DIMGAP h.Dim.VertJustTol := 1; // ($DIMTOLJ) h.Dim.DecPlacesPrim := 4; // ($DIMDEC) h.Dim.UnitsFormat := 2; // ($DIMALTU) h.Dim.DecPlacesAltUnit := 2; // ($DIMALTTD) h.Dim.TextStyle := DEFAULT_TEXTSTYLE; // ($DIMTXSTY) h.Dim.DecSeparator := 46; // ($DIMDSEP) h.Dim.TextArrowPlace := 3; // ($DIMATFIT) h.Dim.Units := LenUnitFmt_Decimal; // ($DIMLUNIT) h.Dim.LineWeight := Lineweight_ByLayer; // ($DIMLWD) h.Dim.LineWeightExt := Lineweight_ByLayer; // ($DIMLWE) h.Dim.DecPlacesOther := 4; // ($DIMTDEC) h.Base.DistFormat := LenUnitFmt_Decimal; // $LUNITS h.base.DistPrec := 4; // $LUPREC h.base.SketchInc := 0.1; // ($SKETCHINC) 40 Sketch record increment h.base.MenuName := '.'; h.base.SplineFrame := 0; h.base.SplineCurvType := 6; h.Base.LineSegments := 8; // ($SPLINESEGS) Number of line segments per spline patch h.Base.MeshCount1 := 6; // ($SURFTAB1) 70 Number of mesh tabulations in first direction h.Base.MeshCount2 := 6; // ($SURFTAB2) 70 Number of mesh tabulations in second direction h.Base.SurfType := 6; h.Base.SurfType := 6; h.Base.SurfDensityM := 6; // ($SURFU) 70 Surface density (for PEDIT Smooth) in M direction h.Base.SurfDensityN := 6; // ($SURFV) 70 Surface density (for PEDIT Smooth) in N direction h.Ucs.Base := ''; h.Ucs.Name := ''; h.Ucs.Origin := DxfPoint(0,0,0); h.Ucs.XDir := DxfPoint(1,0,0); h.Ucs.YDir := DxfPoint(0,1,0); h.Ucs.OrthoRef := ''; h.Ucs.OrthoView := 0; h.Ucs.OriginTop := DxfPoint(0,0,0); h.Ucs.OriginBack := DxfPoint(0,0,0); h.Ucs.OriginBottom := DxfPoint(0,0,0); h.Ucs.OriginFront := DxfPoint(0,0,0); h.Ucs.OriginLeft := DxfPoint(0,0,0); h.Ucs.OriginRight := DxfPoint(0,0,0); h.PUcs.Base := ''; h.PUcs.Name := ''; h.PUcs.Origin := DxfPoint(0,0,0); h.PUcs.XDir := DxfPoint(1,0,0); h.PUcs.YDir := DxfPoint(0,1,0); h.PUcs.OrthoRef := ''; h.PUcs.OrthoView := 0; h.PUcs.OriginTop := DxfPoint(0,0,0); h.PUcs.OriginBack := DxfPoint(0,0,0); h.PUcs.OriginBottom := DxfPoint(0,0,0); h.PUcs.OriginFront := DxfPoint(0,0,0); h.PUcs.OriginLeft := DxfPoint(0,0,0); h.PUcs.OriginRight := DxfPoint(0,0,0); h.Base.isWorldView := 1; // $WORLDVIEW h.Base.ShadeEdge := ShadeEdge_Color; // $SHADEDGE h.Base.ShadeDiffuse := 70; // $SHADEDIF h.Base.isTileMode := 1; // $TILEMODE h.Base.MaxViewPorts := 64; // $MAXACTVP h.Base.PaperLimUpRight := DxfPoint(12, 9); h.Base.isRetainXRefVis := 1; h.Base.PaperLineScaling := 1; h.Base.SpaceTreeDepth := 3020; h.Sel.MultiLineStyle := DEFAULT_TEXTSTYLE; h.Sel.MultiLineScale := 1.0; h.Base.isProxyImageSave := 1; h.Base.NewObjLineWeight := Linewieght_ByBlock; h.Base.DefaultUnits := UNITS_NO; h.Base.isInPlaceEditin := 1; h.base.isColorDepmode := 1; { h.Sel.EntLineType := 'ByLayer'; // reference to LType h.Dim.isTextOut := 1; // ($DIMTOH) h.Dim.isTextAbove := 1; // ($DIMTAD) h.Dim.SupZeros := 8; // ($DIMZIN) } {h.Dim.ArrowBlock : string; // ($DIMBLK) h.Dim.Suffix : string; // ($DIMPOST) h.Dim.AltSuffix : string; // ($DIMAPOST) h.Dim.isUseAltUnit : integer; // ($DIMALT) h.Dim.LinearScale : double; // ($DIMLFAC) h.Dim.isTextOutExt : Integer; // ($DIMTOFL) h.Dim.TextVertPos : double; // ($DIMTVP) h.Dim.isForceTextIns : Integer; // ($DIMTIX) h.Dim.isSuppOutExt : Integer; // ($DIMSOXD) h.Dim.isUseSepArrow : Integer; // ($DIMSAH) h.Dim.ArrowBlock1 : string; // ($DIMBLK1) h.Dim.ArrowBlock2 : string; // ($DIMBLK2) h.Dim.LineColor : integer; // ($DIMCLRD) h.Dim.ExtLineColor : integer; // ($DIMCLRE) h.Dim.TextColor : integer; // ($DIMCLRT) h.Dim.DispTolerance : double; // ($DIMTFAC) h.Dim.LineGap : double; // ($DIMGAP) h.Dim.HorzTextJust : integer; // ($DIMJUST) h.Dim.isSuppLine1 : Integer; // ($DIMSD1) h.Dim.isSuppLine2 : Integer; // ($DIMSD2) h.Dim.ZeroSupTol : Integer; // ($DIMTZIN) h.Dim.ZeroSupAltUnitTol : Integer; // ($DIMALTZ) h.Dim.ZeroSupAltTol : Integer; // ($DIMALTTZ) h.Dim.isEditCursorText : Integer; // ($DIMUPT) h.Dim.AngleFormat : Integer; // ($DIMAUNIT) h.Dim.AngleDecPlaces : Integer; // ($DIMADEC) h.Dim.RoundValAlt : double; // ($DIMALTRND) h.Dim.ZeroSupAngUnit : Integer; // ($DIMAZIN) h.Dim.ArrowBlockLead : string; // ($DIMLDRBLK) h.Dim.TextMove : Integer; // ($DIMTMOVE) h.Dim.UnitFrac : Integer; // DIMFRAC h.Dim.ArrowBlockId : string; // ($DIMBLK1) h.Dim.ArrowBlockId1 : string; // ($DIMBLK1) h.Dim.ArrowBlockId2 : string; // ($DIMBLK2) // oboslete __Units: Integer; // ($DIMUNIT) Se __TextArrowPlace: Integer; // ($DIMFIT) Con} end; procedure InitFingerPrintId(var h: TDxfHeader); var g : TGuid; begin CreateGUID(g); h.Base.FingerPrintGuid := GUIDToString(g); end; procedure InitVersionId(var h: TDxfHeader); var g : TGuid; begin CreateGUID(g); h.Base.VersionGuild := GUIDToString(g); end; procedure UpdateVersionIds(var h: TDxfHeader); begin if h.Base.FingerPrintGuid = '' then InitFingerPrintId(h); InitVersionId(h); end; end.
unit dmCuenta; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dmCuentaBase, DB, IBCustomDataSet, IBQuery, IBSQL, kbmMemTable, UtilDB; const SIN_CUENTA = Low(Integer); type TCuenta = class(TCuentaBase) qMaxNumMov: TIBQuery; qMaxNumMovMAX: TIntegerField; qCuentaMovimientos: TIBQuery; iCrearCuenta: TIBSQL; qCuenta: TIBQuery; qCuentaOID_CUENTA: TSmallintField; qCuentaOR_MONEDA: TSmallintField; qCuentaMovimientosOR_CUENTA: TSmallintField; qCuentaMovimientosNUM_MOVIMIENTO: TIntegerField; qCuentaMovimientosFECHA_HORA: TDateTimeField; qCuentaMovimientosTIPO: TIBStringField; qCuentaMovimientosOR_VALOR: TSmallintField; qCuentaMovimientosCAMBIO: TIBBCDField; qCuentaMovimientosCOMISION: TIBBCDField; qCuentaMovimientosPOSICION: TIBStringField; qCuentaMovimientosOR_NUM_MOVIMIENTO: TIntegerField; qCuentaMovimientosGANANCIA: TIBBCDField; qCuentaMovimientosBROKER_ID: TIntegerField; qCuentaMovimientosMONEDA_VALOR: TIBBCDField; qCuentaMovimientosMONEDA: TIBStringField; qCuentaMovimientosNOMBRE: TIBStringField; qCuentaMovimientosSIMBOLO: TIBStringField; qCuentaMovimientosOID_MERCADO: TSmallintField; qCuentaMovimientosMERCADO: TIBStringField; qCuentaMovimientosOR_MONEDA: TSmallintField; qCuentaMovimientosGANANCIA_MONEDA_BASE: TIBBCDField; qCuentaMovimientosCOSTE: TCurrencyField; // uCuentaMovimientos: TIBUpdateDataSet; qCuentaMovimientosNUM_ACCIONES: TIntegerField; qCuentaMovimientosOID_MONEDA: TSmallintField; iCuentaMovimientos: TIBSQL; uCuentaMovimientos: TIBSQL; dCuentaMovimientos: TIBSQL; procedure qCuentaAfterOpen(DataSet: TDataSet); procedure qCuentaMovimientosCalcFields(DataSet: TDataSet); procedure CuentaMovimientosBeforeDelete(DataSet: TDataSet); procedure CuentaMovimientosBeforePost(DataSet: TDataSet); { procedure uCuentaMovimientosBeforeExecureSQL(UpdateKind: TUpdateKind; q: TIBSQL);} private FOIDCuenta: integer; OIDGenerator: TOIDGenerator; protected procedure InicializarNumMovimiento; procedure CargarMovimientos; override; public constructor Create(const AOwner: TComponent); overload; virtual; destructor Destroy; override; // function CerrarMonedas: TCerrarMonedasResult; override; // function CambiarCambioMoneda: TCerrarMonedasResult; override; function Crear(const OIDMonedaBase: integer): integer; procedure Cargar(const OIDCuenta: integer); property OIDCuenta: integer read FOIDCuenta; end; implementation uses dmBD, dmCuentaMovimientosBase, dmDataComun, Math, UtilDBSC; {$R *.dfm} const MONEDA_POR_DEFECTO = 1; { TCuentaBaseBD } {function TCuenta.CambiarCambioMoneda: TCerrarMonedasResult; begin result := inherited CambiarCambioMoneda; case result of cmrCancelado: CuentaMovimientos.CancelUpdates; cmrCambiado: CuentaMovimientos.ApplyUpdates(0); end; end; } procedure TCuenta.Cargar(const OIDCuenta: integer); begin // Si la cuenta ya se ha utilizado y se recarga, tendrá los eventos asignados // y dará error, los inicializamos. OnAnadirCurvaCapital := nil; OnAfterScrollCurvaCapital := nil; OnCapitalRecalculado := nil; OnInicializarCurvaCapital := nil; qCuenta.Close; qCuenta.Params[0].AsInteger := OIDCuenta; qCuenta.Open; SetOIDMoneda(qCuentaOR_MONEDA.Value); InicializarNumMovimiento; end; procedure TCuenta.CargarMovimientos; begin if not CuentaMovimientos.Active then CuentaMovimientos.Open; end; { function TCuenta.CerrarMonedas: TCerrarMonedasResult; begin result := inherited CerrarMonedas; case result of cmrCancelado: CuentaMovimientos.CancelUpdates; cmrCambiado: CuentaMovimientos.ApplyUpdates(0); end; end; } function TCuenta.Crear(const OIDMonedaBase: integer): integer; begin if OIDGenerator = nil then OIDGenerator := TOIDGenerator.Create(scdUsuario, 'CUENTA'); result := OIDGenerator.NextOID; iCrearCuenta.ParamByName('OID_CUENTA').AsInteger := result; iCrearCuenta.ParamByName('OR_MONEDA').AsInteger := OIDMonedaBase; iCrearCuenta.ExecQuery; FOIDMoneda := OIDMonedaBase; FOIDCuenta := result; // Si creamos una cuenta, inicializamos los movimientos, ya que Inicializar // no inicializa los movimientos, sino que a partir de los movimientos crea // las posiciones abiertas y cerradas CuentaMovimientos.Close; CuentaMovimientos.Open; Inicializar; end; constructor TCuenta.Create(const AOwner: TComponent); begin inherited Create(AOwner, MONEDA_POR_DEFECTO); FOIDCuenta := SIN_CUENTA; end; procedure TCuenta.CuentaMovimientosBeforeDelete(DataSet: TDataSet); begin inherited; dCuentaMovimientos.ParamByName('OR_CUENTA').AsInteger := FOIDCuenta; dCuentaMovimientos.ParamByName('NUM_MOVIMIENTO').AsInteger := CuentaMovimientosNUM_MOVIMIENTO.Value; ExecQuery(dCuentaMovimientos, true); end; procedure TCuenta.CuentaMovimientosBeforePost(DataSet: TDataSet); procedure insertar; begin AssignParams(CuentaMovimientos, iCuentaMovimientos); iCuentaMovimientos.ParamByName('OR_CUENTA').AsInteger := FOIDCuenta; iCuentaMovimientos.ParamByName('OR_MONEDA').AsInteger := CuentaMovimientosOID_MONEDA.Value; { iCuentaMovimientos.ParamByName('NUM_MOVIMIENTO').AsInteger := CuentaMovimientosNUM_MOVIMIENTO.Value; iCuentaMovimientos.ParamByName('FECHA_HORA').AsDateTime := CuentaMovimientosFECHA_HORA.Value; iCuentaMovimientos.ParamByName('TIPO').AsString := CuentaMovimientosTIPO.Value; iCuentaMovimientos.ParamByName('OR_VALOR').AsInteger := CuentaMovimientosOR_VALOR.Value; iCuentaMovimientos.ParamByName('NUM_ACCIONES').AsInteger := CuentaMovimientosNUM_ACCIONES.Value; iCuentaMovimientos.ParamByName('CAMBIO').AsCurrency := CuentaMovimientosCAMBIO.Value; iCuentaMovimientos.ParamByName('COMISION').AsCurrency := CuentaMovimientosCOMISION.Value; if CuentaMovimientosPOSICION.IsNull then iCuentaMovimientos.ParamByName('POSICION').Clear else iCuentaMovimientos.ParamByName('POSICION').AsString := CuentaMovimientosPOSICION.Value; iCuentaMovimientos.ParamByName('OR_NUM_MOVIMIENTO').AsInteger := CuentaMovimientosOR_NUM_MOVIMIENTO.Value; iCuentaMovimientos.ParamByName('GANANCIA').AsCurrency := CuentaMovimientosGANANCIA.Value; iCuentaMovimientos.ParamByName('BROKER_ID').AsInteger := CuentaMovimientosBROKER_ID.Value; iCuentaMovimientos.ParamByName('OR_MONEDA').AsInteger := CuentaMovimientosOID_MONEDA.Value; iCuentaMovimientos.ParamByName('MONEDA_VALOR').AsCurrency := CuentaMovimientosMONEDA_VALOR.Value; iCuentaMovimientos.ParamByName('GANANCIA_MONEDA_BASE').AsCurrency := CuentaMovimientosGANANCIA_MONEDA_BASE.Value;} ExecQuery(iCuentaMovimientos, true); end; procedure modificar; begin AssignParams(CuentaMovimientos, uCuentaMovimientos); { uCuentaMovimientos.ParamByName('OR_NUM_MOVIMIENTO').AsInteger := CuentaMovimientosOR_NUM_MOVIMIENTO.Value; uCuentaMovimientos.ParamByName('MONEDA_VALOR').AsCurrency := CuentaMovimientosMONEDA_VALOR.Value; uCuentaMovimientos.ParamByName('GANANCIA').AsCurrency := CuentaMovimientosGANANCIA.Value; uCuentaMovimientos.ParamByName('GANANCIA_MONEDA_BASE').AsCurrency := CuentaMovimientosGANANCIA_MONEDA_BASE.Value; uCuentaMovimientos.ParamByName('NUM_MOVIMIENTO').AsInteger := CuentaMovimientosNUM_MOVIMIENTO.Value;} uCuentaMovimientos.ParamByName('OR_CUENTA').AsInteger := FOIDCuenta; ExecQuery(uCuentaMovimientos, true); end; begin inherited; if CuentaMovimientos.State = dsInsert then begin insertar; end else begin if CuentaMovimientos.State = dsEdit then modificar; end; end; destructor TCuenta.Destroy; begin if OIDGenerator <> nil then OIDGenerator.Free; inherited; end; procedure TCuenta.InicializarNumMovimiento; begin qMaxNumMov.Close; qMaxNumMov.Params[0].AsInteger := OIDCuenta; qMaxNumMov.Open; OIDNumMovimiento := qMaxNumMovMAX.Value; qMaxNumMov.Close; end; {procedure TCuenta.uCuentaMovimientosBeforeExecureSQL(UpdateKind: TUpdateKind; q: TIBSQL); begin inherited; q.ParamByName('OR_CUENTA').Value := FOIDCuenta; { object uCuentaMovimientos: TIBUpdateDataSet ModifySQL.Strings = ( 'update CUENTA_MOVIMIENTOS' 'set OR_NUM_MOVIMIENTO = :OR_NUM_MOVIMIENTO,' 'MONEDA_VALOR = :MONEDA_VALOR,' 'GANANCIA = :GANANCIA,' 'GANANCIA_MONEDA_BASE = :GANANCIA_MONEDA_BASE' 'where' 'OR_CUENTA = :OR_CUENTA and' 'NUM_MOVIMIENTO = :NUM_MOVIMIENTO') InsertSQL.Strings = ( 'insert into CUENTA_MOVIMIENTOS' ' (OR_CUENTA, NUM_MOVIMIENTO, FECHA_HORA, TIPO, OR_VALOR, NUM_AC' + 'CIONES, CAMBIO,' ' COMISION, POSICION, OR_NUM_MOVIMIENTO, GANANCIA, BROKER_ID,OR_' + 'MONEDA,' ' MONEDA_VALOR, GANANCIA_MONEDA_BASE)' 'values' ' (:OR_CUENTA, :NUM_MOVIMIENTO, :FECHA_HORA, :TIPO, :OR_VALOR, :' + 'NUM_ACCIONES, :CAMBIO,' ' :COMISION, :POSICION, :OR_NUM_MOVIMIENTO, :GANANCIA, :BROKER_I' + 'D, :OID_MONEDA,' ' :MONEDA_VALOR, :GANANCIA_MONEDA_BASE)') DeleteSQL.Strings = ( 'delete from CUENTA_MOVIMIENTOS' 'where' ' NUM_MOVIMIENTO = :NUM_MOVIMIENTO and' ' OR_CUENTA = :OR_CUENTA') DataSet = CuentaMovimientos OnBeforeExecureSQL = uCuentaMovimientosBeforeExecureSQL Left = 184 Top = 128 end } //end; procedure TCuenta.qCuentaAfterOpen(DataSet: TDataSet); begin inherited; FOIDCuenta := qCuentaOID_CUENTA.Value; FOIDMoneda := qCuentaOR_MONEDA.Value; CuentaMovimientos.Close; qCuentaMovimientos.Params[0].AsInteger := OIDCuenta; // Antes de cargar los movimientos se tiene que desactivar el updateDataSet, // sino al cargar los datos hace insert y se tiran las querys CuentaMovimientos.BeforeDelete := nil; CuentaMovimientos.BeforePost := nil; // uCuentaMovimientos.DataSet := nil; CuentaMovimientos.LoadFromDataSet(qCuentaMovimientos, []); // uCuentaMovimientos.DataSet := CuentaMovimientos; CuentaMovimientos.BeforeDelete := CuentaMovimientosBeforeDelete; CuentaMovimientos.BeforePost := CuentaMovimientosBeforePost; Inicializar; end; procedure TCuenta.qCuentaMovimientosCalcFields(DataSet: TDataSet); var mov: TMovimientoInversion; moneda: PDataComunMoneda; function GetCosteMovimiento: currency; begin result := (qCuentaMovimientosNUM_ACCIONES.Value * qCuentaMovimientosCAMBIO.Value); if mov = miVentaAcciones then result := result - qCuentaMovimientosCOMISION.Value else result := result + qCuentaMovimientosCOMISION.Value; if qCuentaMovimientosMONEDA.Value = 'GBP' then result := result / 100; end; procedure DescValor; var valor: PDataComunValor; begin valor := DataComun.FindValor(qCuentaMovimientosOR_VALOR.Value); qCuentaMovimientosSIMBOLO.Value := valor^.Simbolo; qCuentaMovimientosNOMBRE.Value := valor^.Nombre; qCuentaMovimientosOID_MERCADO.Value := valor^.Mercado^.OIDMercado; qCuentaMovimientosMERCADO.Value := valor^.Mercado^.Pais; end; begin inherited; mov := GetMovimientoInversion(qCuentaMovimientosTIPO.Value); case mov of miCompraAcciones: begin qCuentaMovimientosCOSTE.Value := -GetCosteMovimiento; DescValor; end; miVentaAcciones: begin qCuentaMovimientosCOSTE.Value := GetCosteMovimiento; DescValor; end; end; moneda := DataComun.FindMoneda(qCuentaMovimientosOR_MONEDA.Value); qCuentaMovimientosOID_MONEDA.Value := moneda^.OIDMoneda; qCuentaMovimientosMONEDA.Value := moneda^.Nombre; end; end.
//Эта программа переворачивает слово program ReverseWord; var Text,TextReverse,L:string; N:integer; begin writeln('Введите предложение: '); readln(Text); Text:=LowerCase(Text); for n:=1 to length(Text) do begin TextReverse:=Text[n] + TextReverse; end; if TextReverse = Text then writeln('Слово перевертыш') else writeln('Слово не перевертыш'); end.