text stringlengths 14 6.51M |
|---|
{
Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit LogViewer.Receivers.MQTT;
{ MQTT channel receiver. }
interface
{$REGION 'documentation'}
{ In contrast to ZMQ, MQTT requires a message broker to route messages between
servers (publishers) and clients (subscribers).
There are many online message brokers available to connect to, and you can run
your own one using Mosquitto for example.
}
{$ENDREGION}
uses
System.Classes,
Vcl.ExtCtrls,
Spring, Spring.Collections,
MQTT,
DDuce.DynamicRecord,
LogViewer.Interfaces, LogViewer.Receivers.Base;
{$REGION 'documentation'}
{$ENDREGION}
type
TMQTTChannelReceiver = class(TChannelReceiver, IChannelReceiver, IMQTT)
private
FMQTT: TMQTT;
protected
{$REGION 'property access methods'}
//function GetSettings: TMQTTSettings;
procedure SetEnabled(const Value: Boolean); override;
{$ENDREGION}
//procedure SettingsChanged(Sender: TObject);
function CreateSubscriber(
ASourceId : UInt32;
AThreadId : UInt32;
const ASourceName : string
): ISubscriber; override;
public
procedure AfterConstruction; override;
constructor Create(
AManager : ILogViewerManager;
AMQTT : TMQTT;
const AName : string
); reintroduce;
//
// property Settings: TMQTTSettings
// read GetSettings;
end;
implementation
{$REGION 'construction and destruction'}
procedure TMQTTChannelReceiver.AfterConstruction;
begin
inherited AfterConstruction;
end;
{$ENDREGION}
{$REGION 'protected methods'}
constructor TMQTTChannelReceiver.Create(AManager: ILogViewerManager;
AMQTT: TMQTT; const AName: string);
begin
inherited Create(AManager, AName);
FMQTT := AMQTT;
end;
function TMQTTChannelReceiver.CreateSubscriber(ASourceId, AThreadId: UInt32;
const ASourceName: string): ISubscriber;
begin
end;
{$ENDREGION}
{$REGION 'property access methods'}
procedure TMQTTChannelReceiver.SetEnabled(const Value: Boolean);
begin
inherited;
end;
{$ENDREGION}
end.
|
{
* CGEventTypes.h
* CoreGraphics
*
* Copyright (c) 2004 Apple Computer, Inc. All rights reserved.
*
}
{ Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, August 2005 }
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit CGEventTypes;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes,MacOSXPosix,CGRemoteOperation,CGBase;
{$ALIGN POWER}
{
* The CGEventRef object may be created or copied, retained, released, and
* modified. The object provides an opaque representation of one low level
* hardware event.
}
type
CGEventRef = ^SInt32; { an opaque 32-bit type }
{
* Types common to both CGEvent.h and CGEventSource.h
}
type
_CGMouseButton = SInt32;
const
kCGMouseButtonLeft = 0;
kCGMouseButtonRight = 1;
kCGMouseButtonCenter = 2;
type
CGMouseButton = UInt32;
{
* The flags field includes both modifier key state at the time the event was created,
* as well as other event related state.
*
* Note that any bits not specified are reserved.
}
type
_CGEventFlags = SInt32;
(*
Uncomment when IOKit is translated
const { Masks for the bits in event flags }
{ device-independent modifier key bits }
kCGEventFlagMaskAlphaShift = NX_ALPHASHIFTMASK;
kCGEventFlagMaskShift = NX_SHIFTMASK;
kCGEventFlagMaskControl = NX_CONTROLMASK;
kCGEventFlagMaskAlternate = NX_ALTERNATEMASK;
kCGEventFlagMaskCommand = NX_COMMANDMASK;
{ Special key identifiers }
kCGEventFlagMaskHelp = NX_HELPMASK;
kCGEventFlagMaskSecondaryFn = NX_SECONDARYFNMASK;
{ Identifies key events from numeric keypad area on extended keyboards }
kCGEventFlagMaskNumericPad = NX_NUMERICPADMASK;
{ Indicates if mouse/pen movement events are not being coalesced }
kCGEventFlagMaskNonCoalesced = NX_NONCOALSESCEDMASK;
*)
type
CGEventFlags = UInt64; { Flags for events }
{
*
* The following enumeration describes all event types currently presented
* in this API. Apple reserves the right to extend or create new event
* types at any time.
*
* Notes:
* Tablet devices may generate mice events with embedded tablet
* data, or tablet pointer and proximity events. The tablet
* events as mouse events allow tablets to be used with programs
* which are not tablet-aware.
}
{ Event types }
type
_CGEventType = SInt32;
(*
Uncomment when IOKit is translated
const
kCGEventNull = NX_NULLEVENT; { Placeholder; the Null Event }
{ mouse events }
kCGEventLeftMouseDown = NX_LMOUSEDOWN; { left mouse-down event }
kCGEventLeftMouseUp = NX_LMOUSEUP; { left mouse-up event }
kCGEventRightMouseDown = NX_RMOUSEDOWN; { right mouse-down event }
kCGEventRightMouseUp = NX_RMOUSEUP; { right mouse-up event }
kCGEventMouseMoved = NX_MOUSEMOVED; { mouse-moved event }
kCGEventLeftMouseDragged = NX_LMOUSEDRAGGED; { left mouse-dragged event }
kCGEventRightMouseDragged = NX_RMOUSEDRAGGED; { right mouse-dragged event }
{ keyboard events }
kCGEventKeyDown = NX_KEYDOWN; { key-down event }
kCGEventKeyUp = NX_KEYUP; { key-up event }
kCGEventFlagsChanged = NX_FLAGSCHANGED; { flags-changed (modifier keys and status) event }
{ Specialized control devices }
kCGEventScrollWheel = NX_SCROLLWHEELMOVED; { Scroll wheel input device }
kCGEventTabletPointer = NX_TABLETPOINTER; { specialized tablet pointer event, in addition to tablet mouse event }
kCGEventTabletProximity = NX_TABLETPROXIMITY; { specialized tablet proximity event, in addition to tablet mouse event }
kCGEventOtherMouseDown = NX_OMOUSEDOWN; { Mouse button 2-31 down }
kCGEventOtherMouseUp = NX_OMOUSEUP; { Mouse button 2-31 up }
kCGEventOtherMouseDragged = NX_OMOUSEDRAGGED; { Drag with mouse button 2-31 down }
*)
{
* Out of band types, delivered for unusual conditions
* These are delivered to the event tap callback to notify of unusual
* conditions that disable the event tap.
}
const
kCGEventTapDisabledByTimeout = $FFFFFFFE;
kCGEventTapDisabledByUserInput = $FFFFFFFF;
type
CGEventType = UInt32;
type
CGEventTimestamp = UInt64; { Event timestamp, roughly, nanoseconds since startup }
{
* Low level functions provide access to specialized fields of the events
* The fields are identified by tokens defined in this enumeration.
}
type
_CGEventField = SInt32;
const
{ Additional keys and values found in mouse events, including the OtherMouse events: }
kCGMouseEventNumber = 0;
{ Key associated with an integer encoding the mouse button event number as an integer. Matching mouse-down and mouse-up events will have the same event number. }
kCGMouseEventClickState = 1;
{ Key associated with an integer encoding the mouse button clickState as an integer. A clickState of 1 represents a single click. A clickState of 2 represents a double-click. A clickState of 3 represents a triple-click. }
kCGMouseEventPressure = 2;
{ Key associated with a double encoding the mouse button pressurr. The pressure value may range from 0 to 1.0, with 0 representing the mouse being up. This value is commonly set by tablet pens mimicing a mouse. }
kCGMouseEventButtonNumber = 3;
{ Key associated with an integer representing the mouse button number. The left mouse button reports as button 0. A right mouse button reports as button 1. A middle button reports as button 2, and additional buttons report as the appropriate USB button. }
kCGMouseEventDeltaX = 4;
kCGMouseEventDeltaY = 5;
{ Key associated with an integer encoding the mouse delta since the last mouse movement event. }
kCGMouseEventInstantMouser = 6;
{ Key associated with an integer value, non-zero if the event should be ignored by the Inkwell subsystem. }
kCGMouseEventSubtype = 7;
{
* Key associated with an integer encoding the mouse event subtype as a kCFNumberIntType.
*
* Tablets may generate specially annotated mouse events,
* which will contain additional keys and values.
*
* Mouse events of subtype kCGEventMouseSubtypeTabletPoint may also use the tablet accessor keys.
* Mouse events of subtype kCGEventMouseSubtypeTabletProximity may also use the tablet proximity accessor keys.
}
{ Additional keys and values found in keyboard events: }
kCGKeyboardEventAutorepeat = 8;
{ Key associated with an integer, non-zero when when this is an autorepeat of a key-down, and zero otherwise. }
kCGKeyboardEventKeycode = 9;
{ Key associated with the integer virtual keycode of the key-down or key-up event. }
kCGKeyboardEventKeyboardType = 10;
{ Key associated with the integer representing the keyboard type identifier. }
{ Additional keys and values found in scroll wheel events: }
kCGScrollWheelEventDeltaAxis1 = 11;
kCGScrollWheelEventDeltaAxis2 = 12;
kCGScrollWheelEventDeltaAxis3 = 13;
{ Key associated with an integer value representing a change in scrollwheel position. }
kCGScrollWheelEventInstantMouser = 14;
{ Key associated with an integer value, non-zero if the event should be ignored by the Inkwell subsystem. }
{
* Additional keys and values found in tablet pointer events,
* and in mouse events containing embedded tablet event data:
}
kCGTabletEventPointX = 15;
kCGTabletEventPointY = 16;
kCGTabletEventPointZ = 17;
{ Key associated with an integer encoding the absolute X, Y, or Z tablet coordinate in tablet space at full tablet resolution. }
kCGTabletEventPointButtons = 18;
{ Key associated with an integer encoding the tablet button state. Bit 0 is the first button, and a set bit represents a closed or pressed button. Up to 16 buttons are supported. }
kCGTabletEventPointPressure = 19;
{ Key associated with a double encoding the tablet pen pressure. 0 represents no pressure, and 1.0 represents maximum pressure. }
kCGTabletEventTiltX = 20;
kCGTabletEventTiltY = 21;
{ Key associated with a double encoding the tablet pen tilt. 0 represents no tilt, and 1.0 represents maximum tilt. }
kCGTabletEventRotation = 22;
{ Key associated with a double encoding the tablet pen rotation. }
kCGTabletEventTangentialPressure = 23;
{ Key associated with a double encoding the tangential pressure on the device. 0 represents no pressure, and 1.0 represents maximum pressure. }
kCGTabletEventDeviceID = 24;
{ Key associated with an integer encoding the system-assigned unique device ID. }
kCGTabletEventVendor1 = 25;
kCGTabletEventVendor2 = 26;
kCGTabletEventVendor3 = 27;
{ Key associated with an integer containing vendor-specified values.}
{
* Additional keys and values found in tablet proximity events,
* and in mouse events containing embedded tablet proximity data:
}
kCGTabletProximityEventVendorID = 28;
{ Key associated with an integer encoding the vendor-defined ID, typically the USB vendor ID. }
kCGTabletProximityEventTabletID = 29;
{ Key associated with an integer encoding the vendor-defined tablet ID, typically the USB product ID. }
kCGTabletProximityEventPointerID = 30;
{ Key associated with an integer encoding the vendor-defined ID of the pointing device. }
kCGTabletProximityEventDeviceID = 31;
{ Key associated with an integer encoding the system-assigned device ID. }
kCGTabletProximityEventSystemTabletID = 32;
{ Key associated with an integer encoding the system-assigned unique tablet ID. }
kCGTabletProximityEventVendorPointerType = 33;
{ Key associated with an integer encoding the vendor-assigned pointer type. }
kCGTabletProximityEventVendorPointerSerialNumber = 34;
{ Key associated with an integer encoding the vendor-defined pointer serial number. }
kCGTabletProximityEventVendorUniqueID = 35;
{ Key associated with an integer encoding the vendor-defined unique ID. }
kCGTabletProximityEventCapabilityMask = 36;
{ Key associated with an integer encoding the device capabilities mask. }
kCGTabletProximityEventPointerType = 37;
{ Key associated with an integer encoding the pointer type. }
kCGTabletProximityEventEnterProximity = 38;
{ Key associated with an integer, non-zero when pen is in proximity to the tablet, and zero when leaving the tablet. }
kCGEventTargetProcessSerialNumber = 39;
{ Key for the event target process serial number as a 64 bit longword. }
kCGEventTargetUnixProcessID = 40;
{ Key for the event target Unix process ID }
kCGEventSourceUnixProcessID = 41;
{ Key for the event source, or poster's Unix process ID }
kCGEventSourceUserData = 42;
{ Key for the event source user-supplied data, up to 64 bits }
kCGEventSourceUserID = 43;
{ Key for the event source Unix effective UID }
kCGEventSourceGroupID = 44;
{ Key for the event source Unix effective GID }
kCGEventSourceStateID = 45;
{ Key for the event source state ID used to create this event }
type
CGEventField = UInt32;
{ Values used with the kCGMouseEventSubtype }
type
_CGEventMouseSubtype = SInt32;
const
kCGEventMouseSubtypeDefault = 0;
kCGEventMouseSubtypeTabletPoint = 1;
kCGEventMouseSubtypeTabletProximity = 2;
type
CGEventMouseSubtype = UInt32;
{
* Event Taps
*
* Taps may be placed at the point where HIDSystem events enter
* the server, at the point where HIDSystem and remote control
* events enter a session, at the point where events have been
* annotated to flow to a specific application, or at the point
* where events are delivered to the application. Taps may be
* inserted at a specified point at the head of pre-existing filters,
* or appended after any pre-existing filters.
*
* Taps may be passive event listeners, or active filters.
* An active filter may pass an event through unmodified, modify
* an event, or discard an event. When a tap is registered, it
* identifies the set of events to be observed with a mask, and
* indicates if it is a passive or active event filter. Multiple
* event type bitmasks may be ORed together.
*
* Taps may only be placed at kCGHIDEventTap by a process running
* as the root user. NULL is returned for other users.
*
* Taps placed at kCGHIDEventTap, kCGSessionEventTap,
* kCGAnnotatedSessionEventTap, or on a specific process may
* only receive key up and down events if access for assistive
* devices is enabled (Preferences Universal Access panel,
* Keyboard view). If the tap is not permitted to monitor these
* when the tap is being created, then the appropriate bits
* in the mask are cleared. If that results in an empty mask,
* then NULL is returned.
*
* The CGEventTapProxy is an opaque reference to state within
* the client application associated with the tap. The tap
* function may pass this reference to other functions, such as
* the event-posting routines.
*
}
{ Possible tapping points for events }
type
_CGEventTapLocation = SInt32;
const
kCGHIDEventTap = 0;
kCGSessionEventTap = 1;
kCGAnnotatedSessionEventTap = 2;
type
CGEventTapLocation = UInt32;
type
_CGEventTapPlacement = SInt32;
const
kCGHeadInsertEventTap = 0;
kCGTailAppendEventTap = 1;
type
CGEventTapPlacement = UInt32;
type
_CGEventTapOptions = SInt32;
const
kCGEventTapOptionListenOnly = $00000001;
type
CGEventTapOptions = UInt32;
type
CGEventMask = UInt64;
{
#define CGEventMaskBit(eventType) ((CGEventMask)1 << (eventType))
}
type
CGEventTapProxy = ^SInt32; { an opaque 32-bit type }
{
* The callback is passed a proxy for the tap, the event type, the incoming event,
* and the refcon the callback was registered with.
* The function should return the (possibly modified) passed in event,
* a newly constructed event, or NULL if the event is to be deleted.
*
* The CGEventRef passed into the callback is retained by the calling code, and is
* released after the callback returns and the data is passed back to the event
* system. If a different event is returned by the callback function, then that
* event will be released by the calling code along with the original event, after
* the event data has been passed back to the event system.
}
type
CGEventTapCallBack = function( proxy: CGEventTapProxy; typ: CGEventType; event: CGEventRef; refcon: UnivPtr ): CGEventRef;
{
* When an event tap is installed or released, a notification
* is posted via the notify_post() API. See notify (3) and
* notify.h for details.
}
const
kCGNotifyEventTapAdded = 'com.apple.coregraphics.eventTapAdded';
const
kCGNotifyEventTapRemoved = 'com.apple.coregraphics.eventTapRemoved';
{
* Structure used to report information on event taps
}
type
CGEventTapInformationPtr = ^CGEventTapInformation;
CGEventTapInformation = record
eventTapID: UInt32;
tapPoint: CGEventTapLocation; { HID, session, annotated session }
options: CGEventTapOptions; { Listener, Filter }
eventsOfInterest: CGEventMask; { Mask of events being tapped }
tappingProcess: pid_t; { Process that is tapping events }
processBeingTapped: pid_t; { Zero if not a per-process tap }
enabled: CBool; { True if tap is enabled }
minUsecLatency: Float32; { Minimum latency in microseconds }
avgUsecLatency: Float32; { Average latency in microseconds }
maxUsecLatency: Float32; { Maximum latency in microseconds }
end;
{
* The CGEventSourceRef is an opaque representation of the source of an event.
*
* API is provided to obtain the CGEventSource from an event, and to create
* a new event with a CGEventSourceRef.
}
type
CGEventSourceRef = ^SInt32; { an opaque 32-bit type }
type
CGEventSourceStateID = UInt32;
const
kCGEventSourceStatePrivate = -1;
kCGEventSourceStateCombinedSessionState = 0;
kCGEventSourceStateHIDSystemState = 1;
type
CGEventSourceKeyboardType = UInt32;
const
kCGAnyInputEventType = $FFFFFFFF;
end.
|
unit DBDateTimePicker;
interface
uses
Winapi.Messages, System.SysUtils, System.Classes, Vcl.Controls, Vcl.ComCtrls,
Data.DB, Vcl.DBCtrls;
type
TDBDateTimePicker = class(TDateTimePicker)
private
{ Private declarations }
FDataLink: TFieldDataLink;
FReadOnly: Boolean;
function GetDataField: string;
function GetDataSource: TDataSource;
procedure SetDataField(const AValue: string);
procedure SetDataSource(const AValue: TDataSource);published
procedure DataChange(Sender: TObject);
procedure UpdateData(Sender: TObject);
function GetField: TField;
procedure SetDateTimeJumpMinMax(const AValue: TDateTime);
procedure SetReadOnly(const AValue: Boolean);
protected
{ Protected declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure WndProc(var Message: TMessage); override;
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure Change; override;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
public
{ Public declarations }
function DateIsNull: Boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property DataField: string read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
property ReadOnly : boolean read FReadOnly write SetReadOnly default False;
end;
procedure Register;
implementation
uses
System.Math;
const
NullDate = 0;
constructor TDBDateTimePicker.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle:=ControlStyle - [csReplicatable]; // El control no se permite en un DBCtrlGrid
FReadOnly:= False;
FDataLink:= TFieldDataLink.Create;
FDataLink.Control:= Self;
Self.DateTime:= NullDate;
FDataLink.OnDataChange:= DataChange;
FDataLink.OnUpdateData:= UpdateData;
end;
destructor TDBDateTimePicker.Destroy;
begin
FDataLink.OnDataChange:= nil;
FDataLink.OnUpdateData:= nil;
FreeAndNil(FDataLink);
inherited Destroy;
end;
procedure TDBDateTimePicker.SetReadOnly(const AValue: Boolean);
begin
if FReadOnly <> AValue then
begin
FReadOnly:= AValue;
Self.TabStop:= not AValue;
end;
end;
function TDBDateTimePicker.GetDataSource: TDataSource;
begin
Result:= FDataLink.DataSource;
end;
procedure TDBDateTimePicker.SetDataSource(const AValue: TDataSource);
begin
if FDataLink.DataSource<>AValue then
begin
FDataLink.DataSource:= AValue;
if Assigned(AValue) then AValue.FreeNotification(Self);
end;
end;
function TDBDateTimePicker.GetDataField: string;
begin
Result:= FDataLink.FieldName;
end;
procedure TDBDateTimePicker.SetDataField(const AValue: string);
begin
FDataLink.FieldName:= AValue;
end;
procedure TDBDateTimePicker.SetDateTimeJumpMinMax(const AValue: TDateTime);
var
TempMinDate: TDateTime;
TempMaxDate: TDateTime;
begin
TempMinDate:= Trunc(Self.MinDate);
TempMaxDate:= Self.MaxDate;
Self.MinDate:= NullDate;
Self.MaxDate:= StrToDate('31/12/9999');
try
Self.DateTime:= AValue;
finally
Self.MinDate:= TempMinDate;
Self.MaxDate:= TempMaxDate;
end;
end;
function TDBDateTimePicker.GetField: TField;
begin
Result:= FDataLink.Field;
end;
procedure TDBDateTimePicker.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and Assigned(FDataLink) and
(AComponent = Self.DataSource) then
Self.DataSource:= nil;
end;
procedure TDBDateTimePicker.DataChange(Sender: TObject);
begin
if Assigned(FDataLink.Field) and not FDataLink.Field.IsNull then
SetDateTimeJumpMinMax(FDataLink.Field.AsDateTime)
else
Self.DateTime:= NullDate;
end;
procedure TDBDateTimePicker.CMEnter(var Message: TCMEnter);
begin
inherited;
FDataLink.CanModify;
end;
procedure TDBDateTimePicker.Change;
begin
if FDataLink.Edit then
begin
FDataLink.Modified;
inherited Change;
end
else
FDataLink.Reset
end;
function TDBDateTimePicker.DateIsNull: Boolean;
begin
Result:= Self.DateTime = NullDate;
end;
procedure TDBDateTimePicker.UpdateData(Sender: TObject);
begin
if Assigned(FDataLink.Field) then
if DateIsNull then
FDataLink.Field.Clear
else
FDataLink.Field.AsDateTime:= Self.DateTime;
end;
procedure TDBDateTimePicker.CMExit(var Message: TCMExit);
begin
try
FDataLink.UpdateRecord;
except
SetFocus;
raise;
end;
inherited;
end;
procedure TDBDateTimePicker.WndProc(var Message: TMessage);
begin
if not (csDesigning in ComponentState) then
if FReadOnly OR (not FReadOnly and Assigned(FDatalink) and not FDataLink.Edit) then
if ((Message.Msg >= WM_MOUSEFIRST) and (Message.Msg <= WM_MOUSELAST))
or (Message.Msg = WM_KEYDOWN) or (Message.Msg = WM_KEYUP) then
Exit;
inherited WndProc(Message);
end;
procedure Register;
begin
RegisterComponents('Data Controls', [TDBDateTimePicker]);
end;
end.
|
{
* ImageIO - CGImageProperties.h
* Copyright (c) 2004 Apple Computer, Inc. All rights reserved.
*
}
{ Pascal Translation: Gale R Paeper, <gpaeper@empirenet.com>, 2006 }
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit CGImageProperties;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses CFBase;
{$ALIGN POWER}
{ Properties that, if returned by CGImageSourceCopyProperties or
* CGImageSourceCopyPropertiesAtIndex, contain a dictionary of file-format
* or metadata-format specific key-values. }
var kCGImagePropertyTIFFDictionary: CFStringRef; external name '_kCGImagePropertyTIFFDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGIFDictionary: CFStringRef; external name '_kCGImagePropertyGIFDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyJFIFDictionary: CFStringRef; external name '_kCGImagePropertyJFIFDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifDictionary: CFStringRef; external name '_kCGImagePropertyExifDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyPNGDictionary: CFStringRef; external name '_kCGImagePropertyPNGDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCDictionary: CFStringRef; external name '_kCGImagePropertyIPTCDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDictionary: CFStringRef; external name '_kCGImagePropertyGPSDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyRawDictionary: CFStringRef; external name '_kCGImagePropertyRawDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyCIFFDictionary: CFStringRef; external name '_kCGImagePropertyCIFFDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImageProperty8BIMDictionary: CFStringRef; external name '_kCGImageProperty8BIMDictionary'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{* Properties which may be returned by "CGImageSourceCopyProperties". The
** values apply to the container in general but not necessarily to any
** individual image that it contains. *}
{ The size of the image file in bytes, if known. If present, the value of
* this key is a CFNumberRef. }
var kCGImagePropertyFileSize: CFStringRef; external name '_kCGImagePropertyFileSize'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{* Properties which may be returned by "CGImageSourceCopyPropertiesAtIndex".
** The values apply to a single image of an image source file. *}
{ The number of pixels in the x- and y-dimensions. The value of these keys
* is a CFNumberRef. }
var kCGImagePropertyPixelHeight: CFStringRef; external name '_kCGImagePropertyPixelHeight'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyPixelWidth: CFStringRef; external name '_kCGImagePropertyPixelWidth'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ The DPI in the x- and y-dimensions, if known. If present, the value of
* these keys is a CFNumberRef. }
var kCGImagePropertyDPIHeight: CFStringRef; external name '_kCGImagePropertyDPIHeight'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyDPIWidth: CFStringRef; external name '_kCGImagePropertyDPIWidth'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ The number of bits in each color sample of each pixel. The value of this
* key is a CFNumberRef. }
var kCGImagePropertyDepth: CFStringRef; external name '_kCGImagePropertyDepth'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ The intended display orientation of the image. If present, the value
* of this key is a CFNumberRef with the same value as defined by the
* TIFF and Exif specifications. That is:
* 1 = 0th row is at the top, and 0th column is on the left.
* 2 = 0th row is at the top, and 0th column is on the right.
* 3 = 0th row is at the bottom, and 0th column is on the right.
* 4 = 0th row is at the bottom, and 0th column is on the left.
* 5 = 0th row is on the left, and 0th column is the top.
* 6 = 0th row is on the right, and 0th column is the top.
* 7 = 0th row is on the right, and 0th column is the bottom.
* 8 = 0th row is on the left, and 0th column is the bottom.
* If not present, a value of 1 is assumed. }
var kCGImagePropertyOrientation: CFStringRef; external name '_kCGImagePropertyOrientation'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ The value of this key is kCFBooleanTrue if the image contains floating-
* point pixel samples }
var kCGImagePropertyIsFloat: CFStringRef; external name '_kCGImagePropertyIsFloat'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ The value of this key is kCFBooleanTrue if the image contains indexed
* (a.k.a. paletted) pixel samples }
var kCGImagePropertyIsIndexed: CFStringRef; external name '_kCGImagePropertyIsIndexed'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ The value of this key is kCFBooleanTrue if the image contains an alpha
* (a.k.a. coverage) channel }
var kCGImagePropertyHasAlpha: CFStringRef; external name '_kCGImagePropertyHasAlpha'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ The color model of the image such as "RGB", "CMYK", "Gray", or "Lab".
* The value of this key is CFStringRef. }
var kCGImagePropertyColorModel: CFStringRef; external name '_kCGImagePropertyColorModel'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ The name of the optional ICC profile embedded in the image, if known.
* If present, the value of this key is a CFStringRef. }
var kCGImagePropertyProfileName: CFStringRef; external name '_kCGImagePropertyProfileName'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Possible values for kCGImagePropertyColorModel property }
var kCGImagePropertyColorModelRGB: CFStringRef; external name '_kCGImagePropertyColorModelRGB'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyColorModelGray: CFStringRef; external name '_kCGImagePropertyColorModelGray'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyColorModelCMYK: CFStringRef; external name '_kCGImagePropertyColorModelCMYK'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyColorModelLab: CFStringRef; external name '_kCGImagePropertyColorModelLab'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Possible keys for kCGImagePropertyTIFFDictionary }
var kCGImagePropertyTIFFCompression: CFStringRef; external name '_kCGImagePropertyTIFFCompression'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFPhotometricInterpretation: CFStringRef; external name '_kCGImagePropertyTIFFPhotometricInterpretation'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFDocumentName: CFStringRef; external name '_kCGImagePropertyTIFFDocumentName'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFImageDescription: CFStringRef; external name '_kCGImagePropertyTIFFImageDescription'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFMake: CFStringRef; external name '_kCGImagePropertyTIFFMake'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFModel: CFStringRef; external name '_kCGImagePropertyTIFFModel'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFOrientation: CFStringRef; external name '_kCGImagePropertyTIFFOrientation'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFXResolution: CFStringRef; external name '_kCGImagePropertyTIFFXResolution'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFYResolution: CFStringRef; external name '_kCGImagePropertyTIFFYResolution'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFResolutionUnit: CFStringRef; external name '_kCGImagePropertyTIFFResolutionUnit'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFSoftware: CFStringRef; external name '_kCGImagePropertyTIFFSoftware'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFTransferFunction: CFStringRef; external name '_kCGImagePropertyTIFFTransferFunction'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFDateTime: CFStringRef; external name '_kCGImagePropertyTIFFDateTime'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFArtist: CFStringRef; external name '_kCGImagePropertyTIFFArtist'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFHostComputer: CFStringRef; external name '_kCGImagePropertyTIFFHostComputer'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFCopyright: CFStringRef; external name '_kCGImagePropertyTIFFCopyright'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFWhitePoint: CFStringRef; external name '_kCGImagePropertyTIFFWhitePoint'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyTIFFPrimaryChromaticities: CFStringRef; external name '_kCGImagePropertyTIFFPrimaryChromaticities'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Possible keys for kCGImagePropertyJFIFDictionary }
var kCGImagePropertyJFIFVersion: CFStringRef; external name '_kCGImagePropertyJFIFVersion'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyJFIFXDensity: CFStringRef; external name '_kCGImagePropertyJFIFXDensity'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyJFIFYDensity: CFStringRef; external name '_kCGImagePropertyJFIFYDensity'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyJFIFDensityUnit: CFStringRef; external name '_kCGImagePropertyJFIFDensityUnit'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyJFIFIsProgressive: CFStringRef; external name '_kCGImagePropertyJFIFIsProgressive'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Possible keys for kCGImagePropertyExifDictionary }
var kCGImagePropertyExifExposureTime: CFStringRef; external name '_kCGImagePropertyExifExposureTime'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFNumber: CFStringRef; external name '_kCGImagePropertyExifFNumber'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifExposureProgram: CFStringRef; external name '_kCGImagePropertyExifExposureProgram'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSpectralSensitivity: CFStringRef; external name '_kCGImagePropertyExifSpectralSensitivity'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifISOSpeedRatings: CFStringRef; external name '_kCGImagePropertyExifISOSpeedRatings'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifOECF: CFStringRef; external name '_kCGImagePropertyExifOECF'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifVersion: CFStringRef; external name '_kCGImagePropertyExifVersion'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifDateTimeOriginal: CFStringRef; external name '_kCGImagePropertyExifDateTimeOriginal'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifDateTimeDigitized: CFStringRef; external name '_kCGImagePropertyExifDateTimeDigitized'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifComponentsConfiguration: CFStringRef; external name '_kCGImagePropertyExifComponentsConfiguration'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifCompressedBitsPerPixel: CFStringRef; external name '_kCGImagePropertyExifCompressedBitsPerPixel'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifShutterSpeedValue: CFStringRef; external name '_kCGImagePropertyExifShutterSpeedValue'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifApertureValue: CFStringRef; external name '_kCGImagePropertyExifApertureValue'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifBrightnessValue: CFStringRef; external name '_kCGImagePropertyExifBrightnessValue'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifExposureBiasValue: CFStringRef; external name '_kCGImagePropertyExifExposureBiasValue'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifMaxApertureValue: CFStringRef; external name '_kCGImagePropertyExifMaxApertureValue'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSubjectDistance: CFStringRef; external name '_kCGImagePropertyExifSubjectDistance'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifMeteringMode: CFStringRef; external name '_kCGImagePropertyExifMeteringMode'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifLightSource: CFStringRef; external name '_kCGImagePropertyExifLightSource'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFlash: CFStringRef; external name '_kCGImagePropertyExifFlash'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFocalLength: CFStringRef; external name '_kCGImagePropertyExifFocalLength'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSubjectArea: CFStringRef; external name '_kCGImagePropertyExifSubjectArea'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifMakerNote: CFStringRef; external name '_kCGImagePropertyExifMakerNote'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifUserComment: CFStringRef; external name '_kCGImagePropertyExifUserComment'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSubsecTime: CFStringRef; external name '_kCGImagePropertyExifSubsecTime'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSubsecTimeOrginal: CFStringRef; external name '_kCGImagePropertyExifSubsecTimeOrginal'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSubsecTimeDigitized: CFStringRef; external name '_kCGImagePropertyExifSubsecTimeDigitized'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFlashPixVersion: CFStringRef; external name '_kCGImagePropertyExifFlashPixVersion'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifColorSpace: CFStringRef; external name '_kCGImagePropertyExifColorSpace'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifPixelXDimension: CFStringRef; external name '_kCGImagePropertyExifPixelXDimension'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifPixelYDimension: CFStringRef; external name '_kCGImagePropertyExifPixelYDimension'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifRelatedSoundFile: CFStringRef; external name '_kCGImagePropertyExifRelatedSoundFile'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFlashEnergy: CFStringRef; external name '_kCGImagePropertyExifFlashEnergy'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSpatialFrequencyResponse: CFStringRef; external name '_kCGImagePropertyExifSpatialFrequencyResponse'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFocalPlaneXResolution: CFStringRef; external name '_kCGImagePropertyExifFocalPlaneXResolution'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFocalPlaneYResolution: CFStringRef; external name '_kCGImagePropertyExifFocalPlaneYResolution'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFocalPlaneResolutionUnit: CFStringRef; external name '_kCGImagePropertyExifFocalPlaneResolutionUnit'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSubjectLocation: CFStringRef; external name '_kCGImagePropertyExifSubjectLocation'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifExposureIndex: CFStringRef; external name '_kCGImagePropertyExifExposureIndex'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSensingMethod: CFStringRef; external name '_kCGImagePropertyExifSensingMethod'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFileSource: CFStringRef; external name '_kCGImagePropertyExifFileSource'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSceneType: CFStringRef; external name '_kCGImagePropertyExifSceneType'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifCFAPattern: CFStringRef; external name '_kCGImagePropertyExifCFAPattern'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifCustomRendered: CFStringRef; external name '_kCGImagePropertyExifCustomRendered'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifExposureMode: CFStringRef; external name '_kCGImagePropertyExifExposureMode'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifWhiteBalance: CFStringRef; external name '_kCGImagePropertyExifWhiteBalance'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifDigitalZoomRatio: CFStringRef; external name '_kCGImagePropertyExifDigitalZoomRatio'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifFocalLenIn35mmFilm: CFStringRef; external name '_kCGImagePropertyExifFocalLenIn35mmFilm'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSceneCaptureType: CFStringRef; external name '_kCGImagePropertyExifSceneCaptureType'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifGainControl: CFStringRef; external name '_kCGImagePropertyExifGainControl'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifContrast: CFStringRef; external name '_kCGImagePropertyExifContrast'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSaturation: CFStringRef; external name '_kCGImagePropertyExifSaturation'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSharpness: CFStringRef; external name '_kCGImagePropertyExifSharpness'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifDeviceSettingDescription: CFStringRef; external name '_kCGImagePropertyExifDeviceSettingDescription'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifSubjectDistRange: CFStringRef; external name '_kCGImagePropertyExifSubjectDistRange'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifImageUniqueID: CFStringRef; external name '_kCGImagePropertyExifImageUniqueID'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyExifGamma: CFStringRef; external name '_kCGImagePropertyExifGamma'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Possible keys for kCGImagePropertyGIFDictionary }
var kCGImagePropertyGIFLoopCount: CFStringRef; external name '_kCGImagePropertyGIFLoopCount'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGIFDelayTime: CFStringRef; external name '_kCGImagePropertyGIFDelayTime'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGIFImageColorMap: CFStringRef; external name '_kCGImagePropertyGIFImageColorMap'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGIFHasGlobalColorMap: CFStringRef; external name '_kCGImagePropertyGIFHasGlobalColorMap'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Possible keys for kCGImagePropertyPNGDictionary }
var kCGImagePropertyPNGGamma: CFStringRef; external name '_kCGImagePropertyPNGGamma'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyPNGInterlaceType: CFStringRef; external name '_kCGImagePropertyPNGInterlaceType'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyPNGXPixelsPerMeter: CFStringRef; external name '_kCGImagePropertyPNGXPixelsPerMeter'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyPNGYPixelsPerMeter: CFStringRef; external name '_kCGImagePropertyPNGYPixelsPerMeter'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyPNGsRGBIntent: CFStringRef; external name '_kCGImagePropertyPNGsRGBIntent'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyPNGChromaticities: CFStringRef; external name '_kCGImagePropertyPNGChromaticities'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Possible keys for kCGImagePropertyGPSDictionary }
var kCGImagePropertyGPSVersion: CFStringRef; external name '_kCGImagePropertyGPSVersion'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSLatitudeRef: CFStringRef; external name '_kCGImagePropertyGPSLatitudeRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSLatitude: CFStringRef; external name '_kCGImagePropertyGPSLatitude'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSLongitudeRef: CFStringRef; external name '_kCGImagePropertyGPSLongitudeRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSLongitude: CFStringRef; external name '_kCGImagePropertyGPSLongitude'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSAltitudeRef: CFStringRef; external name '_kCGImagePropertyGPSAltitudeRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSAltitude: CFStringRef; external name '_kCGImagePropertyGPSAltitude'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSTimeStamp: CFStringRef; external name '_kCGImagePropertyGPSTimeStamp'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSSatellites: CFStringRef; external name '_kCGImagePropertyGPSSatellites'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSStatus: CFStringRef; external name '_kCGImagePropertyGPSStatus'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSMeasureMode: CFStringRef; external name '_kCGImagePropertyGPSMeasureMode'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDOP: CFStringRef; external name '_kCGImagePropertyGPSDOP'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSSpeedRef: CFStringRef; external name '_kCGImagePropertyGPSSpeedRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSSpeed: CFStringRef; external name '_kCGImagePropertyGPSSpeed'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSTrackRef: CFStringRef; external name '_kCGImagePropertyGPSTrackRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSTrack: CFStringRef; external name '_kCGImagePropertyGPSTrack'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSImgDirectionRef: CFStringRef; external name '_kCGImagePropertyGPSImgDirectionRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSImgDirection: CFStringRef; external name '_kCGImagePropertyGPSImgDirection'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSMapDatum: CFStringRef; external name '_kCGImagePropertyGPSMapDatum'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDestLatitudeRef: CFStringRef; external name '_kCGImagePropertyGPSDestLatitudeRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDestLatitude: CFStringRef; external name '_kCGImagePropertyGPSDestLatitude'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDestLongitudeRef: CFStringRef; external name '_kCGImagePropertyGPSDestLongitudeRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDestLongitude: CFStringRef; external name '_kCGImagePropertyGPSDestLongitude'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDestBearingRef: CFStringRef; external name '_kCGImagePropertyGPSDestBearingRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDestBearing: CFStringRef; external name '_kCGImagePropertyGPSDestBearing'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDestDistanceRef: CFStringRef; external name '_kCGImagePropertyGPSDestDistanceRef'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDestDistance: CFStringRef; external name '_kCGImagePropertyGPSDestDistance'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSProcessingMethod: CFStringRef; external name '_kCGImagePropertyGPSProcessingMethod'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSAreaInformation: CFStringRef; external name '_kCGImagePropertyGPSAreaInformation'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDateStamp: CFStringRef; external name '_kCGImagePropertyGPSDateStamp'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyGPSDifferental: CFStringRef; external name '_kCGImagePropertyGPSDifferental'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Possible keys for kCGImagePropertyIPTCDictionary }
var kCGImagePropertyIPTCObjectTypeReference: CFStringRef; external name '_kCGImagePropertyIPTCObjectTypeReference'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCObjectAttributeReference: CFStringRef; external name '_kCGImagePropertyIPTCObjectAttributeReference'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCObjectName: CFStringRef; external name '_kCGImagePropertyIPTCObjectName'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCEditStatus: CFStringRef; external name '_kCGImagePropertyIPTCEditStatus'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCEditorialUpdate: CFStringRef; external name '_kCGImagePropertyIPTCEditorialUpdate'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCUrgency: CFStringRef; external name '_kCGImagePropertyIPTCUrgency'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCSubjectReference: CFStringRef; external name '_kCGImagePropertyIPTCSubjectReference'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCCategory: CFStringRef; external name '_kCGImagePropertyIPTCCategory'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCSupplementalCategory: CFStringRef; external name '_kCGImagePropertyIPTCSupplementalCategory'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCFixtureIdentifier: CFStringRef; external name '_kCGImagePropertyIPTCFixtureIdentifier'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCKeywords: CFStringRef; external name '_kCGImagePropertyIPTCKeywords'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCContentLocationCode: CFStringRef; external name '_kCGImagePropertyIPTCContentLocationCode'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCContentLocationName: CFStringRef; external name '_kCGImagePropertyIPTCContentLocationName'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCReleaseDate: CFStringRef; external name '_kCGImagePropertyIPTCReleaseDate'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCReleaseTime: CFStringRef; external name '_kCGImagePropertyIPTCReleaseTime'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCExpirationDate: CFStringRef; external name '_kCGImagePropertyIPTCExpirationDate'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCExpirationTime: CFStringRef; external name '_kCGImagePropertyIPTCExpirationTime'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCSpecialInstructions: CFStringRef; external name '_kCGImagePropertyIPTCSpecialInstructions'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCActionAdvised: CFStringRef; external name '_kCGImagePropertyIPTCActionAdvised'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCReferenceService: CFStringRef; external name '_kCGImagePropertyIPTCReferenceService'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCReferenceDate: CFStringRef; external name '_kCGImagePropertyIPTCReferenceDate'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCReferenceNumber: CFStringRef; external name '_kCGImagePropertyIPTCReferenceNumber'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCDateCreated: CFStringRef; external name '_kCGImagePropertyIPTCDateCreated'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCTimeCreated: CFStringRef; external name '_kCGImagePropertyIPTCTimeCreated'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCDigitalCreationDate: CFStringRef; external name '_kCGImagePropertyIPTCDigitalCreationDate'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCDigitalCreationTime: CFStringRef; external name '_kCGImagePropertyIPTCDigitalCreationTime'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCOriginatingProgram: CFStringRef; external name '_kCGImagePropertyIPTCOriginatingProgram'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCProgramVersion: CFStringRef; external name '_kCGImagePropertyIPTCProgramVersion'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCObjectCycle: CFStringRef; external name '_kCGImagePropertyIPTCObjectCycle'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCByline: CFStringRef; external name '_kCGImagePropertyIPTCByline'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCBylineTitle: CFStringRef; external name '_kCGImagePropertyIPTCBylineTitle'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCCity: CFStringRef; external name '_kCGImagePropertyIPTCCity'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCSubLocation: CFStringRef; external name '_kCGImagePropertyIPTCSubLocation'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCProvinceState: CFStringRef; external name '_kCGImagePropertyIPTCProvinceState'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCCountryPrimaryLocationCode: CFStringRef; external name '_kCGImagePropertyIPTCCountryPrimaryLocationCode'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCCountryPrimaryLocationName: CFStringRef; external name '_kCGImagePropertyIPTCCountryPrimaryLocationName'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCOriginalTransmissionReference: CFStringRef; external name '_kCGImagePropertyIPTCOriginalTransmissionReference'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCHeadline: CFStringRef; external name '_kCGImagePropertyIPTCHeadline'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCCredit: CFStringRef; external name '_kCGImagePropertyIPTCCredit'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCSource: CFStringRef; external name '_kCGImagePropertyIPTCSource'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCCopyrightNotice: CFStringRef; external name '_kCGImagePropertyIPTCCopyrightNotice'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCContact: CFStringRef; external name '_kCGImagePropertyIPTCContact'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCCaptionAbstract: CFStringRef; external name '_kCGImagePropertyIPTCCaptionAbstract'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCWriterEditor: CFStringRef; external name '_kCGImagePropertyIPTCWriterEditor'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCImageType: CFStringRef; external name '_kCGImagePropertyIPTCImageType'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCImageOrientation: CFStringRef; external name '_kCGImagePropertyIPTCImageOrientation'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCLanguageIdentifier: CFStringRef; external name '_kCGImagePropertyIPTCLanguageIdentifier'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCGImagePropertyIPTCStarRating: CFStringRef; external name '_kCGImagePropertyIPTCStarRating'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
end.
|
unit UFormProgress;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TFormProgress = class(TForm)
labCaption: TLabel;
ProgressBar1: TProgressBar;
btnCancel: TButton;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormShow(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
FFinished: boolean;
public
{ Public declarations }
function Progress(const APos, APosMax: Int64): boolean;
end;
var
FormProgress: TFormProgress;
implementation
{$R *.dfm}
function TFormProgress.Progress(const APos, APosMax: Int64): boolean;
var
APercent: Int64;
begin
Assert(APos >= 0, 'Progress position is negative');
Assert(APosMax >= 0, 'Progress maximal position is negative');
Assert(APos <= APosMax, 'Progress position is out of range');
if APosMax = 0 then
APercent:= 0
else
APercent:= APos * 100 div APosMax;
ProgressBar1.Position:= APercent;
labCaption.Caption:= Format('Searching: %d%% (Offset %d of %d)', [APercent, APos, APosMax]);
Application.ProcessMessages;
Result:= not FFinished;
end;
procedure TFormProgress.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
//
end;
procedure TFormProgress.FormShow(Sender: TObject);
begin
FFinished:= False;
end;
procedure TFormProgress.btnCancelClick(Sender: TObject);
begin
FFinished:= True;
end;
end.
|
unit IngGridIB;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, ComCtrls, ExtCtrls, DBActns, ActnList, Menus, ImgList, ToolWin,
Placemnt, ColPos, StdActns, Wwdbigrd, Wwdbgrid, Db, IbCustomDataSet;
type
TFIngGrid = class(TForm)
MainMenu1: TMainMenu;
PopupMenu1: TPopupMenu;
ImageList1: TImageList;
ActionList1: TActionList;
Ventana1: TMenuItem;
Salir1: TMenuItem;
Cancel1: TDataSetCancel;
Delete1: TDataSetDelete;
Edit1: TDataSetEdit;
First1: TDataSetFirst;
Insert1: TDataSetInsert;
Last1: TDataSetLast;
Next1: TDataSetNext;
Post1: TDataSetPost;
Prior1: TDataSetPrior;
Refresh1: TDataSetRefresh;
DataSource1: TDataSource;
Panel1: TPanel;
StatusBar1: TStatusBar;
Editar1: TMenuItem;
Primero1: TMenuItem;
Anterior1: TMenuItem;
Siguiente1: TMenuItem;
Ultimo1: TMenuItem;
N1: TMenuItem;
Agregar1: TMenuItem;
Borrar1: TMenuItem;
Grabar1: TMenuItem;
Anular3: TMenuItem;
Ayuda1: TMenuItem;
Informacion1: TMenuItem;
Salir: TAction;
ControlBar1: TControlBar;
ToolBar1: TToolBar;
ToolButton7: TToolButton;
ToolButton11: TToolButton;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton10: TToolButton;
ToolButton5: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
ToolButton6: TToolButton;
FormPlacement1: TFormPlacement;
Buscar: TAction;
Editar2: TMenuItem;
EditCopy1: TEditCopy;
EditCut1: TEditCut;
EditDelete1: TEditDelete;
EditPaste1: TEditPaste;
EditUndo1: TEditUndo;
Copiar1: TMenuItem;
Cortar1: TMenuItem;
Pegar1: TMenuItem;
N2: TMenuItem;
Eliminar1: TMenuItem;
Deshacer1: TMenuItem;
N3: TMenuItem;
BuscarRegistro1: TMenuItem;
Grilla: TwwDBGrid;
procedure Salir1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SalirExecute(Sender: TObject);
procedure DataSource1UpdateData(Sender: TObject);
procedure BuscarExecute(Sender: TObject);
procedure GrillaTitleButtonClick(Sender: TObject; AFieldName: String);
procedure GrillaCalcTitleImage(Sender: TObject; Field: TField;
var TitleImageAttributes: TwwTitleImageAttributes);
private
{ Private declarations }
FVieProc: TNotifyEvent;
FVieName: string;
FAsc: boolean;
FNoCerrar: boolean;
procedure OnNuevoRegistro( DataSet: TDataSet );
procedure Reordenar( Campo: string );
public
{ Public declarations }
procedure EnHint( Sender: TObject );
end;
var
FIngGrid: TFIngGrid;
implementation
uses BusValCds;
{$R *.DFM}
procedure TFIngGrid.Salir1Click(Sender: TObject);
begin
Close;
end;
procedure TFIngGrid.FormCreate(Sender: TObject);
begin
FAsc := true;
FVieProc := Application.OnHint;
Application.OnHint := EnHint;
if ( Assigned( DataSource1.DataSet )) and not (( DataSource1.DataSet ).Active ) then
begin
( DataSource1.DataSet ).OnNewRecord := OnNuevoRegistro;
( DataSource1.DataSet ).Open;
end
else
FNoCerrar := true;
end;
procedure TFIngGrid.FormDestroy(Sender: TObject);
begin
Application.OnHint := FVieProc;
if not FNoCerrar then
begin
( DataSource1.DataSet ).OnNewRecord := nil;
( DataSource1.DataSet ).Close;
end;
end;
procedure TFIngGrid.EnHint(Sender: TObject);
begin
StatusBar1.SimpleText := Application.Hint;
end;
procedure TFIngGrid.SalirExecute(Sender: TObject);
begin
close;
end;
procedure TFIngGrid.DataSource1UpdateData(Sender: TObject);
begin
// tomar valores de campos para ser insertados en nuevo registro
// como ultimo valor grabado.
end;
procedure TFIngGrid.OnNuevoRegistro(DataSet: TDataSet);
begin
// asignar valores de inicio al nuevo registro
end;
procedure TFIngGrid.BuscarExecute(Sender: TObject);
begin
BusValDlgCds := TBusValDlgCds.create( self );
BusValDlgCds.DataSet := TDataSet( DataSource1.DataSet );
BusValDlgCds.Select( Grilla.SelectedField.FieldName );
BusValDlgCds.ShowModal;
BusValDlgCds.free;
end;
procedure TFIngGrid.Reordenar( Campo: string );
var
FCommand: string;
FPos: integer;
begin
if Campo <> '' then
with TIBDataSet( DataSource1.DataSet ) do
try
if ( Campo = FVieName ) then
FAsc := not FAsc
else
begin
FVieName := Campo;
FAsc := true;
end;
DisableControls;
Close;
Campo := 'ORDER BY ' + Campo;
if not FAsc then
Campo := Campo + ' DESC';
FPos := Pos( 'ORDER BY ', UpperCase( SelectSQL.Text ));
if FPos > 0 then
SelectSQL.Text := Copy( SelectSQL.Text, 1, FPos-1 ) + Campo
else
SelectSQL.Text := SelectSQL.Text + Campo;
Open;
finally
EnableControls;
end;
end;
procedure TFIngGrid.GrillaTitleButtonClick(Sender: TObject;
AFieldName: String);
begin
Reordenar( AFieldName );
end;
procedure TFIngGrid.GrillaCalcTitleImage(Sender: TObject; Field: TField;
var TitleImageAttributes: TwwTitleImageAttributes);
begin
if Field.FieldName = FVieName then
if FAsc then
TitleImageAttributes.imageIndex:= 17
else
TitleImageAttributes.imageIndex:= 18
else
TitleImageAttributes.imageIndex:= -1;
end;
end.
|
unit UPicasaDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.TMSCloudBase, FMX.TMSCloudPicasa,
FMX.Layouts, FMX.ListBox, FMX.Objects, FMX.TMSCloudImage, FMX.TMSCloudBaseFMX,
FMX.TMSCloudCustomGoogle, FMX.TMSCloudGoogleFMX, FMX.TMSCloudCustomPicasa, IOUtils;
type
TForm82 = class(TForm)
ToolBar1: TToolBar;
Button1: TButton;
Button2: TButton;
TMSFMXCloudPicasa1: TTMSFMXCloudPicasa;
Button3: TButton;
lvAlbums: TListBox;
lvPhotos: TListBox;
TMSFMXCloudImage1: TTMSFMXCloudImage;
Label1: TLabel;
Label2: TLabel;
Line1: TLine;
Label3: TLabel;
Label4: TLabel;
lblDescription: TLabel;
Label5: TLabel;
lblTags: TLabel;
lblLocation: TLabel;
Label7: TLabel;
TMSFMXCloudImage2: TTMSFMXCloudImage;
Label8: TLabel;
lblAuthor: TLabel;
lbComments: TListBox;
Label6: TLabel;
SpeedButton8: TSpeedButton;
Image8: TImage;
SpeedButton3: TSpeedButton;
Image3: TImage;
Rectangle1: TRectangle;
procedure Button1Click(Sender: TObject);
procedure TMSFMXCloudPicasa1ReceivedAccessToken(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure lvAlbumsChange(Sender: TObject);
procedure lvPhotosChange(Sender: TObject);
procedure lbCommentsChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SpeedButton8Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
connected: boolean;
PageIndex: integer;
procedure ToggleControls;
procedure GetAlbums;
procedure GetPhotos;
procedure FillPhotos(Photos: TPicasaPhotos);
procedure FillComments(Photo: TPicasaPhoto);
procedure DoSearch;
end;
var
Form82: TForm82;
implementation
{$R *.fmx}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// GAppkey = 'xxxxxxxxx';
// GAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm82.Button1Click(Sender: TObject);
var
acc: boolean;
begin
TMSFMXCloudPicasa1.App.Key := GAppkey;
TMSFMXCloudPicasa1.App.Secret := GAppSecret;
if TMSFMXCloudPicasa1.App.Key <> '' then
begin
TMSFMXCloudPicasa1.PersistTokens.Key := TPath.GetDocumentsPath + '/picasa.ini';
TMSFMXCloudPicasa1.PersistTokens.Section := 'tokens';
TMSFMXCloudPicasa1.LoadTokens;
acc := TMSFMXCloudPicasa1.TestTokens;
if not acc then
begin
TMSFMXCloudPicasa1.RefreshAccess;
TMSFMXCloudPicasa1.DoAuth;
end
else
begin
connected := true;
ToggleControls;
end;
end
else
ShowMessage('Please provide a valid application ID for the client component');
end;
procedure TForm82.Button2Click(Sender: TObject);
begin
TMSFMXCloudPicasa1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm82.Button3Click(Sender: TObject);
begin
GetAlbums;
end;
procedure TForm82.DoSearch;
begin
end;
procedure TForm82.FillComments(Photo: TPicasaPhoto);
var
I: integer;
begin
lbComments.Clear;
TMSFMXCloudPicasa1.GetComments(Photo);
lbComments.BeginUpdate;
if Photo.Comments.Count > 0 then
begin
for I := 0 to Photo.Comments.Count - 1 do
lbComments.Items.AddObject(Photo.Comments[i].Author.FullName, Photo.Comments[i])
end;
lbComments.EndUpdate;
end;
procedure TForm82.FillPhotos(Photos: TPicasaPhotos);
var
I: integer;
begin
lvPhotos.Items.Clear;
TMSFMXCloudImage1.URL := '';
lvPhotos.BeginUpdate;
for I := 0 to Photos.Count - 1 do
lvPhotos.Items.AddObject(Photos[I].FileName, Photos[I]);
lvPhotos.EndUpdate;
end;
procedure TForm82.FormCreate(Sender: TObject);
begin
{$IFDEF IOS}
TFile.Copy(ExtractFilePath(Paramstr(0)) + 'sample.jpg', TPath.GetDocumentsPath + '/sample.jpg', True);
{$ENDIF}
connected := False;
ToggleControls;
end;
procedure TForm82.GetAlbums;
var
I: Integer;
begin
TMSFMXCloudPicasa1.Albums.Clear;
TMSFMXCloudPicasa1.GetAlbums;
lvAlbums.BeginUpdate;
lvAlbums.Items.Clear;
for I := 0 to TMSFMXCloudPicasa1.Albums.Count - 1 do
lvAlbums.Items.AddObject(TMSFMXCloudPicasa1.Albums[i].Title, TMSFMXCloudPicasa1.Albums[i]);
lvAlbums.EndUpdate;
lvAlbums.ItemIndex := 0;
GetPhotos;
end;
procedure TForm82.GetPhotos;
begin
if lvAlbums.ItemIndex >= 0 then
begin
TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].Photos.Clear;
TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].GetPhotos;
FillPhotos(TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex].Photos);
end;
end;
procedure TForm82.lbCommentsChange(Sender: TObject);
begin
if Assigned(lbComments.Selected) then
ShowMessage(TPicasaComment(lbComments.Selected.Data).Text);
end;
procedure TForm82.lvAlbumsChange(Sender: TObject);
begin
if Assigned(lvAlbums.Selected) then
GetPhotos;
end;
procedure TForm82.lvPhotosChange(Sender: TObject);
var
pic: TPicasaPhoto;
begin
if Assigned(lvPhotos.Selected.Data) then
begin
pic := TPicasaPhoto(lvPhotos.Selected.Data);
lblDescription.Text := pic.Summary;
lblTags.Text := pic.Tags.CommaText;
lblLocation.Text := FloatToStr(pic.Latitude) + ' ' + FloatToStr(pic.Longitude);
TMSFMXCloudImage1.URL := '';
TMSFMXCloudImage2.URL := '';
TMSFMXCloudImage1.URL := pic.ImageURL;
TMSFMXCloudImage2.URL := pic.ThumbnailURL;
lblAuthor.Text := 'Author: ' + pic.Author.NickName;
FillComments(pic);
end;
end;
procedure TForm82.SpeedButton3Click(Sender: TObject);
begin
if Assigned(lvAlbums.Selected) then
begin
TMSFMXCloudPicasa1.UploadPhoto(TMSFMXCloudPicasa1.Albums[lvAlbums.ItemIndex],
TPath.GetDocumentsPath + '/sample.jpg', 'test', 'tags');
ShowMessage('Sample Picture has been uploaded');
GetAlbums;
end;
end;
procedure TForm82.SpeedButton8Click(Sender: TObject);
var
ph: TPicasaPhoto;
begin
if Assigned(lvPhotos.Selected) then
begin
ph := TPicasaPhoto(lvPhotos.Selected.Data);
TMSFMXCloudPicasa1.DownloadPhoto(TPath.GetDocumentsPath + '/'+ph.FileName, ph);
ShowMessage('Picture ' + ph.FileName + ' has been downloaded' );
end;
end;
procedure TForm82.TMSFMXCloudPicasa1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudPicasa1.SaveTokens;
Connected := true;
ToggleControls;
end;
procedure TForm82.ToggleControls;
begin
SpeedButton8.Enabled := connected;
SpeedButton3.Enabled := Connected;
Button1.Enabled := not connected;
Button2.Enabled := connected;
Button3.Enabled := connected;
lvPhotos.Enabled := connected;
lvAlbums.Enabled := connected;
lbComments.Enabled := connected;
end;
end.
|
unit RemoveDestinationFromOptimizationResponseUnit;
interface
uses
REST.Json.Types,
GenericParametersUnit;
type
TRemoveDestinationFromOptimizationResponse = class(TGenericParameters)
private
[JSONName('deleted')]
FDeleted: boolean;
[JSONName('route_destination_id')]
FRouteDestinationId: integer;
public
property Deleted: boolean read FDeleted write FDeleted;
property RouteDestinationId: integer read FRouteDestinationId write FRouteDestinationId;
end;
implementation
end.
|
unit RemoveLocationsUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TRemoveLocations = class(TBaseExample)
public
procedure Execute(AddressIds: TArray<integer>);
end;
implementation
procedure TRemoveLocations.Execute(AddressIds: TArray<integer>);
var
ErrorString: String;
Removed: boolean;
begin
Removed := Route4MeManager.AddressBookContact.Remove(AddressIds, ErrorString);
WriteLn('');
if (Removed) then
WriteLn(Format('RemoveLocations executed successfully, %d contacts deleted',
[Length(AddressIds)]))
else
WriteLn(Format('RemoveLocations error: "%s"', [ErrorString]));
end;
end.
|
// @davidberneda
// 2017
unit TeePEG;
{
"Parsing Expression Grammars" (PEG)
Implementation for: Mr. Bryan Ford baford@mit.edu
http://bford.info/pub/lang/peg.pdf
}
interface
uses
Classes, TeePEG_Rules;
type
TRules=class(TChoice)
private
FParser : TParser;
procedure Load; overload;
protected
function Match(const AParser:TParser):Boolean; override;
public
Constructor Create;
Destructor Destroy; override;
procedure Add(const ARule:TRule);
function AsString:String; override;
function Find:TRule;
procedure Load(const S:String); overload;
property Parser:TParser read FParser;
end;
TPEG=class
public
Rules : TRules;
Constructor Create;
Destructor Destroy; override;
procedure Load(const S:String); overload;
procedure Load(const S:TStrings); overload;
end;
implementation
uses
SysUtils, TeePEG_Grammar;
{ TRules }
Constructor TRules.Create;
begin
inherited Create([]);
FParser:=TParser.Create;
end;
Destructor TRules.Destroy;
var t : Integer;
begin
for t:=Low(Items) to High(Items) do
Items[t].Free;
FParser.Free;
inherited;
end;
function TRules.AsString: String;
const
LeftArrow=' <- ';
var t : Integer;
begin
result:='';
for t:=0 to High(Items) do
begin
if t>0 then
result:=result+#13#10;
if Items[t] is TNamedRule then
begin
result:=result+TNamedRule(Items[t]).Name;
result:=result+LeftArrow+TOperator(Items[t]).Rule.AsString;
end
else
result:=result+'Error:'+LeftArrow+Items[t].AsString;
end;
end;
function TRules.Match(const AParser: TParser): Boolean;
begin
result:=False;
end;
procedure TRules.Load(const S: String);
begin
FParser.Text:=S;
Load;
end;
type
TRuleAccess=class(TRule);
function TRules.Find: TRule;
var t : Integer;
begin
for t:=Low(Items) to High(Items) do
if TRuleAccess(Items[t]).Match(FParser) then
begin
result:=Items[t];
Exit;
end;
result:=nil;
end;
procedure TRules.Load;
var Start : Integer;
tmp : TRule;
begin
FParser.Position:=1;
repeat
Start:=FParser.Position;
tmp:=Find;
if tmp=nil then
raise Exception.Create('Invalid syntax at position: '+IntToStr(Start))
else
if FParser.Position=Start then
raise Exception.Create('Inifite loop at position: '+IntToStr(Start));
until FParser.EndOfFile;
end;
procedure TRules.Add(const ARule: TRule);
var L : Integer;
begin
L:=Length(Items);
SetLength(Items,L+1);
Items[L]:=ARule;
end;
{ TPEG }
Constructor TPEG.Create;
begin
inherited Create;
Rules:=TRules.Create;
TGrammar.AddTo(Rules.Items);
end;
Destructor TPEG.Destroy;
begin
Rules.Free;
inherited;
end;
procedure TPEG.Load(const S: String);
begin
Rules.Load(S);
end;
procedure TPEG.Load(const S: TStrings);
begin
Load(S.Text);
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Spin,
StdCtrls, Types;
type
{ TForm1 }
TForm1 = class(TForm)
Label1: TLabel;
ListBox1: TListBox;
Panel1: TPanel;
Panel2: TPanel;
edSleep: TSpinEdit;
procedure FormCreate(Sender: TObject);
procedure Panel1MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
procedure Log(const s: string);
public
end;
var
Form1: TForm1;
implementation
uses LCLIntf;
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
LCLIntf.SetFocus(Panel1.Handle);
end;
procedure TForm1.Panel1MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
Log('mouse wheel, delta '+IntToStr(WheelDelta)+'; '+TimeToStr(Now));
Sleep(edSleep.Value);
Handled:= true;
end;
procedure TForm1.Log(const s: string);
begin
Listbox1.Items.Add(s);
Listbox1.ItemIndex:= Listbox1.Items.Count-1;
end;
end.
|
{Implemente un programa que lea el diámetro D de un círculo e imprima:
a. El radio (R) del círculo (la mitad del diámetro)
b. El área del círculo. Para calcular el área de un círculo debe utilizar la fórmula PI x R2
c. El perímetro del círculo. Para calcular el perímetro del círculo debe utilizar la
fórmula D*PI (o también PI*R*2)}
program ejericicio4;
const
PI = 3.1416;
var
d,r,a,p: Real;
begin
writeln('Ingrese el diametro del Cirdulo');
readln(d);
r:= d / 2;
a:= PI * (r*r);
p:= d*PI;
writeln('el radio del circulo es: ', r:2:2);
writeln('El area de lcirculo es: ', a:2:2);
writeln('El perimetro del circulo es ', p:2:2);
readln;
end.
|
unit Model.Sistemas;
interface
uses Common.ENum, FireDAC.Comp.Client;
type
TSistemas = class
private
FAcao: TAcao;
FDescricao: String;
FCodigo: Integer;
public
property Codigo: Integer read FCodigo write FCodigo;
property Descricao: String read FDescricao write FDescricao;
property Acao: TAcao read FAcao write FAcao;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
end;
implementation
{ TSistemas }
uses DAO.Sistemas;
function TSistemas.Gravar: Boolean;
var
sistemasDAO : TSistemasDAO;
begin
try
Result := False;
sistemasDAO := TSistemasDAO.Create;
case FAcao of
Common.ENum.tacIncluir: Result := sistemasDAO.Inserir(Self);
Common.ENum.tacAlterar: Result := sistemasDAO.Alterar(Self);
Common.ENum.tacExcluir: Result := sistemasDAO.Excluir(Self);
end;
finally
sistemasDAO.Free;
end;
end;
function TSistemas.Localizar(aParam: array of variant): TFDQuery;
var
sistemasDAO : TSistemasDAO;
begin
try
sistemasDAO := TSistemasDAO.Create;
Result := sistemasDAO.Pesquisar(aParam);
finally
sistemasDAO.Free;
end;
end;
end.
|
{ string const unit fo DB-aware modules
Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit rxdconst;
interface
resourcestring
{ RxDBCtrl }
SLocalDatabase = 'Unable complete this operation on local dataset';
SRetryLogin = 'Retry to connect with database?';
SExprNotBoolean = 'Field ''%s'' is not boolean';
SExprBadNullTest = 'NULL-values enabled in ''='' and ''<>''';
SExprBadField = 'Field ''%s'' not used in filter expression';
SCaptureFilter = 'Control locked by filter';
SNotCaptureFilter = 'Control needs to be locked by filter';
SInactiveData = 'inactive';
SBrowseData = 'browse';
SEditData = 'editing';
SInsertData = 'append';
SSetKeyData = 'find';
SCalcFieldsData = 'calc';
SRegistration = 'Register';
SAppTitleLabel = 'Application "%s"';
SHintLabel = 'Enter your user name and password';
SUserNameLabel = '&User name:';
SPasswordLabel = '&Password:';
SMore1 = '&More >>';
SMore2 = '&Less <<';
SInvalidUserName = 'User name or password is not valid';
SChangePassword = 'Change password';
SOldPasswordLabel = '&Old password:';
SNewPasswordLabel = '&New password:';
SConfirmPasswordLabel = '&Confirm:';
SPasswordChanged = 'Password changed';
SPasswordNotChanged = 'Password not changed';
SPasswordsMismatch = 'New password and confirmation not equal';
SDBExceptCaption = 'Error in DB engine';
SServerErrorLabel = 'Server error';
SErrorMsgLabel = 'Error message';
SNextButton = '&Next';
SPrevButton = '&Prior';
SExprIncorrect = 'Error in filter expression';
SExprTermination = 'Error in filter end';
SExprNameError = 'Error in filed name';
SExprStringError = 'Error in string const';
SExprInvalidChar = 'Error symbol in expression: ''%s''';
SExprNoRParen = 'Error '')'', error: %s';
SExprExpected = 'Error %s';
SExprBadCompare = 'Compare opertion needs field and const';
SConfirmSave = 'Data changed. Save?';
SDatabaseName = 'Database locked: %s';
SUnlockCaption = 'Unlock';
SUnlockHint = 'Enter your password';
SDeleteMultipleRecords = 'Delete all selected records?';
SDBComboBoxFieldNotAssigned = '%s:TDBComboBox - DataField not assigned';
SPropDefByLookup = 'PropDefByLookup';
SDataSourceFixed = 'SDataSourceFixed';
SCircularDataLink = 'SCircularDataLink';
sRxAscendign = 'Ascendign';
sRxDescending = 'Descending';
sRxAllFields = 'All fields';
sRxFieldsLookupDisplay = 'Fields as LookupDisplay';
sRxFillFieldsLookupDisp = 'Fill fields in LookupDisplay property';
sRxSortFieldsDisplay = 'Fields as SortField';
sRxFillSortFieldsDisp = 'Fill fields in SortField property';
SDeleteRecordQuestion = 'Delete record?';
SFieldTypeMismatch = 'Type mismatch for field ''%s'', expecting: %s actual: %s';
SInvalidDate = 'Invalid Date';
SFieldRequired = 'Field ''%s'' must have a value';
SNotEditing = 'Dataset not in edit or insert mode';
SUnknownFieldType = 'SUnknownFieldType %s';
SFieldReadOnly = 'SFieldReadOnly %s';
//RXDBgrid
sRxDBGridFind = 'Find data'; //// 'Buscar Ctrl+F';
sRxDBGridFilter = 'Filter data';//'Filtrar Ctrl+T';
sRxDBGridFilterSimple = 'Filter in table';// Ctrl+E'; 'Filtrar en Encabezado Ctrl+E';
sRxDBGridFilterClear = 'Clear filter';// Ctrl+Q';'Quitar Filtro Ctrl+Q';
sRxDBGridSortByColumns = 'Sort data for columns';// Ctrl+C';'Ordenar por Columnas Ctrl+C';
sRxDBGridSelectColumns = 'Select visible columns';// Ctrl+W';'Seleccionar Columnas Ctrl+W';
sRxDBGridEmptiFilter = '(Empty)';
sRxDBGridSelectAllRows = 'Select all rows';// Ctrl+W';'Seleccionar Columnas Ctrl+W';
sRxDBGridCopyCellValue = 'Copy cell value';// Ctrl+W';'Seleccionar Columnas Ctrl+W';
//RxDBGrid filter form
sRxFilterFormSelectExp = 'Enter filter expression for data in table:';
sRxFilterFormOnField = 'On field :';
sRxFilterFormOperaion = 'Operation :';
sRxFilterFormCondition = 'Condition :';
sRxFilterFormOperand = 'Operand :';
sRxFilterFormEnd = 'end.';
sRxFilterFormClear = 'Clear filter';
sRxFilterFormCancel = 'Cancel';
sRxFilterFormApply = 'Apply';
sRxFilterFormCaption = 'Filter conditions';
//TrxSortByForm
sRxSortByFormCaption = 'Sort on field';
sRxSortByFormAllFields = '&Fields in dataset:';
sRxSortByFormSortFields = '&Selected fields:';
sRxSortByFormSortOrder = 'Select f&ield for sort data:';
sRxSortByFormAddField = '&Add field';
sRxSortByFormRemoveField = '&Remove';
sRxSortByFormMoveUpField = '&Up';
sRxSortByFormMoveDnField = '&Down';
sRxSortByFormCaseInsens = '&Case insensitive sort';
//TRxMemoryData
SMemNoRecords = 'No data found';
SInvalidFields = 'No fields defined';
//TrxDBGridFindForm
sRxDbGridFindCaption = 'Find data';
sRxDbGridFindText = 'Text to find';
sRxDbGridFindOnField = 'Find on field';
sRxDbGridFindCaseSens = 'Case sensetive';
sRxDbGridFindPartial = 'Partial key';
sRxDbGridFindDirecion = 'Direction';
sRxDbGridFindRangeAll = 'All';
sRxDbGridFindRangeForw = 'Forward';
sRxDbGridFindRangeBack = 'Backward';
sRxFindMore = 'Find more';
//TrxDBGridColumsForm
sRxDbGridSelColCaption = 'Grid columns';
sRxDbGridSelColHint1 = 'Move selected column up';
sRxDbGridSelColHint2 = 'Move selected column down';
sRxDbGridSelApplyCaption = 'Apply';
sRxDbGridSelApplyHint = 'Apply current column settings';
//seldsfrm
sRxBorrowStructure = 'Borrow structure...';
sRxSelectDatasetStruct = 'Select dataset to copy to';
sRxCopyOnlyMetadata = 'Copy only metadata';
sRxSourceDataset = 'Source dataset';
sUnknownXMLDatasetFormat = 'Unknown XML Dataset format';
sToolsExportSpeadSheet = 'Export to speadsheet';
sExportFileName = 'Export file name';
sOpenAfterExport = 'Open after export';
sPageName = 'Page name';
sExportColumnHeader = 'Export column header';
sExportColumnFooter = 'Export column footer';
sExportCellColors = 'Export cell colors';
sOverwriteExisting = 'Overwrite existing';
sShowColumnHeaderOnAllPage = 'Show column header on all pages';
sPageMargins = 'Page margins';
sLeftCaption = 'Left';
sTopCaption = 'Top';
sRightCaption = 'Right';
sBottomCaption = 'Bottom';
sReportTitle = 'Report title';
sOrientation = 'Orientation';
sPortrait = 'Portrait';
sLandscape = 'Landscape';
sPrintOptions = 'Print options';
sShowTitle = 'Show column title';
sShowFooter = 'Show footer';
sShowFooterColor = 'Show footer color';
sShowGridColor = 'Show grid color';
sShowReportTitle = 'Show report title';
sPrintGrid = 'Print grid';
sHideZeroValues = 'Hide zero values';
sRxDBGridToolsCaption = 'Totals row';
sfvtNon = 'None';
sfvtSum = 'Sum';
sfvtAvg = 'AVG';
sfvtCount = 'Count';
sfvtFieldValue = 'Field value';
sfvtStaticText = 'Static text';
sfvtMax = 'Max value';
sfvtMin = 'Min value';
sfvtRecNo = 'Record no';
sSetupTotalRow = 'Setup total row';
sCollumnName = 'Column name';
sFunction = 'Function';
sBlobText = '(blob)';
const
{ The following strings should not be localized }
sAction = '.Action';
sCount = '.Count';
sVisible = '.Visible';
sItem = '.Item';
sWidth = '.Width';
sTop = '.Top';
sVersion = '.Version';
sLeft = '.Left';
sShowHint = '.ShowHint';
sShowCaption = '.ShowCaption';
sToolBarStyle = '.ToolBarStyle';
sButtonAllign = '.ButtonAllign';
sOptions = '.Options';
sCaption = '.Caption';
sIndex = '.Index';
sSortMarker = '.SortMarker';
sSortField = '.SortField';
implementation
end.
|
unit GX_ToolBarDropDown;
interface
{$I GX_CondDefine.inc}
uses
Windows,
Classes, Controls, Menus,
GX_OtaUtils;
type
IPopupInterface = interface(IUnknown)
['{8D9E1714-D0F2-11D3-A943-625A4B000000}']
// Show popup menu below passed control aligned to
// the control's left bottom corner.
procedure ShowPopupBelowControl(AControl: TControl);
// Show popup menu at position APoint.
procedure PopupAt(const APoint: TPoint);
end;
procedure InitializeGXToolBarDropDowns;
procedure FreeGXToolBarDropDowns;
{ TODO 4 -oAnyone -cFeature: Equip the actions with
an IPopupMenuAction interface. The (editor) toolbar then
may query the action instance for the interface. If
the interface is supported, assign
IPopupMenuAction.PopupMenu to TToolButton.DropDownMenu }
(* Currently unused
type
IPopupMenuAction = interface(IUnknown)
['{AEEA0DC9-275F-47C6-9BD6-ABBD2D67CE43}']
function PopupMenu: TPopupMenu;
end;
*)
type
// Base class for reference-counted, self-destroying
// popup menus.
TRefCountedPopupMenu = class(TPopupMenu, IPopupInterface)
protected
// Added, fresh IUnknown reference counting
// The VCL by default provides reference-counting
// that is only usable with VCLComObject.
FRefCount: Integer;
FPopupPoint: TPoint;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
procedure AddNoneItemIfEmpty;
procedure FillMenuWithContent; virtual; abstract;
function CalculateColumnCount: Cardinal;
public
// IPopupInterface
procedure ShowPopupBelowControl(AControl: TControl); virtual;
procedure PopupAt(const APoint: TPoint); virtual;
end;
type
TBasePopupListing = class(TRefCountedPopupMenu)
protected
FUnitList: TList;
procedure GotoFileClick(Sender: TObject); virtual;
procedure FillMenuWithContent; override;
procedure PopulateUnitList; virtual;
// Abstract method which is called with UnitInfo
// unit information data.
// The implementation looks at UnitInfo and manipulates
// AList based on the data found in UnitInfo.
// Note that Data must always remain associated with UnitInfo;
// it must be stored in AList.
{ TODO 4 -oAnyone -cCleanup: This is a horrible callback interface.
Its main problem is that there are two lots of information and the
awkward treatment of the opaque "Data" pointer. }
procedure ProcessUnitInfo(AList: TStrings; UnitInfo: TUnitInfo; Data: Pointer); virtual; abstract;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// IPopupInterface
procedure ShowPopupBelowControl(AControl: TControl); override;
end;
{ TODO 4 -oAnyone -cFeature: Add hierarchical building of menus following
a directory structure. Model following the implementation as proposed
by "wfiskfr at yahoo.co.uk" as found in
http://groups.yahoo.com/group/GExpertsDiscuss/message/687
Be sure to use MinimizeName to keep the width of menu items under control. }
TUnitPopupListing = class(TBasePopupListing)
protected
procedure ProcessUnitInfo(AList: TStrings; UnitInfo: TUnitInfo; Data: Pointer); override;
end;
TFormPopupListing = class(TBasePopupListing)
protected
procedure ProcessUnitInfo(AList: TStrings; UnitInfo: TUnitInfo; Data: Pointer); override;
end;
TUsesPopupListing = class(TBasePopupListing)
protected
procedure GotoFileClick(Sender: TObject); override;
procedure PopulateUnitList; override;
procedure ProcessUnitInfo(AList: TStrings; UnitInfo: TUnitInfo; Data: Pointer); override;
end;
TComponentPopupListing = class(TRefCountedPopupMenu)
private
procedure FocusInspectorClick(Sender: TObject);
procedure AddComponentsToPopup(CompInfo: TCompInfo);
protected
procedure FillMenuWithContent; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TPositionPopupListing = class(TRefCountedPopupMenu, IPopupInterface)
private
procedure GotoPosition(Sender: TObject);
protected
procedure FillMenuWithContent; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
SysUtils,
Graphics, StdCtrls, Forms, Dialogs,
GX_Actions, GX_ActionBroker,
GX_GxUtils, GX_GenericUtils, GX_IdeUtils,
GX_EditReader, GX_UsesManager, GX_UnitPositions, Math;
const
MinMenuLines = 5;
{ TRefCountedPopupMenu }
function TRefCountedPopupMenu._AddRef: Integer;
begin
Result := InterlockedIncrement(FRefCount);
end;
function TRefCountedPopupMenu._Release: Integer;
begin
Result := InterlockedDecrement(FRefCount);
if Result = 0 then
Destroy;
end;
{ TBasePopupListing }
{$IFOPT D+}
var
InternalPopupListingCount: Integer;
{$ENDIF D+}
procedure TRefCountedPopupMenu.AddNoneItemIfEmpty;
resourcestring
SNone = 'None';
var
TempMenu: TMenuItem;
begin
if Self.Items.Count < 1 then
begin
TempMenu := TMenuItem.Create(Self);
TempMenu.Enabled := False;
TempMenu.Caption := SNone;
Self.Items.Add(TempMenu);
end;
end;
constructor TBasePopupListing.Create(AOwner: TComponent);
begin
{$IFOPT D+}
SendDebug('Creating popup list');
Inc(InternalPopupListingCount);
{$ENDIF D+}
inherited Create(AOwner);
FUnitList := TList.Create;
end;
destructor TBasePopupListing.Destroy;
begin
{$IFOPT D+} SendDebug('Clearing unit list'); {$ENDIF}
ClearUnitInfoList(FUnitList);
FreeAndNil(FUnitList);
inherited Destroy;
{$IFOPT D+}
Dec(InternalPopupListingCount);
SendDebug(Format('Destroying popup list - remaining: %d', [InternalPopupListingCount]));
{$ENDIF D+}
end;
procedure TBasePopupListing.FillMenuWithContent;
var
Menu: TMenuItem;
i: Integer;
UnitInfo: TUnitInfo;
List: TStringList;
begin
PopulateUnitList;
List := TStringList.Create;
try
for i := 0 to FUnitList.Count - 1 do
begin
UnitInfo := TObject(FUnitList[i]) as TUnitInfo;
ProcessUnitInfo(List, UnitInfo, Pointer(i));
end;
List.Sorted := True;
for i := 0 to List.Count - 1 do
begin
Menu := TMenuItem.Create(nil);
Menu.Tag := Integer(List.Objects[i]);
Menu.Caption := List.Strings[i];
if (i > 0) and (Cardinal(i) mod CalculateColumnCount = 0) then
Menu.Break := mbBarBreak;
Menu.OnClick := GotoFileClick;
Self.Items.Add(Menu);
end;
AddNoneItemIfEmpty;
finally
FreeAndNil(List);
end;
end;
procedure TBasePopupListing.GotoFileClick(Sender: TObject);
var
EditRead: TEditReader;
UnitInfo: TUnitInfo;
SendingMenu: TMenuItem;
SendingMenuCaption: string;
begin
SendingMenu := Sender as TMenuItem;
// Compensate for AutoHotKeys in D5+
SendingMenuCaption := StringReplace(SendingMenu.Caption, '&', '', [rfReplaceAll]);
UnitInfo := TObject(FUnitList[SendingMenu.Tag]) as TUnitInfo;
{$IFOPT D+}SendDebug('Opening file: ' + UnitInfo.FileName);{$ENDIF}
GxOtaOpenFile(UnitInfo.FileName);
// Since this edit reader is destroyed almost
// immediately, do not call FreeFileData.
EditRead := TEditReader.Create(UnitInfo.FileName);
try
if SendingMenuCaption = UnitInfo.FormName then
EditRead.ShowForm
else
EditRead.ShowSource;
finally
FreeAndNil(EditRead);
end;
end;
procedure TBasePopupListing.PopulateUnitList;
begin
ClearUnitInfoList(FUnitList);
GxOtaFillUnitInfoListForCurrentProject(FUnitList);
end;
procedure TBasePopupListing.ShowPopupBelowControl(AControl: TControl);
var
MenuPopupPosition: TPoint;
MaxMenuTop: Integer;
begin
Assert(Assigned(AControl));
Assert(Assigned(AControl.Parent));
MenuPopupPosition.X := AControl.Left;
MenuPopupPosition.Y := AControl.Top + AControl.Height + 1;
MaxMenuTop := Screen.Height - (GetStandardMenuItemHeight * MinMenuLines);
if AControl.Parent.ClientToScreen(MenuPopupPosition).Y > MaxMenuTop then
MenuPopupPosition.Y := AControl.Parent.ScreenToClient(Point(0, MaxMenuTop)).Y;
MenuPopupPosition := AControl.Parent.ClientToScreen(MenuPopupPosition);
PopupAt(MenuPopupPosition);
end;
procedure TRefCountedPopupMenu.PopupAt(const APoint: TPoint);
var
Cursor: IInterface;
begin
Cursor := TempHourglassCursor;
Application.ProcessMessages;
FPopupPoint := APoint;
{$IFOPT D+}SendDebug('Filling menu with content');{$ENDIF}
FillMenuWithContent;
{$IFOPT D+}SendDebug('Popping up the menu');{$ENDIF}
Self.Popup(APoint.X, APoint.Y);
end;
procedure TRefCountedPopupMenu.ShowPopupBelowControl(AControl: TControl);
var
MenuPopupPosition: TPoint;
begin
Assert(Assigned(AControl));
Assert(Assigned(AControl.Parent));
MenuPopupPosition.X := AControl.Left;
MenuPopupPosition.Y := AControl.Top + AControl.Height + 1;
MenuPopupPosition := AControl.Parent.ClientToScreen(MenuPopupPosition);
PopupAt(MenuPopupPosition);
end;
function TRefCountedPopupMenu.CalculateColumnCount: Cardinal;
begin
Result := (Screen.Height - FPopupPoint.Y - 10) div GetStandardMenuItemHeight;
if Result < 1 then
Result := 1;
end;
{ TUnitPopupListing }
procedure TUnitPopupListing.ProcessUnitInfo(AList: TStrings;
UnitInfo: TUnitInfo; Data: Pointer);
begin
Assert(Assigned(UnitInfo));
Assert(Assigned(AList));
if IsBdsSourceFile(UnitInfo.FileName) then
if AList.IndexOf(UnitInfo.SourceName) = -1 then
AList.AddObject(UnitInfo.SourceName, Data);
end;
{ TFormPopupListing }
procedure TFormPopupListing.ProcessUnitInfo(AList: TStrings;
UnitInfo: TUnitInfo; Data: Pointer);
var
TrimmedFormName: string;
begin
Assert(Assigned(UnitInfo));
Assert(Assigned(AList));
TrimmedFormName := Trim(UnitInfo.FormName);
if TrimmedFormName <> '' then
AList.AddObject(TrimmedFormName, Data);
end;
{ TUsesPopupListing }
procedure TUsesPopupListing.GotoFileClick(Sender: TObject);
resourcestring
SUnableToLocateFile = 'Unable to locate ';
var
UnitInfo: TUnitInfo;
SendingMenu: TMenuItem;
begin
SendingMenu := Sender as TMenuItem;
UnitInfo := TObject(FUnitList[SendingMenu.Tag]) as TUnitInfo;
if not GxOtaOpenFileFromPath(UnitInfo.FileName) then
ShowMessage(SUnableToLocateFile + UnitInfo.FileName);
end;
procedure TUsesPopupListing.PopulateUnitList;
var
Aliases: TStringList;
function ApplyAlias(const UnitName: string): string;
var
i: Integer;
begin
Result := UnitName;
i := Aliases.IndexOfName(Result);
if i <> -1 then
Result := Aliases.Values[Result];
end;
var
UsesManager: TUsesManager;
UnitInfo: TUnitInfo;
i: Integer;
UsesItem: TUsesItem;
begin
AssertIsDprOrPasOrInc(GxOtaGetCurrentSourceFile);
ClearUnitInfoList(FUnitList);
Aliases := TStringList.Create;
try
GxOtaGetUnitAliases(Aliases);
{$IFOPT D+}SendDebug('Populating empty unit list');{$ENDIF}
UsesManager := TUsesManager.Create(GxOtaGetCurrentSourceEditor);
try
{$IFOPT D+}SendDebug('Iterating through interface uses. Count = ' + IntToStr(UsesManager.InterfaceUses.Count));{$ENDIF}
for i := 0 to UsesManager.InterfaceUses.Count - 1 do
begin
UnitInfo := TUnitInfo.Create;
FUnitList.Add(UnitInfo);
UsesItem := UsesManager.InterfaceUses.Items[i];
UnitInfo.FileName := ApplyAlias(UsesItem.Name) + '.pas';
UnitInfo.FormName := '';
UnitInfo.SourceName := UsesItem.Name;
end;
{$IFOPT D+}SendDebug('Iterating through implementation uses. Count = ' + IntToStr(UsesManager.ImplementationUses.Count));{$ENDIF}
for i := 0 to UsesManager.ImplementationUses.Count - 1 do
begin
UnitInfo := TUnitInfo.Create;
FUnitList.Add(UnitInfo);
UsesItem := UsesManager.ImplementationUses.Items[i];
UnitInfo.FileName := ApplyAlias(UsesItem.Name) + '.pas';
UnitInfo.FormName := '';
UnitInfo.SourceName := UsesItem.Name;
end;
finally
FreeAndNil(UsesManager);
end;
{$IFOPT D+}SendDebug('Unit list count = ' + IntToStr(FUnitList.Count));{$ENDIF}
finally
FreeAndNil(Aliases);
end;
end;
procedure TUsesPopupListing.ProcessUnitInfo(AList: TStrings; UnitInfo: TUnitInfo; Data: Pointer);
var
TrimmedUsesName: string;
begin
Assert(Assigned(UnitInfo));
Assert(Assigned(AList));
TrimmedUsesName := Trim(UnitInfo.SourceName);
if TrimmedUsesName <> '' then
if AList.IndexOf(TrimmedUsesName) = -1 then
AList.AddObject(TrimmedUsesName, Data);
end;
{ TPositionPopupListing }
constructor TPositionPopupListing.Create(AOwner: TComponent);
begin
{$IFOPT D+}
SendDebug('Creating popup list');
Inc(InternalPopupListingCount);
{$ENDIF D+}
inherited Create(AOwner);
end;
destructor TPositionPopupListing.Destroy;
begin
{$IFOPT D+}
Dec(InternalPopupListingCount);
SendDebug(Format('Destroying popup list - remaining: %d', [InternalPopupListingCount]));
{$ENDIF D+}
inherited Destroy;
end;
procedure TPositionPopupListing.GotoPosition(Sender: TObject);
begin
Assert(Sender is TMenuItem);
GxOtaGotoPosition(TMenuItem(Sender).Tag);
GxOtaMakeSourceVisible(GxOtaGetCurrentSourceFile);
end;
procedure TPositionPopupListing.FillMenuWithContent;
var
UnitPositions: TUnitPositions;
MenuItem: TMenuItem;
i: Integer;
UnitPosition: TUnitPosition;
begin
AssertIsDprOrPasOrInc(GxOtaGetCurrentSourceFile);
UnitPositions := TUnitPositions.Create(GxOtaGetCurrentSourceEditor);
try
for i := 0 to UnitPositions.Count - 1 do
begin
UnitPosition := UnitPositions.Positions[i];
if UnitPosition.Position <> -1 then
begin
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := UnitPosition.Name;
MenuItem.Tag := UnitPosition.Position;
MenuItem.OnClick := GotoPosition;
Self.Items.Add(MenuItem);
end;
end;
finally
FreeAndNil(UnitPositions);
end;
AddNoneItemIfEmpty;
end;
{ TComponentPopupListing }
constructor TComponentPopupListing.Create(AOwner: TComponent);
begin
{$IFOPT D+}
SendDebug('Creating popup list');
Inc(InternalPopupListingCount);
{$ENDIF D+}
inherited Create(AOwner);
end;
destructor TComponentPopupListing.Destroy;
begin
{$IFOPT D+}
Dec(InternalPopupListingCount);
SendDebug(Format('Destroying popup list - remaining: %d', [InternalPopupListingCount]));
{$ENDIF D+}
inherited Destroy;
end;
procedure TComponentPopupListing.FocusInspectorClick(Sender: TObject);
const
ObjectInspectorFormName = 'PropertyInspector'; // Do not localize.
var
AppBuilderForm: TCustomForm;
ObjectInspector: TCustomForm;
begin
// Compensate for AutoHotKeys. '&' is not valid in Name anyway
GxOtaSelectComponentOnCurrentForm(StringReplace((Sender as TMenuItem).Caption, '&', '', [rfReplaceAll]));
AppBuilderForm := GetIdeMainForm;
if AppBuilderForm <> nil then
begin
ObjectInspector := AppBuilderForm.FindComponent(ObjectInspectorFormName) as TCustomForm;
if ObjectInspector <> nil then
begin
ObjectInspector.Show;
ObjectInspector.SetFocus;
end
else
begin
{$IFOPT D+} SendDebug('TComponentPopupListing.FocusInspectorClick: Object inspector not found'); {$ENDIF}
end;
end;
end;
function CompareObjects(PointerItem1, PointerItem2: Pointer): Integer;
begin
Result := AnsiCompareStr(TCompInfo(PointerItem1).CompType, TCompInfo(PointerItem2).CompType);
if Result = 0 then
begin
// The types are equal, so we compare the names.
Result := AnsiCompareStr(TCompInfo(PointerItem1).CompName, TCompInfo(PointerItem2).CompName);
end;
end;
procedure TComponentPopupListing.AddComponentsToPopup(CompInfo: TCompInfo);
var
NumberColumns: Integer;
SingleMenuBarHeight: Integer;
i: Integer;
TempMenu1: TMenuItem;
TempMenu2: TMenuItem;
begin
SingleMenuBarHeight := GetSystemMetrics(SM_CYMENU);
NumberColumns := (Screen.Height - 10) div SingleMenuBarHeight;
NumberColumns := Max(NumberColumns, 1);
for i := 0 to Self.Items.Count - 1 do
begin
if SameText(CompInfo.CompType, Self.Items[i].Caption) then
begin
TempMenu1 := TMenuItem.Create(Self);
TempMenu1.Caption := CompInfo.CompName;
TempMenu1.OnClick := FocusInspectorClick;
if (Self.Items[i].Count > 0) and
(Self.Items[i].Count mod NumberColumns = 0) then
begin
TempMenu1.Break := mbBarBreak;
end;
Self.Items[i].Add(TempMenu1);
Exit;
end;
end;
TempMenu2 := TMenuItem.Create(Self);
TempMenu2.Caption := CompInfo.CompType;
Self.Items.Add(TempMenu2);
TempMenu1 := TMenuItem.Create(Self);
TempMenu1.Caption := CompInfo.Compname;
TempMenu1.OnClick := FocusInspectorClick;
TempMenu2.Add(TempMenu1);
end;
procedure TComponentPopupListing.FillMenuWithContent;
var
i: Integer;
List: TList;
CompInfo: TCompInfo;
begin
List := TList.Create;
try
GxOtaFillComponentInfoList(List);
try
List.Sort(CompareObjects);
for i := 0 to List.Count - 1 do
begin
CompInfo := TObject(List.Items[i]) as TCompInfo;
AddComponentsToPopup(CompInfo);
end;
AddNoneItemIfEmpty;
finally
ClearCompInfoList(List);
end;
finally
FreeAndNil(List);
end;
end;
// ***************************************************
type
TGxToolBarDropDownActions = class(TObject)
private
FCurrentlyCreatedPopupMenu: IPopupInterface;
FUnitDropDownActionBitmap: Graphics.TBitmap;
IUnitDropDownAction: IGxAction;
FFormDropDownActionBitmap: Graphics.TBitmap;
IFormDropDownAction: IGxAction;
FComponentDropDownActionBitmap: Graphics.TBitmap;
IComponentDropDownAction: IGxAction;
FUsesDropDownActionBitmap: Graphics.TBitmap;
IUsesDropDownAction: IGxAction;
FPositionDropDownActionBitmap: Graphics.TBitmap;
IPositionDropDownAction: IGxAction;
procedure ShowDropDown;
procedure LoadActionBitmaps;
procedure FreeActionBitmaps;
procedure CreateUnitDropDownMenu(Sender: TObject);
procedure CreateFormDropDownMenu(Sender: TObject);
procedure CreateComponentDropDownMenu(Sender: TObject);
procedure CreateUsesDropDownMenu(Sender: TObject);
procedure CreatePositionDropDownMenu(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
end;
{ TGxToolBarDropDownActions }
constructor TGxToolBarDropDownActions.Create;
resourcestring
SGxUnitDropDown = 'Unit List';
SGxFormDropDown = 'Form List';
SGxComponentDropDown = 'Component List';
SGxUsesDropDown = 'Uses List';
SGxPositionDropDown = 'Unit Positions';
begin
inherited Create;
LoadActionBitmaps;
IUnitDropDownAction := GxActionBroker.RequestAction('GxUnitDropDown', FUnitDropDownActionBitmap);
IUnitDropDownAction.Caption := SGxUnitDropDown;
IUnitDropDownAction.OnExecute := CreateUnitDropDownMenu;
IFormDropDownAction := GxActionBroker.RequestAction('GxFormDropDown', FFormDropDownActionBitmap);
IFormDropDownAction.Caption := SGxFormDropDown;
IFormDropDownAction.OnExecute := CreateFormDropDownMenu;
IComponentDropDownAction := GxActionBroker.RequestAction('GxComponentDropDown', FComponentDropDownActionBitmap);
IComponentDropDownAction.Caption := SGxComponentDropDown;
IComponentDropDownAction.OnExecute := CreateComponentDropDownMenu;
IUsesDropDownAction := GxActionBroker.RequestAction('GxUsesDropDown', FUsesDropDownActionBitmap);
IUsesDropDownAction.Caption := SGxUsesDropDown;
IUsesDropDownAction.OnExecute := CreateUsesDropDownMenu;
IPositionDropDownAction := GxActionBroker.RequestAction('GxPositionDropDown', FPositionDropDownActionBitmap);
IPositionDropDownAction.Caption := SGxPositionDropDown;
IPositionDropDownAction.OnExecute := CreatePositionDropDownMenu;
end;
procedure TGxToolBarDropDownActions.CreateComponentDropDownMenu(Sender: TObject);
begin
FCurrentlyCreatedPopupMenu := TComponentPopupListing.Create(nil);
ShowDropDown;
end;
procedure TGxToolBarDropDownActions.CreateFormDropDownMenu(Sender: TObject);
begin
FCurrentlyCreatedPopupMenu := TFormPopupListing.Create(nil);
ShowDropDown;
end;
procedure TGxToolBarDropDownActions.CreatePositionDropDownMenu(Sender: TObject);
begin
FCurrentlyCreatedPopupMenu := TPositionPopupListing.Create(nil);
ShowDropDown;
end;
procedure TGxToolBarDropDownActions.CreateUnitDropDownMenu(Sender: TObject);
begin
FCurrentlyCreatedPopupMenu := TUnitPopupListing.Create(nil);
ShowDropDown;
end;
procedure TGxToolBarDropDownActions.CreateUsesDropDownMenu(Sender: TObject);
begin
FCurrentlyCreatedPopupMenu := TUsesPopupListing.Create(nil);
ShowDropDown;
end;
destructor TGxToolBarDropDownActions.Destroy;
begin
// Somewhat redundant cleanup.
FCurrentlyCreatedPopupMenu := nil;
IUnitDropDownAction := nil;
IFormDropDownAction := nil;
IComponentDropDownAction := nil;
IUsesDropDownAction := nil;
IPositionDropDownAction := nil;
FreeActionBitmaps;
inherited Destroy;
end;
procedure TGxToolBarDropDownActions.FreeActionBitmaps;
begin
FreeAndNil(FUnitDropDownActionBitmap);
FreeAndNil(FFormDropDownActionBitmap);
FreeAndNil(FComponentDropDownActionBitmap);
FreeAndNil(FUsesDropDownActionBitmap);
FreeAndNil(FPositionDropDownActionBitmap);
end;
procedure TGxToolBarDropDownActions.LoadActionBitmaps;
begin
Assert(not Assigned(FUnitDropDownActionBitmap));
Assert(not Assigned(FFormDropDownActionBitmap));
Assert(not Assigned(FComponentDropDownActionBitmap));
Assert(not Assigned(FUsesDropDownActionBitmap));
Assert(not Assigned(FPositionDropDownActionBitmap));
GxLoadBitmapForExpert('UnitDropDown', FUnitDropDownActionBitmap);
GxLoadBitmapForExpert('FormDropDown', FFormDropDownActionBitmap);
GxLoadBitmapForExpert('ComponentDropDown', FComponentDropDownActionBitmap);
GxLoadBitmapForExpert('UsesDropDown', FUsesDropDownActionBitmap);
GxLoadBitmapForExpert('PositionDropDown', FPositionDropDownActionBitmap);
end;
procedure TGxToolBarDropDownActions.ShowDropDown;
var
MousePosition: TPoint;
ControlUnderCursor: TWinControl;
begin
Assert(Assigned(FCurrentlyCreatedPopupMenu));
MousePosition := Mouse.CursorPos;
ControlUnderCursor := FindVclWindow(MousePosition);
if Assigned(ControlUnderCursor) then
begin
if ControlUnderCursor is TButtonControl then
FCurrentlyCreatedPopupMenu.ShowPopupBelowControl(ControlUnderCursor)
else
FCurrentlyCreatedPopupMenu.PopupAt(MousePosition);
end
else
FCurrentlyCreatedPopupMenu.PopupAt(MousePosition);
end;
var
PrivateToolBarDropDowns: TGxToolBarDropDownActions;
procedure FreeGXToolBarDropDowns;
begin
FreeAndNil(PrivateToolBarDropDowns);
end;
procedure InitializeGXToolBarDropDowns;
begin
PrivateToolBarDropDowns := TGxToolBarDropDownActions.Create;
end;
initialization
finalization
FreeAndNil(PrivateToolBarDropDowns);
{$IFOPT D+} Assert(InternalPopupListingCount = 0, 'Reference-counting leak for toolbar drop-down menus'); {$ENDIF}
end.
|
unit UFloatCanvas;
interface
uses Graphics;
type
TPixFactors = array[0..1, 0..1] of Double;
TFloatCanvas = class(TObject)
private
class function CalcPixFactors(fx,fy : double):TPixFactors;
function GetPixels(x, y: Double): TColor;
public
Canvas : TCanvas;
constructor Create(ACanvas:TCanvas);
property Pixels[x,y:Double]:TColor read GetPixels;
end;
implementation
uses Windows;
{ TFloatCanvas }
class function TFloatCanvas.CalcPixFactors(fx, fy: double): TPixFactors;
begin
Result[0,0] := (1-fx) * (1-fy);
Result[1,0] := fx * (1-fy);
Result[0,1] := (1-fx) * fy;
Result[1,1] := fx * fy;
end;
constructor TFloatCanvas.Create(ACanvas: TCanvas);
begin
inherited Create;
Canvas := ACanvas;
end;
function TFloatCanvas.GetPixels(x, y: Double): TColor;
var
ix, iy : Integer;
p00, p10, p01, p11 : TColor;
matrix : TPixFactors;
r,g,b : word;
function CalcColor(c00,c10,c01,c11:word):Word;
begin
Result := round(
c00 * matrix[0,0]
+ c10 * matrix[1,0]
+ c01 * matrix[0,1]
+ c11 * matrix[1,1]
);
end;
begin
ix := Trunc(x);
iy := Trunc(y);
// Farben aller 4 umgebenden Pixel holen
p00 := Canvas.Pixels[ix,iy];
p10 := Canvas.Pixels[ix+1,iy];
p01 := Canvas.Pixels[ix,iy+1];
p11 := Canvas.Pixels[ix+1,iy+1];
// Interpolationsfaktoren berechnen
matrix := CalcPixFactors(Frac(x), frac(y));
// Interpolation getrennt nach Grundfarben Rot, Grün und Blau durchführen
r := calccolor(GetRValue(p00), GetRValue(p10), GetRValue(p01), GetRValue(p11));
g := calccolor(GetGValue(p00), GetGValue(p10), GetGValue(p01), GetGValue(p11));
b := calccolor(GetBValue(p00), GetBValue(p10), GetBValue(p01), GetBValue(p11));
Result := RGB(r,g,b);
end;
end.
|
unit DebugStruct;
{
Inno Setup
Copyright (C) 1997-2007 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Debug info stuff
$jrsoftware: issrc/Projects/DebugStruct.pas,v 1.20 2009/04/21 13:46:04 mlaan Exp $
}
interface
uses
Windows, Messages, SysUtils;
const
{ Debug client -> debugger messages }
WM_Debugger_Hello = WM_USER + $700;
WM_Debugger_Goodbye = WM_USER + $701;
WM_Debugger_Stepped = WM_USER + $702;
WM_Debugger_SteppedIntermediate = WM_USER + $703;
WM_Debugger_Exception = WM_USER + $704;
WM_Debugger_SetForegroundWindow = WM_USER + $705;
WM_Debugger_QueryVersion = WM_USER + $706;
{ Debug client -> debugger WM_COPYDATA messages }
CD_Debugger_ReplyW = $700;
CD_Debugger_ExceptionW = $701;
CD_Debugger_UninstExeW = $702;
CD_Debugger_LogMessageW = $703;
CD_Debugger_TempDirW = $704;
{ Debugger -> debug client messages }
WM_DebugClient_Detach = WM_USER + $800;
WM_DebugClient_Continue = WM_USER + $801;
WM_DebugClient_SetForegroundWindow = WM_USER + $803;
{ List of all messages the debugger may send the debug client }
DebugClientMessages: array[0..3] of UINT = (
WM_COPYDATA,
WM_DebugClient_Detach,
WM_DebugClient_Continue,
WM_DebugClient_SetForegroundWindow);
{ Debugger -> debug client WM_COPYDATA messages }
CD_DebugClient_EvaluateConstantW = $800;
CD_DebugClient_EvaluateVariableEntry = $801;
CD_DebugClient_CompiledCodeTextA = $802;
CD_DebugClient_CompiledCodeDebugInfoA = $803;
{ The current format of the 'debug info' is as follows:
1. A TDebugInfoHeader record.
2. A variable number (TDebugInfoHeader.DebugEntryCount) of TDebugEntry
records.
3. A variable number (TDebugInfoHeader.VariableDebugEntryCount) of
TVariableDebugEntry records.
4. The ROPS compiled code, the format of which is defined by ROPS.
TDebugInfoHeader.CompiledCodeTextLength specifies the size in bytes.
5. Additional debug info for the ROPS compiled code, the format of which is
defined by ROPS. TDebugInfoHeader.CompiledCodeDebugInfoLength specifies
the size in bytes.
}
const
DebugInfoHeaderID = $64787369;
DebugInfoHeaderVersion = 4;
type
PDebugInfoHeader = ^TDebugInfoHeader;
TDebugInfoHeader = packed record
ID: Cardinal; { = DebugInfoHeaderID }
Version: Integer; { = DebugInfoHeaderVersion }
DebugEntryCount: Integer;
VariableDebugEntryCount: Integer;
CompiledCodeTextLength: Integer;
CompiledCodeDebugInfoLength: Integer;
end;
{ TDebugEntrys associate section entries with line numbers }
TDebugEntryKind = (deDir, deFile, deIcon, deIni, deRegistry, deInstallDelete,
deUninstallDelete, deRun, deUninstallRun, deCodeLine);
PDebugEntry = ^TDebugEntry;
TDebugEntry = packed record
LineNumber: Integer;
Kind: Integer; { TDebugEntryKind }
Index: Integer;
end;
{ TVariableDebugEntrys associate [Code] section variable referenes with line
numbers & column positions }
PVariableDebugEntry = ^TVariableDebugEntry;
TVariableDebugEntry = packed record
LineNumber, Col: Integer;
Param1, Param2, Param3: Integer;
Param4: array [0..127] of AnsiChar;
end;
function GetThreadTopWindow: HWND;
function SendCopyDataMessage(DestWnd, SourceWnd: HWND; CopyDataMsg: DWORD;
Data: Pointer; Size: Cardinal): LRESULT;
function SendCopyDataMessageStr(DestWnd, SourceWnd: HWND; CopyDataMsg: DWORD;
Data: AnsiString): LRESULT;{$IFDEF UNICODE} overload;{$ENDIF}
{$IFDEF UNICODE}
function SendCopyDataMessageStr(DestWnd, SourceWnd: HWND; CopyDataMsg: DWORD;
Data: UnicodeString): LRESULT; overload;
{$ENDIF}
implementation
function EnumProc(Wnd: HWND; lParam: LPARAM): BOOL; stdcall;
begin
if IsWindowVisible(Wnd) then begin
HWND(Pointer(lParam)^) := Wnd;
Result := False;
end
else
Result := True;
end;
function GetThreadTopWindow: HWND;
begin
Result := 0;
EnumThreadWindows(GetCurrentThreadId, @EnumProc, LPARAM(@Result));
end;
function SendCopyDataMessage(DestWnd, SourceWnd: HWND; CopyDataMsg: DWORD;
Data: Pointer; Size: Cardinal): LRESULT;
var
CopyDataStruct: TCopyDataStruct;
begin
CopyDataStruct.dwData := CopyDataMsg;
CopyDataStruct.cbData := Size;
CopyDataStruct.lpData := Data;
Result := SendMessage(DestWnd, WM_COPYDATA, WPARAM(SourceWnd),
LPARAM(@CopyDataStruct));
end;
function SendCopyDataMessageStr(DestWnd, SourceWnd: HWND; CopyDataMsg: DWORD;
Data: AnsiString): LRESULT;
begin
{ Windows 95/98/Me bug workaround: Call UniqueString to ensure the string is
in writable memory. Amazingly enough, sending a WM_COPYDATA message with a
read-only buffer causes a fatal page fault error. }
if (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and
IsBadWritePtr(Pointer(Data), Length(Data)*SizeOf(Data[1])) then
UniqueString(Data);
Result := SendCopyDataMessage(DestWnd, SourceWnd, CopyDataMsg,
Pointer(Data), Length(Data)*SizeOf(Data[1]));
end;
{$IFDEF UNICODE}
function SendCopyDataMessageStr(DestWnd, SourceWnd: HWND; CopyDataMsg: DWORD;
Data: UnicodeString): LRESULT;
begin
{ Windows 95/98/Me bug workaround: Call UniqueString to ensure the string is
in writable memory. Amazingly enough, sending a WM_COPYDATA message with a
read-only buffer causes a fatal page fault error. }
if (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and
IsBadWritePtr(Pointer(Data), Length(Data)*SizeOf(Data[1])) then
UniqueString(Data);
Result := SendCopyDataMessage(DestWnd, SourceWnd, CopyDataMsg,
Pointer(Data), Length(Data)*SizeOf(Data[1]));
end;
{$ENDIF}
end.
|
unit SellAllTask;
interface
uses
Tasks, Kernel, Accounts, CacheAgent, BackupInterfaces, Inventions, FacIds;
type
TMetaSellAllTask =
class(TMetaTask)
private
fFacId : TFacId;
fGoods : integer;
public
property FacId : integer read fFacId write fFacId;
property Goods : integer read fGoods write fGoods;
end;
TSellAllTask =
class(TAtomicTask)
public
Sold : boolean;
public
function Execute : TTaskResult; override;
private
procedure MsgSellToAll(var Msg : TMsgSellToAll); message msgKernel_SellToAll;
public
procedure StoreToCache(Prefix : string; Cache : TObjectCache); override;
end;
procedure RegisterBackup;
implementation
uses
TaskUtils, ResidentialTasks, ClassStorage;
// TSellAllTask
procedure TSellAllTask.MsgSellToAll(var Msg : TMsgSellToAll);
begin
if (Msg.Fac <> nil) and (Msg.Fac.MetaFacility.FacId = TMetaSellAllTask(MetaTask).FacId) and
(Msg.FacTypes = 4)
then
Sold := True;
end;
function TSellAllTask.Execute : TTaskResult;
begin
if Sold
then result := trFinished
else result := trContinue;
end;
procedure TSellAllTask.StoreToCache(Prefix : string; Cache : TObjectCache);
begin
inherited;
Cache.WriteInteger(Prefix + 'CommerceId', TMetaSellAllTask(MetaTask).Goods);
end;
procedure RegisterBackup;
begin
RegisterClass(TSellAllTask);
end;
end.
|
unit Thread.ImportarPedidosTFO;
interface
uses
System.Classes, Control.Entregas, Control.PlanilhaEntradaTFO, System.SysUtils, System.DateUtils, Control.VerbasExpressas,
Control.Bases, Control.EntregadoresExpressas, Generics.Collections, System.StrUtils;
type
TThread_ImportarPedidosTFO = class(TThread)
private
{ Private declarations }
FPlanilha: TPlanilhaEntradaTFOControl;
FEntregas: TEntregasControl;
FVerbas: TVerbasExpressasControl;
FBases: TBasesControl;
FEntregadores: TEntregadoresExpressasControl;
protected
procedure Execute; override;
procedure UpdateLOG(sMensagem: string);
procedure UpdateProgress(dPosition: Double);
procedure BeginProcesso;
procedure TerminateProcess;
public
FFile: String;
iCodigoCliente: Integer;
bCancel : Boolean;
bProcess: Boolean;
dPositionRegister: double;
sLog: String;
sAlerta: String;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TThread_ImportarPedidosTFO.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
uses Common.ENum, Global.Parametros;
{ TThread_ImportarPedidosTFO }
procedure TThread_ImportarPedidosTFO.BeginProcesso;
var
sMensagem: String;
begin
sLog := '';
bCancel := False;
Global.Parametros.pbProcess := True;
sMensagem := '';
sMensagem := '>> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' > iniciando importação do arquivo ' + FFile;
UpdateLog(sMensagem);
sMensagem := '>> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' > tratando os dados da planilha. Aguarde...';
UpdateLog(sMensagem);
end;
procedure TThread_ImportarPedidosTFO.Execute;
var
aParam: Array of variant;
iPos, iPosition, iTotal, iTabela, iFaixa, iAgente, iEntregador,i: Integer;
sCEP, sMensagem: String;
dPos, dPerformance, dVerba, dVerbaTabela: double;
slParam: TStringList;
bProcess: Boolean;
begin
try
try
Synchronize(BeginProcesso);
FPlanilha := TPlanilhaEntradaTFOControl.Create;
FEntregas := TEntregasControl.Create;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importando os dados. Aguarde...';
UpdateLog(sMensagem);
if FPLanilha.GetPlanilha(FFile) then
begin
iPos := 0;
iPosition := 0;
dPos := 0;
iTotal := FPlanilha.Planilha.Planilha.Count;
for i := 0 to Pred(iTotal) do
begin
SetLength(aParam,3);
aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].NossoNumero, icodigoCliente];
if not FEntregas.LocalizarExata(aParam) then
begin
FEntregas.Entregas.NN := FPlanilha.Planilha.Planilha[i].NossoNumero;
FEntregas.Entregas.Distribuidor := 0;
FEntregas.Entregas.Entregador := 0;
FEntregas.Entregas.Cliente := StrToIntDef(FPlanilha.Planilha.Planilha[i].CodigoCliente,0);
FEntregas.Entregas.NF := FPlanilha.Planilha.Planilha[i].NumeroNF;
FEntregas.Entregas.Consumidor := FPlanilha.Planilha.Planilha[i].NomeConsumidor;
FEntregas.Entregas.Endereco := FPlanilha.Planilha.Planilha[i].Logradouro;
FEntregas.Entregas.Complemento := Copy(FPlanilha.Planilha.Planilha[i].Complemento + ' - ' +
FPlanilha.Planilha.Planilha[i].AosCuidados,1,70);
FEntregas.Entregas.Bairro := FPlanilha.Planilha.Planilha[i].Bairro;
FEntregas.Entregas.Cidade := FPlanilha.Planilha.Planilha[i].Cidade;
FEntregas.Entregas.Cep := FPlanilha.Planilha.Planilha[i].CEP;
FEntregas.Entregas.Telefone := Copy(FPlanilha.Planilha.Planilha[i].Telefone,1,30);
FEntregas.Entregas.Expedicao := StrToDateDef(FPlanilha.Planilha.Planilha[i].Expedicao, StrToDate('30/12/1899'));
FEntregas.Entregas.Previsao := StrToDateDef(FPlanilha.Planilha.Planilha[i].Previsao, StrToDate('30/12/1899'));
FEntregas.Entregas.Volumes := StrToIntDef(FPlanilha.Planilha.Planilha[i].Volume,1);
FEntregas.Entregas.Atribuicao := StrToDate('30/12/1899');
FEntregas.Entregas.Baixa := StrToDate('30/12/1899');
FEntregas.Entregas.Baixado := 'N';
FEntregas.Entregas.Pagamento := StrToDate('30/12/1899');
FEntregas.Entregas.Pago := 'N';
FEntregas.Entregas.Fechado := 'N';
FEntregas.Entregas.Status := StrToIntDef(FPlanilha.Planilha.Planilha[I].Status,0);
FEntregas.Entregas.Entrega := StrToDate('30/12/1899');
FPlanilha.Planilha.Planilha[I].Peso := ReplaceStr(FPlanilha.Planilha.Planilha[I].Peso, ' KG', '');
FPlanilha.Planilha.Planilha[I].Peso := ReplaceStr(FPlanilha.Planilha.Planilha[I].Peso, '.', ',');
FEntregas.Entregas.PesoReal := StrToFloatDef(FPlanilha.Planilha.Planilha[I].Peso,0);
FEntregas.Entregas.TipoPeso := 'Entrega';
FEntregas.Entregas.PesoFranquia := 0;
FEntregas.Entregas.Advalorem := 0;
FEntregas.Entregas.PagoFranquia := 0;
FEntregas.Entregas.VerbaEntregador := 0;
FEntregas.Entregas.Extrato := '0';
FEntregas.Entregas.Atraso := 0;
FEntregas.Entregas.VolumesExtra := 0;
FEntregas.Entregas.ValorVolumes := 0;
FEntregas.Entregas.PesoCobrado := 0;
FEntregas.Entregas.Recebimento := StrToDate('30/12/1899');
FEntregas.Entregas.Recebido := 'N';
FEntregas.Entregas.CTRC := 0;
FEntregas.Entregas.Manifesto := 0;
FEntregas.Entregas.Rastreio := '';
FPlanilha.Planilha.Planilha[I].ValorVerba := ReplaceStr(FPlanilha.Planilha.Planilha[I].ValorVerba, 'R$ ', '');
FEntregas.Entregas.VerbaFranquia := StrToFloatDef(FPlanilha.Planilha.Planilha[I].ValorVerba, 0);
FEntregas.Entregas.Lote := 0;
FEntregas.Entregas.Retorno := '';
FEntregas.Entregas.Credito := StrToDate('30/12/1899');;
FEntregas.Entregas.Creditado := 'N';
FEntregas.Entregas.Container :=FPlanilha.Planilha.Planilha[I].Container;
FPlanilha.Planilha.Planilha[I].ValorProuto := ReplaceStr(FPlanilha.Planilha.Planilha[I].ValorProuto, 'R$ ', '');
FPlanilha.Planilha.Planilha[I].ValorProuto := ReplaceStr(FPlanilha.Planilha.Planilha[I].ValorProuto, '.', '');
FEntregas.Entregas.ValorProduto := StrToFloatDef(FPlanilha.Planilha.Planilha[i].ValorProuto, 0);
FEntregas.Entregas.Altura := StrToIntDef(FPlanilha.Planilha.Planilha[I].Altura, 0);
FEntregas.Entregas.Largura := StrToIntDef(FPlanilha.Planilha.Planilha[I].Largura, 0);;
FEntregas.Entregas.Comprimento := StrToIntDef(FPlanilha.Planilha.Planilha[I].Comprimento, 0);;
FEntregas.Entregas.CodigoFeedback := 0;
FEntregas.Entregas.DataFeedback := StrToDate('30/12/1899');
FEntregas.Entregas.Conferido := 0;
FEntregas.Entregas.Pedido := '0';;
FEntregas.Entregas.CodCliente := iCodigoCliente;
FEntregas.Entregas.Acao := tacIncluir;
end
else
begin
FEntregas.Entregas.Status := 909;
FEntregas.Entregas.Rastreio := FEntregas.Entregas.Rastreio + #13 +
'> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' atualizado por importação por ' +
Global.Parametros.pUser_Name;
FEntregas.Entregas.Acao := tacAlterar;
end;
if not FEntregas.Gravar() then
begin
sMensagem := 'Erro ao gravar o NN ' + Fentregas.Entregas.NN + ' !';
UpdateLog(sMensagem);
end;
inc(iPos, 1);
dPos := (iPos / iTotal) * 100;
if not(Self.Terminated) then
begin
UpdateProgress(dPos);
end
else
begin
Abort;
end;
end;
Synchronize(TerminateProcess);
end;
Except on E: Exception do
begin
sMensagem := '** ERROR **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message;
UpdateLog(sMensagem);
bCancel := True;
end;
end;
finally
FPlanilha.Free;
FEntregas.Free;
end;
end;
procedure TThread_ImportarPedidosTFO.TerminateProcess;
begin
Global.Parametros.pbProcess := False;
end;
procedure TThread_ImportarPedidosTFO.UpdateLOG(sMensagem: string);
begin
if Global.Parametros.psLog <> '' then
begin
Global.Parametros.psLog := Global.Parametros.psLog + #13;
end;
Global.Parametros.psLog := Global.Parametros.psLog + sMensagem;
end;
procedure TThread_ImportarPedidosTFO.UpdateProgress(dPosition: Double);
begin
Global.Parametros.pdPos := dPosition;
end;
end.
|
unit ATxTotalCmd;
interface
function TCDefExe: string; //Path to Total Commander's executable (Totalcmd.exe)
function TCDefIni: string; //Path to TC's config file (named wincmd.ini by default)
function TCDefIniFTP: string; //Path to TC's FTP config file (named wcx_ftp.ini by default)
procedure SetTcIniFilename(const fn: string);
function GetTcIniKey(const section, key: string): string;
procedure SetTcIniKey(const section, key: string; const value: string);
implementation
uses
Windows, SysUtils, IniFiles,
ATxSProc, ATxRegistry, ATxUtils;
var
FIniFile: TIniFile = nil;
procedure SetTcIniFilename(const fn: string);
begin
if Assigned(FIniFile) then
FreeAndNil(FIniFile);
FIniFile:= TIniFile.Create(fn);
end;
function tcDefDir: string;
begin
Result:= SExpandVars('%COMMANDER_PATH%');
if SExpanded(Result) then Exit;
Result:=
GetRegKeyStr(HKEY_CURRENT_USER, 'Software\Ghisler\Total Commander', 'InstallDir',
GetRegKeyStr(HKEY_LOCAL_MACHINE, 'Software\Ghisler\Total Commander', 'InstallDir', ''));
end;
function tcDefExe: string;
begin
Result:= tcDefDir;
if Result<>'' then
Result:= Result + '\Totalcmd.exe';
end;
function tcDefIni: string;
begin
Result:= SExpandVars('%COMMANDER_INI%');
if SExpanded(Result) then Exit;
Result:=
GetRegKeyStr(HKEY_CURRENT_USER, 'SOFTWARE\Ghisler\Total Commander', 'IniFileName',
GetRegKeyStr(HKEY_LOCAL_MACHINE, 'SOFTWARE\Ghisler\Total Commander', 'IniFileName',
''));
if Result='' then Exit;
if Pos('\', Result)=0 then
Insert('%windir%\', Result, 1);
if Pos('.\', Result)=1 then
SReplace(Result, '.', tcDefDir);
Result:= SExpandVars(Result);
end;
function tcDefIniFtp: string;
begin
Result:=
GetRegKeyStr(HKEY_CURRENT_USER, 'SOFTWARE\Ghisler\Total Commander', 'FtpIniName',
GetRegKeyStr(HKEY_LOCAL_MACHINE, 'SOFTWARE\Ghisler\Total Commander', 'FtpIniName',
''));
if Result='' then Exit;
if Pos('\', Result)=0 then
Insert('%windir%\', Result, 1);
if Pos('.\', Result)=1 then
SReplace(Result, '.', tcDefDir);
Result:= SExpandVars(Result);
end;
//----------------------------------------------------------------------------
function ActualFileName(const section: string): string;
var
S: string;
begin
Result:= FIniFile.FileName;
S:= SExpandVars(FIniFile.ReadString(section, 'RedirectSection', ''));
if (S='') or (S='0') then
Exit;
if (S='1') then
Result:= SExpandVars(FIniFile.ReadString('Configuration', 'AlternateUserIni', Result))
else
Result:= S;
if Pos('\', Result)=0 then
Result:= ExtractFilePath(FIniFile.FileName) + Result;
end;
function GetTcIniKey(const section, key: string): string;
var
FN: string;
begin
FN:= ActualFileName(section);
if FN = FIniFile.FileName then
Result:= FIniFile.ReadString(section, key, '')
else
with TIniFile.Create(FN) do
try
Result:= ReadString(section, key, '');
finally
Free;
end;
end;
procedure SetTcIniKey(const section, key: string; const value: string);
var
FN: string;
begin
FN:= ActualFileName(section);
if FN = FIniFile.FileName then
FIniFile.WriteString(section, key, value)
else
with TIniFile.Create(FN) do
try
WriteString(section, key, value);
finally
Free;
end;
end;
initialization
finalization
if Assigned(FIniFile) then
FreeAndNil(FIniFile);
end.
|
unit utools;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
function stringToBoolean(p_string: string): boolean;
implementation
function stringToBoolean(p_string: string): boolean;
begin
IF (p_string='Y') OR (p_string='TRUE') THEN result := TRUE;
IF (p_string='N') OR (p_string='FALSE') OR (p_string='') THEN result := FALSE;
end;
end.
|
unit CabinetUtils;
interface
uses
Windows, SysUtils, Classes;
type
TFDIError = integer;
const
FDIERROR_NONE = 0;
FDIERROR_CABINET_NOT_FOUND = 1;
FDIERROR_NOT_A_CABINET = 2;
FDIERROR_UNKNOWN_CABINET_VERSION = 3;
FDIERROR_CORRUPT_CABINET = 4;
FDIERROR_ALLOC_FAIL = 5;
FDIERROR_BAD_COMPR_TYPE = 6;
FDIERROR_MDI_FAIL = 7;
FDIERROR_TARGET_FILE = 8;
FDIERROR_RESERVE_MISMATCH = 9;
FDIERROR_WRONG_CABINET = 10;
FDIERROR_USER_ABORT = 11;
type
TFDInotificationType = ( fdintCABINET_INFO, fdintPARTIAL_FILE, fdintCOPY_FILE, fdintCLOSE_FILE_INFO, fdintNEXT_CABINET, fdintPROGRESS );
type
TFDINotification =
packed record
cb : longint;
psz1 : pchar;
psz2 : pchar;
psz3 : pchar; // Points to a 256 character buffer
pv : pointer; // Value for client
hf : integer;
date : SHORT;
time : SHORT;
attribs : SHORT;
setID : SHORT; // Cabinet set ID
iCabinet : SHORT; // Cabinet number (0-based)
fdie : TFDIError;
end;
type
TDecompressNotifier = function( UserId : pointer; fdint : TFDInotificationType; var pfdin : TFDINotification ) : integer; stdcall;
function DecompressCabFiles( CabFile : pchar; DestDir : pchar; UserData : pointer; Notifier : TDecompressNotifier ) : BOOL; stdcall;
function SetupIterateCabinetA( CabinetFile : pchar; Reserved : dword; MsgHandler, Context : pointer ) : BOOL; stdcall;
type
TDescompressNotifyCommand = (dncCopyFile, dncCopyProgress, dncCloseFile);
PNotifyDescompressProc = ^TNotifyDescompressProc;
TNotifyDescompressProc = function(command : TDescompressNotifyCommand; text : string; value : integer) : boolean of object;
function DecompressFile(filePath, destPath : string; NotifyProc : TNotifyDescompressProc) : boolean;
const
SPFILENOTIFY_CABINETINFO = $10;
SPFILENOTIFY_FILEINCABINET = $11;
SPFILENOTIFY_NEEDNEWCABINET = $12;
SPFILENOTIFY_FILEEXTRACTED = $13;
FILEOP_ABORT = 0;
FILEOP_DOIT = 1;
FILEOP_SKIP = 2;
FILEOP_RETRY = FILEOP_DOIT;
FILEOP_NEWPATH = 4;
type
PFileInCabinetInfo = ^TFileInCabinetInfo;
TFileInCabinetInfo =
packed record
NameInCabinet : pchar;
FileSize : dword;
Win32Error : dword;
DosDate : short;
DosTime : short;
DosAttribs : short;
FullTargetName : array[0..MAX_PATH-1] of char;
end;
PNotifyListCabFileProc = ^TNotifyListCabFileProc;
TNotifyListCabFileProc = procedure(cabfile : pchar; Info : PFileInCabinetInfo) of object;
function ListCabFile(filePath : string; NotifyProc : TNotifyListCabFileProc) : boolean;
const
CabDllName = 'CABS.DLL';
implementation
uses
Fdi;
// function DecompressCabFiles( CabFile : pchar; DestDir : pchar; UserData : pointer; Notifier : TDecompressNotifier ) : BOOL; stdcall; external CabDllName;
function SetupIterateCabinetA(CabinetFile : pchar; Reserved : dword; MsgHandler, Context : pointer) : BOOL; stdcall; external 'setupapi.dll';
function DecompressNotify( UserId : pointer; fdint : TFDINotificationType; var pfdin : TFDINotification ) : integer; stdcall;
var
Notify : TNotifyDescompressProc;
begin
TMethod(Notify) := TMethod(UserId^);
case fdint of
fdintCOPY_FILE:
begin
if Notify(dncCopyFile, pfdin.psz1, 0)
then Result := 0
else Result := -1;
end;
fdintNEXT_CABINET : Result := -1; //abort
fdintPROGRESS :
begin
if Notify(dncCopyProgress, '', pfdin.cb)
then Result := 0
else Result := -1;
end;
fdintCLOSE_FILE_INFO :
begin
if Notify(dncCloseFile, '', 0)
then Result := 0
else Result := -1;
end;
else Result := 0;
end;
end;
function DecompressFile(filePath, destPath : string; NotifyProc : TNotifyDescompressProc) : boolean;
var
Method : TMethod;
begin
Method := TMethod(NotifyProc);
result := DecompressCabFiles(pchar(filePath), pchar(destPath), @Method, DecompressNotify);
end;
function ListCabNotify(content : pointer; notification, param1, param2 : integer) : integer; stdcall;
var
Notify : TNotifyListCabFileProc;
begin
TMethod(Notify) := TMethod(content^);
case notification of
SPFILENOTIFY_FILEINCABINET :
begin
Notify(pchar(param2), PFileInCabinetInfo(param1));
result := FILEOP_SKIP;
end
else result := FILEOP_ABORT;
end;
end;
function ListCabFile(filePath : string; NotifyProc : TNotifyListCabFileProc) : boolean;
var
Method : TMethod;
begin
Method := TMethod(NotifyProc);
result := SetupIterateCabinetA(pchar(filePath), 0, @ListCabNotify, @Method);
end;
{
function DecompressCabNotify(content : pointer; notification, param1, param2 : integer) : integer; stdcall;
var
path : pchar absolute content;
Info : PFileInCabinetInfo absolute param1;
trg : string;
begin
case notification of
SPFILENOTIFY_FILEINCABINET :
begin
trg := path;
trg := trg + Info.NameInCabinet;
StrCopy(Info.FullTargetName, pchar(trg));
result := FILEOP_DOIT;
end
else result := FILEOP_ABORT;
end;
end;
}
function DecompressCabFiles( CabFile : pchar; DestDir : pchar; UserData : pointer; Notifier : TDecompressNotifier ) : BOOL;
var
begin
end;
end.
|
unit MVCBr.DesignEditors.Helper;
interface
uses System.Classes, DesignIntf, DesignEditors;
type
TMVCBrBaseComponentEditor = class(TComponentEditor)
strict private
FOldEditor: IComponentEditor;
function GetVerbCount: integer; override;
function GetVerb(Index: integer): string; override;
procedure ExecuteVerb(Index: integer); override;
protected
function GetLinkToTypeClass: TComponentClass; virtual; abstract;
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
destructor Destroy; override;
function LocalGetVerb(AIndex: integer): string; virtual;
function LocalGetVerbCount: integer; virtual;
procedure LocalExecuteVerb(AIndex: integer); virtual;
end;
procedure MVCBrDebugLogEditor(ATexto: string);
implementation
uses WinApi.Windows;
procedure MVCBrDebugLogEditor(ATexto: string);
begin
OutputDebugString({$IFDEF UNICODE}PWideChar{$ELSE}PAnsiChar{$ENDIF}(ATexto));
end;
{ TRestSocialBaseEditor }
VAR
PrevEditorClass: TComponentEditorClass = NIL;
constructor TMVCBrBaseComponentEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
var
cmp: TComponent;
Editor: IComponentEditor;
begin
inherited;
cmp := GetLinkToTypeClass.Create(nil);
try
Editor := GetComponentEditor(cmp, NIL);
IF Assigned(Editor) THEN
BEGIN
PrevEditorClass := TComponentEditorClass((Editor AS TObject).ClassType);
END;
IF Assigned(PrevEditorClass) THEN
FOldEditor := TComponentEditor(PrevEditorClass.Create(AComponent, ADesigner));
finally
Editor := NIL;
cmp.Free;
end;
end;
destructor TMVCBrBaseComponentEditor.Destroy;
begin
inherited;
end;
procedure TMVCBrBaseComponentEditor.ExecuteVerb(Index: integer);
var
idx: integer;
begin
// DebugLog('ExecuteVerb: ' + intTostr(index));
if index < FOldEditor.GetVerbCount then
begin
FOldEditor.ExecuteVerb(index)
end
else
begin
idx := index - FOldEditor.GetVerbCount;
LocalExecuteVerb(idx);
end;
end;
function TMVCBrBaseComponentEditor.GetVerb(Index: integer): string;
var
idx: integer;
begin
// DebugLog('GetVerb: ' + intTostr(index));
if index < FOldEditor.GetVerbCount then
result := FOldEditor.GetVerb(index)
else
begin
idx := index - FOldEditor.GetVerbCount;
result := LocalGetVerb(idx);
end;
end;
function TMVCBrBaseComponentEditor.GetVerbCount: integer;
begin
result := FOldEditor.GetVerbCount + LocalGetVerbCount;
// DebugLogEditor('GetVerbCount: ' + intTostr(result));
end;
procedure TMVCBrBaseComponentEditor.LocalExecuteVerb(AIndex: integer);
begin
end;
function TMVCBrBaseComponentEditor.LocalGetVerb(AIndex: integer): string;
begin
result := '';
end;
function TMVCBrBaseComponentEditor.LocalGetVerbCount: integer;
begin
result := 0;
end;
end.
|
unit CriminalRosterViewer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
VoyagerInterfaces, VoyagerServerInterfaces,
StdCtrls, ExtCtrls, FramedButton, CriminalViewer, CrimeMainViewer,
InternationalizerComponent;
const
ActiveSlots = 4;
SocketColor = $00343924;
type
TCriminalRosterView = class(TForm)
Slot1: TPanel;
Panel22: TPanel;
Img1: TImage;
Label11: TLabel;
Slot2: TPanel;
Panel5: TPanel;
Img2: TImage;
Slot3: TPanel;
Panel4: TPanel;
Img3: TImage;
btPrev: TFramedButton;
btMore: TFramedButton;
btHire: TFramedButton;
Slot4: TPanel;
Panel6: TPanel;
Img4: TImage;
CloseBtn: TFramedButton;
InternationalizerComponent1: TInternationalizerComponent;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SlotClick(Sender: TObject);
procedure btMoreClick(Sender: TObject);
procedure btPrevClick(Sender: TObject);
procedure btHireClick(Sender: TObject);
procedure CloseBtnClick(Sender: TObject);
private
fClientView : IClientView;
fMasterURLHandler : IMasterURLHandler;
fIllSystem : olevariant;
fLeader : TStringList;
fTeam : TStringList;
fOnTeamModified : TOnTeamModified;
fCriminals : TStringList;
fOffset : integer;
fCache : string;
private
fImgs : array[0..ActiveSlots - 1] of TImage;
fSlots : array[0..ActiveSlots - 1] of TPanel;
fActSlot : integer;
public
property ClientView : IClientView write fClientView;
property MasterURLHandler : IMasterURLHandler write fMasterURLHandler;
property IllSystem : olevariant write fIllSystem;
property Leader : TStringList write fLeader;
property Team : TStringList write fTeam;
property OnTeamModified : TOnTeamModified write fOnTeamModified;
private
procedure threadedGetCriminals( const parms : array of const );
procedure syncAddCriminal( const parms : array of const );
procedure threadedHireCriminal( const parms : array of const );
procedure syncHireCriminal( const parms : array of const );
private
procedure RenderSlots;
end;
var
CriminalRosterView: TCriminalRosterView;
implementation
{$R *.DFM}
uses
Threads, Events, JPGtoBMP, CrimeProtocol;
procedure TCriminalRosterView.FormShow(Sender: TObject);
var
i : integer;
begin
if fCriminals <> nil
then
begin
for i := 0 to pred(fCriminals.Count) do
fCriminals.Objects[i].Free;
fCriminals.Free;
end;
fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, fCache );
fCriminals := TStringList.Create;
Fork( threadedGetCriminals, priNormal, [fLeader.Values['Name']] );
end;
procedure TCriminalRosterView.threadedGetCriminals( const parms : array of const );
var
name : string absolute parms[0].vPchar;
CriminalList : TStringList;
CriminalProp : TStringList;
i : integer;
begin
CriminalList := TStringList.Create;
try
CriminalList.Text := fIllSystem.RDOGetCriminalNames( name );
for i := 0 to pred(CriminalList.Count) do
begin
CriminalProp := TStringList.Create;
try
CriminalProp.Text := fIllSystem.RDOFindCriminal( CriminalList.Values[IntToStr(i + 1)] );
Join( syncAddCriminal, [CriminalProp] );
except
CriminalProp.Free;
end;
end;
Join( syncAddCriminal, [nil] );
finally
CriminalList.Free;
end;
end;
procedure TCriminalRosterView.syncAddCriminal( const parms : array of const );
var
PropList : TStringList absolute parms[0].vPointer;
idx : integer;
begin
try
if PropList <> nil
then
begin
fCriminals.AddObject( PropList.Values['Name'], PropList );
if (fCriminals.Count - fOffset <= ActiveSlots) and (fCriminals.Count - fOffset > 0)
then
try
idx := fCriminals.Count - fOffset - 1;
fImgs[idx].Picture.Bitmap := TBitmap.Create;
fImgs[idx].Picture.Bitmap.PixelFormat := pf24bit;
fImgs[idx].Picture.Bitmap.Width := fImgs[idx].Width;
fImgs[idx].Picture.Bitmap.Height := fImgs[idx].Height;
LoadJPGToBMP( fCache + tidPath_IBImages + PropList.Values['Picture'] + '.jpg', fImgs[idx].Picture.Bitmap );
//TVFilter( fImgs[idx].Picture.Bitmap );
fSlots[idx].Enabled := true;
except
end;
btPrev.Enabled := fOffset > 0;
btMore.Enabled := fOffset + ActiveSlots < fCriminals.Count;
end
else
begin
for idx := fCriminals.Count - fOffset to ActiveSlots - 1 do
begin
fImgs[idx].Picture.Bitmap := TBitmap.Create;
fImgs[idx].Picture.Bitmap.PixelFormat := pf24bit;
fImgs[idx].Picture.Bitmap.Width := fImgs[idx].Width;
fImgs[idx].Picture.Bitmap.Height := fImgs[idx].Height;
LoadJPGToBMP( fCache + tidPath_IBImages + 'notavail.jpg', fImgs[idx].Picture.Bitmap );
//TVFilter( fImgs[idx].Picture.Bitmap );
fSlots[idx].Enabled := false;
end;
end;
except
end;
end;
procedure TCriminalRosterView.threadedHireCriminal( const parms : array of const );
var
name : string absolute parms[0].vPChar;
leader : string;
team : string;
ErrorCode : TErrorCode;
begin
try
leader := parms[1].vPChar;
team := parms[2].vPChar;
ErrorCode := fIllSystem.RDOHireCriminal( leader, team, name, 100 );
Join( syncHireCriminal, [name, ErrorCode] );
except
end;
end;
procedure TCriminalRosterView.syncHireCriminal( const parms : array of const );
begin
if assigned(fOnTeamModified)
then fOnTeamModified;
Close;
end;
procedure TCriminalRosterView.FormCreate(Sender: TObject);
begin
fImgs[0] := Img1;
fImgs[1] := Img2;
fImgs[2] := Img3;
fImgs[3] := Img4;
fSlots[0] := Slot1;
fSlots[1] := Slot2;
fSlots[2] := Slot3;
fSlots[3] := Slot4;
fActSlot := -1;
end;
procedure TCriminalRosterView.SlotClick(Sender: TObject);
var
idx : integer;
begin
idx := TComponent(Sender).Tag;
if (idx <> fActSlot) and fSlots[idx].Enabled
then
begin
if fActSlot <> -1
then fSlots[fActSlot].Color := SocketColor;
fSlots[idx].Color := clLime;
fActSlot := idx;
CriminalView.ClientView := fClientView;
CriminalView.MasterURLHandler := fMasterURLHandler;
CriminalView.IllSystem := fIllSystem;
CriminalView.TeamMember := false;
CriminalView.Properties := TStringList(fCriminals.Objects[fOffset + idx]);
CriminalView.Show;
end;
end;
procedure TCriminalRosterView.RenderSlots;
var
i : integer;
idx : integer;
begin
for i := 0 to pred(ActiveSlots) do
if i + fOffset < fCriminals.Count
then
begin
idx := i + fOffset;
fImgs[i].Picture.Bitmap := TBitmap.Create;
fImgs[i].Picture.Bitmap.PixelFormat := pf24bit;
fImgs[i].Picture.Bitmap.Width := fImgs[i].Width;
fImgs[i].Picture.Bitmap.Height := fImgs[i].Height;
LoadJPGToBMP( fCache + tidPath_IBImages + TStringList(fCriminals.Objects[idx]).Values['Picture'] + '.jpg', fImgs[i].Picture.Bitmap );
fSlots[i].Enabled := true;
//TVFilter( fImgs[i].Picture.Bitmap );
end
else
begin
LoadJPGToBMP( fCache + tidPath_IBImages + 'notavail.jpg', fImgs[i].Picture.Bitmap );
fSlots[i].Enabled := false;
//TVFilter( fImgs[i].Picture.Bitmap );
end;
btPrev.Enabled := fOffset > 0;
btMore.Enabled := fOffset + ActiveSlots < fCriminals.Count;
end;
procedure TCriminalRosterView.btMoreClick(Sender: TObject);
begin
inc( fOffset );
fSlots[fActSlot].Color := SocketColor;
if fActSlot < ActiveSlots - 1
then inc( fActSlot )
else fActSlot := -1;
RenderSlots;
end;
procedure TCriminalRosterView.btPrevClick(Sender: TObject);
begin
dec( fOffset );
fSlots[fActSlot].Color := SocketColor;
if fActSlot > 0
then dec( fActSlot )
else fActSlot := -1;
RenderSlots;
end;
procedure TCriminalRosterView.btHireClick(Sender: TObject);
var
idx : integer;
begin
if fActSlot <> -1
then
begin
idx := fOffset + fActSlot;
Fork( threadedHireCriminal, priNormal, [TStringList(fCriminals.Objects[idx]).Values['Name'], fLeader.Values['Name'], fTeam.Values['Name']] );
end;
end;
procedure TCriminalRosterView.CloseBtnClick(Sender: TObject);
begin
Close;
end;
end.
|
unit uComponente;
interface
uses
Classes ;
type
TComponente = class;
TComponenteArray = array of TComponente;
TComponente = class(TObject)
private
FX: Integer;
FY: Integer;
FAltura: Integer;
FLargura: Integer;
FParent: TComponente;
procedure SetX(aX: Integer);
procedure SetY(aY: Integer);
procedure SetAltura(aAltura: Integer);
procedure SetLargura(aLargura: Integer);
protected
FComponentes: TComponenteArray;
procedure Reposicionar(aX, aY: Integer); virtual;
procedure Redimensionar(aAltura, aLargura: Integer); virtual;
public
property Parent: TComponente read FParent write FParent;
property X: Integer read FX write SetX;
property Y: Integer read FY write SetY;
property Altura: Integer read FAltura write SetAltura;
property Largura: Integer read FLargura write SetLargura;
constructor Create;
procedure AdicionaComponente(aComponente: TComponente); virtual; abstract;
procedure RemoveComponente(aComponente: TComponente); virtual; abstract;
end;
implementation
{ TComponente }
constructor TComponente.Create;
begin
FAltura := 1;
FLargura := 1;
end;
procedure TComponente.SetAltura(aAltura: Integer);
var
I: Integer;
begin
for I := Low(FComponentes) to High(FComponentes) do
FComponentes[I].Redimensionar(aAltura, FLargura);
FAltura := aAltura;
end;
procedure TComponente.SetLargura(aLargura: Integer);
var
I: Integer;
begin
for I := Low(FComponentes) to High(FComponentes) do
FComponentes[I].Redimensionar(FAltura, aLargura);
FLargura := aLargura;
end;
procedure TComponente.SetX(aX: Integer);
var
I: Integer;
begin
for I := Low(FComponentes) to High(FComponentes) do
FComponentes[I].Reposicionar(aX, FY);
FX := aX;
end;
procedure TComponente.SetY(aY: Integer);
var
I: Integer;
begin
for I := Low(FComponentes) to High(FComponentes) do
FComponentes[I].Reposicionar(FX, aY);
FY := aY;
end;
procedure TComponente.Redimensionar(aAltura, aLargura: Integer);
begin
// TO-DO: Fire related event
end;
procedure TComponente.Reposicionar(aX, aY: Integer);
begin
// TO-DO: Fire related event
end;
end.
|
{$MODE OBJFPC}
program ElimitingWater;
const
InputFile = 'CWATER.INP';
OutputFile = 'CWATER.OUT';
var
fi, fo: TextFile;
a, b, c, d, x, y, res: Int64;
procedure Solve;
var
m, n, r, q, xm, xn, xr, t: Integer;
begin
if a < b then
begin
t := a; a := b; b := t;
end;
m := a; xm := 1;
n := b; xn := 0;
while n <> 0 do
begin
q := m div n;
r := m mod n;
xr := xm - q * xn;
m := n; xm := xn;
n := r; xn := xr;
end;
d := m;
x := xm;
y := (d - a * xm) div b;
end;
procedure Eliminate;
var
t: Int64;
ap, bp, cp: Int64;
begin
if c mod d <> 0 then
begin
res := -1;
Exit;
end;
ap := a div d; bp := b div d; cp := c div d;
x := x * cp; y := y * cp;
//ax + by = c, a(x + bp) + b(y - ap) = c, ...
y := (y mod ap + ap) mod ap;
x := (c - b * y) div a;
//ax + by = c, y >= 0;
if (Abs(x) + Abs(y)) < Abs(x + bp) + Abs(y - ap) then
res := Abs(x) + Abs(y)
else
res := Abs(x + bp) + Abs(y - ap);
end;
procedure SolveAll;
var
ntest, itest: Integer;
begin
ReadLn(fi, ntest);
for itest := 1 to ntest do
begin
ReadLn(fi, a, b, c);
Solve;
Eliminate;
WriteLn(fo, res);
end;
end;
begin
AssignFile(fi, InputFile); Reset(fi);
AssignFile(fo, OutputFile); Rewrite(fo);
try
SolveAll;
finally
CloseFile(fi); CloseFile(fo);
end;
end.
|
unit DirIterator;
interface
uses
Windows, Classes, SysUtils;
const
onArchives = faArchive;
onFolders = faDirectory;
onBoth = onArchives or onFolders;
type
TIteratorOptions = integer;
TFolderIterator =
class
public
constructor Create(const aPath, TheWildCards : string; TheOptions : integer);
destructor Destroy; override;
private
fPath : string; // Absolute path
fWildCards : string; // *.?.* etc.
fCurrent : string; // Name of the current file or folder
fOptions : TIteratorOptions; // Kind of files to iterate on
fSearchRec : TSearchRec; // Search struct
fEmpty : boolean; // True if no file was found
public
procedure Reset;
function Next : boolean;
private
procedure SetOptions(Options : TIteratorOptions);
function GetFullPath : string;
public
property Options : TIteratorOptions read fOptions write SetOptions;
property Empty : boolean read fEmpty;
property Current : string read fCurrent;
property FullPath : string read GetFullPath;
end;
implementation
procedure CloseSearch(var Search : TSearchRec);
begin
if Search.FindHandle <> INVALID_HANDLE_VALUE
then
begin
FindClose(Search);
Search.FindHandle := INVALID_HANDLE_VALUE
end;
end;
// TFolderIterator
constructor TFolderIterator.Create(const aPath, TheWildCards : string; TheOptions : integer);
begin
inherited Create;
fWildCards := TheWildCards;
if aPath[length(aPath)] = '\'
then fPath := aPath
else fPath := aPath + '\';
fOptions := TheOptions;
fSearchRec.FindHandle := INVALID_HANDLE_VALUE; // Uuuf!!
Reset;
end;
destructor TFolderIterator.Destroy;
begin
CloseSearch(fSearchRec);
inherited;
end;
procedure TFolderIterator.Reset;
begin
CloseSearch(fSearchRec);
fEmpty := FindFirst(fPath + fWildCards, fOptions, fSearchRec) <> 0;
if not fEmpty
then
begin
fCurrent := fSearchRec.Name;
if (fCurrent = '.') or (fCurrent = '..')
then fEmpty := not Next;
end
else
begin
fCurrent := '';
CloseSearch(fSearchRec);
end;
end;
function TFolderIterator.Next : boolean;
begin
if FindNext(fSearchRec) = 0
then
begin
fCurrent := fSearchRec.Name;
if (fCurrent = '.') or (fCurrent = '..')
then result := Next
else result := true;
end
else
begin
fCurrent := '';
result := false;
end;
if not result
then CloseSearch(fSearchRec);
end;
procedure TFolderIterator.SetOptions(Options : TIteratorOptions);
begin
fOptions := Options;
Reset;
end;
function TFolderIterator.GetFullPath : string;
begin
if fSearchRec.Attr = onFolders
then result := fPath + fCurrent + '\'
else result := fPath + fCurrent;
end;
end.
|
unit nsQuestions;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\nsQuestions.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "nsQuestions" MUID: (4F9A9C6803D4)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
, l3StringIDEx
, l3MessageID
;
const
{* Локализуемые строки Asks }
str_DocumentEMailSelection_CheckCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_CheckCaption'; rValue : 'Всегда пересылать выделенный фрагмент');
{* 'Всегда пересылать выделенный фрагмент' }
str_DocumentEMailSelection_SettingsCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_SettingsCaption'; rValue : 'Пересылка по EMail');
{* 'Пересылка по EMail' }
str_DocumentEMailSelection_LongHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_LongHint'; rValue : 'Подтверждение при пересылке выделенного фрагмента');
{* 'Подтверждение при пересылке выделенного фрагмента' }
str_ListEMailSelection_CheckCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_CheckCaption'; rValue : 'Всегда пересылать выделенные элементы ');
{* 'Всегда пересылать выделенные элементы ' }
str_ListEMailSelection_SettingsCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_SettingsCaption'; rValue : 'Пересылка по EMail');
{* 'Пересылка по EMail' }
str_ListEMailSelection_LongHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_LongHint'; rValue : 'Подтверждение при пересылке выделенных элементов');
{* 'Подтверждение при пересылке выделенных элементов' }
str_ListPrintSelectedConfirmation_CheckCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_CheckCaption'; rValue : 'Всегда печатать выделенные элементы');
{* 'Всегда печатать выделенные элементы' }
str_ListPrintSelectedConfirmation_SettingsCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_SettingsCaption'; rValue : 'Печать');
{* 'Печать' }
str_ListPrintSelectedConfirmation_LongHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_LongHint'; rValue : 'Подтверждение при печати выделенных элементов');
{* 'Подтверждение при печати выделенных элементов' }
str_PrintSelectedConfirmation_CheckCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_CheckCaption'; rValue : 'Всегда печатать выделенный фрагмент');
{* 'Всегда печатать выделенный фрагмент' }
str_PrintSelectedConfirmation_SettingsCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_SettingsCaption'; rValue : 'Печать');
{* 'Печать' }
str_PrintSelectedConfirmation_LongHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_LongHint'; rValue : 'Подтверждение при печати выделенного фрагмента');
{* 'Подтверждение при печати выделенного фрагмента' }
str_ExportSelectionToWord_CheckCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_CheckCaption'; rValue : 'Всегда экспортировать выделенный фрагмент');
{* 'Всегда экспортировать выделенный фрагмент' }
str_ExportSelectionToWord_SettingsCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_SettingsCaption'; rValue : 'Экспорт в MS-Word');
{* 'Экспорт в MS-Word' }
str_ExportSelectionToWord_LongHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_LongHint'; rValue : 'Подтверждение при открытии в MS-Word выделенного фрагмента');
{* 'Подтверждение при открытии в MS-Word выделенного фрагмента' }
str_ListExportSelectionToWord_CheckCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_CheckCaption'; rValue : 'Всегда экспортировать выделенные элементы');
{* 'Всегда экспортировать выделенные элементы' }
str_ListExportSelectionToWord_SettingsCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_SettingsCaption'; rValue : 'Экспорт в MS-Word');
{* 'Экспорт в MS-Word' }
str_ListExportSelectionToWord_LongHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_LongHint'; rValue : 'Подтверждение при открытии в MS-Word выделенных элементов');
{* 'Подтверждение при открытии в MS-Word выделенных элементов' }
str_DocumentEMailSelection: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection'; rValue : 'Переслать по E-mail:');
{* 'Переслать по E-mail:' }
str_ListEMailSelection: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection'; rValue : 'Пересылка по EMail');
{* 'Пересылка по EMail' }
str_ListPrintSelectedConfirmation: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation'; rValue : 'Печатать:');
{* 'Печатать:' }
str_PrintSelectedConfirmation: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation'; rValue : 'Печатать:');
{* 'Печатать:' }
str_ExportSelectionToWord: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord'; rValue : 'Экспортировать в MS-Word');
{* 'Экспортировать в MS-Word' }
str_ListExportSelectionToWord: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord'; rValue : 'Экспортировать в MS-Word:');
{* 'Экспортировать в MS-Word:' }
str_ConsultDocumentsNotFound: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ConsultDocumentsNotFound'; rValue : 'Информация по данному запросу отсутствует в установленном у Вас комплекте.');
{* 'Информация по данному запросу отсутствует в установленном у Вас комплекте.' }
str_ConsultDocumentsNotFoundNoSpec: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ConsultDocumentsNotFoundNoSpec'; rValue : 'Информация по данному запросу отсутствует в установленном у Вас комплекте.');
{* 'Информация по данному запросу отсутствует в установленном у Вас комплекте.' }
implementation
uses
l3ImplUses
{$If NOT Defined(NoVCL)}
, Dialogs
{$IfEnd} // NOT Defined(NoVCL)
//#UC START# *4F9A9C6803D4impl_uses*
//#UC END# *4F9A9C6803D4impl_uses*
;
const
{* Варианты выбора для диалога DocumentEMailSelection }
str_DocumentEMailSelection_Choice_Selection: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_Choice_Selection'; rValue : 'Выделенный фрагмент');
{* 'Выделенный фрагмент' }
str_DocumentEMailSelection_Choice_WholeDocument: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_Choice_WholeDocument'; rValue : 'Документ целиком');
{* 'Документ целиком' }
{* Варианты выбора для диалога ListEMailSelection }
str_ListEMailSelection_Choice_Selected: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_Choice_Selected'; rValue : 'Выделенные элементы');
{* 'Выделенные элементы' }
str_ListEMailSelection_Choice_WholeList: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_Choice_WholeList'; rValue : 'Список целиком');
{* 'Список целиком' }
{* Варианты выбора для диалога ListPrintSelectedConfirmation }
str_ListPrintSelectedConfirmation_Choice_Selected: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_Choice_Selected'; rValue : 'Выделенные элементы');
{* 'Выделенные элементы' }
str_ListPrintSelectedConfirmation_Choice_WholeList: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_Choice_WholeList'; rValue : 'Список целиком');
{* 'Список целиком' }
{* Варианты выбора для диалога PrintSelectedConfirmation }
str_PrintSelectedConfirmation_Choice_Selected: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_Choice_Selected'; rValue : 'Выделенный фрагмент');
{* 'Выделенный фрагмент' }
str_PrintSelectedConfirmation_Choice_WholeDocument: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_Choice_WholeDocument'; rValue : 'Документ целиком');
{* 'Документ целиком' }
{* Варианты выбора для диалога ExportSelectionToWord }
str_ExportSelectionToWord_Choice_Selected: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_Choice_Selected'; rValue : 'Выделенный фрагмент');
{* 'Выделенный фрагмент' }
str_ExportSelectionToWord_Choice_WholeDocument: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_Choice_WholeDocument'; rValue : 'Документ целиком');
{* 'Документ целиком' }
{* Варианты выбора для диалога ListExportSelectionToWord }
str_ListExportSelectionToWord_Choice_Selected: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_Choice_Selected'; rValue : 'Выделенные элементы');
{* 'Выделенные элементы' }
str_ListExportSelectionToWord_Choice_WholeList: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_Choice_WholeList'; rValue : 'Список целиком');
{* 'Список целиком' }
{* Варианты выбора для диалога ConsultDocumentsNotFound }
str_ConsultDocumentsNotFound_Choice_Spec: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ConsultDocumentsNotFound_Choice_Spec'; rValue : 'Обратиться к специалистам Правовой поддержки онлайн');
{* 'Обратиться к специалистам Правовой поддержки онлайн' }
str_ConsultDocumentsNotFound_Choice_Back: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ConsultDocumentsNotFound_Choice_Back'; rValue : 'Вернуться в карточку и изменить условия запроса');
{* 'Вернуться в карточку и изменить условия запроса' }
{* Варианты выбора для диалога ConsultDocumentsNotFoundNoSpec }
str_ConsultDocumentsNotFoundNoSpec_Choice_Back: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ConsultDocumentsNotFoundNoSpec_Choice_Back'; rValue : 'Вернуться в карточку и изменить условия запроса');
{* 'Вернуться в карточку и изменить условия запроса' }
initialization
str_DocumentEMailSelection_CheckCaption.Init;
{* Инициализация str_DocumentEMailSelection_CheckCaption }
str_DocumentEMailSelection_SettingsCaption.Init;
{* Инициализация str_DocumentEMailSelection_SettingsCaption }
str_DocumentEMailSelection_LongHint.Init;
{* Инициализация str_DocumentEMailSelection_LongHint }
str_ListEMailSelection_CheckCaption.Init;
{* Инициализация str_ListEMailSelection_CheckCaption }
str_ListEMailSelection_SettingsCaption.Init;
{* Инициализация str_ListEMailSelection_SettingsCaption }
str_ListEMailSelection_LongHint.Init;
{* Инициализация str_ListEMailSelection_LongHint }
str_ListPrintSelectedConfirmation_CheckCaption.Init;
{* Инициализация str_ListPrintSelectedConfirmation_CheckCaption }
str_ListPrintSelectedConfirmation_SettingsCaption.Init;
{* Инициализация str_ListPrintSelectedConfirmation_SettingsCaption }
str_ListPrintSelectedConfirmation_LongHint.Init;
{* Инициализация str_ListPrintSelectedConfirmation_LongHint }
str_PrintSelectedConfirmation_CheckCaption.Init;
{* Инициализация str_PrintSelectedConfirmation_CheckCaption }
str_PrintSelectedConfirmation_SettingsCaption.Init;
{* Инициализация str_PrintSelectedConfirmation_SettingsCaption }
str_PrintSelectedConfirmation_LongHint.Init;
{* Инициализация str_PrintSelectedConfirmation_LongHint }
str_ExportSelectionToWord_CheckCaption.Init;
{* Инициализация str_ExportSelectionToWord_CheckCaption }
str_ExportSelectionToWord_SettingsCaption.Init;
{* Инициализация str_ExportSelectionToWord_SettingsCaption }
str_ExportSelectionToWord_LongHint.Init;
{* Инициализация str_ExportSelectionToWord_LongHint }
str_ListExportSelectionToWord_CheckCaption.Init;
{* Инициализация str_ListExportSelectionToWord_CheckCaption }
str_ListExportSelectionToWord_SettingsCaption.Init;
{* Инициализация str_ListExportSelectionToWord_SettingsCaption }
str_ListExportSelectionToWord_LongHint.Init;
{* Инициализация str_ListExportSelectionToWord_LongHint }
str_DocumentEMailSelection.Init;
str_DocumentEMailSelection.AddChoice(str_DocumentEMailSelection_Choice_Selection);
str_DocumentEMailSelection.AddChoice(str_DocumentEMailSelection_Choice_WholeDocument);
str_DocumentEMailSelection.AddDefaultChoice(str_DocumentEMailSelection_Choice_Selection);
str_DocumentEMailSelection.SetNeedCheck(true);
str_DocumentEMailSelection.SetCheckCaption(str_DocumentEMailSelection_CheckCaption);
str_DocumentEMailSelection.SetSettingsCaption(str_DocumentEMailSelection_SettingsCaption);
str_DocumentEMailSelection.SetLongHint(str_DocumentEMailSelection_LongHint);
str_DocumentEMailSelection.SetDlgType(mtConfirmation);
{* Инициализация str_DocumentEMailSelection }
str_ListEMailSelection.Init;
str_ListEMailSelection.AddChoice(str_ListEMailSelection_Choice_Selected);
str_ListEMailSelection.AddChoice(str_ListEMailSelection_Choice_WholeList);
str_ListEMailSelection.AddDefaultChoice(str_ListEMailSelection_Choice_Selected);
str_ListEMailSelection.SetNeedCheck(true);
str_ListEMailSelection.SetCheckCaption(str_ListEMailSelection_CheckCaption);
str_ListEMailSelection.SetSettingsCaption(str_ListEMailSelection_SettingsCaption);
str_ListEMailSelection.SetLongHint(str_ListEMailSelection_LongHint);
str_ListEMailSelection.SetDlgType(mtConfirmation);
{* Инициализация str_ListEMailSelection }
str_ListPrintSelectedConfirmation.Init;
str_ListPrintSelectedConfirmation.AddChoice(str_ListPrintSelectedConfirmation_Choice_Selected);
str_ListPrintSelectedConfirmation.AddChoice(str_ListPrintSelectedConfirmation_Choice_WholeList);
str_ListPrintSelectedConfirmation.AddDefaultChoice(str_ListPrintSelectedConfirmation_Choice_Selected);
str_ListPrintSelectedConfirmation.SetNeedCheck(true);
str_ListPrintSelectedConfirmation.SetCheckCaption(str_ListPrintSelectedConfirmation_CheckCaption);
str_ListPrintSelectedConfirmation.SetSettingsCaption(str_ListPrintSelectedConfirmation_SettingsCaption);
str_ListPrintSelectedConfirmation.SetLongHint(str_ListPrintSelectedConfirmation_LongHint);
str_ListPrintSelectedConfirmation.SetDlgType(mtConfirmation);
{* Инициализация str_ListPrintSelectedConfirmation }
str_PrintSelectedConfirmation.Init;
str_PrintSelectedConfirmation.AddChoice(str_PrintSelectedConfirmation_Choice_Selected);
str_PrintSelectedConfirmation.AddChoice(str_PrintSelectedConfirmation_Choice_WholeDocument);
str_PrintSelectedConfirmation.AddDefaultChoice(str_PrintSelectedConfirmation_Choice_Selected);
str_PrintSelectedConfirmation.SetNeedCheck(true);
str_PrintSelectedConfirmation.SetCheckCaption(str_PrintSelectedConfirmation_CheckCaption);
str_PrintSelectedConfirmation.SetSettingsCaption(str_PrintSelectedConfirmation_SettingsCaption);
str_PrintSelectedConfirmation.SetLongHint(str_PrintSelectedConfirmation_LongHint);
str_PrintSelectedConfirmation.SetDlgType(mtConfirmation);
{* Инициализация str_PrintSelectedConfirmation }
str_ExportSelectionToWord.Init;
str_ExportSelectionToWord.AddChoice(str_ExportSelectionToWord_Choice_Selected);
str_ExportSelectionToWord.AddChoice(str_ExportSelectionToWord_Choice_WholeDocument);
str_ExportSelectionToWord.AddDefaultChoice(str_ExportSelectionToWord_Choice_Selected);
str_ExportSelectionToWord.SetNeedCheck(true);
str_ExportSelectionToWord.SetCheckCaption(str_ExportSelectionToWord_CheckCaption);
str_ExportSelectionToWord.SetSettingsCaption(str_ExportSelectionToWord_SettingsCaption);
str_ExportSelectionToWord.SetLongHint(str_ExportSelectionToWord_LongHint);
str_ExportSelectionToWord.SetDlgType(mtConfirmation);
{* Инициализация str_ExportSelectionToWord }
str_ListExportSelectionToWord.Init;
str_ListExportSelectionToWord.AddChoice(str_ListExportSelectionToWord_Choice_Selected);
str_ListExportSelectionToWord.AddChoice(str_ListExportSelectionToWord_Choice_WholeList);
str_ListExportSelectionToWord.AddDefaultChoice(str_ListExportSelectionToWord_Choice_Selected);
str_ListExportSelectionToWord.SetNeedCheck(true);
str_ListExportSelectionToWord.SetCheckCaption(str_ListExportSelectionToWord_CheckCaption);
str_ListExportSelectionToWord.SetSettingsCaption(str_ListExportSelectionToWord_SettingsCaption);
str_ListExportSelectionToWord.SetLongHint(str_ListExportSelectionToWord_LongHint);
str_ListExportSelectionToWord.SetDlgType(mtConfirmation);
{* Инициализация str_ListExportSelectionToWord }
str_ConsultDocumentsNotFound.Init;
str_ConsultDocumentsNotFound.AddChoice(str_ConsultDocumentsNotFound_Choice_Spec);
str_ConsultDocumentsNotFound.AddChoice(str_ConsultDocumentsNotFound_Choice_Back);
str_ConsultDocumentsNotFound.AddCustomChoice(str_ConsultDocumentsNotFound_Choice_Spec);
str_ConsultDocumentsNotFound.SetDlgType(mtWarning);
{* Инициализация str_ConsultDocumentsNotFound }
str_ConsultDocumentsNotFoundNoSpec.Init;
str_ConsultDocumentsNotFoundNoSpec.AddChoice(str_ConsultDocumentsNotFoundNoSpec_Choice_Back);
str_ConsultDocumentsNotFoundNoSpec.SetDlgType(mtWarning);
{* Инициализация str_ConsultDocumentsNotFoundNoSpec }
str_DocumentEMailSelection_Choice_Selection.Init;
{* Инициализация str_DocumentEMailSelection_Choice_Selection }
str_DocumentEMailSelection_Choice_WholeDocument.Init;
{* Инициализация str_DocumentEMailSelection_Choice_WholeDocument }
str_ListEMailSelection_Choice_Selected.Init;
{* Инициализация str_ListEMailSelection_Choice_Selected }
str_ListEMailSelection_Choice_WholeList.Init;
{* Инициализация str_ListEMailSelection_Choice_WholeList }
str_ListPrintSelectedConfirmation_Choice_Selected.Init;
{* Инициализация str_ListPrintSelectedConfirmation_Choice_Selected }
str_ListPrintSelectedConfirmation_Choice_WholeList.Init;
{* Инициализация str_ListPrintSelectedConfirmation_Choice_WholeList }
str_PrintSelectedConfirmation_Choice_Selected.Init;
{* Инициализация str_PrintSelectedConfirmation_Choice_Selected }
str_PrintSelectedConfirmation_Choice_WholeDocument.Init;
{* Инициализация str_PrintSelectedConfirmation_Choice_WholeDocument }
str_ExportSelectionToWord_Choice_Selected.Init;
{* Инициализация str_ExportSelectionToWord_Choice_Selected }
str_ExportSelectionToWord_Choice_WholeDocument.Init;
{* Инициализация str_ExportSelectionToWord_Choice_WholeDocument }
str_ListExportSelectionToWord_Choice_Selected.Init;
{* Инициализация str_ListExportSelectionToWord_Choice_Selected }
str_ListExportSelectionToWord_Choice_WholeList.Init;
{* Инициализация str_ListExportSelectionToWord_Choice_WholeList }
str_ConsultDocumentsNotFound_Choice_Spec.Init;
{* Инициализация str_ConsultDocumentsNotFound_Choice_Spec }
str_ConsultDocumentsNotFound_Choice_Back.Init;
{* Инициализация str_ConsultDocumentsNotFound_Choice_Back }
str_ConsultDocumentsNotFoundNoSpec_Choice_Back.Init;
{* Инициализация str_ConsultDocumentsNotFoundNoSpec_Choice_Back }
end.
|
unit demo2_1;
(************************************************************************
Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht,
Eric W. Engler and Chris Vleghert.
This file is part of TZipMaster Version 1.9.
TZipMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TZipMaster is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TZipMaster. If not, see <http://www.gnu.org/licenses/>.
contact: problems@delphizip.org (include ZipMaster in the subject).
updates: http://www.delphizip.org
DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip
************************************************************************)
interface
{$I DELVER.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, ExtCtrls, StdCtrls, ZipSFXPlus, ZipSFXBase;//, DZUtils;
type
TForm1 = class(TForm)
Panel3: TPanel;
Image1: TImage;
Panel1: TPanel;
Button1: TButton;
btnToSFX: TButton;
btnToEXE: TButton;
btnNewSFX: TButton;
Bevel1: TBevel;
dlgOpenSFX: TOpenDialog;
dlgSaveZIP: TSaveDialog;
ZipSFX1: TZipSFXPlus;
procedure Button1Click(Sender: TObject);
procedure btnToSFXClick(Sender: TObject);
procedure btnNewSFXClick(Sender: TObject);
procedure btnToEXEClick(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
// pick an icon via shell's PickIconDlg
function PickIcon(const hwndOwner: HWND; var sIconFile: string; var iIconNum: Integer): Boolean;
implementation
uses demo2_2;
{$R *.dfm}
// include all available sfx.bin modules
{$R dzsfx_all.res}
//{$R zipmsgus.res}
{$R '..\res\delzip.res'}
procedure TForm1.Button1Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.btnToSFXClick(Sender: TObject);
begin
with TdlgConvertToSFX.Create(self) do
try
ShowModal;
finally
Free;
end;
end;
function PickIconDlgA(hwndOwner: HWND; lpstrFile: PChar; nMaxFile: Word; var lpdwIconIndex: DWORD): Bool;
stdcall external 'shell32.dll' index 62;
function PickIconDlgW(hwndOwner: HWND; lpstrFile: PWideChar; nMaxFile: Word; var lpdwIconIndex: DWORD): Bool;
stdcall external 'shell32.dll' index 62;
// pick an icon via shell's PickIconDlg
function PickIcon(const hwndOwner: HWND; var sIconFile: string; var iIconNum: Integer): Boolean;
var
pch: PChar;
pwch: PWideChar;
{$IFDEF DELPHI3UP}
c: Cardinal;
{$ELSE}
c: Integer;
{$ENDIF}
begin
c := iIconNum;
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
GetMem(pwch, MAX_PATH * sizeof(WideChar));
try
StringToWideChar(sIconFile, pwch, MAX_PATH);
Result := PickIconDlgW(hwndOwner, pwch, MAX_PATH, DWORD(c));
if Result then
begin
iIconNum := c;
sIconFile := WideCharToString(pwch);
end;
finally
FreeMem(pwch);
end;
end
else
begin
GetMem(pch, MAX_PATH);
try
StrPCopy(pch, sIconFile);
Result := PickIconDlgA(hwndOwner, pch, MAX_PATH , DWORD(c));
if Result then
begin
iIconNum := c;
sIconFile := pch;
end;
finally
FreeMem(pch);
end;
end;
end;
procedure TForm1.btnNewSFXClick(Sender: TObject);
begin
with TdlgConvertToSFX.Create(self) do
try
PrepareMakeNew;
ShowModal;
finally
Free;
end;
end;
procedure TForm1.btnToEXEClick(Sender: TObject);
begin
with dlgOpenSFX
do
if Execute then
begin
ZipSFX1.SourceFile := FileName;
with dlgSaveZip do
begin
FileName := ChangeFileExt(ZipSFX1.SourceFile,'.zip');
if Execute then
begin
ZipSFX1.TargetFile := FileName;
ZipSFX1.StartWaitCursor;
try
ZipSFX1.ConvertToZip;
MessageDlg('ZIP archive '+ZipSFX1.TargetFile+#13#10+
'has been created.', mtInformation, [mbOK], 0);
finally
ZipSFX1.StopWaitCursor;
end;
end;
end;
end;
end;
end.
|
unit ChannImport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, FIBDatabase, pFIBDatabase, FIBDataSet,
ExtCtrls, ToolCtrlsEh, DBGridEhToolCtrls,
MemTableDataEh, MemTableEh, GridsEh, DBAxisGridsEh, DBGridEh, StdCtrls, EhLibMTE,
DBCtrlsEh, Mask, FIBQuery, pFIBQuery,
OXmlReadWrite, OXmlUtils, OXmlPDOM, EhLibVCL, DBGridEhGrouping, DynVarsEh;
type
TChImportForm = class(TForm)
pnlBottom: TPanel;
Button1: TButton;
btnSave: TButton;
trRead: TpFIBTransaction;
srcXMLChennals: TDataSource;
dsXMLChennals: TMemTableEh;
trWrite: TpFIBTransaction;
Query: TpFIBQuery;
OpenDialog: TOpenDialog;
pnlChennals: TPanel;
dbgChannels: TDBGridEh;
Label1: TLabel;
Label3: TLabel;
cbType: TDBComboBoxEh;
LabelXML: TLabel;
edXMLFile: TDBEditEh;
btnOpen: TButton;
lblNoNew: TLabel;
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnOpenClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbTypeChange(Sender: TObject);
private
function SaveSource: Boolean;
procedure Load_xmltv_map;
procedure Load_A4onTV_map;
procedure DataSetStart;
procedure DataSetFinish;
procedure DeleteExisitingChannels;
public
end;
var
EPGSourceForm: TChImportForm;
implementation
uses
DM, AtrCommon, JsonDataObjects, PrjConst, OTextReadWrite;
{$R *.dfm}
function TChImportForm.SaveSource: Boolean;
begin
if not dsXMLChennals.Active then
begin
Result := True;
Exit;
end;
if dsXMLChennals.RecordCount = 0 then
begin
Result := True;
Exit;
end;
if dsXMLChennals.State in [dsEdit] then
dsXMLChennals.Post;
dsXMLChennals.DisableControls;
dsXMLChennals.First;
Query.SQL.Text := 'insert into Channels (Ch_Number, Ch_Name, Ch_Notice) values (:Ch_Number, :Ch_Name, :Ch_Notice)';
Query.Transaction.StartTransaction;
while not dsXMLChennals.Eof do
begin
if not dsXMLChennals.FieldByName('NAME').IsNull then
if dsXMLChennals.FieldByName('NAME').AsString <> '' then
begin
if not dsXMLChennals.FieldByName('ATR_ID').IsNull then
Query.ParamByName('Ch_Number').AsInteger := dsXMLChennals['ATR_ID']
else
Query.ParamByName('Ch_Number').Clear;
Query.ParamByName('Ch_Name').AsString := dsXMLChennals['NAME'];
if not dsXMLChennals.FieldByName('Notice').IsNull then
Query.ParamByName('Ch_Notice').AsString := dsXMLChennals['Notice']
else
Query.ParamByName('Ch_Notice').Clear;
Query.ExecQuery;
end;
dsXMLChennals.Next;
end;
Query.Transaction.Commit;
dsXMLChennals.First;
dsXMLChennals.EnableControls;
Result := True;
end;
procedure TChImportForm.DataSetStart;
begin
if dsXMLChennals.Active then
dsXMLChennals.Close;
dsXMLChennals.DisableControls;
dsXMLChennals.Open;
dsXMLChennals.EmptyTable;
end;
procedure TChImportForm.DataSetFinish;
begin
DeleteExisitingChannels;
dsXMLChennals.First;
dsXMLChennals.EnableControls;
lblNoNew.Visible := (dsXMLChennals.RecordCount = 0);
dbgChannels.Visible := (dsXMLChennals.RecordCount > 0);
end;
procedure TChImportForm.DeleteExisitingChannels;
var
s: string;
begin
Query.SQL.Text := 'select Ch_Name from Channels';
Query.Transaction.StartTransaction;
Query.ExecQuery;
while not Query.Eof do
begin
s := Query.FN('Ch_Name').AsString;
if dsXMLChennals.Locate('UNAME', UpperCase(s), [loCaseInsensitive]) then
dsXMLChennals.Delete;
Query.Next;
end;
Query.Transaction.Rollback;
Query.Close;
end;
procedure TChImportForm.Load_xmltv_map;
var
j: Integer;
id: Integer;
s: string;
xXml: OXmlPDOM.IXMLDocument;
nl: OXmlPDOM.IXMLNodeList;
c: PXMLNode;
v: Variant;
begin
if (edXMLFile.Text.IsEmpty) or (not FileExists(edXMLFile.Text)) then
Exit;
xXml := OXmlPDOM.CreateXMLDoc;
xXml.ReaderSettings.ErrorHandling := ehSilent;
xXml.WhiteSpaceHandling := wsPreserveAll;
xXml.LoadFromFile(edXMLFile.Text);
if xXml.DocumentElement = nil then
begin
ShowMessage(rsXMLTVFormatError);
xXml := nil;
Exit;
end;
DataSetStart;
c := xXml.DocumentElement;
nl := c.SelectNodes('//channel');
if nl <> nil then
begin
v := dmMain.GetSingleSqlResult('select max(CH_NUMBER) from CHANNELS');
if VarIsNull(v) then
id := 1
else
id := (v + 1);
for j := 0 to nl.Count - 1 do
begin
dsXMLChennals.Append;
// S := nl.Nodes[j].GetAttribute('id');
// .GetAttribute('channel'); id
// if not TryStrToInt(S, id)
// then id := dmMain.dbTV.Gen_Id('GEN_OPERATIONS_UID', 1);
dsXMLChennals['ATR_ID'] := id;
c := nl.Nodes[j].SelectNode('display-name');
s := c.Text;
dsXMLChennals['NAME'] := s;
dsXMLChennals['UNAME'] := UpperCase(s);
dsXMLChennals.Post;
Inc(id);
end;
end;
DataSetFinish;
end;
procedure TChImportForm.Load_A4onTV_map;
var
i: Integer;
id: Integer;
jsonName: string;
B: TJsonBaseObject;
O, c: TJsonObject;
v: Variant;
begin
jsonName := GetTempDir + 'tv.json';
// dmMain.LoadWeekFromA4onTV(jsonName);
dmMain.LoadChannelsFromA4onTV(jsonName);
if not FileExists(jsonName) then
Exit;
DataSetStart;
B := TJsonBaseObject.ParseFromFile(jsonName);
try
if B <> nil then
begin
O := B as TJsonObject;
if O.Contains('schedule') then
begin
v := dmMain.GetSingleSqlResult('select max(CH_NUMBER) from CHANNELS');
if VarIsNull(v) then
id := 1
else
id := (v + 1);
for i := 0 to O.A['schedule'].Count - 1 do
begin
c := O.A['schedule'][i];
dsXMLChennals.Append;
// id := dmMain.dbTV.Gen_Id('GEN_OPERATIONS_UID', 1);
dsXMLChennals['ATR_ID'] := id;
dsXMLChennals['NAME'] := c.s['channel'];
dsXMLChennals['UNAME'] := UpperCase(c.s['channel']);
dsXMLChennals.Post;
Inc(id);
end;
end;
end;
finally
B.Free;
end;
if System.SysUtils.FileExists(jsonName) then
System.SysUtils.DeleteFile(jsonName);
DataSetFinish;
end;
procedure TChImportForm.btnSaveClick(Sender: TObject);
begin
if SaveSource then
ModalResult := mrOk;;
end;
procedure TChImportForm.btnOpenClick(Sender: TObject);
var
cr: TCursor;
begin
if cbType.Text.Trim = '' then
begin
cbType.SetFocus;
cbType.DropDown;
Exit;
end;
cr := Screen.Cursor;
case cbType.Value of
1:
begin;
Screen.Cursor := crHourGlass;
try
Load_A4onTV_map
finally
Screen.Cursor := cr;
end;
end;
0:
begin;
if edXMLFile.Text <> '' then
OpenDialog.FileName := edXMLFile.Text;
if OpenDialog.Execute then
begin
edXMLFile.Text := OpenDialog.FileName;
if FileExists(edXMLFile.Text) then
begin
Screen.Cursor := crHourGlass;
try
Load_xmltv_map
finally
Screen.Cursor := cr;
end;
end
else
ShowMessage(Format(rsFileNotFound, [edXMLFile.Text]));
end;
end;
end;
end;
procedure TChImportForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then
ModalResult := mrOk;
end;
procedure TChImportForm.FormShow(Sender: TObject);
begin
if VarIsNull(cbType.Value) then
cbType.Value := 1;
end;
procedure TChImportForm.cbTypeChange(Sender: TObject);
begin
edXMLFile.Visible := (cbType.Value <> 1);
LabelXML.Visible := edXMLFile.Visible;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
ColorBox, Spin;
type
{ TForm1 }
TForm1 = class(TForm)
CheckBox1: TCheckBox;
ColorListBox1: TColorListBox;
ColorListBox2: TColorListBox;
Label1: TLabel;
Label2: TLabel;
Panel1: TPanel;
RadioGroup1: TRadioGroup;
RadioGroup2: TRadioGroup;
SpinBevelWidth: TSpinEdit;
SpinBorderWidth: TSpinEdit;
procedure CheckBox1Change(Sender: TObject);
procedure ColorListBox1Click(Sender: TObject);
procedure ColorListBox2Click(Sender: TObject);
procedure RadioGroup1Click(Sender: TObject);
procedure RadioGroup2Click(Sender: TObject);
procedure SpinBevelWidthChange(Sender: TObject);
procedure SpinBorderWidthChange(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.CheckBox1Change(Sender: TObject);
begin
if CheckBox1.Checked then
Panel1.BorderStyle:= bsSingle
else
Panel1.BorderStyle:= bsNone;
end;
procedure TForm1.ColorListBox1Click(Sender: TObject);
begin
Panel1.Color:= ColorListBox1.Selected;
end;
procedure TForm1.ColorListBox2Click(Sender: TObject);
begin
Panel1.Font.Color:= ColorListBox2.Selected;
end;
procedure TForm1.RadioGroup1Click(Sender: TObject);
begin
Panel1.BevelInner:= TPanelBevel(RadioGroup1.ItemIndex);
end;
procedure TForm1.RadioGroup2Click(Sender: TObject);
begin
Panel1.BevelOuter:= TPanelBevel(RadioGroup2.ItemIndex);
end;
procedure TForm1.SpinBevelWidthChange(Sender: TObject);
begin
Panel1.BevelWidth:= SpinBevelWidth.Value;
end;
procedure TForm1.SpinBorderWidthChange(Sender: TObject);
begin
Panel1.BorderWidth:= SpinBorderWidth.Value;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.1 11/29/2004 11:26:00 PM JPMugaas
This should now support SuperTCP 7.1 running under Windows 2000. That does
support long filenames by the dir entry ending with one space followed by the
long-file name.
ShortFileName was added to the listitem class for completeness.
Rev 1.0 11/29/2004 2:44:16 AM JPMugaas
New FTP list parsers for some legacy FTP servers.
}
unit IdFTPListParseSuperTCP;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase;
type
TIdSuperTCPFTPListItem = class(TIdFTPListItem)
protected
FShortFileName : String;
public
property ShortFileName : String read FShortFileName write FShortFileName;
end;
TIdFTPLPSuperTCP = class(TIdFTPListBase)
protected
class function IsValidWin32FileName(const AFileName : String): Boolean;
class function IsValidMSDOSFileName(const AFileName : String): Boolean;
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseSuperTCP"'*)
implementation
uses
IdGlobal, IdFTPCommon, IdGlobalProtocols,
SysUtils;
{ TIdFTPLPSuperTCP }
class function TIdFTPLPSuperTCP.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
var
i : Integer;
LBuf, LBuf2 : String;
begin
{
Maybe like this:
CMT <DIR> 11-21-94 10:17
DESIGN1.DOC 11264 05-11-95 14:20
or this:
CMT <DIR> 11/21/94 10:17
DESIGN1.DOC 11264 05/11/95 14:20
or this with SuperTCP 7.1 running under Windows 2000:
. <DIR> 11-29-2004 22:04 .
.. <DIR> 11-29-2004 22:04 ..
wrar341.exe 1164112 11-22-2004 15:34 wrar341.exe
test <DIR> 11-29-2004 22:14 test
TESTDI~1 <DIR> 11-29-2004 22:16 Test Dir
TEST~1 <DIR> 11-29-2004 22:52 Test
}
Result := False;
for i := 0 to AListing.Count-1 do
begin
LBuf := AListing[i];
//filename and extension - we assume an 8.3 filename type because
//Windows 3.1 only supports that.
Result := IsValidMSDOSFileName(Fetch(LBuf));
if not Result then begin
Exit;
end;
LBuf := TrimLeft(LBuf);
//<DIR> or file size
LBuf2 := Fetch(LBuf);
Result := (LBuf2 = '<DIR>') or IsNumeric(LBuf2); {Do not localize}
if not Result then begin
Exit;
end;
//date
LBuf := TrimLeft(LBuf);
LBuf2 := Fetch(LBuf);
Result := IsMMDDYY(LBuf2, '/') or IsMMDDYY(LBuf2, '-'); {Do not localize}
if Result then
begin
//time
LBuf := TrimLeft(LBuf);
LBuf2 := Fetch(LBuf);
Result := IsHHMMSS(LBuf2, ':'); {Do not localize}
end;
if Result then
begin
//long filename in Win32
//if nothing, a Windows 3.1 server probably
if LBuf <> '' then begin
Result := IsValidWin32FileName(LBuf);
end;
end;
if not Result then begin
Break;
end;
end;
end;
class function TIdFTPLPSuperTCP.GetIdent: String;
begin
Result := 'SuperTCP'; {Do not localize}
end;
class function TIdFTPLPSuperTCP.IsValidMSDOSFileName(const AFileName: String): Boolean;
const
VALID_DOS_CHARS =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrtstuvwxyz0123456789_$~!#%&-{}()@'''+Char(180); {Do not localize}
var
LFileName, LExt : String;
i : Integer;
begin
Result := False;
if (AFileName = CUR_DIR) or (AFileName = PARENT_DIR) then
begin
Result := True;
Exit;
end;
LExt := AFileName;
LFileName := Fetch(LExt, '.'); {Do not localize}
if (Length(LFileName) > 0) and (Length(LFileName) < 9) then
begin
for i := 1 to Length(LFileName) do
begin
if IndyPos(LFileName[i], VALID_DOS_CHARS) = 0 then begin
Exit;
end;
end;
for i := 1 to Length(LExt) do
begin
if IndyPos(LExt[i], VALID_DOS_CHARS) = 0 then begin
Exit;
end;
end;
Result := True;
end;
end;
class function TIdFTPLPSuperTCP.IsValidWin32FileName(const AFileName: String): Boolean;
//from: http://linux-ntfs.sourceforge.net/ntfs/concepts/filename_namespace.html
const
WIN32_INVALID_CHARS = '"*/:<>?\|' + #0; {Do not localize}
WIN32_INVALID_LAST = ' .'; //not permitted as the last character in Win32 {Do not localize}
var
i : Integer;
begin
Result := False;
if (AFileName = CUR_DIR) or (AFileName = PARENT_DIR) then
begin
Result := True;
Exit;
end;
if Length(AFileName) > 0 then
begin
if IndyPos(AFileName[Length(AFileName)], WIN32_INVALID_LAST) > 0 then begin
Exit;
end;
for i := 1 to Length(AFileName) do
begin
if IndyPos(AFileName[i], WIN32_INVALID_CHARS) > 0 then begin
Exit;
end;
end;
Result := True;
end;
end;
class function TIdFTPLPSuperTCP.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdSuperTCPFTPListItem.Create(AOwner);
end;
class function TIdFTPLPSuperTCP.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var
LI : TIdSuperTCPFTPListItem;
LBuf, LBuf2 : String;
begin
{
with SuperTCP 7.1 running under Windows 2000:
. <DIR> 11-29-2004 22:04 .
.. <DIR> 11-29-2004 22:04 ..
wrar341.exe 1164112 11-22-2004 15:34 wrar341.exe
test <DIR> 11-29-2004 22:14 test
TESTDI~1 <DIR> 11-29-2004 22:16 Test Dir
TEST~1 <DIR> 11-29-2004 22:52 Test
}
LI := AItem as TIdSuperTCPFTPListItem;
LBuf := AItem.Data;
//short filename and extension - we assume an 8.3 filename
//type because Windows 3.1 only supports that and under Win32,
//a short-filename is returned here. That's with my testing.
LBuf2 := Fetch(LBuf);
LI.FileName := LBuf2;
LI.ShortFileName := LBuf2;
LBuf := TrimLeft(LBuf);
//<DIR> or file size
LBuf2 := Fetch(LBuf);
if LBuf2 = '<DIR>' then {Do not localize}
begin
LI.ItemType := ditDirectory;
LI.SizeAvail := False;
end else
begin
LI.ItemType := ditFile;
Result := IsNumeric(LBuf2);
if not Result then begin
Exit;
end;
LI.Size := IndyStrToInt64(LBuf2, 0);
end;
//date
LBuf := TrimLeft(LBuf);
LBuf2 := Fetch(LBuf);
if IsMMDDYY(LBuf2, '/') or IsMMDDYY(LBuf2, '-') then begin {Do not localize}
LI.ModifiedDate := DateMMDDYY(LBuf2);
end else
begin
Result := False;
Exit;
end;
//time
LBuf := TrimLeft(LBuf);
LBuf2 := Fetch(LBuf);
Result := IsHHMMSS(LBuf2, ':'); {do not localize}
if Result then begin
LI.ModifiedDate := LI.ModifiedDate + TimeHHMMSS(LBuf2);
end;
// long filename
//We do not use TrimLeft here because a space can start a filename in Windows
//2000 and the entry would be like this:
//
//TESTDI~1 <DIR> 11-29-2004 22:16 Test Dir
//TEST~1 <DIR> 11-29-2004 22:52 Test
//
if LBuf <> '' then begin
LI.FileName := LBuf;
end;
end;
initialization
RegisterFTPListParser(TIdFTPLPSuperTCP);
finalization
UnRegisterFTPListParser(TIdFTPLPSuperTCP);
end.
|
unit uDataSetInterface;
interface
uses
DB;
type
IDataSetInterface = interface(IInterface)
['{C92070BE-9D4F-4B68-BEAD-65A0910639E8}']
function GetDataSet: TDataSet; stdcall;
procedure SetDataSet(const Value: TDataSet); stdcall;
property DataSet: TDataSet read GetDataSet write SetDataSet;
end;
function CreateDataSetInterface(ADataSet: TDataSet): IDataSetInterface;
implementation
type
TDataSetInterface = class(TInterfacedObject, IDataSetInterface)
private
FDataSet: TDataSet;
public
function GetDataSet: TDataSet; stdcall;
procedure SetDataSet(const Value: TDataSet); stdcall;
property DataSet: TDataSet read GetDataSet write SetDataSet;
end;
function TDataSetInterface.GetDataSet: TDataSet;
begin
Result := FDataSet;
end;
procedure TDataSetInterface.SetDataSet(const Value: TDataSet);
begin
if FDataSet <> Value then
begin
FDataSet := Value;
end;
end;
function CreateDataSetInterface(ADataSet: TDataSet): IDataSetInterface;
begin
Result := TDataSetInterface.Create();
Result.DataSet := ADataSet;
end;
end.
|
//Exercicio 43: Faça um algoritmo que calcule e exiba a soma dos dez primeiros termos da seguinte série:
// N = 2/500 - 2/450 + 2/400 - 2/350 + ...
{ Solução em Portugol
Algoritmo Exercicio 43;
Var
N: real;
alternador_sinal, A: inteiro;
Inicio
exiba("Programa que calcula uma soma maluca.");
alternador_sinal <- 1;
N <- 0;
A <- 500;
enquanto (A > 0) faca
N <- N + (2/A) * alternador_sinal;
alternador_sinal := alternador_sinal * (-1);
A <- A - 50;
fimenquanto;
exiba("O valor da soma é: ", N);
Fim.
}
// Solução em Pascal
Program Exercicio43;
uses crt;
var
N: real;
alternador_sinal, A: integer;
begin
clrscr;
writeln('Programa que calcula uma soma maluca.');
N := 0;
A := 500;
alternador_sinal := 1;
while(A > 0)do
Begin
N := N + (2/A) * alternador_sinal;
alternador_sinal := alternador_sinal * (-1);
A := A - 50;
End;
writeln('O valor da soma é: ', N:0:5);
repeat until keypressed;
end. |
unit cmdlinecfgutils;
interface
{$mode delphi}
uses
SysUtils, Classes, cmdlinecfg, process;
function CmdLineCfgCombine(const ancestor, child: TCmdLineCfg; DoDeleteDashTypes: Boolean = true): Boolean;
procedure CmdLineCfgRemoveUnused(cfg: TCmdLineCfg);
function CmdLineCfgDetect(listofcfg: TList {of TCmdLineCfg}; const Dir, FullPathExec: string): TCmdLineCfg;
function ReadOutput(const Dir, ExecCommand: String): string;
// make the Value to be comand-line friendly, by handling CommandLineINvalidChars
// quotes would be added, if white-space characters are found
// todo: command lines replacement, should be system specific!
function CmdLineNormalizeParam(const Value: String): String;
// parses a command line into a list of arguments
// to be compatbile with RTL: ParamStr, ParamCount
procedure CmdLineParse(const cmdline: string; arguments : TStrings);
function CmdLineToExecutable(const cmdline: String; var Executable: string; Args: TStrings): Boolean;
procedure CmdLineAllocMultiValues(opt: TCmdLineCfgOption; const SrcValue: string; Delim: Char; dst: TList);
implementation
function OverrideIfEmpty(const existingValue, ReplacingValue: string): string;
begin
if existingValue='' then Result:=ReplacingValue else Result:=existingValue;
end;
function CmdLineCfgOptionCopy(const opt: TCmdLineCfgOption): TCmdLineCfgOption;
var
i : Integer;
begin
Result:=TCmdLineCfgOption.Create;
Result.Section:=opt.Section;
Result.SubSection:=opt.SubSection;
Result.Name:=opt.Name;
Result.OptType:=opt.OptType;
Result.Key:=opt.Key;
Result.Display:=opt.Display;
Result.Condition:=opt.Condition;
Result.ValCount:=opt.ValCount;
SetLength(Result.Values, Result.ValCount);
for i:=0 to Result.ValCount-1 do begin
Result.Values[i].Condition:=opt.Values[i].Condition;
Result.Values[i].DisplayName:=opt.Values[i].DisplayName;
Result.Values[i].CmdLineValue:=opt.Values[i].DisplayName;
end;
end;
function SortByName(p1,p2: Pointer): Integer;
var
o1, o2: TCmdLineCfgOption;
begin
o1:=TCmdLineCfgOption(p1);
o2:=TCmdLineCfgOption(p2);
Result:=CompareStr(o1.Name, o2.Name);
end;
function CmdLineCfgCombine(const ancestor, child: TCmdLineCfg; DoDeleteDashTypes: Boolean = true): Boolean;
var
i, j : integer;
l1,l2 : TList;
opt : TCmdLineCfgOption;
begin
Result:=Assigned(ancestor) and Assigned(child)
and (ancestor.Version=child.FromVersion) and (ancestor.Executable=child.Executable);
if not Result then Exit;
// executable
// version
// testValue
// fromVersion are not inheritable
child.TestKey:=OverrideIfEmpty(child.TestKey, ancestor.TestKey);
ancestor.Options.Sort(@SortByName);
child.Options.Sort(@SortByName);
i:=0;
j:=0;
for i:=0 to ancestor.Options.Count-1 do begin
opt:=TCmdLineCfgOption(ancestor.Options[i]);
while (j<child.Options.Count) and (CompareStr(opt.Name, TCmdLineCfgOption(child.Options[j]).Name)>0) do
inc(j);
if (j<child.Options.Count) and (CompareStr(opt.Name, TCmdLineCfgOption(child.Options[j]).Name)<0) then begin
child.Options.Add ( CmdLineCfgOptionCopy (opt));
end;
end;
if DoDeleteDashTypes then CmdLineCfgRemoveUnused(child);
end;
procedure CmdLineCfgRemoveUnused(cfg: TCmdLineCfg);
var
i : Integer;
begin
for i:=0 to cfg.Options.Count-1 do
if TCmdLineCfgOption(cfg.Options[i]).OptType='-' then begin
TCmdLineCfgOption(cfg.Options[i]).Free;
cfg.Options[i]:=nil;
end;
cfg.Options.Pack;
end;
function ReadOutput(const Dir, ExecCommand: String): string;
var
p: TProcess;
m: TMemoryStream;
BytesRead : Integer;
n: INteger;
exe : string;
const
READ_BYTES = 1024;
begin
Result:='';
BytesRead:=0;
m:=TMemoryStream.Create;
p:=TProcess.Create(nil);
try
exe:='';
if not CmdLineToExecutable(ExecCommand, exe, p.Parameters) then Exit;
p.Executable:=exe;
p.CurrentDirectory:=Dir;
p.Options:=[poUsePipes, poStdErrToOutput];
p.Execute;
while P.Running do begin
if P.Output.NumBytesAvailable>0 then begin
if M.Size-M.Position<READ_BYTES then begin
M.SetSize(BytesRead + READ_BYTES);
end;
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
if n > 0 then Inc(BytesRead, n) else Sleep(1);
end;
end;
repeat
M.SetSize(BytesRead + READ_BYTES);
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
if n > 0 then Inc(BytesRead, n);
until n <= 0;
if BytesRead > 0 then M.SetSize(BytesRead);
M.Position:=0;
SetLength(Result, M.Size);
if length(Result)>0 then
M.Read(Result[1], M.Size);
finally
p.Free;
end;
end;
function SortByTestKey(c1, c2: TCmdLineCfg {these are actually Pointers in here!}): Integer;
begin
Result:=CompareStr(c1.TestKey, c2.TestKey);
end;
function CmdLineCfgDetect(listofcfg: TList {of TCmdLineCfg}; const Dir, FullPathExec: string): TCmdLineCfg;
var
i : integer;
cfg : TCmdLineCfg;
tk : String;
tv : String;
search : TList;
begin
Result:=nil;
search:=TList.Create;
try
tk:='';
search.Assign(listofcfg);
search.Sort(@SortByTestKey);
for i:=0 to listofcfg.Count-1 do begin
cfg := TCmdLineCfg(listofcfg[i]);
if cfg.TestKey<>tk then begin
tk:=cfg.TestKey;
tv:=trim(ReadOutput(dir, FullPathExec+' '+tk));
end;
if cfg.TestValue=tv then begin
Result:=cfg;
Exit;
end;
end;
finally
search.Free;
end;
end;
function CmdLineNormalizeParam(const Value: String): String;
var
i : Integer;
const
CommandLineInvalidChars : set of Char = ['/','\',':','"','''','?','<','>',' '];
begin
for i:=0 to length(Value) do
if Value[i] in CommandLineInvalidChars then begin
//todo!
Result:='"'+Result+'"';
Exit;
end;
Result:=Value;
end;
function CmdLineToExecutable(const cmdline: String; var Executable: string;
Args: TStrings): Boolean;
var
a : TStringList;
begin
a:=TStringList.Create;
try
CmdLineParse(cmdline, a);
Result:=a.Count>0;
if Result then begin
Executable:=a[0];
a.Delete(0);
Args.Assign(a);
end;
finally
a.Free;
end;
end;
procedure CmdLineParse(const cmdline: string; arguments : TStrings);
var
i : integer;
j : integer;
isprm : Boolean;
p : string;
const
WhiteSpace : set of char = [#32,#9,#8,#13,#10];
QuoteChar = '"'; // yeah! be academic!
begin
if not Assigned(arguments) then eXit;
j:=1;
i:=1;
isprm:=false;
p:='';
while i<=length(cmdline) do begin
if not (cmdline[i] in WhiteSpace) then begin
if not isprm then j:=i;
if cmdline[i]=QuoteChar then begin
p:=p+Copy(cmdline, j, i-j);
inc(i);
j:=i;
while (i<=length(cmdline)) and (cmdline[i]<>'"') do
inc(i);
p:=p+Copy(cmdline, j, i-j);
j:=i+1;
end;
isprm:=true;
end else if isprm then begin
arguments.Add(p+Copy(cmdline, j, i-j));
isprm:=false;
p:='';
end;
inc(i);
end;
if isprm then arguments.Add(p+Copy(cmdline, j, i-j));
end;
procedure CmdLineAllocMultiValues(opt: TCmdLineCfgOption; const SrcValue: string; Delim: Char; dst: TList);
var
i, j : Integer;
vl : TCmdLineOptionValue;
v : string;
begin
if not Assigned(opt) or not Assigned(dst) or (SrcValue='') then Exit;
i:=1; j:=1;
while i<=length(SrcValue) do begin
if SrcValue[i]=Delim then begin
v:=Trim(Copy(SrcValue, j, i-j));
j:=i+1;
if v<>'' then dst.Add( TCmdLineOptionValue.Create(opt, v));
end;
inc(i);
end;
if j<i then begin
v:=Trim(Copy(SrcValue, j, i-j));
j:=i+1;
if v<>'' then dst.Add( TCmdLineOptionValue.Create(opt, v));
end;
end;
end.
|
unit BaiduMapAPI.ViewService;
//author:Xubzhlin
//Email:371889755@qq.com
//百度地图API 服务 单元
//官方链接:http://lbsyun.baidu.com/
//TBaiduMapViewService 百度地图 地图服务
interface
uses System.Classes, System.SysUtils, System.Types,
FMX.Platform, FMX.Controls, FMX.Maps;
type
TBaiduMapMarker = class(TMapMarker)
Data:Pointer;
end;
TOnBaiduMapMarkerClick = procedure(Sender:TObject; Marker:TBaiduMapMarker) of object;
TBaiduMapView = class;
IBaiduMapBaseService = interface
['{CFB73BF8-5A30-4D2B-AB0D-CC48656E36DA}']
procedure SetControl(const Value: TBaiduMapView);
function GetControl:TBaiduMapView;
end;
IBaiduMapViewService = interface(IBaiduMapBaseService)
['{2C200D6D-DA0B-469B-80A5-888EC1EDA415}']
procedure ShowBaiduMap;
procedure UpdateBaiduMapFromControl;
//通过 增加 Maker
function AddMarker(const Descriptor: TMapMarkerDescriptor): TBaiduMapMarker;
//通过 绘制 轨迹
function AddPolyline(const Descriptor: TMapPolylineDescriptor): TMapPolyline;
//通过 绘制 轨迹
function AddPolygon(const Descriptor: TMapPolygonDescriptor): TMapPolygon;
//通过 绘制 圆形
function AddCircle(const Descriptor: TMapCircleDescriptor): TMapCircle;
//设置 地图的中心位置
procedure SetCenterCoordinate(const Coordinate:TMapCoordinate);
//设置 当前mapView缩放
procedure SetZoomLevel(Level:Single);
end;
TBaiduMapBaseService = class(TInterfacedObject, IBaiduMapBaseService)
private
FControl: TBaiduMapView;
procedure SetControl(const Value: TBaiduMapView);
function GetControl:TBaiduMapView;
procedure SetVisible(const Value: Boolean);
protected
procedure DoSetControl; virtual; abstract;
procedure DoSetVisible(const Value: Boolean); virtual; abstract;
public
procedure DoMarkerClick(const Marker: TBaiduMapMarker);
property Control:TBaiduMapView read FControl;
property Visible:Boolean write SetVisible;
end;
TBaiduMapViewService = class;
TBaiduMapView = class(TControl)
private
FOnMakerClick:TOnBaiduMapMarkerClick;
FBaiduMapViewService:TBaiduMapViewService;
procedure UpdateBaiduMapView;
protected
procedure AncestorVisibleChanged(const Visible: Boolean); override;
procedure ParentChanged; override;
procedure DoAbsoluteChanged; override;
procedure Move; override;
procedure Resize; override;
procedure Paint; override;
procedure Show; override;
procedure Hide; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
procedure ShowBaiduMap;
constructor Create(AOwner: TComponent);
destructor Destroy; override;
published
property ViewService: TBaiduMapViewService read FBaiduMapViewService;
property OnMakerClick:TOnBaiduMapMarkerClick read FOnMakerClick write FOnMakerClick;
property Size;
property Align;
property Anchors;
property Height;
property Padding;
property Margins;
property Position;
property Visible default True;
property Width;
end;
TBaiduMapViewService = class(TBaiduMapBaseService, IBaiduMapViewService)
private
FAppKey:String;
FScale: Single;
protected
procedure DoSetControl; override;
procedure DoShowBaiduMap; virtual; abstract;
procedure DoUpdateBaiduMapFromControl; virtual; abstract;
function DoAddMarker(const Descriptor: TMapMarkerDescriptor): TBaiduMapMarker; virtual; abstract;
function DoAddPolyline(const Descriptor: TMapPolylineDescriptor):TMapPolyline; virtual; abstract;
function DoAddPolygon(const Descriptor: TMapPolygonDescriptor):TMapPolygon; virtual; abstract;
function DoAddCircle(const Descriptor: TMapCircleDescriptor): TMapCircle; virtual; abstract;
procedure DoSetCenterCoordinate(const Coordinate:TMapCoordinate); virtual; abstract;
procedure DoSetZoomLevel(Level:Single); virtual; abstract;
public
procedure ShowBaiduMap;
procedure UpdateBaiduMapFromControl;
function AddMarker(const Descriptor: TMapMarkerDescriptor): TBaiduMapMarker;
function AddPolyline(const Descriptor: TMapPolylineDescriptor): TMapPolyline;
function AddPolygon(const Descriptor: TMapPolygonDescriptor):TMapPolygon;
function AddCircle(const Descriptor: TMapCircleDescriptor): TMapCircle;
procedure SetCenterCoordinate(const Coordinate:TMapCoordinate);
procedure SetZoomLevel(Level:Single);
constructor Create(AKey:String); virtual;
destructor Destroy; override;
property AppKey:String read FAppKey;
property Scale:Single read FScale;
end;
implementation
{$IFDEF IOS}
uses
BaiduMapAPI.SDKInitializer, BaiduMapAPI.ViewService.iOS;
{$ENDIF}
{$IFDEF ANDROID}
uses
BaiduMapAPI.SDKInitializer, BaiduMapAPI.ViewService.Android;
{$ENDIF ANDROID}
{ TBaiduMapView }
procedure TBaiduMapView.AncestorVisibleChanged(const Visible: Boolean);
begin
inherited;
UpdateBaiduMapView;
end;
constructor TBaiduMapView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{$IFDEF IOS}
FBaiduMapViewService:=TiOSBaiduMapViewService.Create(TSDKInitializer.AppKey);
{$ENDIF}
{$IFDEF ANDROID}
FBaiduMapViewService:=TAndroidBaiduMapViewService.Create(TSDKInitializer.AppKey);
{$ENDIF ANDROID}
FBaiduMapViewService.SetControl(Self);
end;
destructor TBaiduMapView.Destroy;
begin
if FBaiduMapViewService <> nil then
FBaiduMapViewService.SetControl(nil);
FBaiduMapViewService:=nil;
inherited;
end;
procedure TBaiduMapView.DoAbsoluteChanged;
begin
inherited;
UpdateBaiduMapView;
end;
procedure TBaiduMapView.Hide;
begin
inherited;
UpdateBaiduMapView;
end;
procedure TBaiduMapView.Move;
begin
inherited;
UpdateBaiduMapView;
end;
procedure TBaiduMapView.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
{
if (Operation = opRemove) and (AComponent = FBaiduMapView) then
BaiduMapView := nil;
}
end;
procedure TBaiduMapView.Paint;
begin
inherited;
if (csDesigning in ComponentState) and not Locked and not FInPaintTo then
DrawDesignBorder;
end;
procedure TBaiduMapView.ParentChanged;
begin
inherited;
UpdateBaiduMapView;
end;
procedure TBaiduMapView.Resize;
begin
inherited;
UpdateBaiduMapView;
end;
procedure TBaiduMapView.Show;
begin
inherited;
UpdateBaiduMapView;
end;
procedure TBaiduMapView.ShowBaiduMap;
begin
FBaiduMapViewService.ShowBaiduMap;
end;
procedure TBaiduMapView.UpdateBaiduMapView;
begin
if (FBaiduMapViewService <> nil) then
FBaiduMapViewService.UpdateBaiduMapFromControl;
end;
{ TBaiduMapBaseService }
procedure TBaiduMapBaseService.DoMarkerClick(const Marker: TBaiduMapMarker);
begin
if (Control<>nil) and Assigned(Control.OnMakerClick) then
begin
Control.OnMakerClick(Self, Marker);
end;
end;
function TBaiduMapBaseService.GetControl: TBaiduMapView;
begin
Result:=FControl;
end;
procedure TBaiduMapBaseService.SetControl(const Value: TBaiduMapView);
begin
FControl:=Value;
DoSetControl;
end;
procedure TBaiduMapBaseService.SetVisible(const Value: Boolean);
begin
DoSetVisible(Value);
end;
{ TBaiduMapViewService }
function TBaiduMapViewService.AddCircle(
const Descriptor: TMapCircleDescriptor): TMapCircle;
begin
Result:=DoAddCircle(Descriptor);
end;
function TBaiduMapViewService.AddMarker(
const Descriptor: TMapMarkerDescriptor): TBaiduMapMarker;
begin
Result:=DoAddMarker(Descriptor);
end;
function TBaiduMapViewService.AddPolygon(
const Descriptor: TMapPolygonDescriptor): TMapPolygon;
begin
Result:=DoAddPolygon(Descriptor);
end;
function TBaiduMapViewService.AddPolyline(
const Descriptor: TMapPolylineDescriptor): TMapPolyline;
begin
Result:=DoAddPolyline(Descriptor);
end;
constructor TBaiduMapViewService.Create(AKey: String);
var
ScreenSrv:IFMXScreenService;
begin
inherited Create;
FAppKey:=AKey;
if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService,
ScreenSrv) then
FScale := ScreenSrv.GetScreenScale
else
FScale := 1;
end;
destructor TBaiduMapViewService.Destroy;
begin
inherited;
end;
procedure TBaiduMapViewService.DoSetControl;
begin
if FControl<>nil then
UpdateBaiduMapFromControl;
end;
procedure TBaiduMapViewService.ShowBaiduMap;
begin
DoShowBaiduMap;
end;
procedure TBaiduMapViewService.UpdateBaiduMapFromControl;
begin
DoUpdateBaiduMapFromControl;
end;
procedure TBaiduMapViewService.SetCenterCoordinate(
const Coordinate: TMapCoordinate);
begin
DoSetCenterCoordinate(Coordinate);
end;
procedure TBaiduMapViewService.SetZoomLevel(Level: Single);
begin
DoSetZoomLevel(Level);
end;
end.
|
unit Route4MeExamplesUnit;
interface
uses
SysUtils, System.Generics.Collections,
Route4MeManagerUnit, OutputUnit, NullableBasicTypesUnit,
CommonTypesUnit, IConnectionUnit, BulkGeocodingRequestUnit,
DataObjectUnit, AddressBookContactUnit, OrderUnit, RouteParametersUnit,
AddOrderToRouteRequestUnit, AddressUnit, EnumsUnit, UserParametersUnit,
TerritoryUnit, DirectionPathPointUnit;
type
TRoute4MeExamples = class
strict private
FOutput: IOutput;
FConnection: IConnection;
function MakeExample(Clazz: TClass): TObject;
public
constructor Create(Output: IOutput; Connection: IConnection);
destructor Destroy; override;
function SingleDriverRoute10Stops: TDataObject;
function SingleDriverRoundTrip: TDataObject;
function SingleDriverRoundTripGeneric: NullableString;
function MultipleDepotMultipleDriver: TDataObject;
function MultipleDepotMultipleDriverTimeWindow: TDataObject;
function SingleDepotMultipleDriverNoTimeWindow: TDataObject;
function MultipleDepotMultipleDriverWith24StopsTimeWindow: TDataObject;
function SingleDriverMultipleTimeWindows: TDataObject;
procedure ResequenceRouteDestinations(Route: TDataObjectRoute);
procedure ResequenceAllRouteDestinations(RouteId: String);
function AddRouteDestinations(RouteId: String): TArray<integer>;
function AddRouteDestinationsOptimally(RouteId: String): TArray<integer>;
procedure RemoveRouteDestination(RouteId: String; DestinationId: integer);
procedure MoveDestinationToRoute(ToRouteId: String;
RouteDestinationId, AfterDestinationId: integer);
procedure GetOptimization(OptimizationProblemId: String);
procedure GetOptimizations;
procedure RemoveOptimization(OptimizationProblemId: String);
function AddDestinationToOptimization(OptimizationId: String;
AndReOptimize: boolean): TDataObject;
procedure RemoveDestinationFromOptimization(OptimizationId: String;
DestinationId: integer; AndReOptimize: boolean);
procedure ReOptimization(OptimizationProblemId: String);
procedure ReoptimizeRoute(RouteId: String);
procedure MergeRoutes(RouteIds: TListString);
procedure UpdateRoute(RouteId: String);
procedure UpdateRoutesCustomFields(RouteId: String; RouteDestinationId: integer);
procedure GetRoute(RouteId: String; GetRouteDirections, GetRoutePathPoints: boolean);
function GetRoutes(Limit, Offset: integer): TDataObjectRouteList;
function SearchRoutesForSpecifiedText(Text: String): TDataObjectRouteList;
procedure BatchForwardGeocodeAddress(Address: String);
procedure BulkForwardGeocodeAddresses(Addresses: TAddressInfoArray);
procedure ReverseGeocodeAddress(Location: TDirectionPathPoint);
procedure GetSingleGeocodingAddress(Pk: integer);
procedure GetGeocodingAddresses;
procedure GetLimitedGeocodingAddresses(Limit, Offset: integer);
procedure GetZipCodes(ZipCode: String);
procedure GetLimitedZipCodes(ZipCode: String; Limit, Offset: integer);
procedure GetZipCodeAndHouseNumber(ZipCode, HouseNumber: String);
procedure GetLimitedZipCodeAndHouseNumber(ZipCode, HouseNumber: String; Limit, Offset: integer);
procedure GetUsers();
procedure ValidateSession(SessionGuid: String; MemberId: integer);
procedure RegisterAccount(Plan, Industry, FirstName, LastName, Email: String;
Terms: boolean; DeviceType: TDeviceType;
Password, PasswordConfirmation: String);
procedure GetUserDetails(MemberId: integer);
function AddNewUser(Parameters: TUserParameters): NullableInteger;
procedure UpdateUser(Parameters: TUserParameters);
procedure RemoveUser(MemberId: integer);
function Authentication(EMail, Password: String): NullableString;
procedure DeviceLicense(DeviceId: String; DeviceType: TDeviceType);
procedure UserLicense(MemberId, SessionId: integer; DeviceId: String;
DeviceType: TDeviceType; Subscription, Token, Payload: String);
procedure RegisterWebinar(EMail, FirstName, LastName, Phone, Company: String;
MemberId: integer; Date: TDateTime);
function AddConfigValue(Key, Value: String): boolean;
function UpdateConfigValue(Key, Value: String): boolean;
function DeleteConfigValue(Key: String): boolean;
procedure GetConfigValue(Key: String);
procedure GetAllConfigValues;
function LogSpecificMessage(Message: String; RouteId: String): boolean;
procedure GetAllActivities(Limit, Offset: integer);
procedure GetTeamActivities(RouteId: String; Limit, Offset: integer);
procedure GetAreaAddedActivities;
procedure GetAreaUpdatedActivities;
procedure GetAreaRemovedActivities;
procedure GetDestinationDeletedActivities;
procedure GetDestinationOutOfSequenceActivities;
procedure GetDriverArrivedEarlyActivities;
procedure GetDriverArrivedLateActivities;
procedure GetDriverArrivedOnTimeActivities;
procedure GetGeofenceEnteredActivities;
procedure GetGeofenceLeftActivities;
procedure GetDestinationInsertedActivities(RouteId: String);
procedure GetAllDestinationInsertedActivities;
procedure GetDestinationMarkedAsDepartedActivities(RouteId: String);
procedure GetAllDestinationMarkedAsDepartedActivities;
procedure GetAllDestinationMarkedAsVisitedActivities;
procedure GetMemberCreatedActivities;
procedure GetMemberDeletedActivities;
procedure GetMemberModifiedActivities;
procedure GetDestinationMovedActivities;
procedure GetNoteInsertedActivities(RouteId: String);
procedure GetAllNoteInsertedActivities;
procedure GetRouteDeletedActivities;
procedure GetRouteOptimizedActivities;
procedure GetRouteOwnerChangedActivities;
procedure GetDestinationUpdatedActivities;
procedure GetAddress(RouteId: String; RouteDestinationId: integer);
procedure MarkAddressAsDetectedAsVisited(RouteId: String; RouteDestinationId: integer;
IsVisited: boolean);
procedure MarkAddressAsDetectedAsDeparted(RouteId: String; RouteDestinationId: integer;
IsDeparted: boolean);
procedure MarkAddressAsVisited(RouteId: String; AddressId, MemberId: integer;
IsVisited: boolean);
procedure MarkAddressAsDeparted(RouteId: String; AddressId, MemberId: integer;
IsDeparted: boolean);
procedure AddAddressNote(RouteId: String; AddressId: integer);
procedure GetAddressNotes(RouteId: String; RouteDestinationId: integer);
function DuplicateRoute(RouteId: String): NullableString;
procedure ShareRoute(RouteId: String; RecipientEmail: String);
procedure DeleteRoutes(RouteIds: TStringArray);
function CreateLocation(FirstName, Address: String): TAddressBookContact;
procedure GetLocation(Query: String);
procedure DisplayRouted;
procedure LocationSearch(Query: String; Fields: TArray<String>);
procedure GetLocationsByIds(AddressesIds: TArray<integer>);
procedure GetLocations;
procedure UpdateLocation(Contact: TAddressBookContact);
procedure RemoveLocations(AddressIds: TArray<integer>);
function AddCircleAvoidanceZone: NullableString;
function AddPolygonAvoidanceZone: NullableString;
function AddRectangularAvoidanceZone: NullableString;
procedure GetAvoidanceZones;
procedure GetAvoidanceZone(TerritoryId: String);
procedure UpdateAvoidanceZone(TerritoryId: String);
procedure DeleteAvoidanceZone(TerritoryId: String);
function AddOrder(): TOrder;
procedure GetOrders; overload;
procedure GetOrder(OrderId: integer);
procedure GetOrders(Date: TDate); overload;
procedure GetOrdersScheduledFor(Date: TDate);
procedure GetOrdersWithCustomFields(Fields: TArray<String>);
procedure GetOrdersWithSpecifiedText(SpecifiedText: String);
procedure UpdateOrder(Order: TOrder);
procedure RemoveOrders(OrderIds: TIntegerArray);
procedure AddOrderToRoute(RouteId: String; Parameters: TRouteParameters;
OrderedAddresses: TOrderedAddressArray);
procedure AddOrderToOptimization(OptimizationId: String;
Parameters: TRouteParameters; OrderedAddresses: TOrderedAddressArray);
procedure SetGPSPosition(RouteId: String);
procedure TrackDeviceLastLocationHistory(RouteId: String);
procedure GetLocationHistoryFromTimeRange(RouteId: String; StartDate, EndDate: TDateTime);
procedure GetAssetTrackingData(TrackingNumber: String);
procedure GenericExample(Connection: IConnection);
procedure GenericExampleShortcut(Connection: IConnection);
function AddCircleTerritory: NullableString;
function AddPolygonTerritory: NullableString;
function AddRectangularTerritory: NullableString;
procedure RemoveTerritory(TerritoryId: String);
procedure GetTerritories;
procedure GetTerritory(TerritoryId: String);
procedure UpdateTerritory(TerritoryId: String);
procedure GetVehicle(VehicleId: String);
procedure GetAllVehicles;
procedure PreviewFile(FileId: string);
procedure UploadFileGeocoding(FileId: string);
procedure GetAllVendors;
procedure GetVendor(VendorId: integer);
procedure SearchVendors(Size: TVendorSizeType; IsIntegrated: boolean;
Feature, Country, Search: String; Page, PerPage: integer);
procedure CompareVendors(VendorIds: TStringArray);
end;
implementation
uses
BaseExampleUnit,
SingleDriverRoute10StopsUnit, MultipleDepotMultipleDriverUnit,
MultipleDepotMultipleDriverTimeWindowUnit,
SingleDepotMultipleDriverNoTimeWindowUnit,
SingleDriverMultipleTimeWindowsUnit, SingleDriverRoundTripUnit,
SingleDriverRoundTripGenericUnit,
MultipleDepotMultipleDriverWith24StopsTimeWindowUnit, RemoveLocationsUnit,
ResequenceRouteDestinationsUnit, AddRouteDestinationsUnit,
AddRouteDestinationsOptimallyUnit, RemoveRouteDestinationUnit,
MoveDestinationToRouteUnit, GetOptimizationsUnit, GetOptimizationUnit,
AddDestinationToOptimizationUnit, RemoveDestinationFromOptimizationUnit,
ReoptimizeRouteUnit, ReOptimizationUnit, UpdateRouteUnit, GetRoutesUnit,
GetRouteUnit, GetUsersUnit, LogSpecificMessageUnit, GetAllActivitiesUnit,
GetAddressUnit, GetAddressNotesUnit, AddAddressNoteUnit, DuplicateRouteUnit,
AddCircleAvoidanceZoneUnit, GetAvoidanceZoneUnit, GetAvoidanceZonesUnit,
UpdateAvoidanceZoneUnit, DeleteAvoidanceZoneUnit, AddOrderUnit, GetOrdersUnit,
UpdateOrderUnit, RemoveOrdersUnit, SetGPSPositionUnit, CreateLocationUnit,
TrackDeviceLastLocationHistoryUnit, GenericExampleShortcutUnit, ShareRouteUnit,
GenericExampleUnit, MergeRoutesUnit, UpdateRoutesCustomFieldsUnit,
DeleteRoutesUnit, RemoveOptimizationUnit, ResequenceAllRouteDestinationsUnit,
AddOrderToRouteUnit, AddOrderToOptimizationUnit, GetOrderUnit,
GetOrdersByDateUnit, GetOrdersScheduledForUnit, GetOrdersWithCustomFieldsUnit,
GetOrdersWithSpecifiedTextUnit, MarkAddressAsDepartedUnit,
MarkAddressAsVisitedUnit, MarkAddressAsDetectedAsVisitedUnit,
MarkAddressAsDetectedAsDepartedUnit, BatchForwardGeocodeAddressUnit,
ValidateSessionUnit, RegisterAccountUnit, GetUserDetailsUnit, AddNewUserUnit,
UpdateUserUnit, RemoveAddressBookContactsRequestUnit, RemoveUserUnit,
AuthenticationUnit, DeviceLicenseUnit, UserLicenseUnit, RegisterWebinarUnit,
GetTeamActivitiesUnit, GetAllDestinationMarkedAsDepartedActivitiesUnit,
GetAreaRemovedActivitiesUnit, GetAreaUpdatedActivitiesUnit,
GetDestinationDeletedActivitiesUnit, GetDestinationOutOfSequenceActivitiesUnit,
GetDriverArrivedEarlyActivitiesUnit, GetDriverArrivedLateActivitiesUnit,
GetDriverArrivedOnTimeActivitiesUnit, GetDestinationMarkedAsDepartedActivitiesUnit,
GetGeofenceEnteredActivitiesUnit, GetAllDestinationInsertedActivitiesUnit,
GetDestinationInsertedActivitiesUnit, GetGeofenceLeftActivitiesUnit,
GetAllDestinationMarkedAsVisitedActivitiesUnit, GetAreaAddedActivitiesUnit,
GetMemberCreatedActivitiesUnit, GetMemberDeletedActivitiesUnit,
GetMemberModifiedActivitiesUnit, GetDestinationMovedActivitiesUnit,
GetNoteInsertedActivitiesUnit, GetAllNoteInsertedActivitiesUnit,
GetRouteDeletedActivitiesUnit, GetRouteOwnerChangedActivitiesUnit,
GetDestinationUpdatedActivitiesUnit, GetRouteOptimizedActivitiesUnit,
GetLocationsByIdsUnit, GetLocationsUnit, UpdateLocationUnit, GetLocationUnit,
DisplayRoutedUnit, LocationSearchUnit, AddPolygonAvoidanceZoneUnit,
AddRectangularAvoidanceZoneUnit, AddCircleTerritoryUnit, RemoveTerritoryUnit,
AddPolygonTerritoryUnit, AddRectangularTerritoryUnit, GetTerritoriesUnit,
GetTerritoryUnit, UpdateTerritoryUnit, ReverseGeocodeAddressUnit,
GetSingleGeocodingAddressUnit, GetLimitedGeocodingAddressesUnit,
GetGeocodingAddressesUnit, GetZipCodesUnit, GetLimitedZipCodesUnit,
GetZipCodeAndHouseNumberUnit, GetLimitedZipCodeAndHouseNumberUnit,
BulkForwardGeocodeAddressesUnit, SearchRoutesForSpecifiedTextUnit,
GetLocationHistoryFromTimeRangeUnit, GetAssetTrackingDataUnit,
AddConfigValueUnit, DeleteConfigValueUnit, UpdateConfigValueUnit,
GetConfigValueUnit, GetAllConfigValuesUnit, GetVehiclesUnit, GetVehicleUnit, PreviewFileUnit, UploadFileGeocodingUnit, GetAllVendorsUnit, GetVendorUnit, SearchVendorsUnit,
CompareVendorsUnit;
procedure TRoute4MeExamples.GetAreaAddedActivities;
var
Example: TGetAreaAddedActivities;
begin
Example := MakeExample(TGetAreaAddedActivities) as TGetAreaAddedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAreaRemovedActivities;
var
Example: TGetAreaRemovedActivities;
begin
Example := MakeExample(TGetAreaRemovedActivities) as TGetAreaRemovedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAreaUpdatedActivities;
var
Example: TGetAreaUpdatedActivities;
begin
Example := MakeExample(TGetAreaUpdatedActivities) as TGetAreaUpdatedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAssetTrackingData(TrackingNumber: String);
var
Example: TGetAssetTrackingData;
begin
Example := MakeExample(TGetAssetTrackingData) as TGetAssetTrackingData;
try
Example.Execute(TrackingNumber);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.CreateLocation(FirstName, Address: String): TAddressBookContact;
var
Example: TCreateLocation;
begin
Example := MakeExample(TCreateLocation) as TCreateLocation;
try
Result := Example.Execute(FirstName, Address);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.AddAddressNote(RouteId: String; AddressId: integer);
var
Example: TAddAddressNote;
begin
Example := MakeExample(TAddAddressNote) as TAddAddressNote;
try
Example.Execute(RouteId, AddressId);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddCircleAvoidanceZone: NullableString;
var
Example: TAddCircleAvoidanceZone;
begin
Example := MakeExample(TAddCircleAvoidanceZone) as TAddCircleAvoidanceZone;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddDestinationToOptimization(OptimizationId: String;
AndReOptimize: boolean): TDataObject;
var
Example: TAddDestinationToOptimization;
begin
Example := MakeExample(TAddDestinationToOptimization) as TAddDestinationToOptimization;
try
Result := Example.Execute(OptimizationId, AndReOptimize);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddConfigValue(Key, Value: String): boolean;
var
Example: TAddConfigValue;
begin
Example := MakeExample(TAddConfigValue) as TAddConfigValue;
try
Result := Example.Execute(Key, Value);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddNewUser(Parameters: TUserParameters): NullableInteger;
var
Example: TAddNewUser;
begin
Example := MakeExample(TAddNewUser) as TAddNewUser;
try
Result := Example.Execute(Parameters);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddOrder: TOrder;
var
Example: TAddOrder;
begin
Example := MakeExample(TAddOrder) as TAddOrder;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.AddOrderToOptimization(OptimizationId: String;
Parameters: TRouteParameters; OrderedAddresses: TOrderedAddressArray);
var
Example: TAddOrderToOptimization;
begin
Example := MakeExample(TAddOrderToOptimization) as TAddOrderToOptimization;
try
Example.Execute(OptimizationId, Parameters, OrderedAddresses);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.AddOrderToRoute(RouteId: String;
Parameters: TRouteParameters; OrderedAddresses: TOrderedAddressArray);
var
Example: TAddOrderToRoute;
begin
Example := MakeExample(TAddOrderToRoute) as TAddOrderToRoute;
try
Example.Execute(RouteId, Parameters, OrderedAddresses);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddPolygonAvoidanceZone: NullableString;
var
Example: TAddPolygonAvoidanceZone;
begin
Example := MakeExample(TAddPolygonAvoidanceZone) as TAddPolygonAvoidanceZone;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddPolygonTerritory: NullableString;
var
Example: TAddPolygonTerritory;
begin
Example := MakeExample(TAddPolygonTerritory) as TAddPolygonTerritory;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddRectangularAvoidanceZone: NullableString;
var
Example: TAddRectangularAvoidanceZone;
begin
Example := MakeExample(TAddRectangularAvoidanceZone) as TAddRectangularAvoidanceZone;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddRectangularTerritory: NullableString;
var
Example: TAddRectangularTerritory;
begin
Example := MakeExample(TAddRectangularTerritory) as TAddRectangularTerritory;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddRouteDestinations(RouteId: String): TArray<integer>;
var
Example: TAddRouteDestinations;
begin
Example := MakeExample(TAddRouteDestinations) as TAddRouteDestinations;
try
Result := Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddRouteDestinationsOptimally(
RouteId: String): TArray<integer>;
var
Example: TAddRouteDestinationsOptimally;
begin
Example := MakeExample(TAddRouteDestinationsOptimally) as TAddRouteDestinationsOptimally;
try
Result := Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.AddCircleTerritory: NullableString;
var
Example: TAddCircleTerritory;
begin
Example := MakeExample(TAddCircleTerritory) as TAddCircleTerritory;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.Authentication(EMail, Password: String): NullableString;
var
Example: TAuthentication;
begin
Example := MakeExample(TAuthentication) as TAuthentication;
try
Result := Example.Execute(EMail, Password);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.CompareVendors(VendorIds: TStringArray);
var
Example: TCompareVendors;
begin
Example := MakeExample(TCompareVendors) as TCompareVendors;
try
Example.Execute(VendorIds);
finally
FreeAndNil(Example);
end;
end;
constructor TRoute4MeExamples.Create(Output: IOutput; Connection: IConnection);
begin
FOutput := Output;
FConnection := Connection;
end;
procedure TRoute4MeExamples.DeleteAvoidanceZone(TerritoryId: String);
var
Example: TDeleteAvoidanceZone;
begin
Example := MakeExample(TDeleteAvoidanceZone) as TDeleteAvoidanceZone;
try
Example.Execute(TerritoryId);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.DeleteConfigValue(Key: String): boolean;
var
Example: TDeleteConfigValue;
begin
Example := MakeExample(TDeleteConfigValue) as TDeleteConfigValue;
try
Result := Example.Execute(Key);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.DeleteRoutes(RouteIds: TStringArray);
var
Example: TDeleteRoutes;
begin
Example := MakeExample(TDeleteRoutes) as TDeleteRoutes;
try
Example.Execute(RouteIds);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDestinationDeletedActivities;
var
Example: TGetDestinationDeletedActivities;
begin
Example := MakeExample(TGetDestinationDeletedActivities) as TGetDestinationDeletedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDestinationInsertedActivities(RouteId: String);
var
Example: TGetDestinationInsertedActivities;
begin
Example := MakeExample(TGetDestinationInsertedActivities) as TGetDestinationInsertedActivities;
try
Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAllDestinationInsertedActivities;
var
Example: TGetAllDestinationInsertedActivities;
begin
Example := MakeExample(TGetAllDestinationInsertedActivities) as TGetAllDestinationInsertedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDestinationMarkedAsDepartedActivities(RouteId: String);
var
Example: TGetDestinationMarkedAsDepartedActivities;
begin
Example := MakeExample(TGetDestinationMarkedAsDepartedActivities) as TGetDestinationMarkedAsDepartedActivities;
try
Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAllDestinationMarkedAsDepartedActivities;
var
Example: TGetAllDestinationMarkedAsDepartedActivities;
begin
Example := MakeExample(TGetAllDestinationMarkedAsDepartedActivities) as TGetAllDestinationMarkedAsDepartedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAllDestinationMarkedAsVisitedActivities;
var
Example: TGetAllDestinationMarkedAsVisitedActivities;
begin
Example := MakeExample(TGetAllDestinationMarkedAsVisitedActivities) as TGetAllDestinationMarkedAsVisitedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAllNoteInsertedActivities;
var
Example: TGetAllNoteInsertedActivities;
begin
Example := MakeExample(TGetAllNoteInsertedActivities) as TGetAllNoteInsertedActivities;
try
Example.Execute();
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAllVehicles;
var
Example: TGetVehicles;
begin
Example := MakeExample(TGetVehicles) as TGetVehicles;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAllVendors;
var
Example: TGetAllVendors;
begin
Example := MakeExample(TGetAllVendors) as TGetAllVendors;
try
Example.Execute();
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDestinationMovedActivities;
var
Example: TGetDestinationMovedActivities;
begin
Example := MakeExample(TGetDestinationMovedActivities) as TGetDestinationMovedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDestinationOutOfSequenceActivities;
var
Example: TGetDestinationOutOfSequenceActivities;
begin
Example := MakeExample(TGetDestinationOutOfSequenceActivities) as TGetDestinationOutOfSequenceActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDestinationUpdatedActivities;
var
Example: TGetDestinationUpdatedActivities;
begin
Example := MakeExample(TGetDestinationUpdatedActivities) as TGetDestinationUpdatedActivities;
try
Example.Execute();
finally
FreeAndNil(Example);
end;
end;
destructor TRoute4MeExamples.Destroy;
begin
FOutput := nil;
FConnection := nil;
inherited;
end;
procedure TRoute4MeExamples.DeviceLicense(DeviceId: String; DeviceType: TDeviceType);
var
Example: TDeviceLicense;
begin
Example := MakeExample(TDeviceLicense) as TDeviceLicense;
try
Example.Execute(DeviceId, DeviceType);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.DisplayRouted;
var
Example: TDisplayRouted;
begin
Example := MakeExample(TDisplayRouted) as TDisplayRouted;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDriverArrivedEarlyActivities;
var
Example: TGetDriverArrivedEarlyActivities;
begin
Example := MakeExample(TGetDriverArrivedEarlyActivities) as TGetDriverArrivedEarlyActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDriverArrivedLateActivities;
var
Example: TGetDriverArrivedLateActivities;
begin
Example := MakeExample(TGetDriverArrivedLateActivities) as TGetDriverArrivedLateActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetDriverArrivedOnTimeActivities;
var
Example: TGetDriverArrivedOnTimeActivities;
begin
Example := MakeExample(TGetDriverArrivedOnTimeActivities) as TGetDriverArrivedOnTimeActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.DuplicateRoute(RouteId: String): NullableString;
var
Example: TDuplicateRoute;
begin
Example := MakeExample(TDuplicateRoute) as TDuplicateRoute;
try
Result := Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.BatchForwardGeocodeAddress(Address: String);
var
Example: TBatchForwardGeocodeAddress;
begin
Example := MakeExample(TBatchForwardGeocodeAddress) as TBatchForwardGeocodeAddress;
try
Example.Execute(Address);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.BulkForwardGeocodeAddresses(Addresses: TAddressInfoArray);
var
Example: TBulkForwardGeocodeAddresses;
begin
Example := MakeExample(TBulkForwardGeocodeAddresses) as TBulkForwardGeocodeAddresses;
try
Example.Execute(Addresses);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GenericExample(Connection: IConnection);
var
Example: TGenericExample;
begin
Example := MakeExample(TGenericExample) as TGenericExample;
try
Example.Execute(Connection);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GenericExampleShortcut(Connection: IConnection);
var
Example: TGenericExampleShortcut;
begin
Example := MakeExample(TGenericExampleShortcut) as TGenericExampleShortcut;
try
Example.Execute(Connection);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetGeocodingAddresses;
var
Example: TGetGeocodingAddresses;
begin
Example := MakeExample(TGetGeocodingAddresses) as TGetGeocodingAddresses;
try
Example.Execute();
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetGeofenceEnteredActivities;
var
Example: TGetGeofenceEnteredActivities;
begin
Example := MakeExample(TGetGeofenceEnteredActivities) as TGetGeofenceEnteredActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetGeofenceLeftActivities;
var
Example: TGetGeofenceLeftActivities;
begin
Example := MakeExample(TGetGeofenceLeftActivities) as TGetGeofenceLeftActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetLocationsByIds(AddressesIds: TArray<integer>);
var
Example: TGetLocationsByIds;
begin
Example := MakeExample(TGetLocationsByIds) as TGetLocationsByIds;
try
Example.Execute(AddressesIds);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetMemberCreatedActivities;
var
Example: TGetMemberCreatedActivities;
begin
Example := MakeExample(TGetMemberCreatedActivities) as TGetMemberCreatedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetMemberDeletedActivities;
var
Example: TGetMemberDeletedActivities;
begin
Example := MakeExample(TGetMemberDeletedActivities) as TGetMemberDeletedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetMemberModifiedActivities;
var
Example: TGetMemberModifiedActivities;
begin
Example := MakeExample(TGetMemberModifiedActivities) as TGetMemberModifiedActivities;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetNoteInsertedActivities(RouteId: String);
var
Example: TGetNoteInsertedActivities;
begin
Example := MakeExample(TGetNoteInsertedActivities) as TGetNoteInsertedActivities;
try
Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetTeamActivities(RouteId: String; Limit, Offset: integer);
var
Example: TGetTeamActivities;
begin
Example := MakeExample(TGetTeamActivities) as TGetTeamActivities;
try
Example.Execute(RouteId, Limit, Offset);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetTerritories;
var
Example: TGetTerritories;
begin
Example := MakeExample(TGetTerritories) as TGetTerritories;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetTerritory(TerritoryId: String);
var
Example: TGetTerritory;
begin
Example := MakeExample(TGetTerritory) as TGetTerritory;
try
Example.Execute(TerritoryId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAddress(RouteId: String;
RouteDestinationId: integer);
var
Example: TGetAddress;
begin
Example := MakeExample(TGetAddress) as TGetAddress;
try
Example.Execute(RouteId, RouteDestinationId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetLimitedGeocodingAddresses(Limit, Offset: integer);
var
Example: TGetLimitedGeocodingAddresses;
begin
Example := MakeExample(TGetLimitedGeocodingAddresses) as TGetLimitedGeocodingAddresses;
try
Example.Execute(Limit, Offset);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetLimitedZipCodeAndHouseNumber(ZipCode,
HouseNumber: String; Limit, Offset: integer);
var
Example: TGetLimitedZipCodeAndHouseNumber;
begin
Example := MakeExample(TGetLimitedZipCodeAndHouseNumber) as TGetLimitedZipCodeAndHouseNumber;
try
Example.Execute(ZipCode, HouseNumber, Limit, Offset);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetLimitedZipCodes(ZipCode: String; Limit, Offset: integer);
var
Example: TGetLimitedZipCodes;
begin
Example := MakeExample(TGetLimitedZipCodes) as TGetLimitedZipCodes;
try
Example.Execute(ZipCode, Limit, Offset);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetLocation(Query: String);
var
Example: TGetLocation;
begin
Example := MakeExample(TGetLocation) as TGetLocation;
try
Example.Execute(Query);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetLocationHistoryFromTimeRange(RouteId: String;
StartDate, EndDate: TDateTime);
var
Example: TGetLocationHistoryFromTimeRange;
begin
Example := MakeExample(TGetLocationHistoryFromTimeRange) as TGetLocationHistoryFromTimeRange;
try
Example.Execute(RouteId, StartDate, EndDate);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetLocations;
var
Example: TGetLocations;
begin
Example := MakeExample(TGetLocations) as TGetLocations;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAddressNotes(RouteId: String;
RouteDestinationId: integer);
var
Example: TGetAddressNotes;
begin
Example := MakeExample(TGetAddressNotes) as TGetAddressNotes;
try
Example.Execute(RouteId, RouteDestinationId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAllActivities(Limit, Offset: integer);
var
Example: TGetAllActivities;
begin
Example := MakeExample(TGetAllActivities) as TGetAllActivities;
try
Example.Execute(Limit, Offset);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAllConfigValues;
var
Example: TGetAllConfigValues;
begin
Example := MakeExample(TGetAllConfigValues) as TGetAllConfigValues;
try
Example.Execute();
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAvoidanceZone(TerritoryId: String);
var
Example: TGetAvoidanceZone;
begin
Example := MakeExample(TGetAvoidanceZone) as TGetAvoidanceZone;
try
Example.Execute(TerritoryId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetAvoidanceZones;
var
Example: TGetAvoidanceZones;
begin
Example := MakeExample(TGetAvoidanceZones) as TGetAvoidanceZones;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetConfigValue(Key: String);
var
Example: TGetConfigValue;
begin
Example := MakeExample(TGetConfigValue) as TGetConfigValue;
try
Example.Execute(Key);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetOptimization(OptimizationProblemId: String);
var
Example: TGetOptimization;
begin
Example := MakeExample(TGetOptimization) as TGetOptimization;
try
Example.Execute(OptimizationProblemId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetOptimizations;
var
Example: TGetOptimizations;
begin
Example := MakeExample(TGetOptimizations) as TGetOptimizations;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetOrder(OrderId: integer);
var
Example: TGetOrder;
begin
Example := MakeExample(TGetOrder) as TGetOrder;
try
Example.Execute(OrderId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetOrders(Date: TDate);
var
Example: TGetOrdersByDate;
begin
Example := MakeExample(TGetOrdersByDate) as TGetOrdersByDate;
try
Example.Execute(Date);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetOrdersScheduledFor(Date: TDate);
var
Example: TGetOrdersScheduledFor;
begin
Example := MakeExample(TGetOrdersScheduledFor) as TGetOrdersScheduledFor;
try
Example.Execute(Date);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetOrdersWithCustomFields(Fields: TArray<String>);
var
Example: TGetOrdersWithCustomFields;
begin
Example := MakeExample(TGetOrdersWithCustomFields) as TGetOrdersWithCustomFields;
try
Example.Execute(Fields);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetOrdersWithSpecifiedText(SpecifiedText: String);
var
Example: TGetOrdersWithSpecifiedText;
begin
Example := MakeExample(TGetOrdersWithSpecifiedText) as TGetOrdersWithSpecifiedText;
try
Example.Execute(SpecifiedText);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetOrders;
var
Example: TGetOrders;
begin
Example := MakeExample(TGetOrders) as TGetOrders;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetRoute(RouteId: String; GetRouteDirections,
GetRoutePathPoints: boolean);
var
Example: TGetRoute;
begin
Example := MakeExample(TGetRoute) as TGetRoute;
try
Example.Execute(RouteId, GetRouteDirections, GetRoutePathPoints);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetRouteDeletedActivities;
var
Example: TGetRouteDeletedActivities;
begin
Example := MakeExample(TGetRouteDeletedActivities) as TGetRouteDeletedActivities;
try
Example.Execute();
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetRouteOptimizedActivities;
var
Example: TGetRouteOptimizedActivities;
begin
Example := MakeExample(TGetRouteOptimizedActivities) as TGetRouteOptimizedActivities;
try
Example.Execute();
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetRouteOwnerChangedActivities;
var
Example: TGetRouteOwnerChangedActivities;
begin
Example := MakeExample(TGetRouteOwnerChangedActivities) as TGetRouteOwnerChangedActivities;
try
Example.Execute();
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.GetRoutes(Limit, Offset: integer): TDataObjectRouteList;
var
Example: TGetRoutes;
begin
Example := MakeExample(TGetRoutes) as TGetRoutes;
try
Result := Example.Execute(Limit, Offset);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetSingleGeocodingAddress(Pk: integer);
var
Example: TGetSingleGeocodingAddress;
begin
Example := MakeExample(TGetSingleGeocodingAddress) as TGetSingleGeocodingAddress;
try
Example.Execute(Pk);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetUserDetails(MemberId: integer);
var
Example: TGetUserDetails;
begin
Example := MakeExample(TGetUserDetails) as TGetUserDetails;
try
Example.Execute(MemberId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetUsers;
var
Example: TGetUsers;
begin
Example := MakeExample(TGetUsers) as TGetUsers;
try
Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetVehicle(VehicleId: string);
var
Example: TGetVehicle;
begin
Example := MakeExample(TGetVehicle) as TGetVehicle;
try
Example.Execute(VehicleId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetVendor(VendorId: integer);
var
Example: TGetVendor;
begin
Example := MakeExample(TGetVendor) as TGetVendor;
try
Example.Execute(VendorId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetZipCodeAndHouseNumber(ZipCode, HouseNumber: String);
var
Example: TGetZipCodeAndHouseNumber;
begin
Example := MakeExample(TGetZipCodeAndHouseNumber) as TGetZipCodeAndHouseNumber;
try
Example.Execute(ZipCode, HouseNumber);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.GetZipCodes(ZipCode: String);
var
Example: TGetZipCodes;
begin
Example := MakeExample(TGetZipCodes) as TGetZipCodes;
try
Example.Execute(ZipCode);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.LocationSearch(Query: String; Fields: TArray<String>);
var
Example: TLocationSearch;
begin
Example := MakeExample(TLocationSearch) as TLocationSearch;
try
Example.Execute(Query, Fields);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.LogSpecificMessage(Message, RouteId: String): boolean;
var
Example: TLogSpecificMessage;
begin
Example := MakeExample(TLogSpecificMessage) as TLogSpecificMessage;
try
Result := Example.Execute(Message, RouteId);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.MakeExample(Clazz: TClass): TObject;
var
Example: TBaseExample;
begin
Example := Clazz.Create as TBaseExample;
Example.Init(FOutput, FConnection);
Result := Example;
end;
procedure TRoute4MeExamples.MarkAddressAsDeparted(RouteId: String;
AddressId, MemberId: integer; IsDeparted: boolean);
var
Example: TMarkAddressAsDeparted;
begin
Example := MakeExample(TMarkAddressAsDeparted) as TMarkAddressAsDeparted;
try
Example.Execute(RouteId, AddressId, MemberId, IsDeparted);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.MarkAddressAsDetectedAsDeparted(RouteId: String;
RouteDestinationId: integer; IsDeparted: boolean);
var
Example: TMarkAddressAsDetectedAsDeparted;
begin
Example := MakeExample(TMarkAddressAsDetectedAsDeparted) as TMarkAddressAsDetectedAsDeparted;
try
Example.Execute(RouteId, RouteDestinationId, IsDeparted);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.MarkAddressAsDetectedAsVisited(RouteId: String;
RouteDestinationId: integer; IsVisited: boolean);
var
Example: TMarkAddressAsDetectedAsVisited;
begin
Example := MakeExample(TMarkAddressAsDetectedAsVisited) as TMarkAddressAsDetectedAsVisited;
try
Example.Execute(RouteId, RouteDestinationId, IsVisited);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.MarkAddressAsVisited(RouteId: String;
AddressId, MemberId: integer; IsVisited: boolean);
var
Example: TMarkAddressAsVisited;
begin
Example := MakeExample(TMarkAddressAsVisited) as TMarkAddressAsVisited;
try
Example.Execute(RouteId, AddressId, MemberId, IsVisited);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.MergeRoutes(RouteIds: TListString);
var
Example: TMergeRoutes;
begin
Example := MakeExample(TMergeRoutes) as TMergeRoutes;
try
Example.Execute(RouteIds);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.MoveDestinationToRoute(ToRouteId: String;
RouteDestinationId, AfterDestinationId: integer);
var
Example: TMoveDestinationToRoute;
begin
Example := MakeExample(TMoveDestinationToRoute) as TMoveDestinationToRoute;
try
Example.Execute(ToRouteId, RouteDestinationId, AfterDestinationId);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.MultipleDepotMultipleDriver: TDataObject;
var
Example: TMultipleDepotMultipleDriver;
begin
Example := MakeExample(TMultipleDepotMultipleDriver) as TMultipleDepotMultipleDriver;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.MultipleDepotMultipleDriverTimeWindow: TDataObject;
var
Example: TMultipleDepotMultipleDriverTimeWindow;
begin
Example := MakeExample(TMultipleDepotMultipleDriverTimeWindow) as TMultipleDepotMultipleDriverTimeWindow;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.MultipleDepotMultipleDriverWith24StopsTimeWindow: TDataObject;
var
Example: TMultipleDepotMultipleDriverWith24StopsTimeWindow;
begin
Example := MakeExample(TMultipleDepotMultipleDriverWith24StopsTimeWindow) as TMultipleDepotMultipleDriverWith24StopsTimeWindow;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.PreviewFile(FileId: string);
var
Example: TPreviewFile;
begin
Example := MakeExample(TPreviewFile) as TPreviewFile;
try
Example.Execute(FileId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RegisterAccount(Plan, Industry, FirstName, LastName,
Email: String; Terms: boolean; DeviceType: TDeviceType; Password,
PasswordConfirmation: String);
var
Example: TRegisterAccount;
begin
Example := MakeExample(TRegisterAccount) as TRegisterAccount;
try
Example.Execute(Plan, Industry, FirstName, LastName, Email, Terms,
DeviceType, Password, PasswordConfirmation);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RegisterWebinar(EMail, FirstName, LastName, Phone,
Company: String; MemberId: integer; Date: TDateTime);
var
Example: TRegisterWebinar;
begin
Example := MakeExample(TRegisterWebinar) as TRegisterWebinar;
try
Example.Execute(EMail, FirstName, LastName, Phone, Company, MemberId, Date);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RemoveLocations(
AddressIds: TArray<integer>);
var
Example: TRemoveLocations;
begin
Example := MakeExample(TRemoveLocations) as TRemoveLocations;
try
Example.Execute(AddressIds);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RemoveDestinationFromOptimization(
OptimizationId: String; DestinationId: integer; AndReOptimize: boolean);
var
Example: TRemoveDestinationFromOptimization;
begin
Example := MakeExample(TRemoveDestinationFromOptimization) as TRemoveDestinationFromOptimization;
try
Example.Execute(OptimizationId, DestinationId, AndReOptimize);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RemoveOptimization(OptimizationProblemId: String);
var
Example: TRemoveOptimization;
begin
Example := MakeExample(TRemoveOptimization) as TRemoveOptimization;
try
Example.Execute(OptimizationProblemId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RemoveOrders(OrderIds: TIntegerArray);
var
Example: TRemoveOrders;
begin
Example := MakeExample(TRemoveOrders) as TRemoveOrders;
try
Example.Execute(OrderIds);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RemoveRouteDestination(RouteId: String;
DestinationId: integer);
var
Example: TRemoveRouteDestination;
begin
Example := MakeExample(TRemoveRouteDestination) as TRemoveRouteDestination;
try
Example.Execute(RouteId, DestinationId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RemoveTerritory(TerritoryId: String);
var
Example: TRemoveTerritory;
begin
Example := MakeExample(TRemoveTerritory) as TRemoveTerritory;
try
Example.Execute(TerritoryId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.RemoveUser(MemberId: integer);
var
Example: TRemoveUser;
begin
Example := MakeExample(TRemoveUser) as TRemoveUser;
try
Example.Execute(MemberId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.ReOptimization(OptimizationProblemId: String);
var
Example: TReOptimization;
begin
Example := MakeExample(TReOptimization) as TReOptimization;
try
Example.Execute(OptimizationProblemId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.ReoptimizeRoute(RouteId: String);
var
Example: TReoptimizeRoute;
begin
Example := MakeExample(TReoptimizeRoute) as TReoptimizeRoute;
try
Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.ResequenceAllRouteDestinations(RouteId: String);
var
Example: TResequenceAllRouteDestinations;
begin
Example := MakeExample(TResequenceAllRouteDestinations) as TResequenceAllRouteDestinations;
try
Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.ResequenceRouteDestinations(Route: TDataObjectRoute);
var
Example: TResequenceRouteDestinations;
begin
Example := MakeExample(TResequenceRouteDestinations) as TResequenceRouteDestinations;
try
Example.Execute(Route);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.ReverseGeocodeAddress(
Location: TDirectionPathPoint);
var
Example: TReverseGeocodeAddress;
begin
Example := MakeExample(TReverseGeocodeAddress) as TReverseGeocodeAddress;
try
Example.Execute(Location);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.SearchRoutesForSpecifiedText(
Text: String): TDataObjectRouteList;
var
Example: TSearchRoutesForSpecifiedText;
begin
Example := MakeExample(TSearchRoutesForSpecifiedText) as TSearchRoutesForSpecifiedText;
try
Result := Example.Execute(Text);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.SearchVendors(Size: TVendorSizeType;
IsIntegrated: boolean; Feature, Country, Search: String; Page,
PerPage: integer);
var
Example: TSearchVendors;
begin
Example := MakeExample(TSearchVendors) as TSearchVendors;
try
Example.Execute(Size, IsIntegrated, Feature, Country, Search, Page, PerPage);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.SetGPSPosition(RouteId: String);
var
Example: TSetGPSPosition;
begin
Example := MakeExample(TSetGPSPosition) as TSetGPSPosition;
try
Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.ShareRoute(RouteId, RecipientEmail: String);
var
Example: TShareRoute;
begin
Example := MakeExample(TShareRoute) as TShareRoute;
try
Example.Execute(RouteId, RecipientEmail);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.SingleDepotMultipleDriverNoTimeWindow: TDataObject;
var
Example: TSingleDepotMultipleDriverNoTimeWindow;
begin
Example := MakeExample(TSingleDepotMultipleDriverNoTimeWindow) as TSingleDepotMultipleDriverNoTimeWindow;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.SingleDriverMultipleTimeWindows: TDataObject;
var
Example: TSingleDriverMultipleTimeWindows;
begin
Example := MakeExample(TSingleDriverMultipleTimeWindows) as TSingleDriverMultipleTimeWindows;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.SingleDriverRoundTrip: TDataObject;
var
Example: TSingleDriverRoundTrip;
begin
Example := MakeExample(TSingleDriverRoundTrip) as TSingleDriverRoundTrip;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.SingleDriverRoundTripGeneric: NullableString;
var
Example: TSingleDriverRoundTripGeneric;
begin
Example := MakeExample(TSingleDriverRoundTripGeneric) as TSingleDriverRoundTripGeneric;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.SingleDriverRoute10Stops: TDataObject;
var
Example: TSingleDriverRoute10Stops;
begin
Example := MakeExample(TSingleDriverRoute10Stops) as TSingleDriverRoute10Stops;
try
Result := Example.Execute;
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.TrackDeviceLastLocationHistory(RouteId: String);
var
Example: TTrackDeviceLastLocationHistory;
begin
Example := MakeExample(TTrackDeviceLastLocationHistory) as TTrackDeviceLastLocationHistory;
try
Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UpdateLocation(
Contact: TAddressBookContact);
var
Example: TUpdateLocation;
begin
Example := MakeExample(TUpdateLocation) as TUpdateLocation;
try
Example.Execute(Contact);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UpdateAvoidanceZone(TerritoryId: String);
var
Example: TUpdateAvoidanceZone;
begin
Example := MakeExample(TUpdateAvoidanceZone) as TUpdateAvoidanceZone;
try
Example.Execute(TerritoryId);
finally
FreeAndNil(Example);
end;
end;
function TRoute4MeExamples.UpdateConfigValue(Key, Value: String): boolean;
var
Example: TUpdateConfigValue;
begin
Example := MakeExample(TUpdateConfigValue) as TUpdateConfigValue;
try
Result := Example.Execute(Key, Value);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UpdateRoutesCustomFields(RouteId: String;
RouteDestinationId: integer);
var
Example: TUpdateRoutesCustomFields;
begin
Example := MakeExample(TUpdateRoutesCustomFields) as TUpdateRoutesCustomFields;
try
Example.Execute(RouteId, RouteDestinationId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UpdateTerritory(TerritoryId: String);
var
Example: TUpdateTerritory;
begin
Example := MakeExample(TUpdateTerritory) as TUpdateTerritory;
try
Example.Execute(TerritoryId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UpdateUser(Parameters: TUserParameters);
var
Example: TUpdateUser;
begin
Example := MakeExample(TUpdateUser) as TUpdateUser;
try
Example.Execute(Parameters);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UploadFileGeocoding(FileId: string);
var
Example: TUploadFileGeocoding;
begin
Example := MakeExample(TUploadFileGeocoding) as TUploadFileGeocoding;
try
Example.Execute(FileId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UserLicense(MemberId, SessionId: integer;
DeviceId: String; DeviceType: TDeviceType;
Subscription, Token, Payload: String);
var
Example: TUserLicense;
begin
Example := MakeExample(TUserLicense) as TUserLicense;
try
Example.Execute(MemberId, SessionId, DeviceId, DeviceType,
Subscription, Token, Payload);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.ValidateSession(SessionGuid: String; MemberId: integer);
var
Example: TValidateSession;
begin
Example := MakeExample(TValidateSession) as TValidateSession;
try
Example.Execute(SessionGuid, MemberId);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UpdateOrder(Order: TOrder);
var
Example: TUpdateOrder;
begin
Example := MakeExample(TUpdateOrder) as TUpdateOrder;
try
Example.Execute(Order);
finally
FreeAndNil(Example);
end;
end;
procedure TRoute4MeExamples.UpdateRoute(RouteId: String);
var
Example: TUpdateRoute;
begin
Example := MakeExample(TUpdateRoute) as TUpdateRoute;
try
Example.Execute(RouteId);
finally
FreeAndNil(Example);
end;
end;
end.
|
{-----------------------------------------------------------------------------
hpp_contacts (historypp project)
Version: 1.0
Created: 31.03.2003
Author: Oxygen
[ Description ]
Some helper routines for contacts
[ History ]
1.0 (31.03.2003) - Initial version
[ Modifications ]
[ Knows Inssues ]
None
Copyright (c) Art Fedorov, 2003
-----------------------------------------------------------------------------}
unit hpp_contacts;
interface
uses
Windows, SysUtils,
m_globaldefs, m_api,
hpp_global, hpp_miranda_mmi;
function GetContactDisplayName(hContact: THandle; Proto: String = ''; Contact: boolean = false): WideString;
function GetContactProto(hContact: THandle): String;
function GetContactID(hContact: THandle; Proto: String = ''; Contact: boolean = false): String;
function GetContactCodePage(hContact: THandle; Proto: String = ''): Cardinal;
function GetContactRTLMode(hContact: THandle; Proto: String = ''): boolean;
function GetContactRTLModeTRTL(hContact: THandle; Proto: String = ''): TRTLMode;
implementation
uses TntSystem, TntSysUtils;
{$I m_database.inc}
{$I m_clist.inc}
{$I m_contacts.inc}
function GetContactProto(hContact: THandle): String;
begin
Result := PChar(PluginLink.CallService(MS_PROTO_GETCONTACTBASEPROTO,hContact,0));
end;
function GetContactDisplayName(hContact: THandle; Proto: String = ''; Contact: boolean = false): WideString;
var
ci: TContactInfo;
RetPAnsiChar,UA: PAnsiChar;
RetPWideChar,UW: PWideChar;
begin
if (hContact = 0) and Contact then
Result := AnsiToWideString(Translate('Server'),hppCodepage)
else begin
if Proto = '' then Proto := GetContactProto(hContact);
if Proto = '' then Result := AnsiToWideString(Translate('''(Unknown Contact)'''),hppCodepage)
else begin
ci.cbSize := SizeOf(ci);
ci.hContact := hContact;
ci.szProto := PChar(Proto);
if hppCoreUnicode then ci.dwFlag := CNF_DISPLAY + CNF_UNICODE
else ci.dwFlag := CNF_DISPLAY;
if PluginLink.CallService(MS_CONTACT_GETCONTACTINFO,0,Integer(@ci)) = 0 then begin
if hppCoreUnicode then begin
RetPWideChar := PWideChar(ci.retval.pszVal);
UW := TranslateW('''(Unknown Contact)''');
if WideCompareText(RetPWideChar,UW) = 0 then
Result := AnsiToWideString(GetContactID(hContact,Proto),CP_ACP)
else
Result := RetPWideChar;
MirandaFree(RetPWideChar);
end else begin
RetPAnsiChar := ci.retval.pszVal;
UA := Translate('''(Unknown Contact)''');
if AnsiCompareText(RetPAnsiChar,UA) = 0 then
Result := AnsiToWideString(GetContactID(hContact,Proto),CP_ACP)
else
Result := AnsiToWideString(RetPAnsiChar,CP_ACP);
MirandaFree(RetPAnsiChar);
end;
end else
Result := GetContactID(hContact,Proto);
if Result = '' then Result := AnsiToWideString(Translate(@Proto[1]),hppCodepage);
end;
end;
end;
function GetContactID(hContact: THandle; Proto: String = ''; Contact: boolean = false): String;
var
ci: TContactInfo;
begin
if (hContact = 0) and Contact then
Result := ''
else begin
if Proto = '' then Proto := GetContactProto(hContact);
ci.cbSize := SizeOf(ci);
ci.hContact := hContact;
ci.szProto := PChar(Proto);
ci.dwFlag := CNF_UNIQUEID;
if PluginLink.CallService(MS_CONTACT_GETCONTACTINFO,0,Integer(@ci)) = 0 then begin
case ci.type_ of
CNFT_BYTE:
Result := intToStr(ci.retval.bVal);
CNFT_WORD:
Result := intToStr(ci.retval.wVal);
CNFT_DWORD:
Result := intToStr(ci.retval.dVal);
CNFT_ASCIIZ:
Result := ci.retval.pszVal;
end;
end else
//Result := PCharToWideString(PChar(Translate('Unknown id')),CP_ACP);
Result := '';
end;
end;
function GetContactCodePage(hContact: THandle; Proto: String = ''): Cardinal;
begin
if Proto = '' then Proto := GetContactProto(hContact);
if Proto = '' then
Result := CP_ACP
else begin
Result := DBGetContactSettingWord(hContact,PChar(Proto),'AnsiCodePage',MaxInt);
If Result = MaxInt then
Result := DBGetContactSettingWord(0,PChar(Proto),'AnsiCodePage',CP_ACP);
end;
end;
function GetContactRTLMode(hContact: THandle; Proto: String = ''): boolean;
var
Temp: Byte;
begin
if Proto = '' then Proto := GetContactProto(hContact);
if Proto = '' then
Result := SysLocale.MiddleEast
else begin
if hContact = 0 then
Temp := DBGetContactSettingByte(hContact,PChar(Proto),'RTL',255);
If Temp = 255 then
Temp := DBGetContactSettingWord(0,PChar(Proto),'RTL',byte(SysLocale.MiddleEast));
Result := boolean(Temp);
end;
end;
function GetContactRTLModeTRTL(hContact: THandle; Proto: String = ''): TRTLMode;
var
Temp: Byte;
begin
if Proto = '' then Proto := GetContactProto(hContact);
if Proto = '' then
Result := hppRTLDefault
else begin
Temp := DBGetContactSettingByte(hContact,PChar(Proto),'RTL',255);
case Temp of
0: Result := hppRTLDisable;
1: Result := hppRTLEnable;
else
Result := hppRTLDefault;
end;
end;
end;
end.
|
unit uPublic;
interface
uses System.SysUtils;
const
IOC_IN = $80000000;
IOC_VENDOR = $18000000;
IOC_out = $40000000;
SIO_KEEPALIVE_VALS = IOC_IN or IOC_VENDOR or 4;
DATA_BUFSIZE = 8192;
// 定义 KeepAlive 数据结构
type
TTCP_KEEPALIVE = packed record
onoff: integer;
keepalivetime: integer;
keepaliveinterval: integer;
end;
function yyyyMMddHHmmss(): string;
function yyyyMMddHHmmsszzz(): string;
implementation
function yyyyMMddHHmmss: string;
begin
Result := FormatDateTime('[yyyy-MM-dd HH:mm:ss]', Now());
end;
function yyyyMMddHHmmsszzz: string;
begin
Result := FormatDateTime('[yyyy-MM-dd HH:mm:ss.zzz]', Now());
end;
end.
|
unit fcScrollBar;
{
//
// Components : TfcScrollBar
//
// Copyright (c) 1999 by Woll2Woll Software
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fcCommon, ExtCtrls;
type
TfcCustomScrollBar = class;
TfcScrollBarHitTest = (htNone, htIncBtn, htDecBtn, htPageUp, htPageDown, htThumb);
TfcScrollPosChangeEvent = procedure(Sender: TfcCustomScrollBar; PriorValue, NewValue: Integer) of object;
TfcScrollbarRepeatInterval = class(TPersistent)
private
FInitialDelay: Integer;
FRepeatInterval: Integer;
public
constructor Create;
published
property InitialDelay: Integer read FInitialDelay write FInitialDelay;
property Interval: Integer read FRepeatInterval write FRepeatInterval;
end;
TfcCustomScrollBar = class(TGraphicControl)
private
// Property Storage Variables
FOnChange: TfcScrollPosChangeEvent;
FKind: TScrollBarKind;
FMax: Integer;
FMin: Integer;
FPageSize: Integer;
FPosition: Integer;
FSmallChange: TScrollBarInc;
FTimer: TTimer;
// FTimerClear: boolean;
FFixedThumbSize: boolean;
// Other Storage Variables
FClickedPos: TfcScrollBarHitTest;
FRepeatInterval: TfcScrollbarRepeatInterval;
DragOffset: integer;
DragOrigPosition: integer;
FContinuousDrag: boolean;
FMinThumbSize: integer;
FPriorPosition: integer;
// Property Access Methods
procedure SetKind(Value: TScrollBarKind);
procedure SetMax(Value: Integer);
procedure SetMin(Value: Integer);
procedure SetPageSize(Value: Integer);
procedure SetPosition(Value: Integer);
procedure SetSmallChange(Value: TScrollBarInc);
// procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
procedure CMDesignHitTest(var Message: TCMDesignHitTest); message CM_DESIGNHITTEST;
protected
// Overridden Methods
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure Paint; override;
procedure PaintScrollRegion(All: boolean); virtual;
// Virtual Methods
function GetSectionRect(Section: TfcScrollBarHitTest): TRect;
procedure MouseLoop(X, Y: Integer); virtual;
procedure MouseLoop_MouseUp(X, Y: Integer; ACursorPos: TPoint); virtual;
procedure ScrollPosChange(OldPos, NewPos: Integer); virtual;
procedure TimerEvent(Sender: TObject);
procedure Scroll(ScrollCode: integer; Position: integer); virtual;
procedure WndProc(var Message: TMessage); override;
function ScrollScreenRange: integer;
public
Patch: Variant;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// Public Methods
function GetHitTestInfo(X, Y: Integer): TfcScrollBarHitTest; virtual;
procedure Invalidate; override;
procedure MoveScrollPos;
procedure SetParams(APosition, AMax, AMin: Integer); virtual;
// procedure InvalidateThumb;
// Public Properties
property MinThumbSize: integer read FMinThumbSize write FMinThumbSize default 8;
property FixedThumbSize: boolean read FFixedThumbSize write FFixedThumbSize;
property Kind: TScrollBarKind read FKind write SetKind;
property Max: Integer read FMax write SetMax;
property Min: Integer read FMin write SetMin;
property PageSize: Integer read FPageSize write SetPageSize;
property PriorPosition: integer read FPriorPosition;
property Position: Integer read FPosition write SetPosition;
property SmallChange: TScrollBarInc read FSmallChange write SetSmallChange;
property ContinuousDrag: boolean read FContinuousDrag write FContinuousDrag;
property RepeatInterval: TfcScrollBarRepeatInterval read FRepeatInterval write FRepeatInterval;
property OnChange: TfcScrollPosChangeEvent read FOnChange write FOnChange;
end;
TfcScrollBar = class(TfcCustomScrollBar)
published
property Kind;
property Max;
property Min;
property PageSize;
property Position;
property SmallChange;
property OnChange;
end;
procedure Register;
implementation
const incr=1;
procedure Register;
begin
// RegisterComponents('First Class', [TfcScrollBar]);
end;
constructor TfcScrollbarRepeatInterval.Create;
begin
FInitialDelay := 500;
FRepeatInterval := 50;
end;
destructor TfcCustomScrollBar.Destroy;
begin
FRepeatInterval.Free;
inherited;
end;
constructor TfcCustomScrollBar.Create(AOwner: TComponent);
begin
inherited;
FKind := sbVertical;
Width := GetSystemMetrics(SM_CXVSCROLL);
Height := 100;
FMin := 0;
FMax := 100;
FSmallChange := 1;
FPageSize := 10; //Width;
FRepeatInterval := TfcScrollbarRepeatInterval.Create;
FTimer := TTimer.Create(self);
FTimer.Interval := RepeatInterval.InitialDelay;
FTimer.OnTimer := TimerEvent;
DragOrigPosition:= -1;
FMinThumbSize:= 8;
end;
procedure TfcCustomScrollBar.TimerEvent(Sender: TObject);
var ACursor: TPoint;
begin
if GetKeyState(VK_LBUTTON) >= 0 then
begin
FTimer.Enabled := False;
// FTimerClear:= True;
invalidate; { Repaint so pageUp/pageDown area repainted }
// Update;
// FTimerClear:= False;
Exit;
end;
FTimer.Interval := RepeatInterval.Interval;
GetCursorPos(ACursor);
ACursor := ScreenToClient(ACursor);
if GetHitTestInfo(ACursor.X, ACursor.Y)=FClickedPos then
begin
MoveScrollPos;
end;
Invalidate;
// PaintScrollRegion(False); { Don't invalidate whole region to prevent flicker }
end;
procedure TfcCustomScrollBar.SetKind(Value: TScrollBarKind);
begin
if FKind <> Value then
begin
FKind := Value;
end;
end;
procedure TfcCustomScrollBar.SetMax(Value: Integer);
begin
if FMax <> Value then
begin
FMax := Value;
end;
end;
procedure TfcCustomScrollBar.SetMin(Value: Integer);
begin
if FMin <> Value then
begin
FMin := Value;
end;
end;
procedure TfcCustomScrollBar.SetPageSize(Value: Integer);
begin
if FPageSize <> Value then
begin
FPageSize := Value;
end;
end;
procedure TfcCustomScrollBar.SetPosition(Value: Integer);
begin
if FPosition <> Value then
begin
FPosition := Value;
if FPosition > Max-PageSize+1 then FPosition := Max-PageSize+1;
if FPosition < Min then FPosition := Min;
end;
end;
procedure TfcCustomScrollBar.SetSmallChange(Value: TScrollBarInc);
begin
if FSmallChange <> Value then
begin
FSmallChange := Value;
end;
end;
procedure TfcCustomScrollBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
FClickedPos := GetHitTestInfo(X, Y);
if FClickedPos in [htIncBtn, htDecBtn, htPageUp, htPageDown] then
begin
MoveScrollPos;
FTimer.Interval := RepeatInterval.InitialDelay;
FTimer.Enabled := True;
Invalidate;
end;
MouseLoop(X, Y);
end;
procedure TfcCustomScrollBar.Invalidate;
var r: TRect;
begin
r := BoundsRect;
if Parent <> nil then InvalidateRect(Parent.Handle, @r, False);
end;
{procedure TfcCustomScrollBar.InvalidateThumb;
var r,br: TRect;
begin
if Parent <> nil then begin
r:= GetSectionRect(htThumb);
r.Left:= Left + r.Left;
r.Top:= Top + r.Top;
r.right:= Left + r.Right;
r.Bottom:= Top + r.Bottom;
InvalidateRect(Parent.Handle, @r, False);
r:= GetSectionRect(htPageUp);
r.Left:= Left + r.Left;
r.Top:= Top + r.Top;
r.right:= Left + r.Right;
r.Bottom:= Top + r.Bottom;
InvalidateRect(Parent.Handle, @r, False);
r:= GetSectionRect(htPageDown);
r.Left:= Left + r.Left;
r.Top:= Top + r.Top;
r.right:= Left + r.Right;
r.Bottom:= Top + r.Bottom;
InvalidateRect(Parent.Handle, @r, False);
end;
end;
}
procedure TfcCustomScrollBar.MouseLoop(X, Y: Integer);
var ACursor: TPoint;
Msg: TMsg;
FirstTimeMouseMove: boolean;
begin
SetCapture(Parent.Handle);
FirstTimeMouseMove:= True;
DragOffset:= 0;
try
while GetCapture = Parent.Handle do
begin
GetCursorPos(ACursor);
case Integer(GetMessage(Msg, 0, 0, 0)) of
-1: Break;
0: begin
PostQuitMessage(Msg.WParam);
Break;
end;
end;
case Msg.Message of
WM_MOUSEMOVE: begin
if FClickedPos in [htIncBtn, htDecBtn, htPageUp, htPageDown] then
continue;
if FirstTimeMouseMove then DragOrigPosition:= Position;
ACursor := ScreenToClient(ACursor);
if ACursor.X<0 then continue;
if ACursor.Y<0 then continue;
if Kind = sbVertical then
begin
DragOffset:= Acursor.y-y;
if FirstTimeMouseMove then begin
if (Y=ACursor.Y) then continue;
FirstTimeMouseMove:= False;
end
end
else begin
DragOffset:= Acursor.x-x;
if FirstTimeMouseMove then begin
if (X=ACursor.X) then continue;
FirstTimeMouseMove:= False;
end
end;
if ContinuousDrag and (FClickedPos in [htThumb]) then begin
FPriorPosition:= position;
position:= Trunc(DragOrigPosition + DragOffset/ScrollScreenRange * (Max-Min+incr-PageSize));
Scroll(SB_THUMBPOSITION, position);
end;
PaintScrollRegion(False); { Don't invalidate whole region to prevent flicker }
end;
WM_LBUTTONUP: begin
MouseLoop_MouseUp(X, Y, ACursor);
TranslateMessage(Msg); // So OnMouseUp fires
DispatchMessage(Msg);
if GetCapture = Parent.Handle then ReleaseCapture;
end;
else begin
TranslateMessage(Msg); // So OnMouseUp fires
DispatchMessage(Msg);
end;
end;
end;
finally
if GetCapture = Parent.Handle then ReleaseCapture;
DragOffset:= 0;
DragOrigPosition:= -1;
end;
end;
procedure TfcCustomScrollBar.MouseLoop_MouseUp(X, Y: Integer; ACursorPos: TPoint);
begin
if FClickedPos in [htIncBtn, htDecBtn, htPageUp, htPageDown] then
begin
FTimer.Enabled := False;
FClickedPos := htNone;
Invalidate;
end
else begin
if (DragOrigPosition>=0) and (DragOffset<>0) then
begin
position:= Trunc(DragOrigPosition + DragOffset/ScrollScreenRange * (Max-Min+incr-PageSize));
Scroll(SB_THUMBPOSITION, position);
end
end;
end;
procedure TfcCustomScrollBar.ScrollPosChange(OldPos, NewPos: Integer);
begin
if Assigned(FOnChange) then FOnChange(self, OldPos, NewPos);
end;
type TfcDirection = (sbLeft, sbRight, sbUp, sbDown);
procedure TfcCustomScrollBar.Paint;
begin
PaintScrollRegion(True);
end;
procedure TfcCustomScrollBar.PaintScrollRegion(All: boolean);
procedure PaintButton(Rect: TRect; Direction: TfcDirection; Down: Boolean);
const
SCROLLDIRECTIONS: array[TfcDirection] of Integer = (DFCS_SCROLLLEFT, DFCS_SCROLLRIGHT,
DFCS_SCROLLDOWN, DFCS_SCROLLUP);
PUSHED: array[Boolean] of Integer = (0, DFCS_FLAT or DFCS_PUSHED);
begin
DrawFrameControl(Canvas.Handle, Rect, DFC_SCROLL, SCROLLDIRECTIONS[Direction] or PUSHED[Down]);
end;
procedure PaintClient(Rect: TRect; Down: Boolean);
var ACursor: TPoint;
begin
GetCursorPos(ACursor);
ACursor := ScreenToClient(ACursor);
if Down and (GetHitTestInfo(ACursor.X, ACursor.Y)=FClickedPos) then
begin
// Canvas.Brush.color:= clBlack;
// Canvas.FillRect(Rect);
fcDither(Canvas, Rect, clBlack, RGB(64,64,64));
exit;
end;
fcDither(Canvas, Rect, clSilver, clWhite);
end;
procedure PaintThumb(Rect: TRect);
begin
if Kind=sbVertical then
Rect.Left:= Rect.Left + 1;
DrawFrameControl(Canvas.Handle, Rect, DFC_BUTTON, DFCS_BUTTONPUSH);
with Rect, Canvas do begin
Pen.Color := clBtnFace;
Polyline([Point(Left-1, Bottom-1), Point(Left-1, Top-1), Point(Right+1, Top-1)]);
end;
end;
var IncDir, DecDir: TfcDirection;
begin
if Kind = sbVertical then
begin
IncDir := sbUp;
DecDir := sbDown;
end else begin
IncDir := sbRight;
DecDir := sbLeft;
end;
// if fClickedPos = htPageUp then
// Screen.cursor:= crArrow;
if All then
begin
PaintButton(GetSectionRect(htIncBtn), IncDir, FClickedPos = htIncBtn);
PaintButton(GetSectionRect(htDecBtn), DecDir, FClickedPos = htDecBtn);
end;
PaintClient(GetSectionRect(htPageUp), FClickedPos=htPageUp);
PaintClient(GetSectionRect(htPageDown), FClickedPos=htPageDown);
PaintThumb(GetSectionRect(htThumb));
end;
{ Number of pixels in scroll area, thumb region excluded }
Function TfcCustomScrollBar.ScrollScreenRange: integer;
var ThumbSize: integer;
begin
if Kind = sbVertical then begin
if FixedThumbSize then
ThumbSize:= 16
else begin
ThumbSize:= Trunc(PageSize/(Max-Min+incr) * (Height-(GetSectionRect(htDecBtn).Bottom-1)*2));
ThumbSize:= fcmax(ThumbSize, MinThumbSize);
end;
result:= Height-(GetSectionRect(htDecBtn).Bottom)*2-ThumbSize;
end
else begin
ThumbSize:= Trunc(PageSize/(Max-Min+incr) * (Width-(GetSectionRect(htDecBtn).Right-1)*2));
result:= Width-(GetSectionRect(htDecBtn).Right)*2-ThumbSize
end;
if result=0 then result:= 1; { Don't allow 0 }
end;
function TfcCustomScrollBar.GetSectionRect(Section: TfcScrollBarHitTest): TRect;
var ThumbSize, StartPos: integer;
Function ScrollScreenRange: integer;
begin
if Kind = sbVertical then
result:= Height-(GetSectionRect(htDecBtn).Bottom)*2-ThumbSize
else
result:= Width-(GetSectionRect(htDecBtn).Right)*2-ThumbSize
end;
begin
if PageSize>=Max-Min+incr then exit;
case Section of
htNone: result := Rect(0, 0, 0, 0);
htThumb: begin
if FixedThumbSize then
ThumbSize:= 16
else begin
if Kind = sbVertical then begin
ThumbSize:=
Trunc(PageSize/(Max-Min+incr) * (Height-(GetSectionRect(htDecBtn).Bottom-1)*2));
ThumbSize:= fcmax(ThumbSize, MinThumbSize);
end
else
ThumbSize:= Trunc(PageSize/(Max-Min+incr) * (Width-(GetSectionRect(htDecBtn).Right-1)*2));
end;
if DragOrigPosition>=0 then
StartPos:= Trunc(((DragOrigPosition-Min)/(Max-Min+incr-PageSize)) * ScrollScreenRange)
else
StartPos:= Trunc(((Position-Min)/(Max-Min+incr-PageSize)) * ScrollScreenRange);
StartPos:= fcLimit(StartPos+DragOffset, 0, ScrollScreenRange);
if Kind = sbVertical then
begin
StartPos:= StartPos + GetSectionRect(htDecBtn).bottom;
result := Rect(0, StartPos+1, Width, StartPos + ThumbSize);
end
else begin
StartPos:= StartPos + GetSectionRect(htDecBtn).Right;
result := Rect(StartPos+1, 1, StartPos + ThumbSize, Height);
end;
end;
htIncBtn:
if Kind = sbVertical then
result := Rect(0,
Height-fcMin(GetSystemMetrics(SM_CYVSCROLL), Height div 3),
Width, Height)
else result := Rect(
Width-fcMin(GetSystemMetrics(SM_CXHSCROLL), Width div 3), 0,
Width, Height);
htDecBtn:
if Kind = sbVertical then
result := Rect(0, 0, Width,
fcMin(GetSystemMetrics(SM_CYVSCROLL), Height div 3))
else result := Rect(0, 0,
fcMin(GetSystemMetrics(SM_CXHSCROLL), Width div 3),
Height);
htPageUp:
if Kind = sbVertical then
result := Rect(0, GetSectionRect(htThumb).Bottom, Width, GetSectionRect(htIncBtn).Top)
else result := Rect(GetSectionRect(htThumb).Right, 0, GetSectionRect(htIncBtn).Left, Height);
htPageDown:
if Kind = sbVertical then
result := Rect(0, GetSectionRect(htDecBtn).Bottom, Width, GetSectionRect(htThumb).Top)
else result := Rect(GetSectionRect(htDecBtn).Right, 0, GetSectionRect(htThumb).Left, Height);
end;
end;
function TfcCustomScrollBar.GetHitTestInfo(X, Y: Integer): TfcScrollBarHitTest;
begin
for result := Low(TfcScrollBarHitTest) to High(TfcScrollBarHitTest) do
if PtInRect(GetSectionRect(result), Point(x, y)) then Break;
end;
procedure TfcCustomScrollBar.MoveScrollPos;
var OldPos, NewPos: Integer;
begin
OldPos := FPosition;
FPriorPosition:= FPosition;
case FClickedPos of
htIncBtn: begin
Position := Position + SmallChange;
{if OldPos<>Position then }Scroll(SB_LINEDOWN, Position);
end;
htDecBtn: begin
Position := Position - SmallChange;
{if OldPos<>Position then} Scroll(SB_LINEUP, Position);
end;
htPageUp: begin
Position := Position + PageSize;
{if OldPos<>Position then }Scroll(SB_PAGEDOWN, Position);
end;
htPageDown: begin
Position := Position - PageSize;
{if OldPos<>Position then }Scroll(SB_PAGEUP, Position);
end;
end;
NewPos := FPosition;
ScrollPosChange(OldPos, NewPos);
end;
procedure TfcCustomScrollBar.SetParams(APosition, AMax, AMin: Integer);
begin
FPosition := APosition;
FMax := AMax;
FMin := AMin;
end;
procedure TfcCustomScrollBar.Scroll(ScrollCode: integer; Position: integer);
begin
end;
{procedure TfcCustomScrollBar.WMNCHitTest(var Message: TWMNCHitTest);
begin
DefaultHandler(Message);
end;
}
procedure TfcCustomScrollBar.CMDesignHitTest(var Message: TCMDesignHitTest);
//var HitTest: TfcHitTests;
begin
{ HitTest:= GetHitTestInfoAt(Message.xPos, Message.yPos);
if fchtToRight in HitTest then begin
Message.Result:= 1;
end
else }
message.result:= 1;
// inherited;
end;
procedure TfcCustomScrollBar.WndProc(var Message: TMessage);
begin
inherited;
end;
end.
|
unit CSRequests;
{ Задачи и запросы, которыми обменивается клиент с сервером }
{ $Id: CSRequests.pas,v 1.1 2010/02/24 10:30:50 narry Exp $ }
// $Log: CSRequests.pas,v $
// Revision 1.1 2010/02/24 10:30:50 narry
// - удаление зависимости проектов от парня
//
interface
uses
Classes,
l3Base,l3Types,
dt_Types,
CsDataPipe, csRequestTypes, csInterfaces,
ddProgressObj, ddAppConfigTypes;
type
TcsRequest = class(Tl3Base, IcsRequest)
private
f_Data: TddAppConfigNode;
f_OnChange: TcsRequestNotifyEvent;
function IsFiles(aStrings: TStrings): Boolean;
function pm_GetData: TddAppConfigNode; stdcall;
function pm_GetDate: TDateTime; stdcall;
function pm_GetDescription: string; stdcall;
function pm_GetIndex: LongInt; stdcall;
function pm_GetOnChange: TcsRequestNotifyEvent; stdcall;
function pm_GetPriority: Integer; stdcall;
function pm_GetTaskFolder: string; stdcall;
function pm_GetTaskID: ShortString;
function pm_GetTaskType: TcsRequestType; stdcall;
function pm_GetUserID: TUserID; stdcall;
function pm_GetVersion: Integer; stdcall;
procedure pm_SetDescription(const Value: string); stdcall;
procedure pm_SetIndex(const Value: LongInt); stdcall;
procedure pm_SetOnChange(const Value: TcsRequestNotifyEvent); stdcall;
procedure pm_SetPriority(const Value: Integer); stdcall;
procedure pm_SetTaskType(const Value: TcsRequestType); stdcall;
procedure pm_SetUserID(const Value: TUserID); stdcall;
procedure pm_SetVersion(const Value: Integer); stdcall;
protected
procedure Cleanup; override;
procedure pm_SetTaskFolder(const Value: string); virtual;
procedure ReadFileFrom(aStream: TStream; aFolderName: String; aMode: TddFileRenameMode = dd_frmUnique);
procedure ReadFilesFrom(aStream: TStream; aFilesList: TStrings; const aTempFolder: String; aMode: TddFileRenameMode =
dd_frmUnique);
procedure ReadFolderFrom(aStream: TStream; const aFolder: String; aMode: TddFileRenameMode =
dd_frmUnique);
procedure ReadString(aStream: TStream; out aStr: String);
procedure ReadStrings(aStream: TStream; aStrings: TStrings);
procedure WriteFilesTo(aStream: TStream; aFilesList: TStrings);
procedure WriteFileTo(aStream: TStream; aFileName: String; const aLocalName: String = '');
procedure WriteFolderTo(aStream: TStream; const aFolder: String);
procedure WriteString(aStream: TStream; const Str: String);
procedure WriteStrings(aStream: TStream; aStrings: TStrings);
public
constructor Create(aOwner: TObject; aUserID: TUserID); reintroduce; virtual;
procedure Assign(P: TPersistent); override;
procedure LoadFrom(aStream: TStream; aIsPipe: Boolean);
function OCompare(anObject: TObject): Long; override;
procedure SaveTo(aStream: TStream; aIsPipe: Boolean);
procedure SaveToPipe(aPipe: TCsDataPipe); virtual;
property Data: TddAppConfigNode read pm_GetData;
property Date: TDateTime read pm_GetDate;
property Description: string read pm_GetDescription write pm_SetDescription;
property Index: LongInt read pm_GetIndex write pm_SetIndex;
property Priority: Integer read pm_GetPriority write pm_SetPriority;
property TaskFolder: string read pm_GetTaskFolder write pm_SetTaskFolder;
property TaskID: ShortString read pm_GetTaskID;
property TaskType: TcsRequestType read pm_GetTaskType write pm_SetTaskType;
property UserID: TUserID read pm_GetUserID write pm_SetUserID;
property Version: Integer read pm_GetVersion write pm_SetVersion;
property OnChange: TcsRequestNotifyEvent read pm_GetOnChange write pm_SetOnChange;
end;
TcsRequestClass = class of TcsRequest;
TcsRequestRecord = record
TaskClass: TcsRequestClass;
Description: String;
end;
type
TcsRequestArray = array[TcsRequestType] of TcsRequestRecord;
function CompareTaskStatus(aStatus1, aStatus2 : TcsRequestStatus): Integer;
const
dd_tpHighest = 0;
dd_tpHigh = 25;
dd_tpNormal = 50;
dd_tpLow = 75;
dd_tpLowest = 100;
dd_tpDead = High(Integer);
dd_tpAutoClass = dd_tpLowest;
dd_tpAutoClassRun = Pred(dd_tpAutoClass);
CorrectPriorities : array[TPriority] of Integer =
(dd_tpLowest, dd_tpLow, dd_tpNormal, dd_tpHigh, dd_tpHighest);
TaskStatusNames: array[TcsRequestStatus] of String = (
'не определен',
'в очереди',
'выполняется',
'заморожено',
'выполнение приостановлено',
'ожидание доставки пользователю',
'обработано',
'удалено',
'выполнение привело к ошибке'
);
const
reqDescription = 0;
reqIndex = 1;
reqDate = 2;
reqPriority = 3;
reqID = 4;
reqType = 5;
reqUser = 6;
reqVersion = 7;
reqFolder = 8;
reqChildProperty = 9;
implementation
Uses
Math, DateUtils, SysUtils, StrUtils,
ddAppConfigUtils, ddAppConfigConst,
l3FileUtils, l3Stream, l3Memory, ddAppConfigStrings, l3LongintList;
(*
const
TaskTypeNames: TcsRequestArray = (
(TaskClass:TddImportTaskItem; Description:'импорт'),
(TaskClass:TddExportTaskItem; Description:'экспорт'),
(TaskClass:TddProcessTask; Description:'автоклассификация документов'),
(TaskClass:TddAnnotationTaskItem; Description:'экспорт специальных аннотаций'),
(TaskClass:TDictEditQuery; Description:'изменение словаря'),
(TaskClass:TddRequestTask; Description:'запрос'),
(TaskClass:TddGetTaskRequest; Description:'запрос задания'),
(TaskClass:TddLineRequest; Description:'запрос очереди'),
(TaskClass:TddServerStatusRequest; Description:'запрос статуса сервера'),
(TaskClass:TcsRequestResultRequest; Description:'запрос результата задания'),
(TaskClass:TddFNSExport; Description:'экпорт для ФНС'),
(TaskClass:TUserEditQuery; Description:'изменения данных пользователей'),
(TaskClass:TDeleteDocsQuery; Description:'Удаление документов'),
(TaskClass:TddCommonDataRequest; Description:'Общие данные'),
(TaskClass:TddAutoExportTask; Description:'Автоматический экспорт документов'),
(TaskClass:TalcuAutoAnnoExport; Description:'Автоматический экспорт аннотаций'),
(TaskClass:TRemoteDictEditQuery; Description:'Удаленное редактирование словарей'),
(TaskClass:TddRegionUploadTask; Description:'Экспорт внешних дельт'),
(TaskClass:TddRunCommandTask; Description:'Выполнение команды на сервере'),
(TaskClass:TddDossierMakeTask; Description:'Создание справок постановленим ААС'),
(TaskClass:TddCaseCodeTask; Description:'Создание номеров дел для постановлений ФАС'),
(TaskClass:TalcuPrimeExportLite; Description:'Экспорт аннотаций в формате Прайм')
);
*)
function CompareTaskStatus(aStatus1, aStatus2 : TcsRequestStatus): Integer;
begin
Result := CompareValue(Ord(aStatus1), Ord(aStatus2));
end;
{
********************************* TcsRequest **********************************
}
constructor TcsRequest.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited Create(aOwner);
f_Data:= MakeNode('RequestData', 'Данные',
makeString('Описание', '', #0,
makeInteger('Индекс', -1,
MakedateTime('Дата создания', Now,
MakeInteger('Приоритет', dd_tpNormal,
MakeString('ID запроса','', #0,
makeInteger('Тип', 0,
makeInteger('ID пользователя', aUserID,
MakeInteger('Версия', 1,
MakeFolderName('Папка', '',
nil))))))))));
end;
procedure TcsRequest.Assign(P: TPersistent);
var
l_Task: TcsRequest;
begin
if P is TcsRequest then
begin
l_Task := TcsRequest(P);
f_Data.Assign(l_Task.Data);
end
else
inherited;
end;
procedure TcsRequest.Cleanup;
begin
inherited;
l3Free(f_Data);
end;
procedure TcsRequest.LoadFrom(aStream: TStream; aIsPipe: Boolean);
var
l_Type: Integer;
i: Integer;
l_Bool: Boolean;
l_DT: TDateTime;
l_Int: Integer;
l_Str: String;
l_Obj: TObject;
l_Item: TddBaseConfigItem;
begin
with aStream do
begin
for i:= 0 to Pred(data.Count) do
begin
l_Item:= Data.Items[i];
case l_Item.Value.Kind of
dd_vkBoolean:
begin
astream.Read(l_Bool, SizeOf(Boolean));
l_Item.BooleanValue:= l_Bool;
end;
dd_vkDateTime:
begin
aStream.Read(l_DT, SizeOf(TDateTime));
l_Item.DateTimeValue:= l_DT;
end;
dd_vkInteger:
begin
aStream.Read(l_Int, SizeOf(Integer));
l_Item.IntegerValue:= l_Int;
end;
dd_vkString:
begin
ReadString(aStream, l_Str);
l_Item.StringValue:= l_Str;
if aIsPipe then
if l_Item is TddFolderNameConfigItem then
ReadFolderFrom(aStream, TaskFolder)
else
if l_Item is TddFileNameConfigItem then
ReadFileFrom(aStream, TaskFolder);
end;
dd_vkObject:
begin
// Дальше временный код
l_Obj:= l_Item.ObjectValue;
(*
if l_Obj is TStrings then
//Тут может быть как список строк, так и имена файлов...
if IsFiles(TStrings(l_Obj)) then
WriteFilesTo(aStream, TStrings(l_Obj))
else
WriteStrings(aStream, TStrings(l_Obj))
else
if l_Obj is Tl3LongintList then
Tl3LongintList(l_Obj).Save(aStream);
*)
end;
end;
end; // for i
end; // with aStream
end;
function TcsRequest.IsFiles(aStrings: TStrings): Boolean;
begin
Result:= False;
if aStrings.Count > 0 then
Result := ExtractFileName(aStrings[0]) <> '';
end;
function TcsRequest.OCompare(anObject: TObject): Long;
begin
Result:= CompareValue(Priority, TcsRequest(anObject).Priority);
if Result = 0 then
Result := CompareDateTime(Date, TcsRequest(anObject).Date);
end;
function TcsRequest.pm_GetData: TddAppConfigNode;
begin
Result:= f_Data;
end;
function TcsRequest.pm_GetDate: TDateTime;
begin
Result:= f_Data.Items[reqDate].DateTimeValue;
end;
function TcsRequest.pm_GetDescription: string;
begin
Result:= f_Data.Items[reqDescription].StringValue;
end;
function TcsRequest.pm_GetIndex: LongInt;
begin
Result:= f_Data.Items[reqIndex].IntegerValue;
end;
function TcsRequest.pm_GetOnChange: TcsRequestNotifyEvent;
begin
Result:= f_OnChange;
end;
function TcsRequest.pm_GetPriority: Integer;
begin
Result:= f_Data.Items[reqPriority].IntegerValue;
end;
function TcsRequest.pm_GetTaskFolder: string;
begin
Result:= f_Data.Items[reqFolder].StringValue;
end;
function TcsRequest.pm_GetTaskID: ShortString;
begin
Result := SysUtils.Format('%d-%s', [UserID, FormatDateTime('dd-mm-ss-zzz', Date)]);
end;
function TcsRequest.pm_GetTaskType: TcsRequestType;
begin
Result:= TcsRequestType(f_Data.Items[reqType].IntegerValue);
end;
function TcsRequest.pm_GetUserID: TUserID;
begin
Result:= f_Data.Items[reqUser].IntegerValue;
end;
function TcsRequest.pm_GetVersion: Integer;
begin
Result:= f_Data.Items[reqVersion].IntegerValue;
end;
procedure TcsRequest.pm_SetDescription(const Value: string);
begin
f_Data.Items[reqDescription].StringValue:= Value;
end;
procedure TcsRequest.pm_SetIndex(const Value: LongInt);
begin
f_Data.Items[reqIndex].IntegerValue:= Value;
end;
procedure TcsRequest.pm_SetOnChange(const Value: TcsRequestNotifyEvent);
begin
f_OnChange:= Value;
end;
procedure TcsRequest.pm_SetPriority(const Value: Integer);
begin
f_Data.Items[reqPriority].IntegerValue:= Value;
end;
procedure TcsRequest.pm_SetTaskFolder(const Value: string);
begin
f_Data.Items[reqFolder].StringValue:= Value;
end;
procedure TcsRequest.pm_SetTaskType(const Value: TcsRequestType);
begin
f_Data.Items[reqType].IntegerValue:= Ord(Value);
end;
procedure TcsRequest.pm_SetUserID(const Value: TUserID);
begin
f_Data.Items[reqUser].IntegerValue:= Value;
end;
procedure TcsRequest.pm_SetVersion(const Value: Integer);
begin
f_Data.Items[reqVersion].IntegerValue:= Value;
end;
procedure TcsRequest.ReadFileFrom(aStream: TStream; aFolderName: String; aMode: TddFileRenameMode = dd_frmUnique);
var
l_Stream: TStream;
l_FileName, l_LocalFileName: string;
l_Len: Int64;
l_FileOpenMode: Tl3FileMode;
begin
{ TODO 1 -oДмитрий Дудко -cнедоделка : Нужно провести рефакторинг }
ReadString(aStream, l_FileName);
if l_FileName <> '' then
begin
l_LocalFileName := ConcatDirName(aFolderName, l_FileName);
ForceDirectories(ExtractFilePath(l_LocalFileName));
if FileExists(l_LocalFileName) then
case aMode of
dd_frmUnique : // создать уникальное имя Для нового файла
begin
l_FileName := GetUniqFileName(aFolderName, l_FileName, ''); // Для чего это нужно?!!!!
l_FileOpenMode:= l3_fmWrite;
end;
dd_frmBackup: // создать bak-копию старого файла
begin
RenameToBack(l_LocalFileName);
l_FileName := l_LocalFileName;
l_FileOpenMode:= l3_fmWrite;
end;
dd_frmAdd: // добавить в существующие
begin
l_FileOpenMode:= l3_fmAppend;
l_FileName := l_LocalFileName;
end;
dd_frmReplace: // Заменить существующий
begin
l_FileName := l_LocalFileName;
l_FileOpenMode:= l3_fmWrite;
end;
end
else
begin
l_FileName := l_LocalFileName;
l_FileOpenMode:= l3_fmWrite;
end;
aStream.Read(l_Len, SizeOf(Int64));
if l_Len > 0 then
begin
l_Stream := Tl3FileStream.Create(l_FileName, l_FileOpenMode);
try
l_Stream.CopyFrom(aStream, l_Len);
finally
l3Free(l_Stream);
end;
end; // l_Len > 0
end;
end;
procedure TcsRequest.ReadFilesFrom(aStream: TStream; aFilesList: TStrings; const aTempFolder: String; aMode:
TddFileRenameMode = dd_frmUnique);
var
i, l_Count: Integer;
begin
aStream.Read(l_Count, SizeOf(Integer));
for i:= 0 to Pred(l_Count) do
ReadFileFrom(aStream, aTempFolder, aMode);
end;
procedure TcsRequest.ReadFolderFrom(aStream: TStream; const aFolder: String; aMode:
TddFileRenameMode = dd_frmUnique);
var
l_Files: TStrings;
begin
l_Files:= TStringList.Create;
try
ReadFilesFrom(aStream, l_Files, aFolder, aMode);
finally
l3Free(l_Files);
end;
end;
procedure TcsRequest.ReadString(aStream: TStream; out aStr: String);
var
l_Len: Integer;
begin
aStr := '';
if aStream.Size - aStream.Position >= SizeOf(l_Len) then
begin
aStream.Read(l_Len, SizeOf(l_Len));
if l_Len <= aStream.Size - aStream.Position then
begin
SetLength(aStr, l_Len);
if l_Len > 0 then
aStream.Read(aStr[1], l_Len);
end;
end; // aStream.Size - aStream.Position >= SizeOf(l_Len)
end;
procedure TcsRequest.ReadStrings(aStream: TStream; aStrings: TStrings);
var
i, l_Count: Integer;
l_S: String;
begin
aStrings.Clear;
if aStream.Size - aStream.Position >= SizeOf(l_Count) then
begin
aStream.Read(l_Count, SizeOf(l_Count));
for i:= 0 to Pred(l_Count) do
begin
ReadString(aStream, l_S);
aStrings.Add(l_S);
end;
end;
end;
procedure TcsRequest.SaveTo(aStream: TStream; aIsPipe: Boolean);
var
l_Type: Integer;
i: Integer;
l_Bool: Boolean;
l_DT: TDateTime;
l_Int: Integer;
l_Str: String;
l_Obj: TObject;
l_Item: TddBaseConfigItem;
begin
with aStream do
begin
for i:= 0 to Pred(data.Count) do
begin
l_Item:= Data.Items[i];
case l_Item.Value.Kind of
dd_vkBoolean:
begin
l_Bool:= l_Item.BooleanValue;
astream.Write(l_Bool, SizeOf(Boolean));
end;
dd_vkDateTime:
begin
l_DT:= l_Item.DateTimeValue;
aStream.Write(l_DT, SizeOf(TDateTime));
end;
dd_vkInteger:
begin
l_Int:= l_Item.IntegerValue;
aStream.write(l_Int, SizeOf(Integer));
end;
dd_vkString:
begin
l_Str:= l_Item.StringValue;
writeString(aStream, l_Str);
if aIsPipe then
if l_Item is TddFolderNameConfigItem then
WriteFolderTo(aStream, l_Str)
else
if l_Item is TddFileNameConfigItem then
WriteFileTo(aStream, l_str);
end;
dd_vkObject:
begin
// Дальше временный код
l_Obj:= l_Item.ObjectValue;
if l_Obj is TStrings then
//Тут может быть как список строк, так и имена файлов...
if IsFiles(TStrings(l_Obj)) then
WriteFilesTo(aStream, TStrings(l_Obj))
else
WriteStrings(aStream, TStrings(l_Obj))
else
if l_Obj is Tl3LongintList then
Tl3LongintList(l_Obj).Save(aStream);
end;
end;
end; // for i
end; // with aStream
end;
procedure TcsRequest.SaveToPipe(aPipe: TCsDataPipe);
var
l_Stream: Tl3MemoryStream;
begin
l_Stream:= Tl3MemoryStream.Create;
try
SaveTo(l_Stream, True);
l_Stream.Seek(0, 0);
aPipe.Write(l_Stream);
finally
l3Free(l_Stream);
end;
end;
procedure TcsRequest.WriteFilesTo(aStream: TStream; aFilesList: TStrings);
var
i, l_Count, j: Integer;
l_FileName, l_LocalFile, l_LocalFolder: String;
begin
l_LocalFolder:= '';
l_Count := aFilesList.Count;
if l_Count > 0 then
if AnsiStartsText('###', aFilesList.Strings[0]) then
Dec(l_Count);
aStream.Write(l_Count, SizeOf(Integer));
for i:= 0 to Pred(aFilesList.Count) do
begin
l_FileName := aFilesList.Strings[i];
if AnsiStartsText('###', l_FileName) then
begin
Delete(l_FileName, 1, 3);
l_LocalFolder := l_FileName;
end
else
begin
l_LocalFile := l_FileName;
Delete(l_LocalFile, 1, Length(l_LocalFolder));
WriteFileTo(aStream, l_FileName, l_LocalFile);
end;
end;
end;
procedure TcsRequest.WriteFileTo(aStream: TStream; aFileName: String; const aLocalName: String = '');
var
l_Stream: TStream;
l_Len: Int64;
begin
if aLocalName = '' then
WriteString(aStream, ExtractFileName(aFileName))
else
WriteString(aStream, aLocalName);
l_Len := GetFileSize(aFileName);
aStream.Write(l_Len, SizeOf(Int64));
l_Stream := Tl3FileStream.Create(aFileName, l3_fmRead);
try
aStream.CopyFrom(l_Stream, l_Len);
finally
l3Free(l_Stream);
end;
end;
procedure TcsRequest.WriteFolderTo(aStream: TStream; const aFolder: String);
var
l_FileList: TStrings;
procedure _LoadFolder(aSubFolder: String; aList: TStrings);
var
l_SR : TSearchRec;
l_Name : String;
begin
if FindFirst(ConcatDirName(aSubFolder, '\*.*'), faAnyFile, l_SR) = 0 then
begin
repeat
if l_SR.Name[1] <> '.' then
begin
l_Name := ConcatDirName(aSubFolder, l_SR.Name);
if l_SR.Attr and faDirectory = faDirectory then
_LoadFolder(l_Name, aList)
else
l_FileList.Add(l_Name);
end; // l_SR.Name[1] <> '.'
until FindNext(l_sr) <> 0;
FindClose(l_SR);
end; // FindFirst(aFolder, faAnyFile, l_SR)
end;
begin
l_FileList := TStringList.Create;
try
l_FileList.Add(IncludeTrailingBackslash('###'+aFolder));
_LoadFolder(aFolder, l_FileList);
WriteFilesTo(aStream, l_FileList);
finally
l3Free(l_FileList);
end;
end;
procedure TcsRequest.WriteString(aStream: TStream; const Str: String);
var
l_Len: Integer;
begin
l_Len := Length(Str);
aStream.Write(l_Len, SizeOf(l_Len));
if l_Len > 0 then
aStream.Write(Str[1], l_Len);
end;
procedure TcsRequest.WriteStrings(aStream: TStream; aStrings: TStrings);
var
i, l_Count: Integer;
begin
l_Count := aStrings.Count;
aStream.Write(l_Count, SizeOf(l_Count));
for i:= 0 to Pred(l_Count) do
WriteString(aStream, aStrings[i]);
end;
end.
|
{ Subroutine SST_FLAG_USED_EXP (EXP)
*
* Flag all symbols eventually referenced by the expression EXP as used.
}
module sst_FLAG_USED_EXP;
define sst_flag_used_exp;
%include 'sst2.ins.pas';
procedure sst_flag_used_exp ( {flag symbols eventually used from expression}
in exp: sst_exp_t); {expression that may reference symbols}
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
term_p: sst_exp_term_p_t; {points to current term in expression}
ele_p: sst_ele_exp_p_t; {points to current set elements descriptor}
ifarg_p: sst_exp_chain_p_t; {points to current itrinsic function argument}
msg_parm: {references to paramters for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
begin
if exp.dtype_p <> nil then begin {this expression has a data type ?}
sst_flag_used_dtype (exp.dtype_p^); {flag symbols used by data type}
end;
term_p := addr(exp.term1); {init current term to first in expression}
while term_p <> nil do begin {once for each term in expression}
if exp.term1.next_p <> nil then begin {expression has more than one term ?}
sst_flag_used_dtype (term_p^.dtype_p^); {declare dtype syms for this term}
end;
case term_p^.ttype of {what kind of term is this ?}
{
* Term is a constant.
}
sst_term_const_k: ;
{
* Term is a variable reference.
}
sst_term_var_k: begin
sst_flag_used_var (term_p^.var_var_p^);
end;
{
* Term is a function reference.
}
sst_term_func_k: begin
sst_flag_used_var (term_p^.func_var_p^);
sst_flag_used_rout (term_p^.func_proc_p^);
end;
{
* Term is an intrinsic function reference.
}
sst_term_ifunc_k: begin
ifarg_p := term_p^.ifunc_args_p; {init current ifunc argument to first arg}
while ifarg_p <> nil do begin {once for each argument}
sst_flag_used_exp (ifarg_p^.exp_p^);
ifarg_p := ifarg_p^.next_p; {advance to next argument}
end; {back and process this new argument}
end;
{
* Term is explicit type-casting function.
}
sst_term_type_k: begin
sst_flag_used_dtype (term_p^.type_dtype_p^);
sst_flag_used_exp (term_p^.type_exp_p^);
end;
{
* Term is a SET value.
}
sst_term_set_k: begin
ele_p := term_p^.set_first_p; {init first elements descriptor to current}
while ele_p <> nil do begin {once for each elements descriptor in set}
sst_flag_used_exp (ele_p^.first_p^); {flag ele range start value exp as used}
if ele_p^.last_p <> nil then begin {ele end range expression exists ?}
sst_flag_used_exp (ele_p^.last_p^);
end;
ele_p := ele_p^.next_p; {advance to next elements descriptor}
end; {back and process this new elements descriptor}
end;
{
* Term is nested expression.
}
sst_term_exp_k: begin
sst_flag_used_exp (term_p^.exp_exp_p^); {process nested expression}
end;
{
* Term is the value of a field in a record.
}
sst_term_field_k: begin
sst_flag_used_symbol (term_p^.field_sym_p^);
sst_flag_used_exp (term_p^.field_exp_p^);
end;
{
* Term is the value of a range of array subscripts.
}
sst_term_arele_k: begin
sst_flag_used_exp (term_p^.arele_exp_p^);
end;
{
* Unrecognized or illegal term type.
}
otherwise
sys_msg_parm_int (msg_parm[1], ord(term_p^.ttype));
syo_error (term_p^.str_h, 'sst', 'term_type_unknown', msg_parm, 1);
end; {end of term type cases we needed to handle}
term_p := term_p^.next_p; {advance to next term in expression}
end; {back and process this new term in expression}
end;
|
unit PI.View.Devices;
interface
uses
// RTL
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
// FMX
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.ListBox, FMX.Controls.Presentation, FMX.StdCtrls,
// PushIt
PI.Types;
type
TDevicesView = class(TForm)
ListBox: TListBox;
BottomLayout: TLayout;
CancelButton: TButton;
UseButton: TButton;
DeviceTimer: TTimer;
procedure UseButtonClick(Sender: TObject);
procedure DeviceTimerTimer(Sender: TObject);
procedure ListBoxItemClick(const Sender: TCustomListBox; const Item: TListBoxItem);
private
FDeviceInfos: TDeviceInfos;
FSelectedDeviceInfo: TDeviceInfo;
FOnDevicesChange: TNotifyEvent;
procedure DeviceBroadcastHandler(Sender: TObject; const ADeviceInfo: TDeviceInfo);
procedure DeviceSelected;
function GetIsMonitoring: Boolean;
procedure ItemDblClickHandler(Sender: TObject);
procedure SetIsMonitoring(const Value: Boolean);
procedure UpdateDeviceInfoViews;
public
constructor Create(AOwner: TComponent); override;
property DeviceInfos: TDeviceInfos read FDeviceInfos;
property IsMonitoring: Boolean read GetIsMonitoring write SetIsMonitoring;
property SelectedDeviceInfo: TDeviceInfo read FSelectedDeviceInfo;
property OnDevicesChange: TNotifyEvent read FOnDevicesChange write FOnDevicesChange;
end;
var
DevicesView: TDevicesView;
implementation
{$R *.fmx}
uses
// PushIt
PI.Resources, PI.Network, PI.View.DeviceInfo;
type
TDeviceInfoItem = class(TListBoxItem)
private
FView: TDeviceInfoView;
procedure ViewClickHandler(Sender: TObject);
procedure ViewDblClickHandler(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
property View: TDeviceInfoView read FView;
end;
{ TDeviceInfoItem }
constructor TDeviceInfoItem.Create(AOwner: TComponent);
begin
inherited;
FView := TDeviceInfoView.Create(Self);
Height := FView.Height;
FView.OnClick := ViewClickHandler;
FView.OnDblClick := ViewDblClickHandler;
FView.Align := TAlignLayout.Client;
FView.Parent := Self;
end;
procedure TDeviceInfoItem.ViewClickHandler(Sender: TObject);
begin
ListBox.OnItemClick(ListBox, Self);
end;
procedure TDeviceInfoItem.ViewDblClickHandler(Sender: TObject);
begin
OnDblClick(Self);
end;
{ TDevicesView }
constructor TDevicesView.Create(AOwner: TComponent);
begin
inherited;
Network.OnDeviceBroadcast := DeviceBroadcastHandler;
end;
procedure TDevicesView.DeviceBroadcastHandler(Sender: TObject; const ADeviceInfo: TDeviceInfo);
begin
if FDeviceInfos.Add(ADeviceInfo) then
UpdateDeviceInfoViews;
end;
procedure TDevicesView.DeviceSelected;
begin
FSelectedDeviceInfo := TDeviceInfoItem(ListBox.ListItems[ListBox.ItemIndex]).View.DeviceInfo;
ModalResult := mrOk;
end;
procedure TDevicesView.DeviceTimerTimer(Sender: TObject);
begin
if FDeviceInfos.Expire(2) then
UpdateDeviceInfoViews;
end;
function TDevicesView.GetIsMonitoring: Boolean;
begin
Result := Network.UDPServer.Active;
end;
procedure TDevicesView.ItemDblClickHandler(Sender: TObject);
begin
DeviceSelected;
end;
procedure TDevicesView.ListBoxItemClick(const Sender: TCustomListBox; const Item: TListBoxItem);
begin
UseButton.Enabled := True;
end;
procedure TDevicesView.SetIsMonitoring(const Value: Boolean);
begin
Network.UDPServer.Active := Value;
end;
procedure TDevicesView.UseButtonClick(Sender: TObject);
begin
DeviceSelected;
end;
procedure TDevicesView.UpdateDeviceInfoViews;
var
I: Integer;
LItem: TDeviceInfoItem;
begin
if csDestroying in ComponentState then
Exit; // <======
ListBox.Clear;
for I := 0 to FDeviceInfos.Count - 1 do
begin
LItem := TDeviceInfoItem.Create(Self);
LItem.View.DeviceInfo := FDeviceInfos[I];
ListBox.ItemHeight := LItem.View.Height;
LItem.OnDblClick := ItemDblClickHandler;
LItem.Parent := ListBox;
end;
if ListBox.Items.Count = 0 then
UseButton.Enabled := False;
if Assigned(FOnDevicesChange) then
FOnDevicesChange(Self);
end;
end.
|
unit fNewStatistics;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DanHexEdit, ComCtrls,cMegaROM, cConfiguration;
type
TfrmNStatistics = class(TForm)
lblStatisticsName: TLabel;
lblValue: TLabel;
txtValue: TDanHexEdit;
lstStatistics: TListBox;
cbValue: TComboBox;
cmdOK: TButton;
cmdCancel: TButton;
procedure FormShow(Sender: TObject);
procedure lstStatisticsClick(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
private
_Stats : Array Of Byte;
_PrevID : Integer;
_ROMData : TMegamanROM;
_EditorConfig : TRRConfig;
procedure LoadStatistics;
procedure SaveStatistics;
procedure PopulateTreeView;
procedure LoadData(pIndex : Integer);
procedure SaveData(pIndex : Integer);
{ Private declarations }
public
property ROMData : TMegamanROM read _ROMData write _ROMData;
property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig;
{ Public declarations }
end;
var
frmNStatistics: TfrmNStatistics;
implementation
{$R *.dfm}
procedure TfrmNStatistics.LoadStatistics;
var
i : Integer;
begin
setlength(_Stats,_ROMData.Statistics.Count);
for i := 0 to high(_Stats) do
begin
_Stats[i] := _ROMData.Statistics[i].Value;
end;
end;
procedure TfrmNStatistics.SaveStatistics;
var
i : Integer;
begin
for i := 0 to high(_Stats) do
begin
_ROMData.Statistics[i].Value := _Stats[i];
end;
end;
procedure TfrmNStatistics.FormShow(Sender: TObject);
begin
LoadStatistics;
PopulateTreeview;
end;
procedure TfrmNStatistics.LoadData(pIndex : Integer);
begin
lblStatisticsName.Caption := 'Statistics Name: ' + _ROMData.Statistics[pIndex].Name;
if _ROMData.Statistics[pIndex].List <> '' then
begin
cbValue.Visible := True;
txtValue.Visible := False;
cbValue.Items.BeginUpdate;
cbValue.Items.Clear;
cbValue.Items.LoadFromFile(ExtractFileDir(Application.EXEname) + '\Data\' + _ROMData.Statistics[pIndex].List);
cbValue.Items.EndUpdate;
cbValue.ItemIndex := _Stats[pIndex];
end
else
begin
cbValue.Visible := False;
txtValue.Visible := True;
txtValue.Text := IntToHex(_Stats[pIndex],2);
end;
end;
procedure TfrmNStatistics.SaveData(pIndex : Integer);
begin
if _ROMData.Statistics[pIndex].List <> '' then
begin
_Stats[pIndex] := cbValue.ItemIndex;
end
else
begin
_Stats[pIndex] := StrToInt('$' + txtValue.Text);
if (_Stats[pIndex] > _ROMData.Statistics[pIndex].MaximumValue) then
_Stats[pIndex] := _ROMData.Statistics[pIndex].MaximumValue;
end;
end;
procedure TfrmNStatistics.PopulateTreeView;
var
i : Integer;
begin
lstStatistics.Items.BeginUpdate;
lstStatistics.Items.Clear;
for i := 0 to _ROMData.Statistics.Count -1 do
begin
lstStatistics.Items.Add(_ROMData.Statistics[i].Name);
end;
lstStatistics.Items.EndUpdate;
lstStatistics.ItemIndex := 0;
_PrevID := 0;
LoadData(_PrevID);
end;
procedure TfrmNStatistics.lstStatisticsClick(Sender: TObject);
begin
SaveData(_PrevID);
_PrevID := lstStatistics.ItemIndex;
LoadData(_PrevID);
end;
procedure TfrmNStatistics.cmdOKClick(Sender: TObject);
begin
SaveData(_PrevID);
SaveStatistics;
end;
end.
|
unit RedirFunc;
{
Inno Setup
Copyright (C) 1997-2007 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Functions for dealing with WOW64 file system redirection.
The *Redir functions are counterparts to common functions that offer
built-in support for disabling FS redirection.
$jrsoftware: issrc/Projects/RedirFunc.pas,v 1.11 2007/09/10 11:59:14 mlaan Exp $
}
interface
uses
Windows, SysUtils, FileClass, VerInfo;
type
TPreviousFsRedirectionState = record
DidDisable: Boolean;
OldValue: Pointer;
end;
function AreFsRedirectionFunctionsAvailable: Boolean;
function DisableFsRedirectionIf(const Disable: Boolean;
var PreviousState: TPreviousFsRedirectionState): Boolean;
procedure RestoreFsRedirection(const PreviousState: TPreviousFsRedirectionState);
function CreateDirectoryRedir(const DisableFsRedir: Boolean; const Filename: String): BOOL;
function CreateProcessRedir(const DisableFsRedir: Boolean;
const lpApplicationName: PChar; const lpCommandLine: PChar;
const lpProcessAttributes, lpThreadAttributes: PSecurityAttributes;
const bInheritHandles: BOOL; const dwCreationFlags: DWORD;
const lpEnvironment: Pointer; const lpCurrentDirectory: PChar;
const lpStartupInfo: TStartupInfo;
var lpProcessInformation: TProcessInformation): BOOL;
function CopyFileRedir(const DisableFsRedir: Boolean;
const ExistingFilename, NewFilename: String; const FailIfExists: BOOL): BOOL;
function DeleteFileRedir(const DisableFsRedir: Boolean; const Filename: String): BOOL;
function DirExistsRedir(const DisableFsRedir: Boolean; const Filename: String): Boolean;
function FileOrDirExistsRedir(const DisableFsRedir: Boolean; const Filename: String): Boolean;
function FindFirstFileRedir(const DisableFsRedir: Boolean; const Filename: String;
var FindData: TWin32FindData): THandle;
function GetFileAttributesRedir(const DisableFsRedir: Boolean; const Filename: String): DWORD;
function GetShortNameRedir(const DisableFsRedir: Boolean; const Filename: String): String;
function GetVersionNumbersRedir(const DisableFsRedir: Boolean; const Filename: String;
var VersionNumbers: TFileVersionNumbers): Boolean;
function IsDirectoryAndNotReparsePointRedir(const DisableFsRedir: Boolean;
const Name: String): Boolean;
function MoveFileRedir(const DisableFsRedir: Boolean;
const ExistingFilename, NewFilename: String): BOOL;
function MoveFileExRedir(const DisableFsRedir: Boolean;
const ExistingFilename, NewFilename: String; const Flags: DWORD): BOOL;
function NewFileExistsRedir(const DisableFsRedir: Boolean; const Filename: String): Boolean;
function RemoveDirectoryRedir(const DisableFsRedir: Boolean; const Filename: String): BOOL;
function SetFileAttributesRedir(const DisableFsRedir: Boolean; const Filename: String;
const Attrib: DWORD): BOOL;
function SetNTFSCompressionRedir(const DisableFsRedir: Boolean; const FileOrDir: String; Compress: Boolean): Boolean;
type
TFileRedir = class(TFile)
private
FDisableFsRedir: Boolean;
protected
function CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle; override;
public
constructor Create(const DisableFsRedir: Boolean; const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing);
end;
TTextFileReaderRedir = class(TTextFileReader)
private
FDisableFsRedir: Boolean;
protected
function CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle; override;
public
constructor Create(const DisableFsRedir: Boolean; const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing);
end;
TTextFileWriterRedir = class(TTextFileWriter)
private
FDisableFsRedir: Boolean;
protected
function CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle; override;
public
constructor Create(const DisableFsRedir: Boolean; const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing);
end;
implementation
uses
CmnFunc2;
var
Wow64DisableWow64FsRedirectionFunc: function(var OldValue: Pointer): BOOL; stdcall;
Wow64RevertWow64FsRedirectionFunc: function(OldValue: Pointer): BOOL; stdcall;
FsRedirectionFunctionsAvailable: Boolean;
function AreFsRedirectionFunctionsAvailable: Boolean;
begin
Result := FsRedirectionFunctionsAvailable;
end;
function DisableFsRedirectionIf(const Disable: Boolean;
var PreviousState: TPreviousFsRedirectionState): Boolean;
{ If Disable is False, the function does not change the redirection state and
always returns True.
If Disable is True, the function attempts to disable WOW64 file system
redirection, so that c:\windows\system32 goes to the 64-bit System directory
instead of the 32-bit one.
Returns True if successful, False if not (which normally indicates that
either the user is running 32-bit Windows, or a 64-bit version prior to
Windows Server 2003 SP1). For extended error information when False is
returned, call GetLastError. }
begin
PreviousState.DidDisable := False;
if not Disable then
Result := True
else begin
if FsRedirectionFunctionsAvailable then begin
{ Note: Disassembling Wow64DisableWow64FsRedirection and the Rtl function
it calls, it doesn't appear as if it can ever actually fail on 64-bit
Windows. But it always fails on the 32-bit version of Windows Server
2003 SP1 (with error code 1 - ERROR_INVALID_FUNCTION). }
Result := Wow64DisableWow64FsRedirectionFunc(PreviousState.OldValue);
if Result then
PreviousState.DidDisable := True;
end
else begin
{ The functions do not exist prior to Windows Server 2003 SP1 }
SetLastError(ERROR_INVALID_FUNCTION);
Result := False;
end;
end;
end;
procedure RestoreFsRedirection(const PreviousState: TPreviousFsRedirectionState);
{ Restores the previous WOW64 file system redirection state after a call to
DisableFsRedirectionIf. There is no indication of failure (which is
extremely unlikely). }
begin
if PreviousState.DidDisable then
Wow64RevertWow64FsRedirectionFunc(PreviousState.OldValue);
end;
{ *Redir functions }
function CreateDirectoryRedir(const DisableFsRedir: Boolean; const Filename: String): BOOL;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := CreateDirectory(PChar(Filename), nil);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function CreateProcessRedir(const DisableFsRedir: Boolean;
const lpApplicationName: PChar; const lpCommandLine: PChar;
const lpProcessAttributes, lpThreadAttributes: PSecurityAttributes;
const bInheritHandles: BOOL; const dwCreationFlags: DWORD;
const lpEnvironment: Pointer; const lpCurrentDirectory: PChar;
const lpStartupInfo: TStartupInfo;
var lpProcessInformation: TProcessInformation): BOOL;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := CreateProcess(lpApplicationName, lpCommandLine,
lpProcessAttributes, lpThreadAttributes,
bInheritHandles, dwCreationFlags, lpEnvironment,
lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function CopyFileRedir(const DisableFsRedir: Boolean;
const ExistingFilename, NewFilename: String; const FailIfExists: BOOL): BOOL;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := CopyFile(PChar(ExistingFilename), PChar(NewFilename), FailIfExists);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function DeleteFileRedir(const DisableFsRedir: Boolean; const Filename: String): BOOL;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := Windows.DeleteFile(PChar(Filename));
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function DirExistsRedir(const DisableFsRedir: Boolean; const Filename: String): Boolean;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := DirExists(Filename);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function FileOrDirExistsRedir(const DisableFsRedir: Boolean; const Filename: String): Boolean;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := FileOrDirExists(Filename);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function FindFirstFileRedir(const DisableFsRedir: Boolean; const Filename: String;
var FindData: TWin32FindData): THandle;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := INVALID_HANDLE_VALUE;
Exit;
end;
try
Result := FindFirstFile(PChar(Filename), FindData);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function GetFileAttributesRedir(const DisableFsRedir: Boolean; const Filename: String): DWORD;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := $FFFFFFFF;
Exit;
end;
try
Result := GetFileAttributes(PChar(Filename));
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function GetShortNameRedir(const DisableFsRedir: Boolean; const Filename: String): String;
var
PrevState: TPreviousFsRedirectionState;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := Filename;
Exit;
end;
try
Result := GetShortName(Filename);
finally
RestoreFsRedirection(PrevState);
end;
end;
function GetVersionNumbersRedir(const DisableFsRedir: Boolean; const Filename: String;
var VersionNumbers: TFileVersionNumbers): Boolean;
var
PrevState: TPreviousFsRedirectionState;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := GetVersionNumbers(Filename, VersionNumbers);
finally
RestoreFsRedirection(PrevState);
end;
end;
function IsDirectoryAndNotReparsePointRedir(const DisableFsRedir: Boolean;
const Name: String): Boolean;
var
PrevState: TPreviousFsRedirectionState;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := IsDirectoryAndNotReparsePoint(Name);
finally
RestoreFsRedirection(PrevState);
end;
end;
function MoveFileRedir(const DisableFsRedir: Boolean;
const ExistingFilename, NewFilename: String): BOOL;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := MoveFile(PChar(ExistingFilename), PChar(NewFilename));
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function MoveFileExRedir(const DisableFsRedir: Boolean;
const ExistingFilename, NewFilename: String; const Flags: DWORD): BOOL;
var
NewFilenameP: PChar;
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if (NewFilename = '') and (Flags and MOVEFILE_DELAY_UNTIL_REBOOT <> 0) then
NewFilenameP := nil
else
NewFilenameP := PChar(NewFilename);
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := MoveFileEx(PChar(ExistingFilename), NewFilenameP, Flags);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function NewFileExistsRedir(const DisableFsRedir: Boolean; const Filename: String): Boolean;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := NewFileExists(Filename);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function RemoveDirectoryRedir(const DisableFsRedir: Boolean; const Filename: String): BOOL;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := RemoveDirectory(PChar(Filename));
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function SetFileAttributesRedir(const DisableFsRedir: Boolean; const Filename: String;
const Attrib: DWORD): BOOL;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := SetFileAttributes(PChar(Filename), Attrib);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
function SetNTFSCompressionRedir(const DisableFsRedir: Boolean; const FileOrDir: String; Compress: Boolean): Boolean;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(DisableFsRedir, PrevState) then begin
Result := False;
Exit;
end;
try
Result := SetNTFSCompression(FileOrDir, Compress);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
{ TFileRedir }
constructor TFileRedir.Create(const DisableFsRedir: Boolean; const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing);
begin
FDisableFsRedir := DisableFsRedir;
inherited Create(AFilename, ACreateDisposition, AAccess, ASharing);
end;
function TFileRedir.CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(FDisableFsRedir, PrevState) then begin
Result := INVALID_HANDLE_VALUE;
Exit;
end;
try
Result := inherited CreateHandle(AFilename, ACreateDisposition, AAccess,
ASharing);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
{ TTextFileReaderRedir }
constructor TTextFileReaderRedir.Create(const DisableFsRedir: Boolean; const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing);
begin
FDisableFsRedir := DisableFsRedir;
inherited Create(AFilename, ACreateDisposition, AAccess, ASharing);
end;
function TTextFileReaderRedir.CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(FDisableFsRedir, PrevState) then begin
Result := INVALID_HANDLE_VALUE;
Exit;
end;
try
Result := inherited CreateHandle(AFilename, ACreateDisposition, AAccess,
ASharing);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
{ TTextFileWriterRedir }
constructor TTextFileWriterRedir.Create(const DisableFsRedir: Boolean; const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing);
begin
FDisableFsRedir := DisableFsRedir;
inherited Create(AFilename, ACreateDisposition, AAccess, ASharing);
end;
function TTextFileWriterRedir.CreateHandle(const AFilename: String;
ACreateDisposition: TFileCreateDisposition; AAccess: TFileAccess;
ASharing: TFileSharing): THandle;
var
PrevState: TPreviousFsRedirectionState;
ErrorCode: DWORD;
begin
if not DisableFsRedirectionIf(FDisableFsRedir, PrevState) then begin
Result := INVALID_HANDLE_VALUE;
Exit;
end;
try
Result := inherited CreateHandle(AFilename, ACreateDisposition, AAccess,
ASharing);
ErrorCode := GetLastError;
finally
RestoreFsRedirection(PrevState);
end;
SetLastError(ErrorCode);
end;
initialization
Wow64DisableWow64FsRedirectionFunc := GetProcAddress(GetModuleHandle(kernel32),
'Wow64DisableWow64FsRedirection');
Wow64RevertWow64FsRedirectionFunc := GetProcAddress(GetModuleHandle(kernel32),
'Wow64RevertWow64FsRedirection');
FsRedirectionFunctionsAvailable := Assigned(Wow64DisableWow64FsRedirectionFunc) and
Assigned(Wow64RevertWow64FsRedirectionFunc);
{ For GetVersionNumbersRedir: Pre-load shell32.dll since GetFileVersionInfo
and GetFileVersionInfoSize will try to load it when reading version info
on 16-bit files. We can't allow the DLL be loaded for the first time while
FS redirection is disabled. }
SafeLoadLibrary('shell32.dll', SEM_NOOPENFILEERRORBOX);
{ FormatMessage might be called with FS redirection disabled, so ensure
that all the DLLs FormatMessage searches in for messages (e.g. netmsg.dll,
ws03res.dll) are pre-loaded by calling it now with a randomly-chosen
message ID -- one that won't result in a match and cause the function to
return early.
(Note: Presently, FormatMessage loads the DLLs as "data files" so it
actually may not matter whether it gets 32- or 64-bit versions. But let's
be on the safe side.) }
Win32ErrorString($4C783AFB);
end.
|
{$include lem_directives.inc}
unit LemLVLLoader;
interface
uses
Classes, SysUtils,
UMisc,
LemTerrain,
LemInteractiveObject,
LemSteel,
LemDosStructures,
LemLevel,
LemLevelLoad;
type
TLVLLoader = class(TLevelLoader)
private
protected
public
class procedure LoadLevelFromStream(aStream: TStream; aLevel: TLevel; OddLoad: Boolean = false); override;
class procedure StoreLevelInStream(aLevel: TLevel; aStream: TStream); override;
end;
implementation
{ TLVLLoader }
class procedure TLVLLoader.LoadLevelFromStream(aStream: TStream; aLevel: TLevel; OddLoad: Boolean = false);
{-------------------------------------------------------------------------------
Translate a LVL file and fill the collections.
For decoding and technical details see documentation or read the code :)
-------------------------------------------------------------------------------}
var
Buf: TLVLRec;
H, i: Integer;
O: TLVLObject;
T: TLVLTerrain;
S: TLVLSteel;
Obj: TInteractiveObject;
Ter: TTerrain;
Steel: TSteel;
begin
with aLevel do
begin
ClearLevel;
aStream.ReadBuffer(Buf, LVL_SIZE);
{-------------------------------------------------------------------------------
Get the statics. This is easy
-------------------------------------------------------------------------------}
with Info do
begin
if OddLoad = false then
begin
ReleaseRate := SwapWord(Buf.ReleaseRate) mod 256;
LemmingsCount := SwapWord(Buf.LemmingsCount);
RescueCount := SwapWord(Buf.RescueCount);
TimeLimit := SwapWord(Buf.TimeLimit) mod 256;
ClimberCount := SwapWord(Buf.ClimberCount) mod 256;
FloaterCount := SwapWord(Buf.FloaterCount) mod 256;
BomberCount := SwapWord(Buf.BomberCount) mod 256;
BlockerCount := SwapWord(Buf.BlockerCount) mod 256;
BuilderCount := SwapWord(Buf.BuilderCount) mod 256;
BasherCount := SwapWord(Buf.BasherCount) mod 256;
MinerCount := SwapWord(Buf.MinerCount) mod 256;
DiggerCount := SwapWord(Buf.DiggerCount) mod 256;
MusicTrack := Buf.GraphicSet mod 256;
SuperLemming := (Buf.Reserved = $FFFF);
Title := Buf.LevelName;
end;
ScreenPosition := SwapWord(Buf.ScreenPosition);
GraphicSet := SwapWord(Buf.GraphicSet) mod 256;
GraphicSetEx := SwapWord(Buf.GraphicSetEx) mod 256;
if (Buf.GraphicSetEx and $10 = 0) then
OddTarget := $FFFF
else
OddTarget := ((Buf.BuilderCount mod 256) shl 8) + (Buf.BasherCount mod 256);
end;
{-------------------------------------------------------------------------------
Get the objects
-------------------------------------------------------------------------------}
for i := 0 to LVL_MAXOBJECTCOUNT - 1 do
begin
O := Buf.Objects[i];
if O.AsInt64 = 0 then
Continue;
Obj := InteractiveObjects.Add;
Obj.Left := ((Integer(O.B0) shl 8 + Integer(O.B1)) and not 7) - 16;
Obj.Top := Integer(O.B2) shl 8 + Integer(O.B3);
if Obj.Top > 32767 then Obj.Top := Obj.Top - 65536;
Obj.Identifier := Integer(O.B5 and 15);
if O.Modifier and $80 <> 0 then
Obj.DrawingFlags := Obj.DrawingFlags or odf_NoOverwrite;
if O.Modifier and $40 <> 0 then
Obj.DrawingFlags := Obj.DrawingFlags or odf_OnlyOnTerrain;
if O.DisplayMode = $8F then
Obj.DrawingFlags := Obj.DrawingFlags or odf_UpsideDown;
Obj.IsFake := (i >= 16);
end;
{-------------------------------------------------------------------------------
Get the terrain.
-------------------------------------------------------------------------------}
for i := 0 to LVL_MAXTERRAINCOUNT - 1 do
begin
T := Buf.Terrain[i];
if T.D0 = $FFFFFFFF then
Continue;
Ter := Terrains.Add;
Ter.Left := Integer(T.B0 and 15) shl 8 + Integer(T.B1) - 16; // 9 bits
Ter.DrawingFlags := T.B0 shr 5; // the bits are compatible
H := Integer(T.B2) shl 1 + Integer(T.B3 and $80) shr 7;
if H >= 256 then
Dec(H, 512);
Dec(H, 4);
Ter.Top := H;
Ter.Identifier := T.B3 and 63; // max = 63. bit7 belongs to ypos
if T.B0 and 16 <> 0 then Ter.Identifier := Ter.Identifier + 64;
end;
{-------------------------------------------------------------------------------
Get the steel.
-------------------------------------------------------------------------------}
for i := 0 to LVL_MAXSTEELCOUNT - 1 do
begin
S := Buf.Steel[i];
if S.D0 = 0 then
Continue;
Steel := Steels.Add;
Steel.Left := ((Integer(S.B0) shl 1) + (Integer(S.B1 and Bit7) shr 7)) * 4 - 16; // 9 bits
Steel.Top := Integer(S.B1 and not Bit7) * 4; // bit 7 belongs to steelx
Steel.Width := Integer(S.B2 shr 4) * 4 + 4; // first nibble bits 4..7 is width in units of 4 pixels (and then add 4)
Steel.Height := Integer(S.B2 and $F) * 4 + 4; // second nibble bits 0..3 is height in units of 4 pixels (and then add 4)
end;
end; // with aLevel
end;
class procedure TLVLLoader.StoreLevelInStream(aLevel: TLevel; aStream: TStream);
var
Int16: SmallInt; Int32: Integer;
H, i: Integer;
M: Byte;
W: Word;
O: ^TLVLObject;
T: ^TLVLTerrain;
S: ^TLVLSteel;
Obj: TInteractiveObject;
Ter: TTerrain;
Steel: TSteel;
Buf: TLVLRec;
begin
with aLevel do
begin
FillChar(Buf, SizeOf(Buf), 0);
FillChar(Buf.Terrain, Sizeof(Buf.Terrain), $FF);
FillChar(Buf.LevelName, 32, ' ');
{-------------------------------------------------------------------------------
Set the statics.
-------------------------------------------------------------------------------}
with Info do
begin
Buf.ReleaseRate := ReleaseRate;
Buf.LemmingsCount := LemmingsCount;
Buf.RescueCount := RescueCount;
Buf.TimeLimit := TimeLimit;
Buf.ClimberCount := ClimberCount;
Buf.FloaterCount := FloaterCount;
Buf.BomberCount := BomberCount;
Buf.BlockerCount := BlockerCount;
Buf.BuilderCount := BuilderCount;
Buf.BasherCount := BasherCount;
Buf.MinerCount := MinerCount;
Buf.DiggerCount := DiggerCount;
Buf.ScreenPosition := ScreenPosition;
Buf.GraphicSet := GraphicSet;
Buf.GraphicSet := Buf.GraphicSet + (MusicTrack shl 8);
Buf.GraphicSetEx := GraphicSetEx;
// swap
Buf.ReleaseRate := SwapWord(Buf.ReleaseRate);
Buf.LemmingsCount := SwapWord(Buf.LemmingsCount);
Buf.RescueCount := SwapWord(Buf.RescueCount);
Buf.TimeLimit := SwapWord(Buf.TimeLimit);
Buf.ClimberCount := SwapWord(Buf.ClimberCount);
Buf.FloaterCount := SwapWord(Buf.FloaterCount);
Buf.BomberCount := SwapWord(Buf.BomberCount);
Buf.BlockerCount := SwapWord(Buf.BlockerCount);
Buf.BuilderCount := SwapWord(Buf.BuilderCount);
Buf.BasherCount := SwapWord(Buf.BasherCount);
Buf.MinerCount := SwapWord(Buf.MinerCount);
Buf.DiggerCount := SwapWord(Buf.DiggerCount);
Buf.ScreenPosition := SwapWord(Buf.ScreenPosition);
Buf.GraphicSet := SwapWord(Buf.GraphicSet);
Buf.GraphicSetEx := SwapWord(Buf.GraphicSetEx);
// encode superlemming
if SuperLemming then
Buf.Reserved := $FFFF;
if Length(Title) > 0 then
System.Move(Title[1], Buf.LevelName, Length(Title));
end;
{-------------------------------------------------------------------------------
Set the objects.
-------------------------------------------------------------------------------}
for i := 0 to InteractiveObjects.Count - 1 do
begin
Obj := InteractiveObjects[i];
O := @Buf.Objects[i];
// set xpos: revert the misery
Int16 := Obj.Left;
Inc(Int16, 16);
W := Word(Int16);
W := System.Swap(W);
O^.XPos := W;
// set ypos: revert the misery
Int16 := Obj.Top;
if Int16 < 0 then Int16 := Int16 + 65536;
W := Word(Int16);
W := System.Swap(W);
O^.Ypos := W;
// set object id
TWordRec(O^.ObjectID).Hi := Byte(Obj.Identifier);
// set modifier
if odf_NoOverwrite and Obj.DrawingFlags <> 0 then
O^.Modifier := $80
else if odf_OnlyOnTerrain and Obj.DrawingFlags <> 0 then
O^.Modifier := $40;
// set displaymode
if odf_UpsideDown and Obj.DrawingFlags <> 0 then
O^.DisplayMode := $8F
else
O^.DisplayMode := $0F; {default}
end;
{-------------------------------------------------------------------------------
set the terrain
-------------------------------------------------------------------------------}
for i := 0 to Terrains.Count - 1 do
begin
Ter := Terrains[i];
T := @Buf.Terrain[i];
// GET: TerrainX := Integer(T.B0 and 15) shl 8 + Integer(T.B1) - 16;
H := Ter.Left;
Inc(H, 16);
T.B0 := Byte(H shr 8) and 15;
T.B1 := Byte(H);// + 16;
// GET: TerrainDrawingFlags := TTerrainDrawingFlags(Byte(T.B0 shr 5));
M := Byte(Ter.DrawingFlags) shl 5;
T.B0 := T.B0 or M;
// GET:
(*
H := Integer(T.B2) shl 1 + Integer(T.B3 and $80) shr 7;
if H >= 256 then
Dec(H, 512);
Dec(H, 4);
TerrainY := Map(H);
*)
H := Ter.Top;
Inc(H, 4);
if H < 0 then
Inc(H, 512);
T.B3 := Byte((H or Bit8) shl 7); // still don't know if this is right this "or bit8"
// H := H and not Bit8;
H := H shr 1;
T.B2 := Byte(H);
// GET: TerrainId := T.B3 and 63; // max = 63.
T.B3 := T.B3 or (Byte(Ter.Identifier) and 63);
if Ter.Identifier > 63 then T.B0 := T.B0 + 16;
end;
{-------------------------------------------------------------------------------
set the steel.
-------------------------------------------------------------------------------}
for i := 0 to Steels.Count - 1 do
begin
Steel := Steels[i];
S := @Buf.Steel[i];
// GET: SteelX := ((Integer(B0) shl 1) + (Integer(B1 and Bit7) shr 7)) * 4 - 16;
Int32 := Steel.Left;
Int32 := (Int32 + 16) div 4;
S^.B1 := Byte((Int32 or Bit8) shl 7); // still don't know this "or bit8"
// Int32 := Int32 and not Bit8; <-- I THINK THIS WAS WRONG!!
Int32 := Int32 shr 1;
S^.B0 := Byte(Int32);
// GET: SteelY := Integer(S.B1 and not Bit7) * 4;
Int32 := Steel.Top div 4;
S^.B1 := S^.B1 or (Byte(Int32) and not Bit7);
// GET: SteelWidth := Integer(S.B2 shr 4) * 4 + 4;
Int32 := (Steel.Width - 4) div 4;
S^.B2 := Byte(Int32) shl 4;
// GET: SteelHeight := Integer(S.B2 and $F) * 4 + 4;
Int32 := (Steel.Height - 4) div 4;
S^.B2 := S^.B2 or (Byte(Int32) and not $F0); // highest bit set already
end;
aStream.WriteBuffer(Buf, LVL_Size);
end;
end;
end.
|
{
Exercicio 58:Construa um algoritmo que calcule e mostre o Imposto de Renda de um grupo de 10 contribuintes,
considerando que os dados de cada contribuinte, número do CPF, número de dependentes e renda mensal são valores
fornecidos pelo usuário. Para cada contribuinte será feito um desconto de 5% do salário mínimo por dependente.
Os valores da alíquota para cálculo do IR são:
Renda Líquida Alíquota
Até 2,0 salários mínimos Isento
2,01 a 4,0 salários mínimos 5%
4,01 a 7,0 salários mínimos 10%
7,01 a 10,0 salários mínimos 15%
Acima de 10 salários mínimos 20%
}
{ Solução em Portugol
Algoritmo Exercicio 58;
Const
salario_minimo = 1045;
Var
cpf_contribuinte,dependentes,i: inteiro;
renda_mensal: real;
Inicio
exiba("Programa que calcula imposto de renda.");
para i <- 1 até 10 faca
exiba("Digite o CPF do contribuinte: ");
leia(cpf_contribuinte);
enquanto(cpf_contribuinte < 10000000000 ou cpf_contribuinte > 99999999999)
exiba("Digite um CPF válido: ");
leia(cpf_contribuinte);
fimenquanto;
exiba("Digite a quantidade de dependentes do contribuinte: ");
leia(dependentes);
enquanto(contribuintes >= 20)faça
exiba("Você não tem tantos dependentes. Digite o número correto.");
leia(contribuintes);
fimenquanto;
exiba("Digite a renda do contribuinte: ");
leia(renda_mensal);
se((renda_mensal <= 2 * salario_minimo) e (renda_mensal >= 0))
então exiba("O contribuinte está isento.")
senão se((renda_mensal > 2 * salario_minimo) e (renda_mensal <= 4 * salario_minimo))
então exiba("O seu imposto de renda é: ", 0,05 * renda_mensal - 0,05 * dependentes * salario_minimo)
senão se((renda_mensal > 4 * salario_minimo) e (renda_mensal <= 7 * salario_minimo))
então exiba("O seu imposto de renda é: ", 0,1 * renda_mensal - 0,05 * dependentes * salario_minimo)
senão se((renda_mensal > 7 * salario_minimo) e (renda_mensal <= 10 * salario_minimo))
então exiba("O seu imposto de renda é: ", 0,15 * renda_mensal - 0,05 * dependentes * salario_minimo)
senão exiba("O seu imposto de renda é: ", 0,2 * renda_mensal - 0,05 * dependentes * salario_minimo);
fimse;
fimse;
fimse;
fimse;
fimpara;
exiba("Fim do Programa.");
Fim.
}
// Solução em Pascal
Program Exercicio58;
uses crt;
const
salario_minimo = 1045;
var
cpf_contribuinte,dependentes,i: integer;
renda_mensal: real;
begin
clrscr;
writeln('Programa que calcula imposto de renda.');
for i := 1 to 10 do
Begin
writeln('Digite o CPF do contribuinte: ');
readln(cpf_contribuinte);
while((cpf_contribuinte < 100000000) or (cpf_contribuinte > 999999999))do
Begin
writeln('Digite um CPF válido: ');
readln(cpf_contribuinte);
End;
writeln('Digite a quantidade de dependentes do contribuinte: ');
readln(dependentes);
while(dependentes >= 20)do
Begin
writeln('Você não tem tantos dependentes. Digite o número correto.');
readln(dependentes);
End;
writeln('Digite a renda do contribuinte: ');
readln(renda_mensal);
if((renda_mensal <= 2 * salario_minimo) and (renda_mensal >= 0))
then writeln('O contribuinte está isento.')
else if((renda_mensal > 2 * salario_minimo) and (renda_mensal <= 4 * salario_minimo))
then writeln('O seu imposto de renda é: ', (0.05 * renda_mensal - 0.05 * dependentes * salario_minimo):0:2)
else if((renda_mensal > 4 * salario_minimo) and (renda_mensal <= 7 * salario_minimo))
then writeln('O seu imposto de renda é: ', (0.1 * renda_mensal - 0.05 * dependentes * salario_minimo):0:2)
else if((renda_mensal > 7 * salario_minimo) and (renda_mensal <= 10 * salario_minimo))
then writeln('O seu imposto de renda é: ', (0.15 * renda_mensal - 0.05 * dependentes * salario_minimo):0:2)
else writeln('O seu imposto de renda é: ', (0.2 * renda_mensal - 0.05 * dependentes * salario_minimo):0:2);
End;
writeln('Fim do Programa.');
repeat until keypressed;
end. |
{*****************************************************}
{ }
{ EldoS Themes Support Library }
{ }
{ (C) 2002-2003 EldoS Corporation }
{ http://www.eldos.com/ }
{ }
{*****************************************************}
{$include elpack2.inc}
{$IFDEF ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$ELSE}
{$IFDEF LINUX}
{$I ../ElPack.inc}
{$ELSE}
{$I ..\ElPack.inc}
{$ENDIF}
{$ENDIF}
unit ElThemesWindowsXPComboBox;
interface
{$IFDEF ELPACK_THEME_ENGINE}
uses
ElThemesGeneral, ElThemesWindowsXP;
type
TWindowsXPThemeComboBoxDropDown = class(TWindowsXPThemePart)
protected
function GetStateRectIndex(StateID: integer): integer; override;
end;
TWindowsXPThemeComboBox = class(TWindowsXPTheme)
public
constructor Create(Manager: TThemeManager); override;
end;
{$ENDIF}
implementation
{$IFDEF ELPACK_THEME_ENGINE}
uses
ElTmSchema;
{ TWindowsXPThemeComboBoxDropDown }
function TWindowsXPThemeComboBoxDropDown.GetStateRectIndex(StateID: integer): integer;
begin
if (StateID >= CBXS_NORMAL) and (StateID <= CBXS_DISABLED) then
Result := StateID - CBXS_NORMAL
else
Result := 0;
end;
{ TWindowsXPThemeComboBox }
constructor TWindowsXPThemeComboBox.Create(Manager: TThemeManager);
var
Root, Part: TWindowsXPThemePart;
begin
inherited;
Root := TWindowsXPThemePart.Create(Self, nil, 'ComboBox');
AddPart(0, Root);
Part := TWindowsXPThemeComboBoxDropDown.Create(Self, Root, 'ComboBox.DropDownButton');
AddPart(CP_DROPDOWNBUTTON, Part);
end;
{$ENDIF}
end.
|
unit LUX.GPU.Vulkan.Depthr;
interface //#################################################################### ■
uses vulkan_core;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
TVkDepthr<TVkDevice_:class> = class;
TVkDepMem<TVkDevice_:class> = class;
TVkDepVie<TVkDevice_:class> = class;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDepVie
TVkDepVie<TVkDevice_:class> = class
private
type TVkDepthr_ = TVkDepthr<TVkDevice_>;
protected
_Depthr :TVkDepthr_;
_Inform :VkImageViewCreateInfo;
_Handle :VkImageView;
///// アクセス
function GetDevice :TVkDevice_;
function GetHandle :VkImageView;
procedure SetHandle( const Handle_:VkImageView );
///// メソッド
procedure CreateHandle;
procedure DestroHandle;
public
constructor Create; overload;
constructor Create( const Depthr_:TVkDepthr_ ); overload;
destructor Destroy; override;
///// プロパティ
property Device :TVkDevice_ read GetDevice ;
property Depthr :TVkDepthr_ read _Depthr ;
property Inform :VkImageViewCreateInfo read _Inform ;
property Handle :VkImageView read GetHandle write SetHandle;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDepMem
TVkDepMem<TVkDevice_:class> = class
private
type TVkDepthr_ = TVkDepthr<TVkDevice_>;
protected
_Depthr :TVkDepthr_;
_Inform :VkMemoryAllocateInfo;
_Handle :VkDeviceMemory;
///// アクセス
function GetDevice :TVkDevice_;
function GetHandle :VkDeviceMemory;
procedure SetHandle( const Handle_:VkDeviceMemory );
///// メソッド
procedure CreateHandle;
procedure DestroHandle;
public
constructor Create; overload;
constructor Create( const Depthr_:TVkDepthr_ ); overload;
destructor Destroy; override;
///// プロパティ
property Device :TVkDevice_ read GetDevice ;
property Depthr :TVkDepthr_ read _Depthr ;
property Inform :VkMemoryAllocateInfo read _Inform ;
property Handle :VkDeviceMemory read GetHandle write SetHandle;
///// メソッド
function Bind :Boolean;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDepthr
TVkDepthr<TVkDevice_:class> = class
private
type TVkDepthr_ = TVkDepthr<TVkDevice_>;
TVkDepMem_ = TVkDepMem<TVkDevice_>;
TVkDepVie_ = TVkDepVie<TVkDevice_>;
protected
_Device :TVkDevice_;
_Inform :VkImageCreateInfo;
_Handle :VkImage;
_Memory :TVkDepMem_;
_Viewer :TVkDepVie_;
///// アクセス
function GetHandle :VkImage;
procedure SetHandle( const Handle_:VkImage );
///// メソッド
procedure CreateHandle;
procedure DestroHandle;
public
constructor Create; overload;
constructor Create( const Device_:TVkDevice_ ); overload;
destructor Destroy; override;
///// プロパティ
property Device :TVkDevice_ read _Device ;
property Inform :VkImageCreateInfo read _Inform ;
property Handle :VkImage read GetHandle write SetHandle;
property Memory :TVkDepMem_ read _Memory ;
property Viewer :TVkDepVie_ read _Viewer ;
///// メソッド
function GetRequir :VkMemoryRequirements;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses System.SysUtils,
FMX.Types,
vulkan.util,
LUX.GPU.Vulkan;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDepVie
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkDepVie<TVkDevice_>.GetDevice :TVkDevice_;
begin
Result := _Depthr.Device;
end;
//------------------------------------------------------------------------------
function TVkDepVie<TVkDevice_>.GetHandle :VkImageView;
begin
if _Handle = 0 then CreateHandle;
Result := _Handle;
end;
procedure TVkDepVie<TVkDevice_>.SetHandle( const Handle_:VkImageView );
begin
if _Handle <> 0 then DestroHandle;
_Handle := Handle_;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TVkDepVie<TVkDevice_>.CreateHandle;
var
D :TVkDepthr;
F :VkFormat;
begin
D := TVkDepthr( Depthr );
F := D.Inform.format;
with _Inform do
begin
sType := VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
pNext := nil;
flags := 0;
image := D.Handle;
viewType := VK_IMAGE_VIEW_TYPE_2D;
format := F;
with components do
begin
r := VK_COMPONENT_SWIZZLE_R;
g := VK_COMPONENT_SWIZZLE_G;
b := VK_COMPONENT_SWIZZLE_B;
a := VK_COMPONENT_SWIZZLE_A;
end;
with subresourceRange do
begin
aspectMask := Ord( VK_IMAGE_ASPECT_DEPTH_BIT );
if ( F = VK_FORMAT_D16_UNORM_S8_UINT )
or ( F = VK_FORMAT_D24_UNORM_S8_UINT )
or ( F = VK_FORMAT_D32_SFLOAT_S8_UINT ) then
aspectMask := aspectMask or Ord( VK_IMAGE_ASPECT_STENCIL_BIT );
baseMipLevel := 0;
levelCount := 1;
baseArrayLayer := 0;
layerCount := 1;
end;
end;
Assert( vkCreateImageView( TVkDevice( Device ).Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS );
end;
procedure TVkDepVie<TVkDevice_>.DestroHandle;
begin
vkDestroyImageView( TVkDevice( Device ).Handle, _Handle, nil );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkDepVie<TVkDevice_>.Create;
begin
inherited;
_Handle := 0;
end;
constructor TVkDepVie<TVkDevice_>.Create( const Depthr_:TVkDepthr_ );
begin
Create;
_Depthr := Depthr_;
end;
destructor TVkDepVie<TVkDevice_>.Destroy;
begin
Handle := 0;
inherited;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDepMem
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkDepMem<TVkDevice_>.GetDevice :TVkDevice_;
begin
Result := _Depthr.Device;
end;
//------------------------------------------------------------------------------
function TVkDepMem<TVkDevice_>.GetHandle :VkDeviceMemory;
begin
if _Handle = 0 then
begin
CreateHandle;
Assert( Bind );
end;
Result := _Handle;
end;
procedure TVkDepMem<TVkDevice_>.SetHandle( const Handle_:VkDeviceMemory );
begin
if _Handle <> 0 then DestroHandle;
_Handle := Handle_;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TVkDepMem<TVkDevice_>.CreateHandle;
var
R :VkMemoryRequirements;
begin
R := TVkDepthr( Depthr ).GetRequir;
with _Inform do
begin
sType := VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
pNext := nil;
allocationSize := R.size;
Assert( TVkDevice( Device ).memory_type_from_properties( R.memoryTypeBits, Ord( VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT ), memoryTypeIndex ) );
end;
Assert( vkAllocateMemory( TVkDevice( Device ).Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS );
end;
procedure TVkDepMem<TVkDevice_>.DestroHandle;
begin
vkFreeMemory( TVkDevice( Device ).Handle, _Handle, nil );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkDepMem<TVkDevice_>.Create;
begin
inherited;
_Handle := 0;
end;
constructor TVkDepMem<TVkDevice_>.Create( const Depthr_:TVkDepthr_ );
begin
Create;
_Depthr := Depthr_;
end;
destructor TVkDepMem<TVkDevice_>.Destroy;
begin
Handle := 0;
inherited;
end;
/////////////////////////////////////////////////////////////////////// メソッド
function TVkDepMem<TVkDevice_>.Bind :Boolean;
begin
Result := vkBindImageMemory( TVkDevice( Device ).Handle, TVkDepthr( Depthr ).Handle, Handle, 0 ) = VK_SUCCESS;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDepthr
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkDepthr<TVkDevice_>.GetHandle :VkImage;
begin
if _Handle = 0 then
begin
CreateHandle;
Assert( _Memory.Bind );
end;
Result := _Handle;
end;
procedure TVkDepthr<TVkDevice_>.SetHandle( const Handle_:VkImage );
begin
if _Handle <> 0 then
begin
_Memory.Handle := 0;
DestroHandle;
end;
_Handle := Handle_;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TVkDepthr<TVkDevice_>.CreateHandle;
begin
Assert( vkCreateImage( TVkDevice( Device ).Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS );
end;
procedure TVkDepthr<TVkDevice_>.DestroHandle;
begin
vkDestroyImage( TVkDevice( Device ).Handle, _Handle, nil );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkDepthr<TVkDevice_>.Create;
begin
inherited;
_Handle := 0;
_Memory := TVkDepMem_.Create( Self );
_Viewer := TVkDepVie_.Create( Self );
end;
constructor TVkDepthr<TVkDevice_>.Create( const Device_:TVkDevice_ );
var
P :VkFormatProperties;
begin
Create;
_Device := Device_;
TVkDevice( _Device ).Depthr := TVkDepthr( Self );
with _Inform do
begin
sType := VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
pNext := nil;
flags := 0;
imageType := VK_IMAGE_TYPE_2D;
format := VK_FORMAT_D16_UNORM;
extent.width := TVkDevice( Device ).Surfac.PxSizeX;
extent.height := TVkDevice( Device ).Surfac.PxSizeY;
extent.depth := 1;
mipLevels := 1;
arrayLayers := 1;
samples := NUM_SAMPLES;
vkGetPhysicalDeviceFormatProperties( TVkDevice( Device ).Physic, format, @P );
if ( P.linearTilingFeatures and Ord( VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT ) ) <> 0
then tiling := VK_IMAGE_TILING_LINEAR
else
if ( P.optimalTilingFeatures and Ord( VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT ) ) <> 0
then tiling := VK_IMAGE_TILING_OPTIMAL
else
begin
(* Try other depth formats? *)
Log.d( 'image_info.format ' + Ord( format ).ToString + ' Unsupported.' );
RunError( 256-1 );
end;
usage := Ord( VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT );
sharingMode := VK_SHARING_MODE_EXCLUSIVE;
queueFamilyIndexCount := 0;
pQueueFamilyIndices := nil;
initialLayout := VK_IMAGE_LAYOUT_UNDEFINED;
end;
end;
destructor TVkDepthr<TVkDevice_>.Destroy;
begin
_Viewer.Free;
_Memory.Free;
Handle := 0;
inherited;
end;
/////////////////////////////////////////////////////////////////////// メソッド
function TVkDepthr<TVkDevice_>.GetRequir :VkMemoryRequirements;
begin
vkGetImageMemoryRequirements( TVkDevice( Device ).Handle, Handle, @Result );
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■ |
unit RealState.Repository;
{.$DEFINE IS_VIRTUAL_BOX}
interface
uses
Data.DB,
System.SysUtils,
System.Classes,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
FireDAC.Phys.PG,
FireDAC.Phys.PGDef,
FireDAC.VCLUI.Wait,
FireDAC.Comp.Client,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.DApt,
FireDAC.Comp.DataSet;
type
TRepository = class(TDataModule)
Connection: TFDConnection;
procedure DataModuleDestroy(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
procedure ConnectionBeforeConnect(Sender: TObject);
private
function IsDebugMode: Boolean;
function IsVirtualBox: Boolean;
end;
var
Repository: TRepository;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TRepository.DataModuleDestroy(Sender: TObject);
begin
Connection.Close;
end;
procedure TRepository.DataModuleCreate(Sender: TObject);
begin
Connection.Open();
end;
procedure TRepository.ConnectionBeforeConnect(Sender: TObject);
begin
if IsDebugMode and IsVirtualBox then
Connection.Params.Values['Server'] := '10.0.2.2'
else
Connection.Params.Values['Server'] := '127.0.0.1';
end;
function TRepository.IsDebugMode: Boolean;
begin
{$WARNINGS OFF}
Result := DebugHook <> 0;
{$WARNINGS ON}
end;
function TRepository.IsVirtualBox: Boolean;
begin
Result := {$IFDEF IS_VIRTUAL_BOX}True{$ELSE}False{$ENDIF};
end;
end.
|
{=================================================================================
Copyright © combit GmbH, Konstanz
----------------------------------------------------------------------------------
File : ObjTree.pas
Module : List & Label 26
Descr. : Implementation file for the List & Label 26 VCL-Component
Version: 26.000
==================================================================================
}
unit ObjTree;
interface
{$WEAKPACKAGEUNIT ON}
uses Classes, Controls, Windows, ActiveX, SysUtils, Dialogs;
type
TObjTreeNode = class;
TObjTree = class;
TObjSelectionProc = procedure(Item: TObjTreeNode) of object;
TObjTreeNodeList = Class(TStringList)
Private
Function GetNode(Index: Integer) :TObjTreeNode;
Procedure SetNode(Index: Integer; Value: TObjTreeNode);
Public
function AddNode(ANode: TObjTreeNode): Integer;
function DeleteNode(ANode: TObjTreeNode): Boolean;
function DeleteNodeNr(index: Integer): Boolean;
property Nodes[Index: Integer]: TObjTreeNode read GetNode write SetNode;
End;
TObjTreeNode = class(TCollectionItem)
private
FSelectionProc: TObjSelectionProc;
FTag : Integer;
FChildNodes : TObjTreeNodeList;
FParentNode : TObjTreeNode;
protected
procedure DoOnItemSelected(Value: TObjSelectionProc); virtual;
Procedure MakeNodeToChild(ANode:TObjTreeNode); virtual;
public
constructor Create(Collection: TCollection); override;
Destructor Destroy; Override;
function GetInstance(const PropertyName: string): TPersistent; virtual;
procedure UpdateEditorDisplay(Sender: TObject);
Function AddChildNode: TObjTreeNode; virtual;
property OnItemSelected: TObjSelectionProc read FSelectionProc write DoOnItemSelected;
property ChildNodes : TObjTreeNodeList read FChildNodes write FChildNodes;
Property ParentNode : TObjTreeNode read FParentNode write FParentNode;
property Tag: Integer read FTag write FTag;
end;
TObjTree = class(TOwnedCollection)
private
FDesigner: TControl;
function GetItems(Index: Integer): TObjTreeNode;
protected
procedure SetDesigner(Value: TControl); virtual;
public
constructor Create(AOwner: TPersistent; ItemClass: TCollectionItemClass);
destructor Destroy; override;
function AddItem: TObjTreeNode; virtual;
property Designer: TControl read FDesigner write SetDesigner;
property Items[Index: Integer]: TObjTreeNode read GetItems;
end;
implementation
//=====================================================================================================================
// TObjTreeNodeList
//=====================================================================================================================
function TObjTreeNodeList.AddNode(ANode: TObjTreeNode): Integer;
Begin
result:=AddObject('',ANode);
End;
function TObjTreeNodeList.DeleteNode(ANode: TObjTreeNode): Boolean;
var i : Integer;
Begin
for i := 0 to Count-1 do
Begin
if Objects[i] = ANode then
Begin
Delete(i);
Break;
End;
End;
Result := true;
End;
function TObjTreeNodeList.DeleteNodeNr(index: Integer): Boolean;
Begin
Objects[index].Free;
Delete(index);
Result := true;
End;
Function TObjTreeNodeList.GetNode(Index: Integer) :TObjTreeNode;
Begin
result:= TObjTreeNode(Objects[Index]);
End;
Procedure TObjTreeNodeList.SetNode(Index: Integer; Value: TObjTreeNode);
Begin
Objects[Index]:=Value;
End;
//=====================================================================================================================
// TObjTreeNode
//=====================================================================================================================
constructor TObjTreeNode.Create(Collection: TCollection);
Begin
inherited Create(Collection);
FParentNode := Nil;
FChildNodes := TObjTreeNodeList.Create;
End;
Destructor TObjTreeNode.Destroy;
Begin
if ParentNode<>nil then
Begin
ParentNode.ChildNodes.DeleteNode(self);
ParentNode:=nil;
End;
While ChildNodes.Count > 0 do
Begin
ChildNodes.DeleteNodeNr(ChildNodes.Count-1);
End;
FChildNodes.Free;
FChildNodes := nil;
inherited Destroy;
End;
function TObjTreeNode.GetInstance(const PropertyName: string): TPersistent;
begin
result := self;
end;
procedure TObjTreeNode.DoOnItemSelected(Value: TObjSelectionProc);
begin
end;
procedure TObjTreeNode.UpdateEditorDisplay(Sender: TObject);
begin
with (Collection as TObjTree) do
if Designer <> nil then Designer.Update;
end;
Procedure TObjTreeNode.MakeNodeToChild(ANode:TObjTreeNode);
Begin
ANode.ParentNode:=Self;
ChildNodes.AddNode(ANode);
End;
Function TObjTreeNode.AddChildNode: TObjTreeNode;
Var node: TObjTreeNode;
Begin
node := Collection.Add as TObjTreeNode;
MakeNodeToChild(node);
result := node;
End;
//=====================================================================================================================
// TObjTree
//=====================================================================================================================
constructor TObjTree.Create(AOwner: TPersistent;ItemClass: TCollectionItemClass);
Begin
Inherited Create(AOwner, ItemClass);
end;
destructor TObjTree.Destroy;
begin
if Designer <> nil then Designer.Free;
inherited;
end;
function TObjTree.AddItem: TObjTreeNode;
begin
result := Add as TObjTreeNode;
end;
function TObjTree.GetItems(Index: Integer): TObjTreeNode;
begin
result := TObjTreeNode(inherited Items[Index]);
end;
procedure TObjTree.SetDesigner(Value: TControl);
begin
FDesigner := Value;
end;
end.
|
{$IFDEF ios7crypt}
program IOS7Crypt;
{$ELSE}
unit IOS7Crypt;
{$ENDIF}
{$Mode ObjFPC}
uses
getopts,
sysutils;
type
bytes = array of byte;
strings = array of string;
const
XlatSize = 53;
XlatPrime : array[0 .. XlatSize - 1] of byte = (
$64, $73, $66, $64, $3b, $6b, $66, $6f,
$41, $2c, $2e, $69, $79, $65, $77, $72,
$6b, $6c, $64, $4a, $4b, $44, $48, $53,
$55, $42, $73, $67, $76, $63, $61, $36,
$39, $38, $33, $34, $6e, $63, $78, $76,
$39, $38, $37, $33, $32, $35, $34, $6b,
$3b, $66, $67, $38, $37
);
{$IFDEF ios7crypt}{$ELSE}
interface
function Xlat (i : integer; len : integer) : bytes;
function Encrypt (password : string) : string;
function Decrypt (hash : string) : string;
procedure Test;
implementation
{$ENDIF}
function Xlat (i : integer; len : integer) : bytes;
var
J : integer;
begin
SetLength(Xlat, len);
for J := 0 to len - 1 do
Xlat[J] := XlatPrime[(i + J) mod XlatSize];
end;
function Encrypt (password : string) : string;
var
Seed : integer;
Plaintext : bytes;
Keys : bytes;
Ciphertext : bytes;
I : integer;
Hex : string;
begin
if Length(password) = 0 then
Encrypt := ''
else
begin
Seed := Random(16);
Keys := Xlat(Seed, Length(password));
SetLength(Plaintext, Length(password));
for I := 0 to Length(password) - 1 do
{ String indices start at 1, but array indices start at 0 !? }
Plaintext[I] := Ord(password[I + 1]);
SetLength(Ciphertext, Length(password));
for I := 0 to Length(password) - 1 do
Ciphertext[I] := Keys[I] xor Plaintext[I];
Hex := '';
for I := 0 to Length(Ciphertext) - 1 do
Hex := Concat(Hex, AnsiLowerCase(Format('%.2x', [Ciphertext[I]])));
Encrypt := Concat(Format('%.2d', [Seed]), Hex);
end;
end;
function OnlyPairs (text : string) : strings;
var
Len : integer;
I : integer;
begin
Len := Length(text) div 2;
SetLength(OnlyPairs, Len);
for I := 0 to Len - 1 do
OnlyPairs[I] := Copy(text, I * 2 + 1, 2);
end;
function Decrypt (hash : string) : string;
var
Head : string;
Tail : string;
Seed : integer;
HexPairs : strings;
I : integer;
Cipherbyte : integer;
Ciphertext : bytes;
Keys : bytes;
Plaintext : bytes;
Password : string;
begin
if Length(hash) < 4 then
Decrypt := ''
else
begin
Head := Copy(hash, 1, 2);
Tail := Copy(hash, 3, Length(hash) - 2);
try
Seed := StrToInt(Head);
HexPairs := OnlyPairs(Tail);
for I := 0 to Length(HexPairs) do
begin
try
Cipherbyte := StrToInt(Concat('$', HexPairs[I]));
SetLength(Ciphertext, I + 1);
Ciphertext[I] := Cipherbyte;
except
on EConvertError do
begin
end;
end;
end;
Keys := Xlat(Seed, Length(Ciphertext));
SetLength(Plaintext, Length(Ciphertext));
for I := 0 to Length(Ciphertext) do
Plaintext[I] := Keys[I] xor Ciphertext[I];
SetLength(Password, Length(Plaintext));
for I := 0 to Length(Plaintext) do
{ String indices start at 1, but array indices start at 0 !? }
Password[I + 1] := chr(Plaintext[I]);
Decrypt := Password;
except
on EConvertError do
Decrypt := 'invalid hash';
end;
end;
end;
procedure Test;
begin
{ ... }
end;
procedure Usage (Prog : string);
begin
write('Usage: ');
write(Prog);
writeln(' [options]');
writeln('--encrypt -e <password>'#9'Encrypt');
writeln('--decrypt -d <hash>'#9'Decrypt');
writeln('--test -t'#9#9'Unit test');
writeln('--help -h'#9#9'Usage info');
Halt(0);
end;
{$IFDEF ios7crypt}
var
C : char;
OptionIndex : longint;
Options : array[1..7] of TOption;
Mode : string;
Password : string;
Hash : string;
begin
{$ELSE}
initialization
{$ENDIF}
Randomize;
{$IFDEF ios7crypt}
Mode := 'help';
with Options[1] do
begin
name := 'encrypt';
has_arg := 1;
flag := nil;
value := #0;
end;
with Options[2] do
begin
name := 'decrypt';
has_arg := 1;
flag := nil;
value := #0;
end;
with Options[3] do
begin
name := 'test';
has_arg := 0;
value := #0;
end;
with Options[4] do
begin
name := 'help';
has_arg := 0;
end;
C := #0;
repeat
C := getlongopts('e:d:th', @Options[1], OptionIndex);
case C of
'e':
begin
Mode := 'encrypt';
Password := optarg;
end;
'd':
begin
Mode := 'decrypt';
Hash := optarg;
end;
't': Mode := 'test';
'h': Usage(ParamStr(0));
'?': Usage(ParamStr(0));
end;
until C = endofoptions;
if Mode = 'encrypt' then
writeln(Encrypt(Password))
else
if Mode = 'decrypt' then
writeln(Decrypt(Hash))
else
if Mode = 'test' then
Test()
else
Usage(ParamStr(0));
{$ENDIF}
end.
|
unit MainUnit;
//tnotifyevent
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, IBConnection, DB, FileUtil, SynMemo,
SynHighlighterSQL, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
Buttons, DBGrids, DBCtrls, Menus, MetaData, references, bddatamodule, Schedule_Edit,
ConflictsMeta, ConflictsTree;
type
{ TMySql }
TMySql = class(TForm)
SpeedButton1: TSpeedButton;
StartDatasource: TDatasource;
Start_Data_Source: TDatasource;
Main_DB_Grid: TDBGrid;
Host_Name: TLabeledEdit;
Connect_Button: TSpeedButton;
Main_menu: TMainMenu;
File_Menu: TMenuItem;
Help_Menu: TMenuItem;
File_Exit: TMenuItem;
Author_Menu: TMenuItem;
References_Tables: TMenuItem;
Send_Query_Button: TSpeedButton;
StartQuery: TSQLQuery;
Main_Syn_Memo: TSynMemo;
Sql_Syn: TSynSQLSyn;
User_Name: TLabeledEdit;
Password: TLabeledEdit;
DB_Name: TLabeledEdit;
procedure Author_MenuClick(Sender: TObject);
procedure Connect_ButtonClick(Sender: TObject);
procedure File_ExitClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Send_Query_ButtonClick(Sender: TObject);
procedure Create_Reference_Menu();
procedure Reference_Table_Show(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
My_Sql: TMySql;
About_Tables_Items: array of TMenuItem;
implementation
{$R *.lfm}
{ TMySql }
procedure TMySql.Connect_ButtonClick(Sender: TObject);
begin
Data_Module.IBConnection1.UserName := User_Name.Text;
Data_Module.IBConnection1.Password := Password.Text;
Data_Module.IBConnection1.HostName := Host_Name.Text;
Data_Module.IBConnection1.DatabaseName := DB_Name.Text;
end;
procedure TMySql.Author_MenuClick(Sender: TObject);
begin
ShowMessage('Кузнецов Игорь Русланович Б8103а-2');
end;
procedure TMySql.Create_Reference_Menu();
var
i: integer;
My_Menu_Item: TMenuItem;
begin
for i := 0 to High(My_Tables) do
begin
My_Menu_Item := TMenuItem.Create(References_Tables);
with My_Menu_Item do
begin
Caption := '&' + My_Tables[i].FTableRuName;
Name := 'Menu' + My_Tables[i].FTable_Name;
tag := i;
OnClick := @Reference_Table_Show;
end;
SetLength(About_Tables_Items, length(About_Tables_Items) + 1);
About_Tables_Items[High(About_Tables_Items)] := My_Menu_Item;
end;
References_Tables.Add(About_Tables_Items);
end;
procedure TMySql.Reference_Table_Show(Sender: TObject);
var
Table_Discription: TReferenceForm;
begin
Table_Discription := TReferenceForm.Create(My_Tables[(Sender as TMenuItem).Tag],[]);
Table_Discription.Show_Table(My_Tables[(Sender as TMenuItem).Tag]);
end;
procedure TMySql.SpeedButton1Click(Sender: TObject);
begin
Schedule_Edit_form.Show;
end;
procedure TMySql.File_ExitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TMySql.FormCreate(Sender: TObject);
begin
Create_Reference_Menu();
end;
procedure TMySql.FormShow(Sender: TObject);
begin
end;
procedure TMySql.Send_Query_ButtonClick(Sender: TObject);
begin
with StartQuery do
begin
Close;
SQL.Text := Main_Syn_Memo.Text;
Open;
end;
end;
end.
{
query datasource на форме справочника
класс формы, много форм одного класса
reference form
на форме дбгрид. квери, datasource на один connection
создать 3 модуль с формой и модлуль в котором лежат все конекшены
модуль данных -DATAmodule
на нем конекшн и транзакции
завести в программе
создать форму записать селект в квери, квери опен, форм шоу
}//procedure TMySql.GroupsTableMenuClick(Sender: TObject);//var// TableDiscription: TReferenceForm;//begin// TableDiscription:= TReferenceForm.Create(Nil);// TableDiscription.show;//end;
|
unit DAO.PlanilhaEntradaSPLOG;
interface
uses Generics.Collections, System.Classes, System.SysUtils, Forms, Windows, Model.PlanilhaEntradasSPLOG;
type
TPlanilhaEntradaSPLOGDAO = class
public
function GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaSPLOG>;
end;
implementation
{ TPlanilhaEntradaEntregasDAO }
uses Common.Utils;
function TPlanilhaEntradaSPLOGDAO.GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaSPLOG>;
var
ArquivoCSV: TextFile;
sLinha: String;
sDetalhe: TStringList;
entradas : TObjectList<TPlanilhaEntradaSPLOG>;
i : Integer;
begin
try
entradas := TObjectList<TPlanilhaEntradaSPLOG>.Create;
if not FileExists(sFile) then
begin
Application.MessageBox(PChar('Arquivo ' + sFile + ' não foi encontrado!'), 'Atenção', MB_ICONWARNING + MB_OK);
Exit;
end;
AssignFile(ArquivoCSV, sFile);
if sFile.IsEmpty then Exit;
sDetalhe := TStringList.Create;
sDetalhe.StrictDelimiter := True;
sDetalhe.Delimiter := ';';
Reset(ArquivoCSV);
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha;
i := 0;
if sDetalhe[2] <> 'SPLOG BRASIL LOG, TRANS E ACAB' then
begin
Application.MessageBox('Arquivo informado não foi identificado como a Planilha de Entrada de Entregas da SPLOG!',
'Atenção', MB_ICONWARNING + MB_OK);
Exit;
end;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha;
if (sDetalhe[25] = 'RJ') then
begin
if (sDetalhe[0] = '3') then
begin
entradas.Add(TPlanilhaEntradaSPLOG.Create);
i := entradas.Count - 1;
entradas[i].TipoFrete := sDetalhe[1];
entradas[i].CTRC := sDetalhe[2];
entradas[i].CTe := sDetalhe[3];
entradas[i].DACTE := sDetalhe[4];
entradas[i].PrococoloCTe := sDetalhe[5];
entradas[i].DataAutorizacao := sDetalhe[6];
entradas[i].Situacao := sDetalhe[7];
entradas[i].TipoDocumento := sDetalhe[8];
entradas[i].Controle := sDetalhe[9];
entradas[i].PlacaColeta := sDetalhe[10];
entradas[i].Emissao := sDetalhe[11];
entradas[i].Hora := sDetalhe[12];
entradas[i].Login := sDetalhe[13];
entradas[i].CNPJTRemetente := sDetalhe[14];
entradas[i].SEGM := sDetalhe[15];
entradas[i].NomeRemetente := sDetalhe[16];
entradas[i].CidadeRemetente := sDetalhe[17];
entradas[i].UFRemetente := sDetalhe[18];
entradas[i].CNPJDestinatario := sDetalhe[19];
entradas[i].SEGM1 := sDetalhe[20];
entradas[i].NomeDestinatario := sDetalhe[21];
entradas[i].Praca := sDetalhe[22];
entradas[i].Diferenciada := sDetalhe[23];
entradas[i].CidadeDestino := sDetalhe[24];
entradas[i].UFDestino := sDetalhe[25];
entradas[i].LocalEntrega := sDetalhe[26];
entradas[i].EnderecoEntrega := sDetalhe[27];
entradas[i].CidadeEntrega := sDetalhe[28];
entradas[i].CEPEntrega := sDetalhe[29];
entradas[i].DistanciaKM := sDetalhe[30];
entradas[i].CNPJPagador := sDetalhe[31];
entradas[i].SEGM2 := sDetalhe[32];
entradas[i].NomePagador := sDetalhe[33];
entradas[i].TipoMercadoria := sDetalhe[34];
entradas[i].EspecieMercadoria := sDetalhe[35];
entradas[i].NF := sDetalhe[36];
entradas[i].Volumes := sDetalhe[37];
entradas[i].Pares := sDetalhe[38];
entradas[i].PesoReal := sDetalhe[39];
entradas[i].M3 := sDetalhe[40];
entradas[i].PesoCubado := sDetalhe[41];
entradas[i].PesoCalculado := sDetalhe[42];
entradas[i].FretePeso := sDetalhe[43];
entradas[i].FreteValor := sDetalhe[44];
entradas[i].Despacho := sDetalhe[45];
entradas[i].CAT := sDetalhe[46];
entradas[i].ITR := sDetalhe[47];
entradas[i].GRIS := sDetalhe[48];
entradas[i].Coleta := sDetalhe[49];
entradas[i].TDE := sDetalhe[50];
entradas[i].Pedagio := sDetalhe[51];
entradas[i].Suframa := sDetalhe[52];
entradas[i].Outros := sDetalhe[53];
entradas[i].Impostos := sDetalhe[54];
entradas[i].TAS := sDetalhe[55];
entradas[i].Reembolso := sDetalhe[56];
entradas[i].ImpostoCliente := sDetalhe[57];
entradas[i].DevCanhotoNF := sDetalhe[58];
entradas[i].TRT := sDetalhe[59];
entradas[i].AdicionalFrete := sDetalhe[60];
entradas[i].TDA := sDetalhe[61];
entradas[i].TAR := sDetalhe[62];
entradas[i].ValorCalculado := sDetalhe[63];
entradas[i].ValorFreteComissao := sDetalhe[64];
entradas[i].TipoCalculo := sDetalhe[65];
entradas[i].TabelaCalculo := sDetalhe[66];
entradas[i].ResultadoComercial := sDetalhe[67];
entradas[i].ValorBaixa := sDetalhe[68];
entradas[i].NumeroFatura := sDetalhe[69];
entradas[i].EmissaoFatura := sDetalhe[70];
entradas[i].VencimentoFatura := sDetalhe[71];
entradas[i].ICMSTransporte := sDetalhe[72];
entradas[i].ICMSST := sDetalhe[73];
entradas[i].ValorMercadoria := sDetalhe[74];
entradas[i].CodigoUltimaPendencia := sDetalhe[75];
entradas[i].DataUltimaPendencia := sDetalhe[76];
entradas[i].DescricaoUltimaPendencia := sDetalhe[77];
entradas[i].TipoUltimaPendencia := sDetalhe[78];
entradas[i].CodigoUltimaOcorrencia := sDetalhe[79];
entradas[i].DataInclusaoUltimaOcorrencia := sDetalhe[80];
entradas[i].UltimaOcorrencia := sDetalhe[81];
entradas[i].DataPrevisaoEntrega := sDetalhe[82];
entradas[i].DataEntregaAgendada := sDetalhe[83];
entradas[i].DataEntregaRealizada := sDetalhe[84];
entradas[i].Atraso := sDetalhe[85];
entradas[i].RecebidoPor := sDetalhe[86];
entradas[i].NumeroDocumentoRecebedor := sDetalhe[87];
entradas[i].SerieCTRCOrigem := sDetalhe[88];
entradas[i].NumeroCTRCOrigem := sDetalhe[89];
entradas[i].EmissaoCTRCOrigem := sDetalhe[90];
entradas[i].ValorCTRCOrigem := sDetalhe[91];
entradas[i].FreteFOBCTRCOrigem := sDetalhe[92];
entradas[i].TipoFreteOrigem := sDetalhe[93];
entradas[i].ValorICMSOrigem := sDetalhe[94];
entradas[i].DemaisNotasFiscais := sDetalhe[95];
entradas[i].OBS1 := sDetalhe[96];
entradas[i].OBS2 := sDetalhe[97];
entradas[i].OBS3 := sDetalhe[98];
entradas[i].PacoteArquivo := sDetalhe[99];
entradas[i].CapaRemessa := sDetalhe[100];
entradas[i].LocalizacaoAtual := sDetalhe[101];
entradas[i].UltimoRomaneio := sDetalhe[102];
entradas[i].EmissaoUltimoRomaneio := sDetalhe[103];
entradas[i].Placa := sDetalhe[104];
entradas[i].PesoNF := sDetalhe[105];
entradas[i].PesoBalanca := sDetalhe[106];
entradas[i].M3NF := sDetalhe[107];
entradas[i].M3Cubadora := sDetalhe[108];
entradas[i].M3Conferente := sDetalhe[109];
entradas[i].UsaCubadora := sDetalhe[110];
entradas[i].Pedido := sDetalhe[111];
entradas[i].CFOP := sDetalhe[112];
entradas[i].AliquotaICMS := sDetalhe[113];
if not Eoln(ArquivoCSV) then
begin
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha;
if (sDetalhe[0] = '4') then
begin
entradas[i].DANFE := sDetalhe[4];
end;
end;
end;
end;
end;
Result := entradas;
finally
CloseFile(ArquivoCSV);
end;
end;
end.
|
unit Digit;
interface
uses Engine, DGLE, DGLE_Types;
type
TDigitRec = record
Active: Boolean;
X, Y, NX, NY, DX, DY, Value: Integer;
Delta: Single;
end;
var
Digits: array of TDigitRec;
procedure Add(X, Y, Value: Integer);
procedure Update();
procedure Render();
implementation
uses uBox;
procedure Add(X, Y, Value: Integer);
var
I: Integer;
procedure SetDigit(I, X, Y: Integer);
begin
Digits[i].Active := True;
Digits[i].Value := Value;
Digits[i].Delta := 0;
Digits[i].DX := Rand(5, 15);
Digits[i].DY := Rand(1, 10);
Digits[i].X := X;
Digits[i].Y := Y;
end;
begin
if System.Length(Digits) <> 0 then
for i := 0 to System.Length(Digits)-1 do
if not Digits[i].Active then
begin
SetDigit(I, X, Y);
Exit;
end;
SetLength(Digits, System.Length(Digits) + 1);
SetDigit(System.Length(Digits) - 1, X, Y);
end;
procedure Update;
const
A = 0.9;
var
I: Integer;
begin
for I := 0 to System.Length(Digits) - 1 do
if Digits[i].Active then
begin
Digits[i].NX := Round(Sin(Digits[i].Delta * A) * 2 * SCR_LEFT + Digits[i].Delta * 0.2) + TILE_SIZE;
Digits[i].NY := Round(-1.0 * 2 * TILE_SIZE / 14 * Digits[i].Delta - (TILE_SIZE div 2));
Digits[i].Delta := Digits[i].Delta + 0.1;
if (Digits[i].Delta > 9) then Digits[i].Active := False;
end;
end;
procedure Render;
var
I: Integer;
Color: TColor4;
A: Byte;
begin
for I := 0 to System.Length(Digits) - 1 do
if Digits[I].Active then
begin
if (Digits[I].Delta = 0) then Exit;
A := 255 - Round(Digits[I].Delta * 25);
if Digits[I].Value <= 0 then
Color := Color4(255, 0, 0, A)
else Color := Color4(0, 255, 0, A);
TextOut((Digits[I].X - MAP_LEFT) * TILE_SIZE + SCR_LEFT + Digits[i].NX + Digits[I].DX,
(Digits[I].Y - MAP_TOP + 1) * TILE_SIZE + Digits[i].NY + Digits[I].DY, Digits[I].Value, Color);
end;
end;
end.
|
unit GX_CodeFormatterEditCapitalization;
{$I GX_CondDefine.inc}
{$IFDEF GX_VER200_up}
{$DEFINE SUPPORTS_UNICODE_STRING}
{$ENDIF}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
Actions,
ActnList,
Buttons,
ExtCtrls,
GX_EnhancedEditor,
GX_GenericUtils;
type
TfmCodeFormatterEditCapitalization = class(TForm)
p_Buttons: TPanel;
TheActionList: TActionList;
act_AllUpperCase: TAction;
act_AllLowerCase: TAction;
act_FirstCharUp: TAction;
act_ToggleComment: TAction;
act_Import: TAction;
act_Export: TAction;
act_ClearSearch: TAction;
p_Items: TPanel;
ed_Search: TEdit;
b_Clear: TSpeedButton;
b_UpperCase: TSpeedButton;
b_LowerCase: TSpeedButton;
b_FirstCharUp: TSpeedButton;
b_ToggleComment: TSpeedButton;
b_OK: TButton;
b_Cancel: TButton;
b_Import: TButton;
b_Export: TButton;
procedure act_AllUpperCaseExecute(Sender: TObject);
procedure act_AllLowerCaseExecute(Sender: TObject);
procedure act_FirstCharUpExecute(Sender: TObject);
procedure ed_SearchChange(Sender: TObject);
procedure act_ClearSearchExecute(Sender: TObject);
procedure act_ToggleCommentExecute(Sender: TObject);
procedure act_ImportExecute(Sender: TObject);
procedure act_ExportExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
FOrigList: TGXUnicodeString;
FWords: TGxEnhancedEditor;
function TryGetLine(out _Idx: Integer; out _Line: TGXUnicodeString): Boolean;
procedure SetLine(_Idx: Integer; const _Line: TGXUnicodeString);
procedure HandleOnEnterList(Sender: TObject);
procedure HandleOnExitList(Sender: TObject);
public
constructor Create(_Owner: TComponent); override;
procedure ListToForm(_Words: TGXUnicodeStringList);
procedure FormToList(_Words: TGXUnicodeStringList);
function IsChanged: Boolean;
end;
implementation
{$R *.DFM}
uses
GX_dzVclUtils,
GX_dzClassUtils;
{ TfmCodeFormatterCapitalization }
constructor TfmCodeFormatterEditCapitalization.Create(_Owner: TComponent);
begin
inherited;
TControl_SetMinConstraints(Self);
p_Items.BevelOuter := bvNone;
p_Buttons.BevelOuter := bvNone;
FWords := TGxEnhancedEditor.Create(Self);
FWords.Parent := p_Items;
FWords.HighLighter := gxpNone;
FWords.Align := alClient;
FWords.Font.Name := 'Courier New';
FWords.Font.Size := 10;
FWords.OnEnter := HandleOnEnterList;
FWords.OnExit := HandleOnExitList;
FWords.ActiveLineColor := clYellow;
FWords.WantTabs := False;
end;
procedure TfmCodeFormatterEditCapitalization.ListToForm(_Words: TGXUnicodeStringList);
begin
FWords.SetLines(_Words);
FOrigList := _Words.Text;
end;
procedure TfmCodeFormatterEditCapitalization.FormToList(_Words: TGXUnicodeStringList);
var
sl: TGXUnicodeStringList;
begin
sl := TGXUnicodeStringList.Create;
try
FWords.GetLines(sl);
sl.Sort;
_Words.Assign(sl);
finally
FreeAndNil(sl);
end;
end;
procedure TfmCodeFormatterEditCapitalization.HandleOnEnterList(Sender: TObject);
begin
FWords.ActiveLineColor := RGB(250, 255, 230);
end;
procedure TfmCodeFormatterEditCapitalization.HandleOnExitList(Sender: TObject);
begin
FWords.ActiveLineColor := clYellow;
end;
function TfmCodeFormatterEditCapitalization.TryGetLine(out _Idx: Integer; out _Line: TGXUnicodeString): Boolean;
begin
_Idx := FWords.CaretXY.Y;
Result := (_Idx >= 0) or (_Idx < FWords.LineCount);
if Result then
_Line := FWords.GetLine(_Idx);
end;
procedure TfmCodeFormatterEditCapitalization.SetLine(_Idx: Integer; const _Line: TGXUnicodeString);
var
pnt: TPoint;
begin
pnt := FWords.CaretXY;
FWords.SetLine(_Idx, _Line);
FWords.CaretXY := pnt;
end;
procedure TfmCodeFormatterEditCapitalization.act_AllUpperCaseExecute(Sender: TObject);
var
Line: TGXUnicodeString;
Idx: Integer;
begin
if TryGetLine(Idx, Line) then
SetLine(Idx, UpperCase(Line));
end;
procedure TfmCodeFormatterEditCapitalization.act_AllLowerCaseExecute(Sender: TObject);
var
Line: TGXUnicodeString;
Idx: Integer;
begin
if TryGetLine(Idx, Line) then
SetLine(Idx, LowerCase(Line));
end;
{$IFNDEF SUPPORTS_UNICODE_STRING}
function UpCase(_c: WideChar): WideChar; overload;
begin
Result := WideChar(System.UpCase(Char(_c)));
end;
{$ENDIF}
procedure TfmCodeFormatterEditCapitalization.act_FirstCharUpExecute(Sender: TObject);
var
Line: TGXUnicodeString;
Idx: Integer;
begin
if TryGetLine(Idx, Line) and (Line <> '') then begin
Line[1] := UpCase(Line[1]);
SetLine(Idx, Line);
end;
end;
procedure TfmCodeFormatterEditCapitalization.ed_SearchChange(Sender: TObject);
var
s: string;
sl: TGXUnicodeStringList;
Idx: Integer;
begin
s := ed_Search.Text;
if s = '' then
Exit;
sl := TGXUnicodeStringList.Create;
try
FWords.GetLines(sl);
TGXUnicodeStringList_MakeIndex(sl);
sl.Find(s, Idx);
FWords.CaretXY := Point(0, Integer(sl.Objects[Idx]) - 1);
finally
FreeAndNil(sl);
end;
end;
function TfmCodeFormatterEditCapitalization.IsChanged: Boolean;
var
sl: TGXUnicodeStringList;
begin
sl := TGXUnicodeStringList.Create;
try
FWords.GetLines(sl);
sl.Sort;
Result := (sl.Text <> FOrigList);
finally
FreeAndNil(sl);
end;
end;
procedure TfmCodeFormatterEditCapitalization.FormCloseQuery(
Sender: TObject; var CanClose: Boolean);
begin
if mrCancel = ModalResult then begin
if IsChanged and (MessageDlg('Leave without saving changes?', mtInformation,
[mbYes, mbNo], 0) = ID_No) then
CanClose := False;
end;
end;
procedure TfmCodeFormatterEditCapitalization.act_ClearSearchExecute(Sender: TObject);
begin
ed_Search.Text := '';
end;
procedure TfmCodeFormatterEditCapitalization.act_ToggleCommentExecute(Sender: TObject);
var
Idx: Integer;
Line: TGXUnicodeString;
begin
if TryGetLine(Idx, Line) and (Line <> '') then begin
if Line[1] = '*' then
Line := Copy(Line, 2, 255)
else
Line := '*' + Line;
SetLine(Idx, Line);
end;
end;
procedure TfmCodeFormatterEditCapitalization.act_ExportExecute(Sender: TObject);
var
fn: string;
begin
if ShowSaveDialog('Select file to import', 'txt', fn) then
FWords.SaveToFile(fn);
end;
procedure TfmCodeFormatterEditCapitalization.act_ImportExecute(Sender: TObject);
var
fn: string;
begin
if ShowOpenDialog('Select file to import', 'txt', fn) then
FWords.LoadFromFile(fn);
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Debug.Utils
Description : Debug Utils
Author : Kike Pérez
Version : 1.9
Created : 05/06/2020
Modified : 07/07/2020
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Debug.Utils;
{$i QuickLib.inc}
interface
uses
System.SysUtils,
Quick.Logger.Intf,
Quick.Serializer.Intf,
Quick.Commons,
{$IFNDEF NEXTGEN}
Quick.Console,
{$ELSE}
{$IFNDEF DELPHILINUX}
FMX.Types,
{$ENDIF}
{$ENDIF}
Quick.Chrono;
type
TDebugConsoleLogger = class(TInterfacedObject,ILogger)
private
fShowTime : Boolean;
fFormatSettings : TFormatSettings;
function FormatMsg(const aMsg : string) : string;
public
constructor Create;
property ShowTime : Boolean read fShowTime write fShowTime;
property FormatSettings : TFormatSettings read fFormatSettings write fFormatSettings;
procedure Info(const aMsg : string); overload;
procedure Info(const aMsg : string; aParams : array of const); overload;
procedure Succ(const aMsg : string); overload;
procedure Succ(const aMsg : string; aParams : array of const); overload;
procedure Done(const aMsg : string); overload;
procedure Done(const aMsg : string; aParams : array of const); overload;
procedure Warn(const aMsg : string); overload;
procedure Warn(const aMsg : string; aParams : array of const); overload;
procedure Error(const aMsg : string); overload;
procedure Error(const aMsg : string; aParams : array of const); overload;
procedure Critical(const aMsg : string); overload;
procedure Critical(const aMsg : string; aParams : array of const); overload;
procedure Trace(const aMsg : string); overload;
procedure Trace(const aMsg : string; aParams : array of const); overload;
procedure Debug(const aMsg : string); overload;
procedure Debug(const aMsg : string; aParams : array of const); overload;
procedure &Except(const aMsg : string; aValues : array of const); overload;
procedure &Except(const aMsg, aException, aStackTrace : string); overload;
procedure &Except(const aMsg : string; aValues: array of const; const aException, aStackTrace: string); overload;
end;
IDebugMethodEnter = interface
['{3BE4E8C2-CBCF-43BC-B3BE-0A0235C49BF1}']
procedure TimeIt;
end;
TDebugMethodEnter = class(TInterfacedObject,IDebugMethodEnter)
private
fLogger : ILogger;
fCallerMethod : string;
fTimeIt : Boolean;
fChrono : IChronometer;
public
constructor Create(aLogger : ILogger; const aCallerMethod : string);
destructor Destroy; override;
procedure TimeIt;
end;
IDebugMehtodChrono = interface
['{3DDD5389-D55A-4DEA-81FA-980CF41ACE38}']
procedure BreakPoint(const aMessage : string);
procedure Stop;
end;
TDebugMethodChrono = class(TInterfacedObject,IDebugMehtodChrono)
private
fLogger : ILogger;
fCallerMethod : string;
fMsg : string;
fChrono : IChronometer;
public
constructor Create(aLogger: ILogger; const aCallerMethod, aMsg : string);
destructor Destroy; override;
procedure BreakPoint(const aMsg : string);
procedure Stop;
end;
TDebugger = class
private class var
fLogger : ILogger;
fSerializer : ISerializer;
fShowTime : Boolean;
public
class constructor Create;
class destructor Destroy;
class procedure SetLogger(aLogger : ILogger);
class property ShowTime : Boolean read fShowTime write fShowTime;
class function NewChrono(aStarted : Boolean) : IChronometer;
class function TimeIt(aOwner : TObject; const aFunctionName, aDescription : string) : IDebugMehtodChrono;
class function Log : ILogger;
class procedure Trace(aOwner : TObject; const aMsg : string); overload;
class procedure Trace(aOwner : TObject; const aMsg : string; aParams : array of const); overload;
class procedure Trace(const aMsg : string); overload;
class procedure Trace(const aMsg : string; aParams : array of const); overload;
class procedure Trace(const aMsg : string; const aObject : TObject); overload;
class function Enter(aOwner : TObject; const aFunctionName: string) : IDebugMethodEnter;
end;
{$IFDEF NEXTGEN}
procedure cout(const cMsg : string; params : array of const; cEventType : TLogEventType); overload;
procedure cout(const cMsg : string; cEventType : TLogEventType); overload;
{$ENDIF}
implementation
uses
Quick.Json.Serializer;
{$IFDEF NEXTGEN}
procedure cout(const cMsg : string; params : array of const; cEventType : TLogEventType);
begin
FMX.Types.Log.d(Format(cMsg,params));
end;
procedure cout(const cMsg : string; cEventType : TLogEventType); overload;
begin
FMX.Types.Log.d(cMsg);
end;
{$ENDIF}
{ TDebugger }
class constructor TDebugger.Create;
begin
fSerializer := TJsonSerializer.Create(TSerializeLevel.slPublicProperty);
fLogger := TDebugConsoleLogger.Create;
fShowTime := True;
end;
class destructor TDebugger.Destroy;
begin
fSerializer := nil;
fLogger := nil;
end;
class function TDebugger.TimeIt(aOwner : TObject; const aFunctionName, aDescription: string): IDebugMehtodChrono;
begin
if aOwner <> nil then Result := TDebugMethodChrono.Create(fLogger,Format('%s.%s',[aOwner.ClassName,aFunctionName]),aDescription)
else Result := TDebugMethodChrono.Create(fLogger,Format('%s',[aFunctionName]),aDescription);
end;
class function TDebugger.Enter(aOwner : TObject; const aFunctionName: string) : IDebugMethodEnter;
begin
if aOwner <> nil then
begin
fLogger.Debug(Format('[ENTER] >> %s.%s',[aOwner.ClassName,aFunctionName]));
Result := TDebugMethodEnter.Create(fLogger,Format('%s.%s',[aOwner.ClassName,aFunctionName]));
end
else
begin
fLogger.Debug(Format('[ENTER] >> %s',[aFunctionName]));
Result := TDebugMethodEnter.Create(fLogger,aFunctionName);
end;
end;
class function TDebugger.NewChrono(aStarted : Boolean) : IChronometer;
begin
Result := TChronometer.Create(aStarted);
end;
class function TDebugger.Log: ILogger;
begin
Result := fLogger;
end;
class procedure TDebugger.SetLogger(aLogger: ILogger);
begin
if aLogger = nil then raise Exception.Create('Debugger logger cannot be nil!');
fLogger := aLogger;
fShowTime := False;
end;
class procedure TDebugger.Trace(aOwner: TObject; const aMsg: string);
begin
if aOwner <> nil then fLogger.Trace(Format('[TRACE] %s -> %s',[aOwner.ClassName,aMsg]))
else fLogger.Trace(Format('[TRACE] -> %s',[aMsg]))
end;
class procedure TDebugger.Trace(aOwner: TObject; const aMsg: string; aParams: array of const);
begin
Self.Trace(aOwner,Format(aMsg,aParams));
end;
class procedure TDebugger.Trace(const aMsg: string);
begin
fLogger.Trace(Format('[TRACE] %s',[aMsg]));
end;
class procedure TDebugger.Trace(const aMsg: string; aParams: array of const);
begin
Self.Trace(Format(aMsg,aParams));
end;
class procedure TDebugger.Trace(const aMsg: string; const aObject: TObject);
begin
Self.Trace(aMsg + ' ' + fSerializer.ObjectToJson(aObject));
end;
{ TDebugConsoleLogger }
constructor TDebugConsoleLogger.Create;
begin
fFormatSettings.DateSeparator := '/';
fFormatSettings.TimeSeparator := ':';
fFormatSettings.ShortDateFormat := 'DD-MM-YYY HH:NN:SS.ZZZ';
fFormatSettings.ShortTimeFormat := 'HH:NN:SS';
{$IFNDEF NEXTGEN}
Console.LogVerbose := LOG_ALL;
{$ENDIF}
fShowTime := True;
end;
procedure TDebugConsoleLogger.Critical(const aMsg: string; aParams: array of const);
begin
cout(FormatMsg(aMsg),aParams,TLogEventType.etCritical);
end;
procedure TDebugConsoleLogger.Critical(const aMsg: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etCritical);
end;
procedure TDebugConsoleLogger.Debug(const aMsg: string; aParams: array of const);
begin
cout(FormatMsg(aMsg),aParams,TLogEventType.etDebug);
end;
procedure TDebugConsoleLogger.Debug(const aMsg: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etDebug);
end;
procedure TDebugConsoleLogger.Done(const aMsg: string; aParams: array of const);
begin
cout(FormatMsg(aMsg),aParams,TLogEventType.etDone);
end;
procedure TDebugConsoleLogger.Done(const aMsg: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etDone);
end;
procedure TDebugConsoleLogger.Error(const aMsg: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etError);
end;
procedure TDebugConsoleLogger.Error(const aMsg: string; aParams: array of const);
begin
cout(FormatMsg(aMsg),aParams,TLogEventType.etError);
end;
procedure TDebugConsoleLogger.&Except(const aMsg: string; aValues: array of const);
begin
cout(FormatMsg(aMsg),aValues,TLogEventType.etException);
end;
procedure TDebugConsoleLogger.&Except(const aMsg, aException, aStackTrace: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etException);
end;
procedure TDebugConsoleLogger.&Except(const aMsg: string; aValues: array of const; const aException, aStackTrace: string);
begin
cout(FormatMsg(aMsg),aValues,TLogEventType.etException);
end;
function TDebugConsoleLogger.FormatMsg(const aMsg: string): string;
begin
if fShowTime then Result := DateTimeToStr(Now(),fFormatSettings) + ' ' + aMsg
else Result := aMsg
end;
procedure TDebugConsoleLogger.Info(const aMsg: string; aParams: array of const);
begin
cout(FormatMsg(aMsg),aParams,TLogEventType.etInfo);
end;
procedure TDebugConsoleLogger.Info(const aMsg: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etInfo);
end;
procedure TDebugConsoleLogger.Succ(const aMsg: string; aParams: array of const);
begin
cout(FormatMsg(aMsg),aParams,TLogEventType.etSuccess);
end;
procedure TDebugConsoleLogger.Succ(const aMsg: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etSuccess);
end;
procedure TDebugConsoleLogger.Trace(const aMsg: string; aParams: array of const);
begin
cout(FormatMsg(aMsg),aParams,TLogEventType.etTrace);
end;
procedure TDebugConsoleLogger.Trace(const aMsg: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etTrace);
end;
procedure TDebugConsoleLogger.Warn(const aMsg: string; aParams: array of const);
begin
cout(FormatMsg(aMsg),aParams,TLogEventType.etWarning);
end;
procedure TDebugConsoleLogger.Warn(const aMsg: string);
begin
cout(FormatMsg(aMsg),TLogEventType.etWarning);
end;
{ TDebugFunctionEnter }
constructor TDebugMethodEnter.Create(aLogger: ILogger; const aCallerMethod: string);
begin
fLogger := aLogger;
fCallerMethod := aCallerMethod;
end;
destructor TDebugMethodEnter.Destroy;
begin
if fTimeIt then
begin
fChrono.Stop;
fLogger.Debug(Format('[EXIT] >> %s in %s',[fCallerMethod,fChrono.ElapsedTime]));
end
else fLogger.Debug(Format('[EXIT] >> %s',[fCallerMethod]));
inherited;
end;
procedure TDebugMethodEnter.TimeIt;
begin
fTimeIt := True;
fChrono := TChronometer.Create(True);
end;
{ TDebugMethodChrono }
constructor TDebugMethodChrono.Create(aLogger: ILogger; const aCallerMethod, aMsg : string);
begin
fLogger := aLogger;
fCallerMethod := aCallerMethod;
fMsg := aMsg;
fChrono := TChronometer.Create(True);
end;
destructor TDebugMethodChrono.Destroy;
begin
if fChrono.IsRunning then
begin
fChrono.Stop;
fLogger.Trace(Format('[CHRONO] %s -> %s = %s',[fCallerMethod,fMsg,fChrono.ElapsedTime]));
end;
inherited;
end;
procedure TDebugMethodChrono.BreakPoint(const aMsg: string);
begin
fChrono.BreakPoint;
fLogger.Trace(Format('[CHRONO] %s -> %s = %s',[fCallerMethod,aMsg,fChrono.ElapsedTime_BreakPoint]));
end;
procedure TDebugMethodChrono.Stop;
begin
fChrono.Stop;
fLogger.Trace(Format('[CHRONO] %s -> %s = %s',[fCallerMethod,fMsg,fChrono.ElapsedTime]));
end;
end.
|
unit uCopy;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, RzPanel, RzRadGrp,StdCtrls, Gauges, RzButton;
type
TfmCopy = class(TForm)
Group_811: TRzCheckGroup;
pan_Caption: TPanel;
Gauge1: TGauge;
btn_DeviceCopy: TRzBitBtn;
btn_Close: TRzBitBtn;
st_caption: TStaticText;
procedure FormShow(Sender: TObject);
procedure Group_811Change(Sender: TObject; Index: Integer;
NewState: TCheckBoxState);
procedure btn_CloseClick(Sender: TObject);
procedure btn_DeviceCopyClick(Sender: TObject);
private
{ Private declarations }
procedure Ecu_GroupCreate;
Function MDIForm(FormName:string):TForm;
private
function SystemInfo_Registration(aWatchPowerOff,aInDelay,aOutDelay,aDoorType1,aDoorType2,
aDoorType3,aDoorType4,aDoorType5,aDoorType6,aDoorType7,aDoorType8,aLocate:string):Boolean;
function RegistArmDsCheck(aDoorNo,aArmDsCheck:string):Boolean;
function Relay2Type_Registration(aRelay2Type:integer):Boolean;
function RegistArmRelay(aArmRelay:string):Boolean;
function RegistArmAreaUse(aUsed:Boolean):Boolean;
function RegistDoorArmArea(aDoorArmAreaState:string):Boolean;
function RegistZoneExtensionUse(aZoneExtensionUseData:string):Boolean;
function DoorSystemInfo_Registration(aDoorNo,aCardModeType,aDoorModeType,aDoorControlTime,aDoorLongOpenTime,
aScheduleUse,aDoorStatusUse,aDoorLongTimeUse,aDoorLockType,aDoorFireOpenUse,aDoorDSOpenState,
aRemoteOpen:string):Boolean;
function DoorDSCheckUse_Registration(aDoorNo,aDsCheckUse:string):Boolean;
function DoorDSCheckTime_Registration(aDoorNo,aDoorDSCheckTime:string):Boolean; //옵션 시간을 부여함
function ArmDsCheck_Registration(aDoorNo,aArmDSCheck:string):Boolean;
function RegistCardType(aCardType:string):Boolean;
function RegistCardReaderInfo(aReaderNo,aReaderUse,aReaderDoor,aReaderDoorLocate,aReaderBuildingLocate,aReaderArmArea:integer;aLocateName:string):Boolean;
function RegistPortInfo(aPortNo,aWatchType,aWatchTypeCode,aDelayUse,aRecoverUse,aPortDelayTime,aZoneArmArea,aLocate,aZoneUsed:string):Boolean;
function RegistZoneExtensionPortInfo(aExtNo,aZoneExtensionSendData:string):Boolean;
function RegistAlartLampSiren(aAlertLamp,aAlertSiren:string):Boolean;
function RegistAlertLampTime(aAlertLampTime:string):Boolean;
function RegistAlertSirenTime(aAlertSirenTime:string):Boolean;
function CardReaderTelNumberRegist(aNo,aTelNumber:string):Boolean;
public
{ Public declarations }
L_stCaption : string;
L_stDeviceType : string;
L_bArmAreaSkill : Boolean;
L_bZoneExtensionSkill : Boolean;
end;
var
fmCopy: TfmCopy;
implementation
uses
uSocket,
uUtil,
dllFunction,
uCommon,
uCurrentDeviceSetting,
uCheckValiable;
{$R *.dfm}
{ TfmCopy }
procedure TfmCopy.Ecu_GroupCreate;
var
i : integer;
nIndex : integer;
begin
Group_811.Items.Clear;
for I:= 0 to 63 do
begin
Group_811.Items.Add(FillZeroNumber(i,2));
nIndex := DeviceList.IndexOf(FillZeroNumber(i,2));
if nIndex > -1 then
begin
if TCurrentDeviceState(DeviceList.Objects[nIndex]).Connected then
begin
Group_811.ItemChecked[i]:= True;
end;
end;
end;
end;
procedure TfmCopy.FormShow(Sender: TObject);
begin
Ecu_GroupCreate;
pan_Caption.Caption := L_stCaption;
end;
procedure TfmCopy.Group_811Change(Sender: TObject; Index: Integer;
NewState: TCheckBoxState);
var
nIndex : integer;
begin
if NewState = cbUnchecked then Exit;
nIndex := DeviceList.IndexOf(FillZeroNumber(Index,2));
if nIndex < 0 then
begin
Group_811.ItemChecked[Index]:= False;
showmessage('등록되지 않은 컨트롤러입니다.');
Exit;
end;
if Not TCurrentDeviceState(DeviceList.Objects[nIndex]).Connected then
begin
Group_811.ItemChecked[Index]:= False;
showmessage('해당 컨트롤러는 통신연결 상태가 아닙니다.');
Exit;
end;
end;
procedure TfmCopy.btn_CloseClick(Sender: TObject);
begin
Close;
end;
function TfmCopy.MDIForm(FormName: string): TForm;
var
tmpFormClass : TFormClass;
tmpClass : TPersistentClass;
tmpForm : TForm;
clsName : String;
i : Integer;
begin
result := nil;
clsName := FormName;
tmpClass := FindClass(clsName);
if tmpClass <> nil then
begin
for i := 0 to Screen.FormCount - 1 do
begin
if Screen.Forms[i].ClassNameIs(clsName) then
begin
result := Screen.Forms[i];
Exit;
end;
end;
end;
end;
procedure TfmCopy.btn_DeviceCopyClick(Sender: TObject);
var
fmDeviceSetting :TForm;
stDoorControlTime : string;
stDoorLockType : string;
stCardModeType : string;
stDoorModeType : string;
stDoorLongOpenTime : string;
stScheduleUse : string;
stDoorStatusUse : string;
stDoorLongTimeUse : string;
stDoorFireOpenUse : string;
stDoorDSOpenState : string;
stDoorDSCheckTime : string;
stRemoteOpen : string;
stReaderType : string;
i : integer;
stReaderUse : string;
stReaderDoor : string;
cmb_Box : TComboBox;
nPortNumber : integer;
nWatchType : integer;
nDelay : integer;
stWatchTypeCode : string;
mRecoverUse : integer;
nZoneArmArea:integer;
nZoneUsed:integer;
Edit : TEdit;
stTelNo : string;
nExtNo : integer;
nZoneExtensionUse : integer;
stZoneExtensionSendData : string;
arrBitFunction : array [0..7] of char;
stBitfunction : string;
nIndex : integer;
begin
Try
btn_DeviceCopy.Enabled := False;
fmDeviceSetting := MDIForm('TfmCurrentDeviceSetting');
if TfmCurrentDeviceSetting(fmDeviceSetting).pg_DeviceSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).TabMCSetting then
begin
//MCUSetting_Registration;
end else if TfmCurrentDeviceSetting(fmDeviceSetting).pg_DeviceSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).TabArmExtension then
begin
//Main 에서만 동작함
end else if TfmCurrentDeviceSetting(fmDeviceSetting).pg_DeviceSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).TabSystemInfo then
begin
if SystemInfo_Registration(inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_WatchPowerOff.ItemIndex),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).SpinEdit_InDelay.IntValue),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).SpinEdit_OutDelay.IntValue),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_DoorType1.ItemIndex),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_DoorType2.ItemIndex),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_DoorType3.ItemIndex),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_DoorType4.ItemIndex),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_DoorType5.ItemIndex),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_DoorType6.ItemIndex),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_DoorType7.ItemIndex),
inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).ComboBox_DoorType8.ItemIndex),
TfmCurrentDeviceSetting(fmDeviceSetting).Edit_Locate.Text ) then
begin
if L_stDeviceType <> KTT811 then
begin
if Not RegistArmRelay(inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ArmRelay.ItemIndex)) then Exit;
end;
if L_stDeviceType = KTT812 then Relay2Type_Registration(TfmCurrentDeviceSetting(fmDeviceSetting).cmb_Relay2Type.ItemIndex);
if L_bArmAreaSkill then
begin
RegistArmAreaUse(TfmCurrentDeviceSetting(fmDeviceSetting).chk_DoorArmAreaUse.Checked);
if TfmCurrentDeviceSetting(fmDeviceSetting).chk_DoorArmAreaUse.Checked then
RegistDoorArmArea(TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorArmAreaState);
end;
if L_bZoneExtensionSkill then RegistZoneExtensionUse(TfmCurrentDeviceSetting(fmDeviceSetting).GetZoneExtensionUseData);
end;
end else if TfmCurrentDeviceSetting(fmDeviceSetting).pg_DeviceSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).tab_DoorLock then
begin
if TfmCurrentDeviceSetting(fmDeviceSetting).pgDoorLockSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).tabLock_Controler then
begin
for i := 1 to 2 do
begin
if i <= TfmCurrentDeviceSetting(fmDeviceSetting).GetDeviceMaxDoorNumber then //최대 갯수 보다 작으면
begin
if i = 2 then
begin
if L_stDeviceType = KTT812 then //2번째 출입문이고 KTT812 타입이면 릴레이 체크 하자
begin
if TfmCurrentDeviceSetting(fmDeviceSetting).cmb_Relay2Type.ItemIndex = 0 then Exit;
end;
end;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorControlTime(inttostr(i),stDoorControlTime) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorLockType(inttostr(i),stDoorLockType) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorCardMode(inttostr(i),stCardModeType) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorModeType(inttostr(i),stDoorModeType) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorLongOpenTime(inttostr(i),stDoorLongOpenTime) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorScheduleUse(inttostr(i),stScheduleUse) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorStatusUse(inttostr(i),stDoorStatusUse) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorLongTimeUse(inttostr(i),stDoorLongTimeUse) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorFireOpenUse(inttostr(i),stDoorFireOpenUse) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorDSOpenState(inttostr(i),stDoorDSOpenState) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorRemoteOpen(inttostr(i),stRemoteOpen) then continue;
DoorSystemInfo_Registration(inttostr(i),stCardModeType,stDoorModeType,stDoorControlTime,stDoorLongOpenTime,
stScheduleUse,stDoorStatusUse,stDoorLongTimeUse,stDoorLockType,stDoorFireOpenUse,
stDoorDSOpenState,stRemoteOpen);
if L_stDeviceType = KTT812 then
begin
if TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorDSCheckTime(inttostr(i),stDoorDSCheckTime) then
begin
if stDoorDSCheckTime = '0' then //항상검사
begin
DoorDSCheckUse_Registration(inttostr(i),'0');
end else
begin
DoorDSCheckUse_Registration(inttostr(i),'1');
DoorDSCheckTime_Registration(inttostr(i),stDoorDSCheckTime); //옵션 시간을 부여함
end;
end;
cmb_Box := TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_DoorInfo,'cmb_ArmDSCheck',i);
if cmb_Box <> nil then
ArmDsCheck_Registration(inttostr(i),inttostr(cmb_Box.ItemIndex));
end;
end;
end;
end else if TfmCurrentDeviceSetting(fmDeviceSetting).pgDoorLockSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).tabLockExtention then
begin
for i := 3 to FIXMAXDOORNO do
begin
if i <= TfmCurrentDeviceSetting(fmDeviceSetting).GetDeviceMaxDoorNumber then
begin
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorControlTime(inttostr(i),stDoorControlTime) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorLockType(inttostr(i),stDoorLockType) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorCardMode(inttostr(i),stCardModeType) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorModeType(inttostr(i),stDoorModeType) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorLongOpenTime(inttostr(i),stDoorLongOpenTime) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorScheduleUse(inttostr(i),stScheduleUse) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorStatusUse(inttostr(i),stDoorStatusUse) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorLongTimeUse(inttostr(i),stDoorLongTimeUse) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorFireOpenUse(inttostr(i),stDoorFireOpenUse) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorDSOpenState(inttostr(i),stDoorDSOpenState) then continue;
if Not TfmCurrentDeviceSetting(fmDeviceSetting).GetDoorRemoteOpen(inttostr(i),stRemoteOpen) then continue;
DoorSystemInfo_Registration(inttostr(i),stCardModeType,stDoorModeType,stDoorControlTime,stDoorLongOpenTime,
stScheduleUse,stDoorStatusUse,stDoorLongTimeUse,stDoorLockType,stDoorFireOpenUse,
stDoorDSOpenState,stRemoteOpen);
if L_stDeviceType = KTT812 then
begin
cmb_Box := TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_DoorExtensionInfo,'cmb_ArmDSCheck',i);
if cmb_Box <> nil then
ArmDsCheck_Registration(inttostr(i),inttostr(cmb_Box.ItemIndex));
end;
end;
end;
end;
end else if TfmCurrentDeviceSetting(fmDeviceSetting).pg_DeviceSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).tab_CardReader then
begin
stReaderType := inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).cb_CardType.ItemIndex) + '0' + TfmCurrentDeviceSetting(fmDeviceSetting).GetReaderNumType;
RegistCardType(stReaderType);
for i := 1 to G_nCardReaderNumber do
begin
RegistCardReaderInfo(i,
TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_CardReader,'cmb_ReaderUse',i).ItemIndex,
TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_CardReader,'cmb_ReaderDoor',i).ItemIndex,
TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_CardReader,'cmb_ReaderDoorLocate',i).ItemIndex,
TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_CardReader,'cmb_ReaderBuildingLocate',i).ItemIndex,
TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_CardReader,'cmb_ReaderAlarmArea',i).ItemIndex,
'' //위치명
);
end;
end else if TfmCurrentDeviceSetting(fmDeviceSetting).pg_DeviceSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).Tab_Port then
begin
if TfmCurrentDeviceSetting(fmDeviceSetting).pg_PortSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).tab_LocalPort then
begin
nPortNumber := TfmCurrentDeviceSetting(fmDeviceSetting).GetDeviceMaxPortNumber;
for i:= 1 to nPortNumber do
begin
cmb_Box := TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_Port,'cmb_WatchType',i);
nWatchType := 0;
if cmb_Box <> nil then nWatchType := cmb_Box.ItemIndex;
stWatchTypeCode := TfmCurrentDeviceSetting(fmDeviceSetting).GetWatchTypeCode(i,nWatchType);
nDelay := 0;
cmb_Box := TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_Port,'cmb_WatchDelay',i);
if cmb_Box <> nil then
begin
nDelay := cmb_Box.ItemIndex;
end;
mRecoverUse := 0;
cmb_Box := TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_Port,'cmb_recorver',i);
if cmb_Box <> nil then
begin
mRecoverUse := cmb_Box.ItemIndex;
end;
nZoneArmArea := 0;
cmb_Box := TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_Port,'cmb_PortAlarmArea',i);
if cmb_Box <> nil then
begin
nZoneArmArea := cmb_Box.ItemIndex;
end;
nIndex := DeviceList.IndexOf(FillZeroNumber(i,2));
if Not TCurrentDeviceState(DeviceList.Objects[nIndex]).ArmAreaUse then nZoneArmArea := 0;
nZoneUsed := 0;
cmb_Box := TravelComboBoxItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_Port,'cmb_ZonUse',i);
if cmb_Box <> nil then
begin
nZoneUsed := cmb_Box.ItemIndex;
if nZoneUsed < 0 then nZoneUsed := 0;
end;
RegistPortInfo(inttostr(i),
inttostr(nWatchType),
stWatchTypeCode,
inttostr(nDelay), //지연시간 사용유무
inttostr(mRecoverUse),
'04', //포트감지시간
FillZeroNumber(nZoneArmArea,2),
'', //위치명
inttostr(nZoneUsed)
);
end;
if TfmCurrentDeviceSetting(fmDeviceSetting).cmb_alartLamp.ItemIndex < 0 then TfmCurrentDeviceSetting(fmDeviceSetting).cmb_alartLamp.ItemIndex := 0;
if TfmCurrentDeviceSetting(fmDeviceSetting).cmb_alartSiren.ItemIndex < 0 then TfmCurrentDeviceSetting(fmDeviceSetting).cmb_alartSiren.ItemIndex := 0;
RegistAlartLampSiren(inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).cmb_alartLamp.ItemIndex),inttostr(TfmCurrentDeviceSetting(fmDeviceSetting).cmb_alartSiren.ItemIndex));
if Not IsDigit(TfmCurrentDeviceSetting(fmDeviceSetting).ed_alertLampTime.Text) then TfmCurrentDeviceSetting(fmDeviceSetting).ed_alertLampTime.Text := '10';
RegistAlertLampTime(Trim(TfmCurrentDeviceSetting(fmDeviceSetting).ed_alertLampTime.Text));
if Not IsDigit(TfmCurrentDeviceSetting(fmDeviceSetting).ed_alertSirenTime.Text) then TfmCurrentDeviceSetting(fmDeviceSetting).ed_alertSirenTime.Text := '1';
RegistAlertSirenTime(Trim(TfmCurrentDeviceSetting(fmDeviceSetting).ed_alertSirenTime.Text));
end else if TfmCurrentDeviceSetting(fmDeviceSetting).pg_PortSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).tab_ExtensionPort then
begin
nExtNo := TfmCurrentDeviceSetting(fmDeviceSetting).pg_ExtensionPort.ActivePage.Tag;
case nExtNo of
1 : nZoneExtensionUse := TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ZoneExtensionUse1.ItemIndex;
2 : nZoneExtensionUse := TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ZoneExtensionUse2.ItemIndex;
3 : nZoneExtensionUse := TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ZoneExtensionUse3.ItemIndex;
4 : nZoneExtensionUse := TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ZoneExtensionUse4.ItemIndex;
5 : nZoneExtensionUse := TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ZoneExtensionUse5.ItemIndex;
6 : nZoneExtensionUse := TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ZoneExtensionUse6.ItemIndex;
7 : nZoneExtensionUse := TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ZoneExtensionUse7.ItemIndex;
8 : nZoneExtensionUse := TfmCurrentDeviceSetting(fmDeviceSetting).cmb_ZoneExtensionUse8.ItemIndex;
end;
if nZoneExtensionUse < 0 then nZoneExtensionUse := 0;
stZoneExtensionSendData := inttostr(nZoneExtensionUse);
for i:= 1 to FIXMAXZONENO do
begin
FillChar(arrBitFunction, 8, '0');
cmb_Box := TfmCurrentDeviceSetting(fmDeviceSetting).GetPortComboBox(nExtNo,i,'cmb_WatchType');
nWatchType := 0;
if cmb_Box <> nil then nWatchType := cmb_Box.ItemIndex;
stWatchTypeCode := TfmCurrentDeviceSetting(fmDeviceSetting).GetWatchTypeCode(i,nWatchType);
nDelay := 0;
nZoneArmArea := 1;
cmb_Box := TfmCurrentDeviceSetting(fmDeviceSetting).GetPortComboBox(nExtNo,i,'cmb_PortAlarmArea');
if cmb_Box <> nil then
begin
nZoneArmArea := cmb_Box.ItemIndex + 1;
end;
if nWatchType < 0 then nWatchType := 0;
if nZoneArmArea < 0 then nZoneArmArea := 0;
stZoneExtensionSendData := stZoneExtensionSendData + stWatchTypeCode + inttostr(nWatchType) + FillZeroNumber(nZoneArmArea,2);
cmb_Box := TfmCurrentDeviceSetting(fmDeviceSetting).GetPortComboBox(nExtNo,i,'cmb_recorver');
if cmb_Box <> nil then
begin
if cmb_Box.ItemIndex = 1 then arrBitFunction[5] := '1';
end;
stBitfunction := stBitfunction + BinaryToHex(string(arrBitFunction));
end;
stZoneExtensionSendData := stZoneExtensionSendData + stBitfunction;
RegistZoneExtensionPortInfo(inttostr(nExtNo),stZoneExtensionSendData);
end;
end else if TfmCurrentDeviceSetting(fmDeviceSetting).pg_DeviceSetting.ActivePage = TfmCurrentDeviceSetting(fmDeviceSetting).Tab_CardReaderTel then
begin
for i := 0 to 9 do
begin
stTelNo := '';
Edit := TravelEditItem(TfmCurrentDeviceSetting(fmDeviceSetting).gb_cardReaderTel,'ed_cardreaderTel',i);
if Edit <> nil then
begin
stTelNo := Edit.Text;
end;
if Not CardReaderTelNumberRegist(inttostr(i),stTelNo) then break;
end;
end;
Finally
btn_DeviceCopy.Enabled := True;
End;
end;
function TfmCopy.SystemInfo_Registration(aWatchPowerOff,aInDelay,aOutDelay,aDoorType1,aDoorType2,
aDoorType3,aDoorType4,aDoorType5,aDoorType6,aDoorType7,aDoorType8,aLocate:string):Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := '시스템 정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistSystemInfo(FillZeroNumber(i,2),
aWatchPowerOff,
aInDelay,
aOutDelay,
aDoorType1,
aDoorType2,
aDoorType3,
aDoorType4,
aDoorType5,
aDoorType6,
aDoorType7,
aDoorType8,
aLocate);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistArmDsCheck(aDoorNo, aArmDsCheck: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := '경계시 문열림 검사 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
if G_stDeviceType[i] = KTT812 then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistArmDsCheck(FillZeroNumber(i,2),
FillZeroNumber(strtoint(aDoorNo),2),
aArmDsCheck);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistArmRelay(aArmRelay: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := '경해 Relay 동작 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
if G_stDeviceType[i] <> KTT811 then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistArmRelay(FillZeroNumber(i,2),aArmRelay);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.DoorSystemInfo_Registration(aDoorNo, aCardModeType,
aDoorModeType, aDoorControlTime, aDoorLongOpenTime, aScheduleUse,
aDoorStatusUse, aDoorLongTimeUse, aDoorLockType, aDoorFireOpenUse,
aDoorDSOpenState, aRemoteOpen: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := aDoorNo + '번 출입문 설정정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
if G_stDeviceType[i] <> ICU200 then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistDoorSystemInfo(FillZeroNumber(i,2), // 기기번호
aDoorNo, // 문번호
aCardModeType, // 카드 운영모드 (0:Positive, 1:Negative)
aDoorModeType, // 출입문 운영모드 (0:운영, 1:개방)
aDoorControlTime, // Door 제어시간
aDoorLongOpenTime, // 장시간 열림 경보
aScheduleUse, // 스케줄 적용 여부 (0:사용안함, 1:사용)
aDoorStatusUse, // 출입문 상태 전송(0:사용안함, 1:사용)
aDoorLongTimeUse, // 장시간 열림 부저 출력(0:사용안함, 1:사용)
aDoorLockType, // 전기정 타입
aDoorFireOpenUse, // 화재 발생시 문제어
aDoorDSOpenState, //출입문열림상태 (DS OPEN 0x30,DS CLOSE 0x31)
aRemoteOpen);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistCardType(aCardType: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := '카드리더 타입 설정정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
if (G_stDeviceType[i] <> ICU200) and (G_stDeviceType[i] <> ICU100) then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistCardType(FillZeroNumber(i,2),aCardType);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistCardReaderInfo(aReaderNo, aReaderUse, aReaderDoor,
aReaderDoorLocate, aReaderBuildingLocate,aReaderArmArea: integer;
aLocateName: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := inttostr(aReaderNo) + '번 카드리더 설정정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
if (G_stDeviceType[i] <> ICU200) and (G_stDeviceType[i] <> ICU100) then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistCardReaderInfo(FillZeroNumber(i,2),aReaderNo,
aReaderUse, aReaderDoor, aReaderDoorLocate,
aReaderBuildingLocate,aReaderArmArea,aLocateName);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistPortInfo(aPortNo, aWatchType, aWatchTypeCode,
aDelayUse, aRecoverUse, aPortDelayTime,aZoneArmArea, aLocate,aZoneUsed: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := aPortNo + '번 포트 설정정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistPortInfo(FillZeroNumber(i,2), aPortNo, aWatchType,
aDelayUse, aRecoverUse, aPortDelayTime, aWatchTypeCode,aZoneArmArea,
aLocate,aZoneUsed);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistAlartLampSiren(aAlertLamp,
aAlertSiren: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := '비상존 이상발생 설정정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistAlartLampSiren(FillZeroNumber(i,2), aAlertLamp,aAlertSiren);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistAlertLampTime(aAlertLampTime: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := '램프 동작 설정정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistAlertLampTime(FillZeroNumber(i,2),aAlertLampTime);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistAlertSirenTime(aAlertSirenTime: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := '사이렌 동작 설정정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistAlertSirenTime(FillZeroNumber(i,2),aAlertSirenTime);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
End;
end;
result := True;
end;
function TfmCopy.CardReaderTelNumberRegist(aNo,
aTelNumber: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
begin
result := False;
st_caption.Caption := aNo + '번 전화번호 설정정보 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
if (G_stDeviceType[i] = KTT811) then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.CardReaderTelNumberRegist(FillZeroNumber(i,2),aNo,aTelNumber);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.Relay2Type_Registration(aRelay2Type: integer): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
stRegistData : string;
begin
stRegistData := FillZeroNumber(0,9);
if aRelay2Type < 0 then aRelay2Type := 0;
stRegistData[3] := inttostr(aRelay2Type)[1];
result := False;
st_caption.Caption := 'Door2사용구분 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
if G_stDeviceType[i] = KTT812 then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistRelay2Type(FillZeroNumber(i,2),stRegistData);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistArmAreaUse(aUsed: Boolean): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
nIndex : integer;
stArmAreaUse : string;
begin
if aUsed then stArmAreaUse := '1'
else stArmAreaUse := '0';
result := False;
st_caption.Caption := '방범구역 설정 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
stEcuID := FillZeroNumber(i,2);
nIndex := DeviceList.IndexOf(stEcuID);
if nIndex < 0 then continue;
if TCurrentDeviceState(DeviceList.Objects[nIndex]).ArmAreaSkill then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistArmAreaUse(stEcuID,stArmAreaUse);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistDoorArmArea(aDoorArmAreaState: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
nIndex : integer;
begin
result := False;
st_caption.Caption := '방범구역 설정 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
stEcuID := FillZeroNumber(i,2);
nIndex := DeviceList.IndexOf(stEcuID);
if nIndex < 0 then continue;
if TCurrentDeviceState(DeviceList.Objects[nIndex]).ArmAreaSkill then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistDoorArmArea(stEcuID,aDoorArmAreaState);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistZoneExtensionUse(
aZoneExtensionUseData: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
nIndex : integer;
begin
result := False;
st_caption.Caption := '존확장기사용유무 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
stEcuID := FillZeroNumber(i,2);
nIndex := DeviceList.IndexOf(stEcuID);
if nIndex < 0 then continue;
if TCurrentDeviceState(DeviceList.Objects[nIndex]).ZoneExtensionSkill then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistZoneExtensionUse(stEcuID,aZoneExtensionUseData);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.ArmDsCheck_Registration(aDoorNo,
aArmDSCheck: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
nIndex : integer;
begin
result := False;
st_caption.Caption := aDoorNo + '번 출입문 경계시 문열림 검사 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
stEcuID := FillZeroNumber(i,2);
nIndex := DeviceList.IndexOf(stEcuID);
if nIndex < 0 then continue;
if TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT812 then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistArmDsCheck(stEcuID,
FillZeroNumber(strtoint(aDoorNo),2),
aArmDsCheck);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.DoorDSCheckTime_Registration(aDoorNo,
aDoorDSCheckTime: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
nIndex : integer;
begin
result := False;
st_caption.Caption := aDoorNo + '번 출입문 DS검사 시간 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
stEcuID := FillZeroNumber(i,2);
nIndex := DeviceList.IndexOf(stEcuID);
if nIndex < 0 then continue;
if TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT812 then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistDoorDSCheckTime(stEcuID,aDoorNo,aDoorDSCheckTime);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.DoorDSCheckUse_Registration(aDoorNo,
aDsCheckUse: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
nIndex : integer;
begin
result := False;
st_caption.Caption := aDoorNo + '번 출입문 DS검사 사용유무 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
stEcuID := FillZeroNumber(i,2);
nIndex := DeviceList.IndexOf(stEcuID);
if nIndex < 0 then continue;
if TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT812 then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistDoorDSCheckUse(stEcuID,aDoorNo,aDsCheckUse);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
function TfmCopy.RegistZoneExtensionPortInfo(aExtNo,
aZoneExtensionSendData: string): Boolean;
var
i,j : integer;
stEcuID : string;
bResult : Boolean;
nIndex : integer;
begin
result := False;
st_caption.Caption := aExtNo + '번 존확장기 등록중';
Gauge1.MaxValue := Group_811.Items.Count - 1;
for i := 0 to Group_811.Items.Count - 1 do
begin
Gauge1.Progress := i;
if Group_811.ItemChecked[i] then
begin
stEcuID := FillZeroNumber(i,2);
nIndex := DeviceList.IndexOf(stEcuID);
if nIndex < 0 then continue;
if TCurrentDeviceState(DeviceList.Objects[nIndex]).ZoneExtensionSkill then
begin
for j := 0 to G_nLoopCount do
begin
if G_bApplicationTerminate then Exit;
bResult := dmSocket.RegistZoneExtensionPortInfo(stEcuID, aExtNo, aZoneExtensionSendData);
if bResult then Break;
end;
if Not bResult then
begin
if Application.MessageBox(Pchar(FillZeroNumber(i,2) + '번 컨트롤러의 등록이 실패 하였습니다. 계속 하시겠습니까?'),'경고',MB_OKCANCEL)= ID_CANCEL then Exit;
end;
end;
End;
end;
result := True;
end;
end.
|
unit K404361004;
{* [Requestlink:404361004] }
// Модуль: "w:\archi\source\projects\Archi\Tests\K404361004.pas"
// Стереотип: "TestCase"
// Элемент модели: "K404361004" MUID: (50AF42CD0309)
// Имя типа: "TK404361004"
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3IntfUses
{$If NOT Defined(NoScripts)}
, ArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
;
type
TK404361004 = class({$If NOT Defined(NoScripts)}
TArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
)
{* [Requestlink:404361004] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK404361004
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *50AF42CD0309impl_uses*
//#UC END# *50AF42CD0309impl_uses*
;
{$If NOT Defined(NoScripts)}
function TK404361004.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'ScrollTests';
end;//TK404361004.GetFolder
function TK404361004.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '50AF42CD0309';
end;//TK404361004.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK404361004.Suite);
{$IfEnd} // NOT Defined(NoScripts)
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
end.
|
unit GAPI;
interface
uses Crt, Graph;
const
Solid : FillPatternType = ($FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF);
Gray50 : FillPatternType = ($AA, $55, $AA, $55, $AA, $55, $AA, $55);
Squares : FillPatternType = ($F0,$F0,$F0,$F0,$0F,$0F,$0F,$0F);
Hatch : FillPatternType = ($11,$22,$44,$88,$11,$22,$44,$88);
procedure OutTextXY3D(AX,AY: Integer; ATextColor, AShadowColor: Word; Text: string);
procedure OutTextXYFramed(AX, AY: Integer; ATextColor, AFrameColor: Word; Text: string);
function InputString(AX, AY, MaxLen: Integer; var AStr: string; ADisplay: Boolean): Boolean;
function GetOption( AXPos, AYPos: Integer; AAllign: Integer;
ATextColor, ABackColor: Integer; AOptions: string; ADefault: Integer): Integer;
function FileExists(AFName: string): Boolean;
procedure ErrorBeep;
procedure OkBeep;
procedure WarningBeep;
implementation
procedure OutTextXY3D(AX,AY: Integer; ATextColor, AShadowColor: Word; Text: string);
begin
SetColor(AShadowColor);
OutTextXY(AX,AY + 1,Text);
SetColor(ATextColor);
OutTextXY(AX + 1,AY,Text);
end;
procedure OutTextXYFramed(AX, AY: Integer; ATextColor, AFrameColor: Word; Text: string);
begin
SetColor(AFrameColor);
OutTextXY(AX + 1,AY + 1,Text);
OutTextXY(AX - 1,AY - 1,Text);
OutTextXY(AX,AY + 1,Text);
OutTextXY(AX,AY - 1,Text);
OutTextXY(AX + 1,AY,Text);
OutTextXY(AX - 1,AY,Text);
OutTextXY(AX + 1,AY - 1,Text);
OutTextXY(AX - 1,AY + 1,Text);
SetColor(ATextColor);
OutTextXY(AX,AY,Text);
end;
function InputString(AX, AY, MaxLen: Integer; var AStr: string; ADisplay: Boolean): Boolean;
var Str: string;
Pos: Integer;
WindowWidth: Integer;
WindowHeight: Integer;
Buffer: Pointer;
BufferSize: Word;
OldSettings: ViewPortType;
OldColor: Integer;
procedure Draw;
begin
Bar(AX, AY, AX + WindowWidth, AY + WindowHeight);
SetColor(15);
Rectangle(AX, AY, AX + WindowWidth, AY + WindowHeight);
OutTextXY(AX + 3, AY + 3, Str);
end;
procedure Display;
var StrLen: Integer;
S1,S2: String;
I: Integer;
begin
Bar(AX + 1, AY + 1, AX + WindowWidth - 1, AY + WindowHeight - 1);
if ADisplay
then begin
S1 := Copy(Str,1,Pos - 1);
S2 := Copy(Str,Pos,Length(Str));
SetColor(15);
MoveTo(AX + 3, AY + 3);
OutText(S1);
SetColor(12);
OutText('_');
SetColor(15);
OutText(S2);
end
else begin
MoveTo(AX + 3, AY + 3);
SetColor(15);
for I := 1 to Pos - 1
do OutText('*');
SetColor(12);
OutText('_');
for I := Pos to Length(Str)
do OutText('*');
end;
end;
function Edit: Boolean;
var Key: Char;
Update: Boolean;
begin
Key := ReadKey;
Update := False;
while ((Key <> #13) and (Key <> #27))
do begin
if Key in [#32..#127]
then begin
if Pos <= MaxLen
then begin
Str[Pos] := Key;
if Pos > Length(Str)
then begin
Str[0] := Char(Pos);
end;
Pos := Pos + 1;
Update := True;
end;
end
else begin
if (Key = #0)
then begin
Key := ReadKey;
end;
case Key
of #8: begin
if (Pos > 1)
then begin
Pos := Pos - 1;
Delete(Str,Pos,1);
Update := True;
end;
end;
#83: begin
if (Pos <= Length(Str))
then begin
Delete(Str,Pos,1);
Update := True;
end;
end;
#75: begin
if (Pos > 1)
then begin
Pos := Pos - 1;
Update := True;
end;
end;
#77: begin
if (Pos <= Length(Str))
then begin
Pos := Pos + 1;
Update := True;
end;
end;
end;
end;
if Update
then Display;
Key := ReadKey;
end;
if Key = #13
then begin
Edit := True;
AStr := Str;
end
else begin
Edit := False;
end;
end;
begin
{HideMouse;}
SetWriteMode(NormalPut);
SetFillPattern(Solid, 0);
WindowWidth := (MaxLen + 1) * TextWidth('W') + 4;
WindowHeight := TextWidth('W') + 4;
OldColor := GetColor;
GetViewSettings(OldSettings);
SetViewPort(0, 0, GetMaxX, GetMaxY, True);
BufferSize := ImageSize(AX, AY, AX + WindowWidth, AY + WindowHeight);
GetMem(Buffer,BufferSize);
GetImage(AX, AY, AX + WindowWidth, AY + WindowHeight, Buffer^);
if (Length(AStr) <= MaxLen)
then Str := AStr
else Str := Copy(AStr,1,MaxLen);
Pos := Length(Str) + 1;
Draw;
Display;
InputString := Edit;
PutImage(AX,AY, Buffer^,NormalPut);
FreeMem(Buffer,BufferSize);
SetViewPort(OldSettings.X1, OldSettings.Y1, OldSettings.X2, OldSettings.Y2, OldSettings.Clip);
SetColor(OldColor);
{ShowMouse;}
end;
function GetOption( AXPos, AYPos: Integer; AAllign: Integer;
ATextColor, ABackColor: Integer; AOptions: string; ADefault: Integer): Integer;
{const MENUFRAMECOLOR = 15;
MENUBACKCOLOR = 9;
MENUITEMCOLOR = 15;
MENUACTIVECOLOR= 12;}
const MENUFRAMECOLOR = 15;
MENUBACKCOLOR = 12;
MENUITEMCOLOR = 14;
MENUACTIVECOLOR = 15;
MENUSHADOWNCOLOR = 0;
var I: Integer;
StrLength: Integer;
MaxLength: Integer;
CurrentLength: Integer;
OldSettings: ViewPortType;
OldColor: Integer;
XPos: Integer;
YPos: Integer;
ShadowOffset: Integer;
MenuWidth,
MenuHeight,
FrameWidth: Integer;
ItemWidth: Integer;
ItemHeight: Integer;
ItemsOriginX: Integer;
ItemsOriginY: Integer;
ItemsCount: Integer;
ItemsHole: Integer;
BufferSize: Word;
Buffer: Pointer;
procedure DisplayOptions;
var I1, I2, I3: Integer;
S: string;
CrrentOriginY: Integer;
begin
SetColor( MENUFRAMECOLOR);
SetFillPattern( Solid, MENUSHADOWNCOLOR);
Bar( XPos + ShadowOffset, YPos + ShadowOffset, XPos + MenuWidth + ShadowOffset, YPos + MenuHeight + ShadowOffset);
{SetFillPattern( Solid, MENUBACKCOLOR);}
SetFillPattern( Solid, ABackColor);
Bar( XPos, YPos, XPos + MenuWidth, YPos + MenuHeight);
Rectangle( XPos, YPos, XPos + MenuWidth, YPos + MenuHeight);
Rectangle( XPos + 1, YPos + 1, XPos + MenuWidth - 1, YPos + MenuHeight - 1);
Rectangle( XPos + 3, YPos + 3, XPos + MenuWidth - 3, YPos + MenuHeight - 3);
{SetColor( MENUITEMCOLOR);}
SetColor(ATextColor);
I1 := 1;
I3 := 0;
S := '';
CrrentOriginY := ItemsOriginY;
repeat
if (( AOptions[I1] <> #0) and (I1 < StrLength))
then S := S + AOptions[I1]
else begin
OutTextXY( ItemsOriginX , CrrentOriginY , S);
CrrentOriginY := CrrentOriginY + ItemHeight + ItemsHole;
I3 := I3 + 1;
S := '';
end;
I1 := I1 + 1;
until ( I1 > StrLength);
I2 := I1;
end;
procedure DrawActiveFrame( AItemIndex: Integer; AActive: Boolean);
begin
if AActive
then SetColor(MENUACTIVECOLOR)
else SetColor(ABackColor);
Rectangle( ItemsOriginX - 3,
ItemsOriginY + (AItemIndex - 1) * (ItemHeight + ItemsHole) - 3,
ItemsOriginX + ItemWidth + 2,
ItemsOriginY + (AItemIndex - 1) * (ItemHeight + ItemsHole) + ItemHeight + 2);
Rectangle( ItemsOriginX - 5,
ItemsOriginY + (AItemIndex - 1) * (ItemHeight + ItemsHole) - 5,
ItemsOriginX + ItemWidth + 4,
ItemsOriginY + (AItemIndex - 1) * (ItemHeight + ItemsHole) + ItemHeight + 4);
end;
function Select: Integer;
var CurrentItem: Integer;
Key: Char;
begin
if ((ADefault > 0) and (ADefault <= ItemsCount))
then CurrentItem := ADefault
else CurrentItem := 1;
DrawActiveFrame(CurrentItem, True);
while True
do begin
Key := ReadKey;
case Key
of #0: begin
Key := ReadKey;
case Key
of #80: if (CurrentItem < ItemsCount)
then begin
DrawActiveFrame(CurrentItem, False);
CurrentItem := CurrentItem + 1;
DrawActiveFrame(CurrentItem, True);
end;
#72: if (CurrentItem > 1)
then begin
DrawActiveFrame(CurrentItem, False);
CurrentItem := CurrentItem - 1;
DrawActiveFrame(CurrentItem, True);
end;
end;
end;
#13: Break;
#27: begin
CurrentItem := 0;
Break;
end;
end;
end;
Select := CurrentItem;
end;
begin
StrLength := Length(AOptions);
if (StrLength > 0)
then begin
MaxLength := 0;
CurrentLength := 0;
I := 0;
ItemsCount := 0;
while (StrLength > I)
do begin
I := I + 1;
if ((AOptions[I] = #0) or (I = StrLength))
then begin
if (MaxLength < CurrentLength)
then MaxLength := CurrentLength;
CurrentLength := 0;
ItemsCount := ItemsCount + 1;
end
else CurrentLength := CurrentLength + 1;
end;
ShadowOffset := 4;
FrameWidth := 20;
ItemsHole := 8;
ItemWidth := TextWidth('W') * MaxLength;
ItemHeight := TextHeight('W');
MenuWidth := ItemWidth + FrameWidth * 2;
MenuHeight := (ItemHeight + ItemsHole) * ItemsCount - ItemsHole + FrameWidth * 2;
case AAllign
of 2: begin
XPos := AXPos - MenuWidth;
YPos := AYPos;
end;
3: begin
XPos := AXPos - MenuWidth;
YPos := AYPos - MenuHeight;
end;
4: begin
XPos := AXPos;
YPos := AYPos - MenuHeight;
end
else
XPos := AXPos;
YPos := AYPos;
end;
ItemsOriginX := XPos + FrameWidth;
ItemsOriginY := YPos + FrameWidth;
BufferSize := ImageSize( XPos, YPos, XPos + MenuWidth + ShadowOffset, YPos + MenuHeight + ShadowOffset);
OldColor := GetColor;
GetViewSettings(OldSettings);
SetViewPort(0, 0, GetMaxX, GetMaxY, True);
GetMem(Buffer,BufferSize);
GetImage( XPos, YPos, XPos + MenuWidth + ShadowOffset, YPos + MenuHeight + ShadowOffset, Buffer^);
DisplayOptions;
GetOption := Select;
PutImage( XPos, YPos, Buffer^, NormalPut);
FreeMem(Buffer, BufferSize);
SetViewPort(OldSettings.X1, OldSettings.Y1, OldSettings.X2, OldSettings.Y2, OldSettings.Clip);
SetColor(OldColor);
end
else GetOption := 0;
end;
function FileExists(AFName: string): Boolean;
var F: File;
begin
Assign(F, AFName);
{$I-}
Reset(F,1);
if IOResult = 0
then begin
Close(F);
FileExists := True;
end
else FileExists := False;
end;
procedure WarningBeep;
begin
Sound(200);
Delay(200);
NoSound;
end;
procedure ErrorBeep;
begin
Sound(500);
Delay(200);
NoSound;
end;
procedure OkBeep;
begin
Sound(2000);
Delay(30);
NoSound;
end;
end. |
unit CommentAndScrollTest;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "TestFormsTest"
// Модуль: "w:/common/components/gui/Garant/Daily/CommentAndScrollTest.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TCommentAndScrollTest
//
// Тест для добавления и удаления комментария и последующего скроллирования.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
{$If defined(nsTest) AND not defined(NoVCM)}
uses
nevTools,
TextEditorVisitor,
PrimTextLoad_Form
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
type
TCommentAndScrollTest = {abstract} class(TTextEditorVisitor)
{* Тест для добавления и удаления комментария и последующего скроллирования. }
protected
// realized methods
procedure DoVisit(aForm: TPrimTextLoadForm); override;
{* Обработать текст }
protected
// overridden protected methods
procedure CheckTopAnchor(const aView: InevInputView); override;
{* проверить якорь начала отрисовки после окончания прокрутки }
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function F1Like: Boolean; override;
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
protected
// protected methods
procedure MoveCursor4Insert(aForm: TPrimTextLoadForm); virtual;
{* Переместить курсор перед вставкой комментария. }
function GetUserComment(const aPoint: InevBasePoint): InevBasePoint; virtual;
{* Получить пользовательский комментарий }
procedure DoScroll(aForm: TPrimTextLoadForm); virtual;
{* Прокрутка текста в редакторе (если нужна). }
end;//TCommentAndScrollTest
{$IfEnd} //nsTest AND not NoVCM
implementation
{$If defined(nsTest) AND not defined(NoVCM)}
uses
evCursorTools,
evOp,
evTypes,
l3Base,
CommentPara_Const,
eeEditorExport,
TestFrameWork
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// start class TCommentAndScrollTest
procedure TCommentAndScrollTest.MoveCursor4Insert(aForm: TPrimTextLoadForm);
//#UC START# *4CA2F33F01E5_4C9CA365006C_var*
var
i : Integer;
//#UC END# *4CA2F33F01E5_4C9CA365006C_var*
begin
//#UC START# *4CA2F33F01E5_4C9CA365006C_impl*
for i := 0 to 5 do
aForm.Text.Selection.Cursor.Move(aForm.Text.View, ev_ocParaDown);
//#UC END# *4CA2F33F01E5_4C9CA365006C_impl*
end;//TCommentAndScrollTest.MoveCursor4Insert
function TCommentAndScrollTest.GetUserComment(const aPoint: InevBasePoint): InevBasePoint;
//#UC START# *4CA982110056_4C9CA365006C_var*
//#UC END# *4CA982110056_4C9CA365006C_var*
begin
//#UC START# *4CA982110056_4C9CA365006C_impl*
Result := aPoint;
while not Result.InheritsFrom(k2_idCommentPara) do
Result := Result.Inner;
//#UC END# *4CA982110056_4C9CA365006C_impl*
end;//TCommentAndScrollTest.GetUserComment
procedure TCommentAndScrollTest.DoScroll(aForm: TPrimTextLoadForm);
//#UC START# *4CA982800281_4C9CA365006C_var*
//#UC END# *4CA982800281_4C9CA365006C_var*
begin
//#UC START# *4CA982800281_4C9CA365006C_impl*
//#UC END# *4CA982800281_4C9CA365006C_impl*
end;//TCommentAndScrollTest.DoScroll
procedure TCommentAndScrollTest.DoVisit(aForm: TPrimTextLoadForm);
//#UC START# *4BE419AF0217_4C9CA365006C_var*
var
l_UserComment : InevBasePoint;
l_PID : Integer;
i : Integer;
//#UC END# *4BE419AF0217_4C9CA365006C_var*
begin
//#UC START# *4BE419AF0217_4C9CA365006C_impl*
aForm.Text.Select(ev_stDocument);
aForm.Text.Copy;
MoveCursor4Insert(aForm);
(aForm.Text as TeeEditorExport).InsertUserComment;
aForm.Text.Paste;
l3System.ClearClipboard;
l_UserComment := GetUserComment(aForm.Text.Selection.Cursor);
DoScroll(aForm);
l_PID := l_UserComment.Obj^.PID;
l_UserComment.Obj^.OwnerObj.SubRange(aForm.Text.View, l_PID + 1, l_PID + 1).Modify.Delete(aForm.Text.View);
ScrollByLine(aForm, 1, True, False);
CheckTopAnchor(aForm.Text.View);
//#UC END# *4BE419AF0217_4C9CA365006C_impl*
end;//TCommentAndScrollTest.DoVisit
procedure TCommentAndScrollTest.CheckTopAnchor(const aView: InevInputView);
//#UC START# *4C1F0A260192_4C9CA365006C_var*
//#UC END# *4C1F0A260192_4C9CA365006C_var*
begin
//#UC START# *4C1F0A260192_4C9CA365006C_impl*
CheckFalse(aView.TopAnchor.Inner.InheritsFrom(k2_idCommentPara), 'Комментарий мы уже удалили! А TopAnchor его еще держит!');
//#UC END# *4C1F0A260192_4C9CA365006C_impl*
end;//TCommentAndScrollTest.CheckTopAnchor
function TCommentAndScrollTest.GetFolder: AnsiString;
{-}
begin
Result := 'Everest';
end;//TCommentAndScrollTest.GetFolder
function TCommentAndScrollTest.F1Like: Boolean;
//#UC START# *4C9B31F6015E_4C9CA365006C_var*
//#UC END# *4C9B31F6015E_4C9CA365006C_var*
begin
//#UC START# *4C9B31F6015E_4C9CA365006C_impl*
Result := True;
//#UC END# *4C9B31F6015E_4C9CA365006C_impl*
end;//TCommentAndScrollTest.F1Like
function TCommentAndScrollTest.GetModelElementGUID: AnsiString;
{-}
begin
Result := '4C9CA365006C';
end;//TCommentAndScrollTest.GetModelElementGUID
{$IfEnd} //nsTest AND not NoVCM
end. |
unit INFOXDIARYTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TINFOXDIARYRecord = record
PCode: String[6];
PDescription: String[30];
PLeadTime: String[4];
End;
TINFOXDIARYBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TINFOXDIARYRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIINFOXDIARY = (INFOXDIARYPrimaryKey);
TINFOXDIARYTable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFLeadTime: TStringField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPLeadTime(const Value: String);
function GetPLeadTime:String;
procedure SetEnumIndex(Value: TEIINFOXDIARY);
function GetEnumIndex: TEIINFOXDIARY;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TINFOXDIARYRecord;
procedure StoreDataBuffer(ABuffer:TINFOXDIARYRecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFLeadTime: TStringField read FDFLeadTime;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PLeadTime: String read GetPLeadTime write SetPLeadTime;
published
property Active write SetActive;
property EnumIndex: TEIINFOXDIARY read GetEnumIndex write SetEnumIndex;
end; { TINFOXDIARYTable }
procedure Register;
implementation
procedure TINFOXDIARYTable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFLeadTime := CreateField( 'LeadTime' ) as TStringField;
end; { TINFOXDIARYTable.CreateFields }
procedure TINFOXDIARYTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TINFOXDIARYTable.SetActive }
procedure TINFOXDIARYTable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TINFOXDIARYTable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TINFOXDIARYTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TINFOXDIARYTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TINFOXDIARYTable.SetPLeadTime(const Value: String);
begin
DFLeadTime.Value := Value;
end;
function TINFOXDIARYTable.GetPLeadTime:String;
begin
result := DFLeadTime.Value;
end;
procedure TINFOXDIARYTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 6, N');
Add('Description, String, 30, N');
Add('LeadTime, String, 4, N');
end;
end;
procedure TINFOXDIARYTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TINFOXDIARYTable.SetEnumIndex(Value: TEIINFOXDIARY);
begin
case Value of
INFOXDIARYPrimaryKey : IndexName := '';
end;
end;
function TINFOXDIARYTable.GetDataBuffer:TINFOXDIARYRecord;
var buf: TINFOXDIARYRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PLeadTime := DFLeadTime.Value;
result := buf;
end;
procedure TINFOXDIARYTable.StoreDataBuffer(ABuffer:TINFOXDIARYRecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFLeadTime.Value := ABuffer.PLeadTime;
end;
function TINFOXDIARYTable.GetEnumIndex: TEIINFOXDIARY;
var iname : string;
begin
result := INFOXDIARYPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := INFOXDIARYPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TINFOXDIARYTable, TINFOXDIARYBuffer ] );
end; { Register }
function TINFOXDIARYBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..3] of string = ('CODE','DESCRIPTION','LEADTIME' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 3) and (flist[x] <> s) do inc(x);
if x <= 3 then result := x else result := 0;
end;
function TINFOXDIARYBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
end;
end;
function TINFOXDIARYBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PLeadTime;
end;
end;
end.
|
unit ResearchTask;
interface
uses
Tasks, Kernel, Accounts, CacheAgent, BackupInterfaces, Inventions, FacIds;
type
TMetaResearchTask =
class(TMetaTask)
private
fTechnology : string;
fInventionId : TInventionNumId;
fInvention : TInvention;
fStoreId : TFacId;
private
procedure SetTechnology(aTech : string);
public
property Technology : string read fTechnology write SetTechnology;
property InventionId : TInventionNumId read fInventionId;
property Invention : TInvention read fInvention;
property StoreId : integer read fStoreId write fStoreId;
end;
TResearchTask =
class(TAtomicTask)
public
class function GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; override;
function Execute : TTaskResult; override;
procedure StoreToCache(Prefix : string; Cache : TObjectCache); override;
end;
procedure RegisterBackup;
implementation
uses
TaskUtils, ResidentialTasks, ClassStorage;
// TMetaResearchTask
procedure TMetaResearchTask.SetTechnology(aTech : string);
begin
fTechnology := aTech;
if aTech <> ''
then
begin
fInvention := TInvention(TheClassStorage.ClassById[tidClassFamily_Inventions, aTech]);
if fInvention <> nil
then fInventionId := fInvention.NumId;
end;
end;
// TResearchTask
class function TResearchTask.GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer;
var
Company : TCompany;
begin
result := inherited GetPriority(MetaTask, SuperTask, Context);
if result <> tprIgnoreTask
then
begin
Company := TCompany(Context.getContext(tcIdx_Company));
if (Company <> nil) and Company.HasInvention[TMetaResearchTask(MetaTask).InventionId]
then result := tprAccomplished;
end
end;
function TResearchTask.Execute : TTaskResult;
var
Company : TCompany;
begin
Company := TCompany(Context.getContext(tcIdx_Company));
if (Company <> nil) and Company.HasInvention[TMetaResearchTask(MetaTask).InventionId]
then result := trFinished
else result := trContinue;
end;
procedure TResearchTask.StoreToCache(Prefix : string; Cache : TObjectCache);
begin
inherited;
Cache.WriteString (Prefix + 'ResearchId', TMetaResearchTask(MetaTask).Invention.Id);
Cache.WriteString (Prefix + 'ResearchName', TMetaResearchTask(MetaTask).Invention.Name); // >> MLS
Cache.WriteString (Prefix + 'PlaceName', TMetaResearchTask(MetaTask).Invention.Resp); // >> MLS
Cache.WriteString (Prefix + 'ParentName', TMetaResearchTask(MetaTask).Invention.Parent_MLS.Values['0']); // >> MLS
Cache.WriteInteger(Prefix + 'CommerceId', TMetaResearchTask(MetaTask).StoreId);
end;
procedure RegisterBackup;
begin
RegisterClass(TResearchTask);
end;
end.
|
unit uShape;
interface
uses
ObjFactory;
type
TShape = class(TBaseObject)
private
FName: string;
protected
procedure SetName(const aName: string);
public
constructor Create; override;
function ToString: string; override;
property Name: string read FName;
end;
TCircle = class(TShape)
public
constructor Create; override;
function ToString: string; override;
end;
TSquare = class(TShape)
public
constructor Create; override;
function ToString: string; override;
end;
TTriangle = class(TShape)
public
constructor Create; override;
function ToString: string; override;
end;
implementation
{ TShape }
constructor TShape.Create;
begin
FName := 'shape';
end;
procedure TShape.SetName(const aName: string);
begin
FName := aName;
end;
function TShape.ToString: string;
begin
Result := 'I am a shape.';
end;
{ TCircle }
constructor TCircle.Create;
begin
SetName('circle');
end;
function TCircle.ToString: string;
begin
Result := 'I am a circle.';
end;
{ TSquare }
constructor TSquare.Create;
begin
SetName('square');
end;
function TSquare.ToString: string;
begin
Result := 'I am a square.';
end;
{ TTriangle }
constructor TTriangle.Create;
begin
SetName('triangle');
end;
function TTriangle.ToString: string;
begin
Result := 'I am a triangle.';
end;
initialization
ObjectFactory.RegisterClass('circle', TCircle);
ObjectFactory.RegisterClass('square', TSquare);
ObjectFactory.RegisterClass('triangle', TTriangle);
end.
|
unit UGCalendarDemo;
interface
uses
FMX.Forms, FMX.TMSCloudBase, FMX.TMSCloudGCalendar, FMX.Controls,
FMX.Memo, FMX.StdCtrls, FMX.ListBox, FMX.Edit, FMX.Grid, FMX.Layouts, FMX.Dialogs, DateUtils,
FMX.TMSCloudListView, FMX.ExtCtrls, FMX.Objects, System.Classes, FMX.Types, UITypes, SysUtils,
FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomGoogle, FMX.TMSCloudGoogleFMX,
FMX.TMSCloudCustomGCalendar;
type
TForm1 = class(TForm)
StyleBook1: TStyleBook;
TMSFMXCloudGCalendar1: TTMSFMXCloudGCalendar;
Panel1: TPanel;
Button1: TButton;
GroupBox1: TGroupBox;
ComboBox1: TComboBox;
dpCalStartDate: TCalendarEdit;
dpCalEndDate: TCalendarEdit;
btUpdate: TButton;
Label1: TLabel;
Label13: TLabel;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label11: TLabel;
Label10: TLabel;
Edit3: TEdit;
Edit5: TEdit;
StartDate: TCalendarEdit;
EndDate: TCalendarEdit;
StartTime: TCalendarEdit;
EndTime: TCalendarEdit;
cbVisibility: TComboBox;
cbAllday: TCheckBox;
CloudListView1: TTMSFMXCloudListView;
Panel2: TPanel;
Button6: TButton;
Button7: TButton;
Button5: TButton;
GroupBox4: TGroupBox;
lvAtt: TTMSFMXCloudListView;
Label3: TLabel;
Label12: TLabel;
EditAttEmail: TEdit;
EditAttName: TEdit;
btInvite: TButton;
Image1: TImage;
btRemove: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure FillCalendars();
procedure FillCalendarItems();
procedure FillCalendarItemDetails();
procedure ToggleControls();
procedure ClearControls();
procedure Init();
procedure SetCalendarItem(Item: TGCalendarItem);
procedure ComboBox1Change(Sender: TObject);
procedure TMSFMXCloudGCalendar1ReceivedAccessToken(Sender: TObject);
procedure btInviteClick(Sender: TObject);
procedure ListAttendees(Item: TGCalendarItem);
procedure FormCreate(Sender: TObject);
procedure btUpdateClick(Sender: TObject);
procedure cbAlldayClick(Sender: TObject);
procedure ComboBox1Click(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
procedure CloudListView1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Connected: boolean;
Inserting: boolean;
end;
var
Form1: TForm1;
implementation
{$R *.FMX}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// GAppkey = 'xxxxxxxxx';
// GAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm1.TMSFMXCloudGCalendar1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudGCalendar1.SaveTokens;
Init;
end;
procedure TForm1.btInviteClick(Sender: TObject);
var
li: TGCalendarItem;
att: TGAttendee;
begin
if (CloudListView1.ItemIndex >= 0) then
begin
li := CloudListView1.Items[CloudListView1.ItemIndex].Data;
att := li.Attendees.Add;
att.Summary := EditAttName.Text;
att.Email := EditAttEmail.Text;
ListAttendees(li);
EditAttEmail.Text := '';
EditAttName.Text := '';
end;
end;
procedure TForm1.btRemoveClick(Sender: TObject);
begin
TMSFMXCloudGCalendar1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm1.btUpdateClick(Sender: TObject);
begin
FillCalendarItems;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TMSFMXCloudGCalendar1.Logging := true;
TMSFMXCloudGCalendar1.App.Key := GAppkey;
TMSFMXCloudGCalendar1.App.Secret := GAppSecret;
TMSFMXCloudGCalendar1.Logging := true;
if not TMSFMXCloudGCalendar1.TestTokens then
TMSFMXCloudGCalendar1.RefreshAccess;
if not TMSFMXCloudGCalendar1.TestTokens then
TMSFMXCloudGCalendar1.DoAuth
else
Init;
end;
procedure TForm1.Button5Click(Sender: TObject);
var
li: TGCalendarItem;
begin
if not (Inserting) then
begin
ClearControls;
Edit3.SetFocus;
CloudListView1.ItemIndex := -1;
Button5.Text := 'Insert';
Inserting := true;
end
else
begin
Button5.Text := 'New';
li := TMSFMXCloudGCalendar1.Items.Add;
SetCalendarItem(li);
li.CalendarID := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TGCalendar).ID;
TMSFMXCloudGCalendar1.Add(li);
FillCalendarItems;
Inserting := false;
end;
end;
procedure TForm1.Button6Click(Sender: TObject);
var
buttonSelected: integer;
begin
if CloudListView1.ItemIndex >= 0 then
begin
buttonSelected := MessageDlg('Are you sure you want to delete the selected Event?', TMsgDlgType.mtConfirmation, mbOKCancel, 0);
if buttonSelected = mrOk then
begin
TMSFMXCloudGCalendar1.Delete(CloudListView1.Items[CloudListView1.ItemIndex].Data);
FillCalendarItems;
ClearControls;
end;
end
else
begin
ShowMessage('Please select an Event first.');
end;
end;
procedure TForm1.Button7Click(Sender: TObject);
var
li: TGCalendarItem;
SelectedID: string;
begin
if CloudListView1.ItemIndex >= 0 then
begin
li := CloudListView1.Items[CloudListView1.ItemIndex].Data;
SetCalendarItem(li);
TMSFMXCloudGCalendar1.Update(li);
SelectedID := li.ID;
FillCalendarItems;
CloudListView1.ItemIndex := TMSFMXCloudGCalendar1.Items.Find(SelectedID).Index;
end
else
begin
ShowMessage('Please select an Event first.');
end;
end;
procedure TForm1.cbAlldayClick(Sender: TObject);
begin
StartTime.Enabled := not cbAllday.IsChecked;
EndTime.Enabled := not cbAllday.IsChecked;
end;
procedure TForm1.ClearControls;
begin
Edit3.Text := '';
Edit5.Text := '';
Memo1.Lines.Text := '';
cbVisibility.ItemIndex := 0;
cbAllday.IsChecked := false;
StartDate.Date := Now;
EndDate.Date := Now;
StartTime.Date := StrToDateTime(IntToStr(HourOf(IncHour(Time, 1))) + ':00');
EndTime.Date := IncHour(StartTime.Date, 2);
lvAtt.Items.Clear;
EditAttName.Text := '';
EditAttEmail.Text := '';
end;
procedure TForm1.CloudListView1Change(Sender: TObject);
begin
FillCalendarItemDetails;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
FillCalendarItems;
end;
procedure TForm1.ComboBox1Click(Sender: TObject);
begin
FillCalendarItems;
end;
procedure TForm1.FillCalendarItems;
var
I: Integer;
gcal: TGCalendar;
li: TListItem;
begin
if ComboBox1.ItemIndex >= 0 then
begin
gcal := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TGCalendar);
TMSFMXCloudGCalendar1.GetCalendar(gcal.ID, dpCalStartDate.Date, dpCalEndDate.Date);
CloudListView1.Items.Clear;
for I := 0 to TMSFMXCloudGCalendar1.Items.Count - 1 do
begin
li := CloudListView1.Items.Add;
li.Text := FormatDateTime('dd/mm/yyyy hh:nn', TMSFMXCloudGCalendar1.Items[I].StartTime);
li.SubItems.Add(FormatDateTime('dd/mm/yyyy hh:nn', TMSFMXCloudGCalendar1.Items[I].EndTime));
li.SubItems.Add(TMSFMXCloudGCalendar1.Items[I].Summary);
li.SubItems.Add(TMSFMXCloudGCalendar1.Items[I].Description);
li.Data := TMSFMXCloudGCalendar1.Items[I];
end;
end;
end;
procedure TForm1.FillCalendars;
var
I: Integer;
begin
TMSFMXCloudGCalendar1.GetCalendars();
ComboBox1.Items.Clear;
for I := 0 to TMSFMXCloudGCalendar1.Calendars.Count - 1 do
begin
ComboBox1.items.AddObject(TMSFMXCloudGCalendar1.Calendars[I].Summary, TMSFMXCloudGCalendar1.Calendars[I]);
end;
ComboBox1.ItemIndex := 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
TMSFMXCloudGCalendar1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'google.ini';
TMSFMXCloudGCalendar1.PersistTokens.Section := 'tokens';
TMSFMXCloudGCalendar1.LoadTokens;
dpCalStartDate.Date := IncMonth(Now, -1);
dpCalEndDate.Date := IncMonth(Now, 2);
ClearControls;
Inserting := false;
Connected := false;
ToggleControls;
CloudListView1.ColumnByIndex(3).Width := 380;
end;
procedure TForm1.Init;
begin
Connected := true;
FillCalendars;
FillCalendarItems;
ToggleControls;
end;
procedure TForm1.FillCalendarItemDetails();
var
li: TGCalendarItem;
begin
if CloudListView1.ItemIndex >= 0 then
begin
li := CloudListView1.Items[CloudListView1.ItemIndex].Data;
Edit3.Text := li.Summary;
Memo1.Lines.Text := li.Description;
Edit5.Text := li.Location;
StartDate.Date := li.StartTime;
EndDate.Date := li.EndTime;
StartTime.Date := li.StartTime;
EndTime.Date := li.EndTime;
EditAttEmail.Text := '';
EditAttName.Text := '';
cbVisibility.ItemIndex := Ord(li.Visibility);
cbAllday.IsChecked := li.IsAllDay;
ListAttendees(li);
end;
end;
procedure TForm1.ListAttendees(Item: TGCalendarItem);
var
att: string;
I: Integer;
li: TListItem;
begin
att := '';
lvAtt.Items.Clear;
for I := 0 to Item.Attendees.Count - 1 do
begin
case Item.Attendees[I].Status of
rsNeedsAction: att := 'needs action';
rsDeclined: att := 'declined';
rsTentative: att := 'tentative';
rsAccepted: att := 'accpeted';
end;
li := lvAtt.Items.Add;
li.Text := att;
li.SubItems.Add(Item.Attendees[I].Summary);
li.SubItems.Add(Item.Attendees[I].Email);
end;
end;
procedure TForm1.SetCalendarItem(Item: TGCalendarItem);
begin
Item.Summary := Edit3.Text;
Item.Description := Memo1.Lines.Text;
Item.Location := Edit5.Text;
if cbAllday.IsChecked then
begin
Item.StartTime := EncodeDateTime(YearOf(StartDate.Date), MonthOf(StartDate.Date), DayOf(StartDate.Date), 0, 0, 0, 0);
Item.EndTime := EncodeDateTime(YearOf(EndDate.Date), MonthOf(EndDate.Date), DayOf(EndDate.Date), 0, 0, 0, 0);
Item.IsAllDay := true;
end
else
begin
Item.StartTime := EncodeDateTime(YearOf(StartDate.Date), MonthOf(StartDate.Date), DayOf(StartDate.Date), HourOf(StartTime.Date), MinuteOf(StartTime.Date), SecondOf(StartTime.Date),0);
Item.EndTime := EncodeDateTime(YearOf(EndDate.Date), MonthOf(EndDate.Date), DayOf(EndDate.Date), HourOf(EndTime.Date), MinuteOf(EndTime.Date), SecondOf(EndTime.Date),0);
Item.IsAllDay := false;
end;
Item.Visibility := TVisibility(cbVisibility.ItemIndex);
end;
procedure TForm1.ToggleControls;
begin
GroupBox1.Enabled := Connected;
GroupBox2.Enabled := Connected;
GroupBox3.Enabled := Connected;
GroupBox4.Enabled := Connected;
Panel2.Enabled := Connected;
ComboBox1.Enabled := Connected;
dpCalStartDate.Enabled := Connected;
dpCalEndDate.Enabled := Connected;
btUpdate.Enabled := Connected;
CloudListView1.Enabled := Connected;
Edit3.Enabled := Connected;
Edit5.Enabled := Connected;
Memo1.Enabled := Connected;
cbVisibility.Enabled := Connected;
cbAllday.Enabled := Connected;
StartDate.Enabled := Connected;
EndDate.Enabled := Connected;
StartTime.Enabled := Connected;
EndTime.Enabled := Connected;
lvAtt.Enabled := Connected;
EditAttName.Enabled := Connected;
EditAttEmail.Enabled := Connected;
btInvite.Enabled := Connected;
Button5.Enabled := Connected;
Button6.Enabled := Connected;
Button7.Enabled := Connected;
btRemove.Enabled := Connected;
Button1.Enabled := not Connected;
end;
end.
|
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Object: How to use TSmtpCli component
Creation: 09 october 1997
Version: 2.08
EMail: http://www.overbyte.be francois.piette@overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1997-2006 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
Updates:
Oct 26, 1997 V1.00 Released
Jan 10, 1998 V1.01 Added a Port property
Feb 15, 1998 V1.02 Added file attachement support
Mar 06, 1998 V1.03 Check for DisplayMemo overflow (100 lines allowed)
Aug 03, 1998 V2.00 Revised for new asynchronous SMTP component version
Jul 26, 2001 V2.01 Added authentification
Sep 07, 2002 V2.02 Added Cc and Bcc fields.
Added AllInOne demo to show how to "chain" several operations
using OnRequest done, avoiding any wait loop. This is how event
driven operation has to be done.
Sep 15, 2002 V2.02 Corrected typo error in BuildRcptList where CcEdi was used
where ToEdit should.
Thanks to konstantinos.Kokkorogiannis@diala.greenpeace.org
Apr 08, 2003 V2.03 Arno Garrels <arno.garrels@gmx.de> made some useful
changes:
Search for 04/06/2003 Property AuthComboBox.ItemIndex removed
from dfm, caused error message with older Delphi versions.
AuthComboBox.Items "smtpAuthAutoSelect" added.
Apr 19, 2003 V2.04 Replaced BuildRcptList by the new RcptNameAdd component
method.
May 05, 2003 V2.06 Changed the way data is saved to INI file to allow bigger
messages.
Aug 23, 2004 V2.07 Removed unused units
Mar 12, 2005 V2.08 Added CinfirmCheckbox
Mar 19, 2006 V6.00 Demo ported from ICS-V5 to ICS-V6
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsMailSnd1;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, StdCtrls, ExtCtrls, Forms,
IniFiles, OverbyteIcsWndControl, OverbyteIcsSmtpProt;
const
SmtpTestVersion = 2.08;
CopyRight : String = ' MailSnd (c) 1997-2006 F. Piette V2.08 ';
type
TSmtpTestForm = class(TForm)
MsgMemo: TMemo;
DisplayMemo: TMemo;
ToolsPanel: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Subject: TLabel;
Label4: TLabel;
Label5: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
HostEdit: TEdit;
FromEdit: TEdit;
ToEdit: TEdit;
SubjectEdit: TEdit;
SignOnEdit: TEdit;
PortEdit: TEdit;
ClearDisplayButton: TButton;
ConnectButton: TButton;
HeloButton: TButton;
MailFromButton: TButton;
RcptToButton: TButton;
DataButton: TButton;
AbortButton: TButton;
QuitButton: TButton;
MailButton: TButton;
OpenButton: TButton;
UsernameEdit: TEdit;
PasswordEdit: TEdit;
AuthComboBox: TComboBox;
EhloButton: TButton;
AuthButton: TButton;
CcEdit: TEdit;
BccEdit: TEdit;
AllInOneButton: TButton;
PriorityComboBox: TComboBox;
ConfirmCheckBox: TCheckBox;
AttachPanel: TPanel;
Label6: TLabel;
FileAttachMemo: TMemo;
InfoPanel: TPanel;
Label7: TLabel;
SmtpClient: TSmtpCli;
procedure FormCreate(Sender: TObject);
procedure ClearDisplayButtonClick(Sender: TObject);
procedure ConnectButtonClick(Sender: TObject);
procedure SmtpClientRequestDone(Sender: TObject; RqType: TSmtpRequest;
Error: Word);
procedure HeloButtonClick(Sender: TObject);
procedure MailFromButtonClick(Sender: TObject);
procedure RcptToButtonClick(Sender: TObject);
procedure DataButtonClick(Sender: TObject);
procedure AbortButtonClick(Sender: TObject);
procedure QuitButtonClick(Sender: TObject);
procedure MailButtonClick(Sender: TObject);
procedure OpenButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EhloButtonClick(Sender: TObject);
procedure AuthButtonClick(Sender: TObject);
procedure AllInOneButtonClick(Sender: TObject);
procedure SmtpClientDisplay(Sender: TObject; Msg: String);
procedure SmtpClientGetData(Sender: TObject; LineNum: Integer;
MsgLine: Pointer; MaxLen: Integer; var More: Boolean);
procedure SmtpClientHeaderLine(Sender: TObject; Msg: Pointer;
Size: Integer);
private
FIniFileName : String;
FInitialized : Boolean;
FAllInOneFlag : Boolean;
procedure Display(const Msg : String);
procedure ExceptionHandler(Sender: TObject; E: Exception);
end;
var
SmtpTestForm: TSmtpTestForm;
implementation
{$R *.dfm}
const
SectionData = 'Data';
KeyHost = 'HostName';
KeyPort = 'Port';
KeyFrom = 'From';
KeyTo = 'To';
KeyCc = 'Cc';
KeyBcc = 'Bcc';
KeySubject = 'Subject';
KeySignOn = 'SignOn';
KeyUser = 'UserName';
KeyPass = 'Password';
KeyAuth = 'Authentification';
KeyPriority = 'Priority';
KeyConfirm = 'Confirm';
SectionWindow = 'Window';
KeyTop = 'Top';
KeyLeft = 'Left';
KeyWidth = 'Width';
KeyHeight = 'Height';
SectionFileAttach = 'Files';
KeyFileAttach = 'File';
SectionMsgMemo = 'Message';
KeyMsgMemo = 'Msg';
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure SaveStringsToIniFile(
const IniFileName : String;
const IniSection : String;
const IniKey : String;
Strings : TStrings);
var
IniFile : TIniFile;
nItem : Integer;
begin
if (IniFileName = '') or (IniSection = '') or (IniKey = '') or
(not Assigned(Strings)) then
Exit;
IniFile := TIniFile.Create(IniFileName);
IniFile.EraseSection(IniSection);
if Strings.Count <= 0 then
IniFile.WriteString(IniSection, IniKey + 'EmptyFlag', 'Empty')
else
for nItem := 0 to Strings.Count - 1 do
IniFile.WriteString(IniSection,
IniKey + IntToStr(nItem),
Strings.Strings[nItem]);
IniFile.Free;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Return FALSE if non existant in IniFile }
function LoadStringsFromIniFile(
const IniFileName : String;
const IniSection : String;
const IniKey : String;
Strings : TStrings) : Boolean;
var
IniFile : TIniFile;
nItem : Integer;
I : Integer;
Buf : String;
begin
Result := TRUE;
if (IniFileName = '') or (IniSection = '') or (IniKey = '') or
(not Assigned(Strings)) then
Exit;
Strings.Clear;
IniFile := TIniFile.Create(IniFileName);
try
if IniFile.ReadString(IniSection, IniKey + 'EmptyFlag', '') <> '' then
Exit;
IniFile.ReadSectionValues(IniSection, Strings);
finally
IniFile.Free;
end;
nItem := Strings.Count - 1;
while nItem >= 0 do begin
Buf := Strings.Strings[nItem];
if CompareText(IniKey, Copy(Buf, 1, Length(IniKey))) <> 0 then
Strings.Delete(nItem)
else begin
if not (Buf[Length(IniKey) + 1] in ['0'..'9']) then
Strings.Delete(nItem)
else begin
I := Pos('=', Buf);
Strings.Strings[nItem] := Copy(Buf, I + 1, Length(Buf));
end;
end;
Dec(nItem);
end;
Result := (Strings.Count <> 0);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Display a message in display memo box, making sure we don't overflow it. }
procedure TSmtpTestForm.Display(const Msg : String);
begin
DisplayMemo.Lines.BeginUpdate;
try
if DisplayMemo.Lines.Count > 200 then begin
{ We preserve only 200 lines }
while DisplayMemo.Lines.Count > 200 do
DisplayMemo.Lines.Delete(0);
end;
DisplayMemo.Lines.Add(Msg);
finally
DisplayMemo.Lines.EndUpdate;
{ Makes last line visible }
{$IFNDEF VER80}
SendMessage(DisplayMemo.Handle, EM_SCROLLCARET, 0, 0);
{$ENDIF}
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.FormCreate(Sender: TObject);
begin
Application.OnException := ExceptionHandler;
DisplayMemo.Clear;
FIniFileName := LowerCase(ExtractFileName(Application.ExeName));
FIniFileName := Copy(FIniFileName, 1, Length(FIniFileName) - 3) + 'ini';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.FormShow(Sender: TObject);
var
IniFile : TIniFile;
begin
if not FInitialized then begin
FInitialized := TRUE;
IniFile := TIniFile.Create(FIniFileName);
HostEdit.Text := IniFile.ReadString(SectionData, KeyHost,
'localhost');
PortEdit.Text := IniFile.ReadString(SectionData, KeyPort,
'smtp');
FromEdit.Text := IniFile.ReadString(SectionData, KeyFrom,
'first.last@company.com');
ToEdit.Text := IniFile.ReadString(SectionData, KeyTo,
'john.doe@acme;tartempion@brol.fr');
CcEdit.Text := IniFile.ReadString(SectionData, KeyCc,
'');
BccEdit.Text := IniFile.ReadString(SectionData, KeyBcc,
'francois.piette@swing.be');
SubjectEdit.Text := IniFile.ReadString(SectionData, KeySubject,
'This is the message subject');
SignOnEdit.Text := IniFile.ReadString(SectionData, KeySignOn,
'your name');
UsernameEdit.Text := IniFile.ReadString(SectionData, KeyUser,
'account name');
PasswordEdit.Text := IniFile.ReadString(SectionData, KeyPass,
'account password');
AuthComboBox.ItemIndex := IniFile.ReadInteger(SectionData, KeyAuth, 0);
PriorityComboBox.ItemIndex := IniFile.ReadInteger(SectionData, KeyPriority, 2);
ConfirmCheckBox.Checked := Boolean(IniFile.ReadInteger(SectionData, KeyConfirm, 0));
if not LoadStringsFromIniFile(FIniFileName, SectionFileAttach,
KeyFileAttach, FileAttachMemo.Lines) then
FileAttachMemo.Text := 'ics_logo.gif' + #13#10 + 'fp_small.gif';
if not LoadStringsFromIniFile(FIniFileName, SectionMsgMemo,
KeyMsgMemo, MsgMemo.Lines) then
MsgMemo.Text :=
'This is the first line' + #13#10 +
'Then the second one' + #13#10 +
'The next one is empty' + #13#10 +
'' + #13#10 +
'The next one has only a single dot' + #13#10 +
'.' + #13#10 +
'Finally the last one' + #13#10;
Top := IniFile.ReadInteger(SectionWindow, KeyTop, (Screen.Height - Height) div 2);
Left := IniFile.ReadInteger(SectionWindow, KeyLeft, (Screen.Width - Width) div 2);
Width := IniFile.ReadInteger(SectionWindow, KeyWidth, Width);
Height := IniFile.ReadInteger(SectionWindow, KeyHeight, Height);
IniFile.Free;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.FormClose(Sender: TObject;
var Action: TCloseAction);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(FIniFileName);
IniFile.WriteString(SectionData, KeyHost, HostEdit.Text);
IniFile.WriteString(SectionData, KeyPort, PortEdit.Text);
IniFile.WriteString(SectionData, KeyFrom, FromEdit.Text);
IniFile.WriteString(SectionData, KeyTo, ToEdit.Text);
IniFile.WriteString(SectionData, KeyCc, CcEdit.Text);
IniFile.WriteString(SectionData, KeyBcc, BccEdit.Text);
IniFile.WriteString(SectionData, KeySubject, SubjectEdit.Text);
IniFile.WriteString(SectionData, KeySignOn, SignOnEdit.Text);
IniFile.WriteString(SectionData, KeyUser, UsernameEdit.Text);
IniFile.WriteString(SectionData, KeyPass, PasswordEdit.Text);
IniFile.WriteInteger(SectionData, KeyAuth, AuthComboBox.ItemIndex);
IniFile.WriteInteger(SectionData, KeyPriority, PriorityComboBox.ItemIndex);
IniFile.WriteInteger(SectionData, KeyConfirm, Ord(ConfirmCheckBox.Checked));
SaveStringsToIniFile(FIniFileName, SectionFileAttach,
KeyFileAttach, FileAttachMemo.Lines);
SaveStringsToIniFile(FIniFileName, SectionMsgMemo,
KeyMsgMemo, MsgMemo.Lines);
IniFile.WriteInteger(SectionWindow, KeyTop, Top);
IniFile.WriteInteger(SectionWindow, KeyLeft, Left);
IniFile.WriteInteger(SectionWindow, KeyWidth, Width);
IniFile.WriteInteger(SectionWindow, KeyHeight, Height);
IniFile.Free;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF VER80}
function TrimRight(Str : String) : String;
var
i : Integer;
begin
i := Length(Str);
while (i > 0) and (Str[i] = ' ') do
i := i - 1;
Result := Copy(Str, 1, i);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TrimLeft(Str : String) : String;
var
i : Integer;
begin
if Str[1] <> ' ' then
Result := Str
else begin
i := 1;
while (i <= Length(Str)) and (Str[i] = ' ') do
i := i + 1;
Result := Copy(Str, i, Length(Str) - i + 1);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function Trim(Str : String) : String;
begin
Result := TrimLeft(TrimRight(Str));
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.SmtpClientDisplay(Sender: TObject; Msg: String);
begin
Display(Msg);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.SmtpClientGetData(
Sender : TObject;
LineNum : Integer;
MsgLine : Pointer;
MaxLen : Integer;
var More: Boolean);
var
Len : Integer;
begin
if LineNum > MsgMemo.Lines.count then
More := FALSE
else begin
Len := Length(MsgMemo.Lines[LineNum - 1]);
{ Truncate the line if too long (should wrap to next line) }
if Len >= MaxLen then
StrPCopy(MsgLine, Copy(MsgMemo.Lines[LineNum - 1], 1, MaxLen - 1))
else
StrPCopy(MsgLine, MsgMemo.Lines[LineNum - 1]);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.SmtpClientHeaderLine(
Sender : TObject;
Msg : Pointer;
Size : Integer);
begin
{ This demonstrate how to add a line to the message header }
{ Just detect one of the header lines and add text at the end of this }
{ line. Use #13#10 to form a new line }
{ Here we check for the From: header line and add a Comments: line }
if StrLIComp(Msg, 'From:', 5) = 0 then
StrCat(Msg, #13#10 + 'Comments: This is a test');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.ClearDisplayButtonClick(Sender: TObject);
begin
DisplayMemo.Clear;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.ExceptionHandler(Sender: TObject; E: Exception);
begin
Application.ShowException(E);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Connect to the mail server }
procedure TSmtpTestForm.ConnectButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.Host := HostEdit.Text;
SmtpClient.Port := PortEdit.Text;
SmtpClient.HdrPriority := TSmtpPriority(PriorityComboBox.ItemIndex);
SmtpClient.Connect;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Send HELO command with our local identification }
procedure TSmtpTestForm.HeloButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.SignOn := SignOnEdit.Text;
SmtpClient.Helo;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.EhloButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.SignOn := SignOnEdit.Text;
SmtpClient.EHlo;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.AuthButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.Username := UsernameEdit.Text;
SmtpClient.Password := PasswordEdit.Text;
SmtpClient.AuthType := TSmtpAuthType(AuthComboBox.ItemIndex);
SmtpClient.Auth;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ If smtpAuthNone is seleted then Open combines methods Connect and Helo. }
{ If any other authentication type is selected then Open combines methods }
{ Connect, Ehlo and Auth. }
procedure TSmtpTestForm.OpenButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.Host := HostEdit.Text;
SmtpClient.Port := PortEdit.Text;
SmtpClient.SignOn := SignOnEdit.Text;
SmtpClient.Username := UsernameEdit.Text;
SmtpClient.Password := PasswordEdit.Text;
SmtpClient.AuthType := TSmtpAuthType(AuthComboBox.ItemIndex);
SmtpClient.HdrPriority := TSmtpPriority(PriorityComboBox.ItemIndex);
SmtpClient.Open;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Send originator }
procedure TSmtpTestForm.MailFromButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.FromName := FromEdit.Text;
SmtpClient.MailFrom;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Send recipients }
procedure TSmtpTestForm.RcptToButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.RcptName.Clear;
SmtpClient.RcptNameAdd(ToEdit.Text, CcEdit.Text, BccEdit.text);
SmtpClient.RcptTo;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Send text and attached files to mail server }
procedure TSmtpTestForm.DataButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.RcptName.Clear;
SmtpClient.RcptNameAdd(ToEdit.Text, CcEdit.Text, BccEdit.text);
SmtpClient.HdrFrom := FromEdit.Text;
SmtpClient.HdrTo := ToEdit.Text;
SmtpClient.HdrCc := CcEdit.Text;
SmtpClient.HdrSubject := SubjectEdit.Text;
SmtpClient.EmailFiles := FileAttachMemo.Lines;
SmtpClient.ConfirmReceipt := ConfirmCheckBox.Checked;
SmtpClient.Data;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ MailFrom, RcptTo and Data methods combined }
procedure TSmtpTestForm.MailButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.RcptName.Clear;
SmtpClient.RcptNameAdd(ToEdit.Text, CcEdit.Text, BccEdit.text);
SmtpClient.HdrFrom := FromEdit.Text;
SmtpClient.HdrTo := ToEdit.Text;
SmtpClient.HdrCc := CcEdit.Text;
SmtpClient.HdrSubject := SubjectEdit.Text;
SmtpClient.SignOn := SignOnEdit.Text;
SmtpClient.FromName := FromEdit.Text;
SmtpClient.EmailFiles := FileAttachMemo.Lines;
SmtpClient.Host := HostEdit.Text;
SmtpClient.Port := PortEdit.Text;
SmtpClient.Mail;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.QuitButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.Quit;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.AbortButtonClick(Sender: TObject);
begin
FAllInOneFlag := FALSE;
SmtpClient.Abort;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.SmtpClientRequestDone(
Sender : TObject;
RqType : TSmtpRequest;
Error : Word);
begin
{ For every operation, we display the status }
if (Error > 0) and (Error < 10000) then
Display('RequestDone Rq=' + IntToStr(Ord(RqType)) +
' Error='+ SmtpClient.ErrorMessage)
else
Display('RequestDone Rq=' + IntToStr(Ord(RqType)) +
' Error='+ IntToStr(Error));
{ Check if the user has asked for "All-In-One" demo }
if not FAllInOneFlag then
Exit; { No, nothing more to do here }
{ We are in "All-In-One" demo, start next operation }
{ But first check if previous one was OK }
if Error <> 0 then begin
FAllInOneFlag := FALSE; { Terminate All-In-One demo }
Display('Error, stoped All-In-One demo');
Exit;
end;
case RqType of
smtpConnect: begin
if SmtpClient.AuthType = smtpAuthNone then
SmtpClient.Helo
else
SmtpClient.Ehlo;
end;
smtpHelo: SmtpClient.MailFrom;
smtpEhlo: SmtpClient.Auth;
smtpAuth: SmtpClient.MailFrom;
smtpMailFrom: SmtpClient.RcptTo;
smtpRcptTo: SmtpClient.Data;
smtpData: SmtpClient.Quit;
smtpQuit: Display('All-In-One done !');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSmtpTestForm.AllInOneButtonClick(Sender: TObject);
begin
if SmtpClient.Connected then begin
MessageBeep(MB_OK);
Display('All-In-One demo start in non connected state.');
Display('Please quit or abort the connection first.');
Exit;
end;
FAllInOneFlag := TRUE;
{ Initialize all SMTP component properties from our GUI }
SmtpClient.Host := HostEdit.Text;
SmtpClient.Port := PortEdit.Text;
SmtpClient.SignOn := SignOnEdit.Text;
SmtpClient.FromName := FromEdit.Text;
SmtpClient.HdrFrom := FromEdit.Text;
SmtpClient.HdrTo := ToEdit.Text;
SmtpClient.HdrCc := CcEdit.Text;
SmtpClient.HdrSubject := SubjectEdit.Text; { + #13#10#9 + ' Testing continuation line !'};
SmtpClient.EmailFiles := FileAttachMemo.Lines;
SmtpClient.AuthType := TSmtpAuthType(AuthComboBox.ItemIndex);
SmtpClient.Username := UsernameEdit.Text;
SmtpClient.Password := PasswordEdit.Text;
SmtpClient.HdrPriority := TSmtpPriority(PriorityComboBox.ItemIndex);
SmtpClient.ConfirmReceipt := ConfirmCheckBox.Checked;
{ Recipient list is computed from To, Cc and Bcc fields }
SmtpClient.RcptName.Clear;
SmtpClient.RcptNameAdd(ToEdit.Text, CcEdit.Text, BccEdit.text);
Display('Connecting to SMTP server...');
{ Start first operation to do to send an email }
{ Next operations are started from OnRequestDone event }
SmtpClient.Connect
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit DelphiUp.View.Components.Button005;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts,
DelphiUp.View.Components.Buttons.Interfaces,
DelphiUp.View.Components.Buttons.Attributes, DelphiUp.View.Services.Routers,
DelphiUp.View.Services.Utils, FMX.Effects, FMX.Filter.Effects;
type
TComponentButton005 = class(TForm)
Layout1: TLayout;
Layout2: TLayout;
Layout3: TLayout;
Label1: TLabel;
Label2: TLabel;
Rectangle1: TRectangle;
Image1: TImage;
FillRGBEffect1: TFillRGBEffect;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FAttributes : iComponentButtonAttributes<TComponentButton005>;
public
{ Public declarations }
function Component : TFMXObject;
function Attributes : iComponentButtonAttributes<TComponentButton005>;
end;
var
ComponentButton005: TComponentButton005;
implementation
{$R *.fmx}
{ TComponentButton005 }
function TComponentButton005.Attributes: iComponentButtonAttributes<TComponentButton005>;
begin
Result := FAttributes;
end;
function TComponentButton005.Component: TFMXObject;
begin
Result := Layout1;
Label1.Text := FAttributes.Title;
Label1.FontColor := FAttributes.FontColor;
Label1.TextSettings.Font.Size := FAttributes.FontSize;
Label2.Text := FAttributes.SubTitle;
Label2.FontColor := FAttributes.FontColor;
Label2.TextSettings.Font.Size := FAttributes.FontSizeSubTitle;
TServiceUtils.ResourceImage(FAttributes.Image, Image1);
Rectangle1.Fill.Color := FAttributes.DestBackground;
Layout1.Align := FAttributes.Align;
FillRGBEffect1.Color := FAttributes.FontColor;
end;
procedure TComponentButton005.FormCreate(Sender: TObject);
begin
FAttributes := TButtonAttributes<TComponentButton005>.New(Self);
end;
end.
|
unit Model.PlanilhaEntradaDIRECT;
interface
uses Generics.Collections, System.Classes, System.SysUtils;
type
TPlanilhaEntradaDIRECT = class
private
FProduto: String;
FCodigoEmbarcador: Integer;
FDataRegistro: TDate;
FDataChegada: TDate;
FOperacao: String;
FAWB2: String;
FPesoNominal: Double;
FValor: Double;
FBairro: String;
FAWB1: String;
FPedido: String;
FUF: String;
FHoraRegistro: TTime;
FHoraChegada: TTime;
FPesoCubado: Double;
FBaseSigla: String;
FDataChegadaLM: TDate;
FNF: String;
FVolumes: Integer;
FUltimoMotorista: String;
FDataAlteracao: TDate;
FCEP: String;
FPakingList: String;
FNomeConsumidor: String;
FNomeEmbarcador: String;
FMunicipio: String;
FDevolucao: String;
FRemessa: String;
FDataAgendamento: String;
FTomadorNome: String;
FEmissao: TDate;
FHoraChegadaLM: TTime;
FQtdeOcorrencia: Integer;
FUltimaOcorrencia: String;
FSituacao: String;
FBase: String;
FHoraAlteracao: TTime;
FUltimaViagem: String;
FChave: String;
FTipo: String;
FSerie: String;
FCNPJTomador: String;
FMensagem: STring;
FPlanilha: TObjectList<TPlanilhaEntradaDIRECT>;
public
property Remessa: String read FRemessa write FRemessa;
property Pedido: String read FPedido write FPedido;
property DataRegistro: TDate read FDataRegistro write FDataRegistro;
property HoraRegistro: TTime read FHoraRegistro write FHoraRegistro;
property CodigoEmbarcador: Integer read FCodigoEmbarcador write FCodigoEmbarcador;
property NomeEmbarcador: String read FNomeEmbarcador write FNomeEmbarcador;
property NomeConsumidor: String read FNomeConsumidor write FNomeConsumidor;
property Municipio: String read FMunicipio write FMunicipio;
property UF: String read FUF write FUF;
property CEP: String read FCEP write FCEP;
property Bairro: String read FBairro write FBairro;
property Situacao: String read FSituacao write FSituacao;
property DataAlteracao: TDate read FDataAlteracao write FDataAlteracao;
property HoraAlteracao: TTime read FHoraAlteracao write FHoraAlteracao;
property Volumes: Integer read FVolumes write FVolumes;
property Tipo: String read FTipo write FTipo;
property PakingList: String read FPakingList write FPakingList;
property NF: String read FNF write FNF;
property Serie: String read FSerie write FSerie;
property Emissao: TDate read FEmissao write FEmissao;
property Valor: Double read FValor write FValor;
property Chave: String read FChave write FChave;
property Operacao: String read FOperacao write FOperacao;
property TomadorNome: String read FTomadorNome write FTomadorNome;
property CNPJTomador: String read FCNPJTomador write FCNPJTomador;
property Base: String read FBase write FBase;
property BaseSigla: String read FBaseSigla write FBaseSigla;
property PesoCubado: Double read FPesoCubado write FPesoCubado;
property PesoNominal: Double read FPesoNominal write FPesoNominal;
property UltimaOcorrencia: String read FUltimaOcorrencia write FUltimaOcorrencia;
property QtdeOcorrencia: Integer read FQtdeOcorrencia write FQtdeOcorrencia;
property DataAgendamento: String read FDataAgendamento write FDataAgendamento;
property Devolucao: String read FDevolucao write FDevolucao;
property UltimaViagem: String read FUltimaViagem write FUltimaViagem;
property UltimoMotorista: String read FUltimoMotorista write FUltimoMotorista;
property Produto: String read FProduto write FProduto;
property AWB1: String read FAWB1 write FAWB1;
property AWB2: String read FAWB2 write FAWB2;
property DataChegada: TDate read FDataChegada write FDataChegada;
property HoraChegada: TTime read FHoraChegada write FHoraChegada;
property DataChegadaLM: TDate read FDataChegadaLM write FDataChegadaLM;
property HoraChegadaLM: TTime read FHoraChegadaLM write FHoraChegadaLM;
property Mensagem: STring read FMensagem write FMensagem;
property Planilha: TObjectList<TPlanilhaEntradaDIRECT> read FPlanilha write FPlanilha;
function GetPlanilha(sFile: String): boolean;
end;
implementation
{ TPlanilhaEntradaDIRECT }
uses Common.Utils;
function TPlanilhaEntradaDIRECT.GetPlanilha(sFile: String): boolean;
var
ArquivoCSV: TextFile;
sLinha: String;
sDetalhe: TStringList;
i : Integer;
sValor : String;
lstRemessa: TStringList;
iIndex: Integer;
begin
try
Result := False;
FPlanilha := TObjectList<TPlanilhaEntradaDIRECT>.Create;
if not FileExists(sFile) then
begin
FMensagem := 'Arquivo ' + sFile + ' não foi encontrado!';
Exit;
end;
AssignFile(ArquivoCSV, sFile);
if sFile.IsEmpty then Exit;
sDetalhe := TStringList.Create;
sDetalhe.StrictDelimiter := True;
sDetalhe.Delimiter := ';';
Reset(ArquivoCSV);
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha + ';';
lstRemessa := TStringList.Create;
if Pos('REMESSA',sLinha) = 0 then
begin
FMensagem := 'Arquivo informado não foi identificado como a Planilha de Entrada da DIRECT!';
Exit;
end;
i := 0;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha + ';';
if TUtils.ENumero(sDetalhe[0]) then
begin
if not lstRemessa.Find(sDetalhe[0], iIndex) then
begin
lstRemessa.Add(sDetalhe[0]);
lstRemessa.Sort;
sValor := '0';
FPlanilha.Add(TPlanilhaEntradaDIRECT.Create);
i := FPlanilha.Count - 1;
FPlanilha[i].Remessa := sDetalhe[0];
FPlanilha[i].Pedido := sDetalhe[1];
FPlanilha[i].DataRegistro := StrToDateDef(sDetalhe[2], 0);
FPlanilha[i].HoraRegistro := StrToTimeDef(sDetalhe[3], 0);
FPlanilha[i].CodigoEmbarcador := StrToIntDef(sDetalhe[4], 0);
FPlanilha[i].NomeEmbarcador := sDetalhe[5];
FPlanilha[i].NomeConsumidor := sDetalhe[6];
FPlanilha[i].Municipio := sDetalhe[7];
FPlanilha[i].UF := sDetalhe[8];
FPlanilha[i].CEP := sDetalhe[9];
FPlanilha[i].Bairro := sDetalhe[10];
FPlanilha[i].Situacao := sDetalhe[11];
FPlanilha[i].DataAlteracao := StrToDateDef(sDetalhe[12], 0);
FPlanilha[i].HoraAlteracao := StrToTimeDef(sDetalhe[13], 0);
FPlanilha[i].Volumes := StrToIntDef(sDetalhe[14], 0);
FPlanilha[i].Tipo := sDetalhe[15];
FPlanilha[i].PakingList := sDetalhe[16];
FPlanilha[i].NF := sDetalhe[17];
FPlanilha[i].Serie := sDetalhe[18];
FPlanilha[i].Emissao := StrToDateDef(sDetalhe[19], 0);
sValor := StringReplace(sDetalhe[20], '.', ',', [rfReplaceAll, rfIgnoreCase]);
FPlanilha[i].Valor := StrToFloatDef(sValor, 0);
FPlanilha[i].Chave := sDetalhe[21];
FPlanilha[i].Operacao := sDetalhe[22];
FPlanilha[i].TomadorNome := sDetalhe[23];
FPlanilha[i].CNPJTomador := sDetalhe[24];
FPlanilha[i].Base := sDetalhe[25];
FPlanilha[i].BaseSigla := sDetalhe[26];
sValor := StringReplace(sDetalhe[27], '.', ',', [rfReplaceAll, rfIgnoreCase]);
FPlanilha[i].PesoCubado := StrToFloatDef(sValor, 0);
sValor := StringReplace(sDetalhe[28], '.', ',', [rfReplaceAll, rfIgnoreCase]);
FPlanilha[i].PesoNominal := StrToFloatDef(sValor, 0);
FPlanilha[i].UltimaOcorrencia := sDetalhe[31];
FPlanilha[i].QtdeOcorrencia := StrToIntDef(sDetalhe[32], 0);
FPlanilha[i].DataAgendamento := sDetalhe[33];
FPlanilha[i].Devolucao := sDetalhe[34];
FPlanilha[i].UltimaViagem := sDetalhe[35];
FPlanilha[i].UltimoMotorista := sDetalhe[36];
FPlanilha[i].Produto := sDetalhe[37];
FPlanilha[i].AWB1 := sDetalhe[38];
FPlanilha[i].AWB2 := sDetalhe[39];
FPlanilha[i].DataChegada := StrToDateDef(sDetalhe[40], 0);
FPlanilha[i].HoraChegada := StrToTimeDef(sDetalhe[41], 0);
FPlanilha[i].DataChegadaLM := StrToDateDef(sDetalhe[42], 0);
FPlanilha[i].HoraChegadaLM := StrToTimeDef(sDetalhe[43], 0);
end;
end;
end;
if FPlanilha.Count = 0 then
begin
FMensagem := 'Nenhuma informação foi importada da planilha!';
Exit;
end;
Result := True;
finally
CloseFile(ArquivoCSV);
end;
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description:
Creation: April 2004
Version: 1.19
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2004-2011 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium.
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
History:
Aug 20, 2006 V1.01 Added IntToHex for .NET
Oct 28, 2006 V1.02 Added SysErrorMessage
Mar 10, 2008 V1.03 Made some changes to prepare code for Unicode
StrLen takes a PAnsiChar instead of Char argument
StrCopy takes a PAnsiChar instead of Char argument
StrPas takes a PAnsiChar instead of Char argument
Apr 15, 2008 V1.04 A. Garrels - All Str.. functions take PAnsiChar argument
and are overloaded in D12 to also take a PWideChar argument
according to changes in SysUtils.pas.
Apr 20, 2008 V1.05 A. Garrels - Added own implementations for wide-versions of
StrLComp and StrLIComp. Added some other functions from
SysUtils.pas. Since the overloaded functions are included
you would have to reference the unit if both SysUtils.pas
and OverbyteIcsLibrary.pas are in the uses clause, i.e.
either SysUtils.StrLIComp() or OverbyteIcsLibrary.StrLIComp(),
not sure whether that breaks something.
Apr 20, 2008 V1.06 A. Garrels added GetACP and const CP_ACP.
Apr 30, 2008 V1.07 A. Garrels prefixed any Win32 functions with an underscore,
Added Ansi versions of Uppercase, Lowercase, Trim.
May 15, 2008 V1.08 A. Garrels optimized _UpperCase, _LowerCase, _Trim and
added IcsIntToStrA(), IcsIntToHexA() and _CompareText().
New define "USE_ICS_RTL" see below, added missing overloads
of _IntToStr.
May 23, 2008 V1.09 A. Garrels check for empty string in IcsLowerCaseA() and
IcsUpperCaseA().
Jul 01, 2008 V1.10 A. Garrels fixed a bug in IcsCompareTextA().
Jul 02, 2008 V1.11 A. Garrels optimized IcsCompareTextA() a bit.
Aug 03, 2008 V1.12 F. Piette made IcsUpperCaseA, IcsLowerCaseA, IcsTrimA and
IcsCompareTextA public. Added IcsSameTextA.
Aug 07, 2008 V1.13 F. Piette found a bug in some AnsiString-functions.
They always call SetLength() on the result now.
Aug 11, 2008 V1.14 A. Garrels added IcsCompareStrA() and an overload to
_CompareStr().
May 09, 2009 V1.15 Arno added const CP_UTF7, and procedure _ShowException
for future use.
May 15, 2009 V1.16 Arno added some EXTERNALSYM directives to make C++Builder
happy (Ambiguity between '_fastcall Application()' and
'Forms::Application')
Apr 15, 2011 V1.17 Arno prepared for 64-bit.
Aug 26, 2011 V1.18 Arno added 64-bit overloaded versions of _IntToHex.
Nov 10, 2012 v1.19 Bugfix IcsCompareTextA IcsCompareStrA
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsLibrary;
interface
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$I OverbyteIcsDefs.inc}
{$IFDEF COMPILER14_UP}
{$IFDEF NO_EXTENDED_RTTI}
{$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
{$ENDIF}
{$ENDIF}
{ The following define works only for compiler versions < v120. }
{ Comment next line if you want to use the original RTL including FastCode }
{ patches. Otherwise ICS routines are called when they are faster either }
{ faster than original RTL routines or not available in the RTL. Currently }
{ only a few Ansi-versions are implemented. Should we use FastCode? }
{#$DEFINE USE_ICS_RTL}
uses
{$IFDEF CLR}
System.Collections,
System.IO,
System.Threading,
System.Runtime.InteropServices,
System.Reflection,
System.Text,
{$ELSE}
Windows, Classes, Messages,
{$IFNDEF NOFORMS}
Forms,
{$ENDIF}
SysUtils,
{$ENDIF}
OverbyteIcsTypes;
const
OverbyteIcsLibraryVersion = 117;
CopyRight : String = ' OverbyteIcsLibrary (c) 2004-2011 F. Piette V1.17 ';
{$IFDEF CLR}
type
TRTLCriticalSection = class
end;
TList = class(ArrayList)
function GetItems(Index: Integer): TObject;
procedure SetItems(Index: Integer; const Value: TObject);
public
procedure Delete(Index : Integer);
function First: TObject;
function Last: TObject;
procedure Pack;
property Items[Index : Integer] : TObject read GetItems
write SetItems;
end;
TStrings = class
public
procedure SetStrings(nIndex: Integer; const Value: String); virtual; abstract;
function GetStrings(nIndex: Integer): String; virtual; abstract;
public
procedure Clear; virtual; abstract;
procedure Add(const S: String); virtual; abstract;
function Count : Integer; virtual; abstract;
property Strings[nIndex : Integer] : String read GetStrings
write SetStrings;
end;
TStringList = class(TStrings)
protected
FStrings : TList;
public
procedure SetStrings(nIndex: Integer; const Value: String); override;
function GetStrings(nIndex: Integer): String; override;
public
constructor Create;
procedure Clear; override;
procedure Add(const S: String); override;
function Count : Integer; override;
end;
{$ENDIF}
{$IFNDEF VCL}
const
fmCreate = $FFFF;
fmOpenRead = $0000;
fmOpenWrite = $0001;
fmOpenReadWrite = $0002;
fmShareCompat = $0000 platform; // DOS compatibility mode is not portable
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyRead = $0030 platform; // write-only not supported on all platforms
fmShareDenyNone = $0040;
soFromBeginning = 0;
soFromCurrent = 1;
soFromEnd = 2;
type
TFileStream = class
protected
FFileName : String;
FClrStream : System.IO.Stream;
function GetSize : Int64;
procedure SetSize(Value : Int64);
public
constructor Create(const AFileName : String; Mode : Integer);
procedure Seek(Offset : Int64; Origin : Integer);
procedure Write(Ch : Char); overload;
property Size : Int64 read GetSize write SetSize;
end;
{$ENDIF}
{$IFDEF CLR}
const
WM_CREATE = 1;
WM_DESTROY = 2;
WM_CLOSE = 16;
WM_NCCREATE = 129;
WM_QUIT = $0012;
WM_TIMER = $0113;
WS_POPUP = DWORD($80000000);
WS_CAPTION = $C00000; { WS_BORDER or WS_DLGFRAME }
WS_CLIPSIBLINGS = $4000000;
WS_SYSMENU = $80000;
WS_MAXIMIZEBOX = $10000;
WS_MINIMIZEBOX = $20000;
WS_EX_TOOLWINDOW = $80;
WM_USER = $0400;
PM_NOREMOVE = 0;
PM_REMOVE = 1;
PM_NOYIELD = 2;
//WM_MY_MSG = WM_USER + 1;
//GWL_WNDPROC = -4;
function DefWindowProc(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT;
function SetWindowLong(hWnd: HWND; nIndex: Integer; dwNewLong: IntPtr): IntPtr; overload;
function GetWindowLongIntPtr(hWnd: HWND; nIndex: Integer): IntPtr;
function GetMessage(out lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax: UINT): BOOL;
function PostMessage(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): BOOL;
function TranslateMessage(const lpMsg: TMsg): BOOL;
function DispatchMessage(const lpMsg: TMsg): Longint;
function PeekMessage(out lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): BOOL;
function RegisterClass(const lpWndClass: TWndClass): ATOM; overload;
function RegisterClass(const lpWndClassInfo: TWndClassInfo): ATOM; overload;
function UnregisterClass(lpClassName: String; hInstance: HINST): BOOL;
function GetClassInfo(hInstance: HINST; lpClassName: String;out lpWndClass: TWndClassInfo): BOOL;
function CreateWindowEx(dwExStyle: DWORD; lpClassName: String;
lpWindowName: String; dwStyle: DWORD; X, Y, nWidth, nHeight: Integer;
hWndParent: HWND; hMenu: HMENU; hInstance: HINST; lpParam: IntPtr): HWND; overload;
function DestroyWindow(hWnd: HWND): BOOL;
function KillTimer(hWnd: HWND; uIDEvent: Cardinal): BOOL;
function SetTimer(
H : HWND;
uIDEvent : Cardinal;
uElapse : Cardinal;
lpTimerFunc : IntPtr): UINT;
function HInstance: HINST;
function GetCurrentThreadId: DWORD;
procedure Sleep(dwMilliseconds: DWORD);
function GetTickCount: DWORD;
function FormatMessage(dwFlags: DWORD; lpSource: IntPtr;
dwMessageId: DWORD; dwLanguageId: DWORD;
lpBuffer: StringBuilder; nSize: DWORD; Arguments: IntPtr): DWORD;
function SysErrorMessage(ErrCode: Integer): String;
procedure EnterCriticalSection(var lpCriticalSection: TRTLCriticalSection);
procedure LeaveCriticalSection(var lpCriticalSection: TRTLCriticalSection);
procedure InitializeCriticalSection(var lpCriticalSection: TRTLCriticalSection);
procedure DeleteCriticalSection(var lpCriticalSection: TRTLCriticalSection);
function IntToStr(N : Integer) : String;
function IntToHex(N : Integer; Digits : Integer = 0) : String;
function Trim(const S: String): String;
function LowerCase(const S: String): String;
function UpperCase(const S: String): String;
function CompareStr(const S1, S2: String): Integer;
function CompareText(const S1, S2 : String) : Integer;
function FileExists(const FileName: String): Boolean;
{$ELSE}
const
{$EXTERNALSYM fmOpenRead}
fmOpenRead = SysUtils.fmOpenRead;
{$EXTERNALSYM fmShareDenyWrite}
fmShareDenyWrite = SysUtils.fmShareDenyWrite;
{$EXTERNALSYM faAnyFile}
faAnyFile = SysUtils.faAnyFile;
{$EXTERNALSYM faDirectory}
faDirectory = SysUtils.faDirectory;
// {$EXTERNALSYM faVolumeID}
// faVolumeID = SysUtils.faVolumeID; //deprecated; // not used in Win32
{$EXTERNALSYM faReadOnly}
faReadOnly = SysUtils.faReadOnly;
{$EXTERNALSYM faSysFile}
faSysFile = SysUtils.faSysFile;
{$EXTERNALSYM faHidden}
faHidden = SysUtils.faHidden;
{$EXTERNALSYM rfReplaceAll}
rfReplaceAll = SysUtils.rfReplaceAll;
{$EXTERNALSYM MinDateTime}
MinDateTime : TDateTime = -657434.0;
{$EXTERNALSYM MaxDateTime}
{$HINTS OFF}
MaxDateTime : TDateTime = 2958465.99999;
{$HINTS ON}
{$EXTERNALSYM opRemove}
opRemove = Classes.opRemove;
{$EXTERNALSYM csDesigning}
csDesigning = Classes.csDesigning;
{$EXTERNALSYM csDestroying}
csDestroying = Classes.csDestroying;
{$EXTERNALSYM lnDeleted}
lnDeleted = Classes.lnDeleted;
{$IFDEF MSWINDOWS}
{$EXTERNALSYM WM_QUIT}
WM_QUIT = Messages.WM_QUIT;
{$EXTERNALSYM WM_USER}
WM_USER = Messages.WM_USER;
{$EXTERNALSYM WM_TIMER}
WM_TIMER = Messages.WM_TIMER;
{$EXTERNALSYM PM_REMOVE}
PM_REMOVE = Windows.PM_REMOVE;
{$EXTERNALSYM WS_EX_TOOLWINDOW}
WS_EX_TOOLWINDOW = Windows.WS_EX_TOOLWINDOW;
{$EXTERNALSYM WS_POPUP}
WS_POPUP = Windows.WS_POPUP;
{$EXTERNALSYM TIME_ZONE_ID_DAYLIGHT}
TIME_ZONE_ID_DAYLIGHT = Windows.TIME_ZONE_ID_DAYLIGHT;
{$EXTERNALSYM TIME_ZONE_ID_STANDARD}
TIME_ZONE_ID_STANDARD = Windows.TIME_ZONE_ID_STANDARD;
{$EXTERNALSYM CP_ACP}
CP_ACP = Windows.CP_ACP;
{$EXTERNALSYM CP_UTF8}
CP_UTF8 = Windows.CP_UTF8;
{$EXTERNALSYM CP_UTF7}
CP_UTF7 = Windows.CP_UTF7;
{$ENDIF MSWINDOWS}
{#$EXTERNALSYM SysErrorMessage}
function _SysErrorMessage(ErrCode: Integer): String;
procedure _ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
{#$EXTERNALSYM BoolToStr}
function _BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): String;
{#$EXTERNALSYM IntToStr}
function _IntToStr(const N : Integer) : String; overload;
function _IntToStr(const N : Int64) : String; overload;
{$IFDEF COMPILER12_UP}
function _IntToStr(const N : Cardinal) : String; overload;
{$ENDIF}
function IcsIntToStrA(N : Integer): AnsiString;
function IcsIntToHexA(N : Integer; Digits: Byte) : AnsiString;
{#$EXTERNALSYM IntToHex}
function _IntToHex(Value: Integer; Digits: Integer): String; overload;
function _IntToHex(Value: Int64; Digits: Integer): String; overload;
{$IFDEF COMPILER16_UP}
function _IntToHex(Value: UInt64; Digits: Integer): String; overload;
{$ENDIF}
{#$EXTERNALSYM StrToInt}
function _StrToInt(const S: String): Integer;
function _StrToInt64(const S: String): Int64;
function _StrPas(const P : PAnsiChar) : AnsiString; {$IFDEF COMPILER12_UP} overload;
function _StrPas(const P : PWideChar) : UnicodeString; overload;
{$ENDIF}
{#$EXTERNALSYM StrPas}
function _StrLen(const P : PAnsiChar) : Cardinal; {$IFDEF COMPILER12_UP} overload;
function _StrLen(const P : PWideChar) : Cardinal; overload;
{$ENDIF}
{#$EXTERNALSYM StrLen}
function _StrCopy(Dest: PAnsiChar; const Source: PAnsiChar): PAnsiChar; {$IFDEF COMPILER12_UP} overload;
function _StrCopy(Dest: PWideChar; const Source: PWideChar): PWideChar; overload;
{$ENDIF}
{#$EXTERNALSYM StrCopy}
{#$EXTERNALSYM FloatToStr}
function _FloatToStr(Value: Extended): String;
function _Trim(const Str : AnsiString) : AnsiString; {$IFDEF COMPILER12_UP} overload;
function _Trim(const Str : UnicodeString) : UnicodeString; overload;
{$ENDIF}
{#$EXTERNALSYM Trim}
function _StrLower(Str: PAnsiChar): PAnsiChar; {$IFDEF COMPILER12_UP} overload;
function _StrLower(Str: PWideChar): PWideChar; overload;
{$ENDIF}
{#$EXTERNALSYM StrLower}
function _StrIComp(const Str1, Str2: PAnsiChar): Integer; {$IFDEF COMPILER12_UP} overload;
function _StrIComp(const Str1, Str2: PWideChar): Integer; overload;
{$ENDIF}
{#$EXTERNALSYM StrIComp}
function _StrPCopy(Dest: PAnsiChar; const Source: AnsiString): PAnsiChar; {$IFDEF COMPILER12_UP} overload;
function _StrPCopy(Dest: PWideChar; const Source: UnicodeString): PWideChar; overload;
{$ENDIF}
{#$EXTERNALSYM StrPCopy}
function _StrComp(const Str1, Str2: PAnsiChar): Integer; {$IFDEF COMPILER12_UP} overload;
function _StrComp(const Str1, Str2: PWideChar): Integer; overload;
{$ENDIF}
{#$EXTERNALSYM StrComp}
function _StrLComp(const Str1, Str2: PAnsiChar; MaxLen: Cardinal): Integer; {$IFDEF COMPILER12_UP} overload;
function _StrLComp(const Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; overload;
{$ENDIF}
{#$EXTERNALSYM StrLComp}
function _StrLIComp(const Str1, Str2: PAnsiChar; MaxLen: Cardinal): Integer; {$IFDEF COMPILER12_UP} overload;
function _StrLIComp(const Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; overload;
{$ENDIF}
{#$EXTERNALSYM StrLIComp}
function _StrToDateTime(const S: String): TDateTime; overload;
function _StrToDateTime(const S: String; const FormatSettings: TFormatSettings): TDateTime; overload;
{#$EXTERNALSYM StrToDateTime}
function _LowerCase(const S: AnsiString): AnsiString; {$IFDEF COMPILER12_UP} overload;
function _LowerCase(const S: UnicodeString): UnicodeString; overload;
{$ENDIF}
{#$EXTERNALSYM LowerCase}
function _UpperCase(const S: AnsiString): AnsiString; {$IFDEF COMPILER12_UP} overload;
function _UpperCase(const S: UnicodeString): UnicodeString; overload;
{$ENDIF}
{#$EXTERNALSYM UpperCase}
function IcsUpperCaseA(const S: AnsiString): AnsiString;
function IcsLowerCaseA(const S: AnsiString): AnsiString;
function IcsCompareTextA(const S1, S2: AnsiString): Integer;
function IcsTrimA(const Str: AnsiString): AnsiString;
function IcsSameTextA(const S1, S2: AnsiString): Boolean;
{#$EXTERNALSYM CompareStr}
function _CompareStr(const S1, S2: AnsiString): Integer; {$IFDEF COMPILER12_UP} overload;
function _CompareStr(const S1, S2: UnicodeString): Integer; overload;
{$ENDIF}
{#$EXTERNALSYM CompareText}
function _CompareText(const S1, S2: AnsiString): Integer;{$IFDEF COMPILER12_UP} overload;
function _CompareText(const S1, S2: UnicodeString): Integer; overload;
{$ENDIF}
function _AnsiStrComp(S1, S2: PAnsiChar): Integer;
{#$EXTERNALSYM FileExists}
function _FileExists(const FileName: String): Boolean;
{#$EXTERNALSYM DeleteFile}
function _DeleteFile(const FileName: String): Boolean;
{#$EXTERNALSYM ExtractFileExt}
function _ExtractFileExt(const FileName: String): String;
{#$EXTERNALSYM ExtractFilePath}
function _ExtractFilePath(const FileName: String): String;
{#$EXTERNALSYM DateTimeToStr}
function _DateTimeToStr(const DateTime: TDateTime): String;
{#$EXTERNALSYM DecodeDate}
procedure _DecodeDate(Date: TDateTime; var Year, Month, Day: Word);
{#$EXTERNALSYM DecodeTime}
procedure _DecodeTime(Time: TDateTime; var Hour, Min, Sec, MSec: Word);
{#$EXTERNALSYM EncodeTime}
function _EncodeTime(Hour, Min, Sec, MSec: Word): TDateTime;
{#$EXTERNALSYM DirectoryExists}
function _DirectoryExists(const Name: String): Boolean;
{#$EXTERNALSYM ExcludeTrailingPathDelimiter}
function _ExcludeTrailingPathDelimiter(const S: String): String;
{#$EXTERNALSYM IncludeTrailingPathDelimiter}
function _IncludeTrailingPathDelimiter(const S: String): String;
{#$EXTERNALSYM Format}
function _Format(const Fmt: String; const Args: array of const): String;
{#$EXTERNALSYM FindFirst}
function _FindFirst(const Path: String; Attr: Integer; var F: TSearchRec): Integer;
{#$EXTERNALSYM FindNext}
function _FindNext(var F: TSearchRec): Integer;
{#$EXTERNALSYM FindClose}
procedure _FindClose(var F: TSearchRec);
{#$EXTERNALSYM FileDateToDateTime}
function _FileDateToDateTime(FileDate: Integer): TDateTime;
{#$EXTERNALSYM FreeAndNil}
procedure _FreeAndNil(var Obj);
{#$EXTERNALSYM Date}
function _Date : TDateTime;
{#$EXTERNALSYM Now}
function _Now: TDateTime;
{#$EXTERNALSYM StringReplace}
function _StringReplace(const S: String; const OldPattern: String;
const NewPattern: String; Flags: TReplaceFlags): String;
{$IFDEF MSWINDOWS}
{#$EXTERNALSYM GetTimeZoneInformation}
function _GetTimeZoneInformation(var lpTimeZoneInformation: TTimeZoneInformation): DWORD; stdcall;
{#$EXTERNALSYM GetWindowLong}
function _GetWindowLong(H: HWND; nIndex: Integer): Longint; stdcall;
{#$EXTERNALSYM DefWindowProc}
function _DefWindowProc(H: HWND; Msg: UINT; ParamW: WPARAM; ParamL: LPARAM): LRESULT; stdcall;
{#$EXTERNALSYM GetCurrentThreadId}
function _GetCurrentThreadId: DWORD; stdcall;
{#$EXTERNALSYM GetMessage}
function _GetMessage(var lpMsg: TMsg; H: HWND;
wMsgFilterMin, wMsgFilterMax: UINT): BOOL; stdcall;
{#$EXTERNALSYM TranslateMessage}
function _TranslateMessage(const lpMsg: TMsg): BOOL; stdcall;
{#$EXTERNALSYM DispatchMessage}
function _DispatchMessage(const lpMsg: TMsg): LongInt; stdcall;
{#$EXTERNALSYM PeekMessage}
function _PeekMessage(var lpMsg: TMsg; H: HWND;
wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): BOOL; stdcall;
{#$EXTERNALSYM PostMessage}
function _PostMessage(H: HWND; Msg: UINT; ParamW: WPARAM; ParamL: LPARAM): BOOL; stdcall;
{#$EXTERNALSYM EnterCriticalSection}
procedure _EnterCriticalSection(var lpCriticalSection: TRTLCriticalSection); stdcall;
{#$EXTERNALSYM LeaveCriticalSection}
procedure _LeaveCriticalSection(var lpCriticalSection: TRTLCriticalSection); stdcall;
{#$EXTERNALSYM InitializeCriticalSection}
procedure _InitializeCriticalSection(var lpCriticalSection: TRTLCriticalSection); stdcall;
{#$EXTERNALSYM DeleteCriticalSection}
procedure _DeleteCriticalSection(var lpCriticalSection: TRTLCriticalSection); stdcall;
{#$EXTERNALSYM GetClassInfo}
function _GetClassInfo(hInstance: HINST; lpClassName: PChar;
var lpWndClass: TWndClass): BOOL; stdcall;
{#$EXTERNALSYM RegisterClass}
function _RegisterClass(const lpWndClass: TWndClass): ATOM; stdcall;
{#$EXTERNALSYM UnregisterClass}
function _UnregisterClass(lpClassName: PChar; hInstance: HINST): BOOL; stdcall;
{#$EXTERNALSYM CreateWindowEx}
function _CreateWindowEx(dwExStyle: DWORD; lpClassName: PChar;
lpWindowName: PChar; dwStyle: DWORD; X, Y, nWidth, nHeight: Integer;
hWndParent: HWND; h_Menu: HMENU; hInstance: HINST; lpParam: Pointer): HWND;
{#$EXTERNALSYM DestroyWindow}
function _DestroyWindow(H: HWND): BOOL; stdcall;
{#$EXTERNALSYM SetWindowLong}
function _SetWindowLong(H: HWND; nIndex: Integer; dwNewLong: Longint): Longint; stdcall;
{#$EXTERNALSYM WM_USER}
function _LoadLibrary(lpLibFileName: PChar): HMODULE; stdcall;
{#$EXTERNALSYM LoadLibrary}
function _FreeLibrary(hLibModule: HMODULE): BOOL; stdcall;
{#$EXTERNALSYM GetProcAddress}
function _GetProcAddress(hModule: HMODULE; lpProcName: LPCSTR): FARPROC; stdcall;
{#$EXTERNALSYM GetTickCount}
function _GetTickCount: DWORD; stdcall;
{#$EXTERNALSYM Sleep}
procedure _Sleep(dwMilliseconds: DWORD); stdcall;
{#$EXTERNALSYM Sleep}
function _GetACP: Cardinal; stdcall;
{$ENDIF MSWINDOWS}
{$IFNDEF NOFORMS}
{$EXTERNALSYM Application}
function Application : TApplication;
{$ENDIF}
{$ENDIF not CLR}
{$EXTERNALSYM MakeWord}
function MakeWord(a, b: Byte): Word;
{$EXTERNALSYM MakeLong}
function MakeLong(a, b: Word): Longint;
{$EXTERNALSYM HiWord}
function HiWord(L: DWORD): Word;
implementation
{$IFDEF CLR}
const
user32 = 'user32.dll';
kernel32 = 'kernel32.dll';
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = False, EntryPoint = 'DefWindowProc')]
function DefWindowProc(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'SetWindowLong')]
function SetWindowLong(hWnd: HWND; nIndex: Integer; dwNewLong: IntPtr): IntPtr; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'GetWindowLong')]
function GetWindowLongIntPtr(hWnd: HWND; nIndex: Integer): IntPtr; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'GetMessage')]
function GetMessage; external;
[DllImport(user32, CharSet = CharSet.Ansi, SetLastError = True, EntryPoint = 'TranslateMessage')]
function TranslateMessage; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'DispatchMessage')]
function DispatchMessage; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'PeekMessage')]
function PeekMessage; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'PostMessage')]
function PostMessage; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'RegisterClass')]
function RegisterClass(const lpWndClass: TWndClass): ATOM; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'RegisterClass')]
function RegisterClass(const lpWndClassInfo: TWndClassInfo): ATOM; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'UnregisterClass')]
function UnregisterClass; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'GetClassInfo')]
function GetClassInfo; external;
[DllImport(user32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'CreateWindowEx')]
function CreateWindowEx(dwExStyle: DWORD; lpClassName: String;
lpWindowName: String; dwStyle: DWORD; X, Y, nWidth, nHeight: Integer;
hWndParent: HWND; hMenu: HMENU; hInstance: HINST; lpParam: IntPtr): HWND; external;
[DllImport(user32, CharSet = CharSet.Ansi, SetLastError = True, EntryPoint = 'DestroyWindow')]
function DestroyWindow; external;
[DllImport(user32, CharSet = CharSet.Ansi, SetLastError = True, EntryPoint = 'SetTimer')]
function SetTimer; external;
[DllImport(user32, CharSet = CharSet.Ansi, SetLastError = True, EntryPoint = 'KillTimer')]
function KillTimer; external;
[DllImport(kernel32, CharSet = CharSet.Ansi, SetLastError = True, EntryPoint = 'GetTickCount')]
function GetTickCount; external;
[DllImport(kernel32, CharSet = CharSet.Ansi, SetLastError = True, EntryPoint = 'Sleep')]
procedure Sleep; external;
[DllImport(kernel32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'FormatMessage')]
function FormatMessage; external;
const
FORMAT_MESSAGE_ALLOCATE_BUFFER = $100;
FORMAT_MESSAGE_IGNORE_INSERTS = $200;
FORMAT_MESSAGE_FROM_STRING = $400;
FORMAT_MESSAGE_FROM_HMODULE = $800;
FORMAT_MESSAGE_FROM_SYSTEM = $1000;
FORMAT_MESSAGE_ARGUMENT_ARRAY = $2000;
FORMAT_MESSAGE_MAX_WIDTH_MASK = 255;
function SysErrorMessage(ErrCode: Integer): String;
var
Buffer : StringBuilder;
BufSize : Integer;
Len : Integer;
begin
BufSize := 256;
Buffer := StringBuilder.Create(BufSize);
Len := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or
FORMAT_MESSAGE_IGNORE_INSERTS or
FORMAT_MESSAGE_ARGUMENT_ARRAY,
nil, ErrCode, 0, Buffer, BufSize, nil);
while (Len > 0) and
(AnsiChar(Buffer[Len - 1]) in [#0..#32, '.']) do
Dec(Len);
Buffer.Length := Len;
Result := Buffer.ToString;
end;
function GetCurrentThreadId: DWORD;
begin
Result := Thread.CurrentThread.GetHashCode;
end;
function HInstance: HINST;
begin
Result := HINST(Integer(Marshal.GetHInstance(Assembly.GetCallingAssembly.GetModules[0])));
end;
procedure EnterCriticalSection(var lpCriticalSection: TRTLCriticalSection);
begin
Monitor.Enter(lpCriticalSection);
end;
procedure LeaveCriticalSection(var lpCriticalSection: TRTLCriticalSection);
begin
Monitor.Exit(lpCriticalSection);
end;
procedure InitializeCriticalSection(var lpCriticalSection: TRTLCriticalSection);
begin
lpCriticalSection := TRTLCriticalSection.Create;
end;
procedure DeleteCriticalSection(var lpCriticalSection: TRTLCriticalSection);
begin
lpCriticalSection.Free;
end;
function TList.GetItems(Index: Integer): TObject;
begin
Result := Item[Index];
end;
procedure TList.SetItems(Index: Integer; const Value: TObject);
begin
Item[Index] := Value;
end;
procedure TList.Delete(Index : Integer);
begin
RemoveAt(Index);
end;
function TList.First: TObject;
begin
Result := Item[0];
end;
function TList.Last: TObject;
begin
Result := Item[Count - 1];
end;
procedure TList.Pack;
begin
end;
constructor TStringList.Create;
begin
inherited Create;
FStrings := TList.Create;
end;
procedure TStringList.Clear;
begin
FStrings.Clear;
end;
procedure TStringList.Add(const S: String);
begin
FStrings.Add(S);
end;
function TStringList.Count : Integer;
begin
Result := FStrings.Count;
end;
procedure TStringList.SetStrings(nIndex: Integer; const Value: String);
begin
FStrings.Items[nIndex] := Value;
end;
function TStringList.GetStrings(nIndex: Integer): String;
begin
Result := String(FStrings.Items[nIndex]);
end;
{$IFNDEF VCL}
constructor TFileStream.Create(const AFileName: String; Mode: Integer);
var
LMode : System.IO.FileMode;
LAccess : System.IO.FileAccess;
LShare : System.IO.FileShare;
begin
inherited Create;
if Mode = fmCreate then begin
LMode := System.IO.FileMode.Create;
LAccess := System.IO.FileAccess.ReadWrite;
end
else begin
LMode := System.IO.FileMode.Open;
case Mode and $F of
fmOpenReadWrite: LAccess := System.IO.FileAccess.ReadWrite;
fmOpenWrite: LAccess := System.IO.FileAccess.Write;
else
LAccess := System.IO.FileAccess.Read;
end;
end;
case Mode and $F0 of
fmShareDenyWrite: LShare := System.IO.FileShare.Read;
fmShareDenyRead: LShare := System.IO.FileShare.Write;
fmShareDenyNone: LShare := System.IO.FileShare.None;
else
LShare := System.IO.FileShare.ReadWrite;
end;
FClrStream := System.IO.FileStream.Create(AFileName, LMode, LAccess, LShare);
FFileName := AFileName;
end;
function TFileStream.GetSize: Int64;
begin
Result := FClrStream.Length;
end;
procedure TFileStream.SetSize(Value: Int64);
begin
FClrStream.SetLength(Value);
end;
procedure TFileStream.Seek(Offset : Int64; Origin: Integer);
var
so : System.IO.SeekOrigin;
begin
case Origin of
soFromBeginning : so := System.IO.SeekOrigin.Begin;
soFromCurrent : so := System.IO.SeekOrigin.Current;
soFromEnd : so := System.IO.SeekOrigin.End;
else
so := System.IO.SeekOrigin.Begin;
end;
FClrStream.Seek(Offset, so);
end;
procedure TFileStream.Write(Ch: Char);
begin
FClrStream.WriteByte(Byte(Ch));
end;
{$ENDIF}
function IntToStr(N : Integer) : String;
begin
Result := N.ToString;
end;
function IntToHex(N : Integer; Digits : Integer) : String;
begin
if Digits = 0 then
Result := System.String.Format('{0:X}', System.Object(N))
else
Result := System.String.Format('{0:X' + Digits.ToString() + '}',
System.Object(N));
end;
function Trim(const S: String): String;
begin
if S = '' then
Result := ''
else
Result := S.Trim;
end;
function LowerCase(const S: String): String;
begin
Result := S.ToLower;
end;
function UpperCase(const S: String): String;
begin
Result := S.ToUpper;
end;
function CompareText(const S1, S2 : String) : Integer;
begin
if S1.ToUpper = S2.ToUpper then
Result := 0
else if S1.ToUpper < S2.ToUpper then
Result := -1
else
Result := 1;
end;
function CompareStr(const S1, S2 : String) : Integer;
begin
Result := System.String.Compare(S1, S2);
end;
function FileExists(const FileName: String): Boolean;
begin
Result := System.IO.File.Exists(FileName);
end;
{$ELSE}
function _SysErrorMessage(ErrCode: Integer): String;
begin
Result := SysUtils.SysErrorMessage(ErrCode);
end;
procedure _ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
begin
SysUtils.ShowException(ExceptObject, ExceptAddr);
end;
function _BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): String;
begin
Result := SysUtils.BoolToStr(B, UseBoolStrs);
end;
function _IntToStr(const N : Integer) : String;
begin
Result := SysUtils.IntToStr(N);
end;
function _IntToStr(const N : Int64) : String;
begin
Result := SysUtils.IntToStr(N);
end;
{$IFDEF COMPILER12_UP}
function _IntToStr(const N : Cardinal) : String;
begin
Result := SysUtils.IntToStr(N);
end;
{$ENDIF}
{ Author Arno Garrels - Needs optimization! }
{ It's a bit slower that the RTL routine. }
{ We should realy use a FastCode function here. }
function IntToStrA(N : Integer) : AnsiString;
var
I : Integer;
Buf : array [0..11] of AnsiChar;
Sign : Boolean;
begin
if N >= 0 then
Sign := FALSE
else begin
Sign := TRUE;
if N = Low(Integer) then
begin
Result := '-2147483648';
Exit;
end
else
N := Abs(N);
end;
I := Length(Buf);
repeat
Dec(I);
Buf[I] := AnsiChar(N mod 10 + $30);
N := N div 10;
until N = 0;
if Sign then begin
Dec(I);
Buf[I] := '-';
end;
SetLength(Result, Length(Buf) - I);
Move(Buf[I], Pointer(Result)^, Length(Buf) - I);
end;
function IcsIntToStrA(N : Integer) : AnsiString;
begin
{$IFDEF USE_ICS_RTL}
Result := IntToStrA(N);
{$ELSE}
{$IFNDEF COMPILER12_UP}
Result := SysUtils.IntToStr(N);
{$ELSE}
Result := IntToStrA(N);
{$ENDIF}
{$ENDIF}
end;
{ Author Arno Garrels - Feel free to optimize! }
{ It's anyway faster than the RTL routine. }
function IntToHexA(N : Integer; Digits: Byte) : AnsiString;
var
Buf : array [0..7] of Byte;
V : Cardinal;
I : Integer;
begin
V := Cardinal(N);
I := Length(Buf);
if Digits > I then Digits := I;
repeat
Dec(I);
Buf[I] := V mod 16;
if Buf[I] < 10 then
Inc(Buf[I], $30)
else
Inc(Buf[I], $37);
V := V div 16;
until V = 0;
while Digits > Length(Buf) - I do begin
Dec(I);
Buf[I] := $30;
end;
SetLength(Result, Length(Buf) - I);
Move(Buf[I], Pointer(Result)^, Length(Buf) - I);
end;
function IcsIntToHexA(N : Integer; Digits: Byte) : AnsiString;
begin
{$IFDEF USE_ICS_RTL}
Result := IntToHexA(N, Digits);
{$ELSE}
{$IFNDEF COMPILER12_UP}
Result := SysUtils.IntToHex(N, Digits);
{$ELSE}
Result := IntToHexA(N, Digits);
{$ENDIF}
{$ENDIF}
end;
function _StrToInt(const S: String): Integer;
begin
Result := SysUtils.StrToInt(S);
end;
function _StrToInt64(const S: String): Int64;
begin
Result := SysUtils.StrToInt64(S);
end;
function _StrPas(const P : PAnsiChar) : AnsiString; // Unicode change
begin
Result := SysUtils.StrPas(P);
end;
{$IFDEF COMPILER12_UP}
function _StrPas(const P : PWideChar): UnicodeString; // Unicode change
begin
Result := SysUtils.StrPas(P);
end;
{$ENDIF}
function _StrLen(const P : PAnsiChar) : Cardinal; // Unicode change
begin
Result := SysUtils.StrLen(P);
end;
{$IFDEF COMPILER12_UP}
function _StrLen(const P : PWideChar) : Cardinal; // Unicode change
begin
Result := SysUtils.StrLen(P);
end;
{$ENDIF}
function _StrCopy(Dest: PAnsiChar; const Source: PAnsiChar): PAnsiChar; // Unicode change
begin
Result := SysUtils.StrCopy(Dest, Source);
end;
{$IFDEF COMPILER12_UP}
function _StrCopy(Dest: PWideChar; const Source: PWideChar): PWideChar; // Unicode change
begin
Result := SysUtils.StrCopy(Dest, Source);
end;
{$ENDIF}
{$IFDEF COMPILER12_UP}
function _TrimLeft(const Str: AnsiString): AnsiString;
var
I, L : Integer;
begin
L := Length(Str);
I := 1;
while (I <= L) and (Str[I] <= ' ') do
Inc(I);
Result := Copy(Str, I, Maxint);
end;
function _TrimRight(const Str: AnsiString): AnsiString;
var
I : Integer;
begin
I := Length(Str);
while (I > 0) and (Str[I] <= ' ') do
Dec(I);
Result := Copy(Str, 1, I);
end;
{$ENDIF}
{ Author Arno Garrels - Feel free to optimize! }
{ It's a bit faster than the RTL routine. }
function IcsTrimA(const Str: AnsiString): AnsiString;
var
I, L : Integer;
begin
L := Length(Str);
I := 1;
while (I <= L) and (Str[I] <= ' ') do
Inc(I);
if I > L then
Result := ''
else begin
while Str[L] <= ' ' do
Dec(L);
SetLength(Result, L - I + 1);
Move(Str[I], Pointer(Result)^, L - I + 1);
end;
end;
function _Trim(const Str: AnsiString): AnsiString;
begin
{$IFDEF USE_ICS_RTL}
Result := IcsTrimA(Str);
{$ELSE}
{$IFNDEF COMPILER12_UP}
Result := SysUtils.Trim(Str);
{$ELSE}
Result := IcsTrimA(Str);
{$ENDIF}
{$ENDIF}
end;
{$IFDEF COMPILER12_UP}
function _Trim(const Str : UnicodeString) : UnicodeString;
begin
Result := SysUtils.Trim(Str);
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function _StrLower(Str: PAnsiChar): PAnsiChar;
begin
Result := SysUtils.StrLower(Str);
end;
{$IFDEF COMPILER12_UP}
function _StrLower(Str: PWideChar): PWideChar;
begin
Result := SysUtils.StrLower(Str);
end;
{$ENDIF}
function _StrPCopy(Dest: PAnsiChar; const Source: AnsiString): PAnsiChar; // Unicode change
begin
Result := SysUtils.StrPCopy(Dest, Source);
end;
{$IFDEF COMPILER12_UP}
function _StrPCopy(Dest: PWideChar; const Source: UnicodeString): PWideChar;
begin
Result := SysUtils.StrPCopy(Dest, Source);
end;
{$ENDIF}
function _StrComp(const Str1, Str2 : PAnsiChar): Integer;
begin
Result := SysUtils.StrComp(Str1, Str2);
end;
{$IFDEF COMPILER12_UP}
function _StrComp(const Str1, Str2 : PWideChar): Integer;
begin
Result := SysUtils.StrComp(Str1, Str2);
end;
{$ENDIF}
function _StrIComp(const Str1, Str2: PAnsiChar): Integer;
begin
Result := SysUtils.StrIComp(Str1, Str2);
end;
{$IFDEF COMPILER12_UP}
function _StrIComp(const Str1, Str2: PWideChar): Integer;
begin
Result := SysUtils.StrIComp(Str1, Str2);
end;
{$ENDIF}
function _StrLComp(const Str1, Str2: PAnsiChar; MaxLen: Cardinal): Integer;
begin
Result := SysUtils.StrLComp(Str1, Str2, MaxLen);
end;
{$IFDEF COMPILER12_UP}
function _StrLComp(const Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
(*
{ Currently buggy so use our own implementation // fixed in build 3047}
function Min(I1, I2: Cardinal): Cardinal; inline;
begin
if I1 < I2 then
Result := I1
else
Result := I2;
end;
*)
begin
Result := SysUtils.StrLComp(Str1, Str2, MaxLen);
{ Result := CompareStringW(LOCALE_USER_DEFAULT,
NORM_IGNOREWIDTH,
Str1, Min(MaxLen, SysUtils.StrLen(Str1)),
Str2, Min(MaxLen, SysUtils.StrLen(Str2))) - 2; }
end;
{$ENDIF}
function _StrLIComp(const Str1, Str2: PAnsiChar; MaxLen: Cardinal): Integer;
begin
Result := SysUtils.StrLIComp(Str1, Str2, MaxLen);
end;
{$IFDEF COMPILER12_UP}
function _StrLIComp(const Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
(*
{ Currently buggy so use our own implementation } // fixed in build 3047}
function Min(I1, I2: Cardinal): Cardinal; inline;
begin
if I1 < I2 then
Result := I1
else
Result := I2;
end;
*)
begin
Result := SysUtils.StrLIComp(Str1, Str2, MaxLen);
{ Result := CompareStringW(LOCALE_USER_DEFAULT,
NORM_IGNOREWIDTH or NORM_IGNORECASE,
Str1, Min(MaxLen, SysUtils.StrLen(Str1)),
Str2, Min(MaxLen, SysUtils.StrLen(Str2))) - 2;}
end;
{$ENDIF}
{ Author Arno Garrels - Feel free to optimize! }
{ It's anyway faster than the RTL routine. }
function IcsLowerCaseA(const S: AnsiString): AnsiString;
var
Ch : AnsiChar;
L, I : Integer;
Source, Dest: PAnsiChar;
begin
L := Length(S);
if L = 0 then
Result := ''
else begin
SetLength(Result, L);
Source := Pointer(S);
Dest := Pointer(Result);
for I := 1 to L do begin
Ch := Source^;
if Ch in ['A'..'Z'] then Inc(Ch, 32);
Dest^ := Ch;
Inc(Source);
Inc(Dest);
end;
end;
end;
function _LowerCase(const S: AnsiString): AnsiString;
begin
{$IFDEF USE_ICS_RTL}
Result := IcsLowerCaseA(S);
{$ELSE}
{$IFNDEF COMPILER12_UP}
Result := SysUtils.LowerCase(S);
{$ELSE}
Result := IcsLowerCaseA(S);
{$ENDIF}
{$ENDIF}
end;
{$IFDEF COMPILER12_UP}
function _LowerCase(const S: UnicodeString): UnicodeString;
begin
Result := SysUtils.LowerCase(S);
end;
{$ENDIF}
{ Author Arno Garrels - Feel free to optimize! }
{ It's anyway faster than the RTL routine. }
function IcsUpperCaseA(const S: AnsiString): AnsiString;
var
Ch : AnsiChar;
L, I : Integer;
Source, Dest: PAnsiChar;
begin
L := Length(S);
if L = 0 then
Result := ''
else begin
SetLength(Result, L);
Source := Pointer(S);
Dest := Pointer(Result);
for I := 1 to L do begin
Ch := Source^;
if Ch in ['a'..'z'] then Dec(Ch, 32);
Dest^ := Ch;
Inc(Source);
Inc(Dest);
end;
end;
end;
function _UpperCase(const S: AnsiString): AnsiString;
begin
{$IFDEF USE_ICS_RTL}
Result := IcsUpperCaseA(S);
{$ELSE}
{$IFNDEF COMPILER12_UP}
Result := SysUtils.UpperCase(S);
{$ELSE}
Result := IcsUpperCaseA(S);
{$ENDIF}
{$ENDIF}
end;
{$IFDEF COMPILER12_UP}
function _UpperCase(const S: UnicodeString): UnicodeString;
begin
Result := SysUtils.UpperCase(S);
end;
{$ENDIF}
function IcsSameTextA(const S1, S2: AnsiString): Boolean;
begin
Result := (IcsCompareTextA(S1, S2) = 0);
end;
{ Author Arno Garrels - Feel free to optimize! }
{ It's anyway faster than the RTL routine. }
function IcsCompareTextA(const S1, S2: AnsiString): Integer;
var
L1, L2, I : Integer;
MinLen : Integer;
Ch1, Ch2 : AnsiChar;
P1, P2 : PAnsiChar;
begin
L1 := Length(S1);
L2 := Length(S2);
if L1 > L2 then
MinLen := L2
else
MinLen := L1;
P1 := Pointer(S1);
P2 := Pointer(S2);
for I := 0 to MinLen -1 do
begin
Ch1 := P1[I];
Ch2 := P2[I];
if (Ch1 <> Ch2) then
begin
{ Strange, but this is how the original works, }
{ for instance, "a" is smaller than "[" . }
if (Ch1 > Ch2) then
begin
if Ch1 in ['a'..'z'] then
Dec(Byte(Ch1), 32);
end
else begin
if Ch2 in ['a'..'z'] then
Dec(Byte(Ch2), 32);
end;
end;
if (Ch1 <> Ch2) then
begin
Result := Byte(Ch1) - Byte(Ch2);
Exit;
end;
end;
Result := L1 - L2;
end;
function _CompareText(const S1, S2: AnsiString): Integer;
begin
{$IFDEF USE_ICS_RTL}
Result := IcsCompareTextA(S1, S2);
{$ELSE}
{$IFNDEF COMPILER12_UP}
Result := SysUtils.CompareText(S1, S2);
{$ELSE}
Result := IcsCompareTextA(S1, S2);
{$ENDIF}
{$ENDIF}
end;
{$IFDEF COMPILER12_UP}
function _CompareText(const S1, S2: UnicodeString): Integer;
begin
Result := SysUtils.CompareText(S1, S2);
end;
{$ENDIF}
function _AnsiStrComp(S1, S2: PAnsiChar): Integer;
begin
Result := SysUtils.AnsiStrComp(S1, S2);
end;
function IcsCompareStrA(const S1, S2: AnsiString): Integer;
var
L1, L2, I : Integer;
MinLen : Integer;
P1, P2 : PAnsiChar;
begin
L1 := Length(S1);
L2 := Length(S2);
if L1 > L2 then
MinLen := L2
else
MinLen := L1;
P1 := Pointer(S1);
P2 := Pointer(S2);
for I := 0 to MinLen -1 do
begin
if (P1[I] <> P2[I]) then
begin
Result := Ord(P1[I]) - Ord(P2[I]);
Exit;
end;
end;
Result := L1 - L2;
end;
function _CompareStr(const S1, S2: AnsiString): Integer;
begin
{$IFDEF USE_ICS_RTL}
Result := IcsCompareStrA(S1, S2);
{$ELSE}
{$IFNDEF COMPILER12_UP}
Result := SysUtils.CompareStr(S1, S2);
{$ELSE}
Result := IcsCompareStrA(S1, S2);
{$ENDIF}
{$ENDIF}
end;
{$IFDEF COMPILER12_UP}
function _CompareStr(const S1, S2: UnicodeString): Integer;
begin
Result := SysUtils.CompareStr(S1, S2);
end;
{$ENDIF}
function _StringReplace(const S: String; const OldPattern: String;
const NewPattern: String; Flags: TReplaceFlags): String;
begin
Result := SysUtils.StringReplace(S, OldPattern, NewPattern, Flags);
end;
function _FileExists(const FileName: String): Boolean;
begin
Result := SysUtils.FileExists(FileName);
end;
procedure _FreeAndNil(var Obj);
begin
SysUtils.FreeAndNil(Obj);
end;
function _DeleteFile(const FileName: String): Boolean;
begin
Result := SysUtils.DeleteFile(FileName);
end;
function _ExtractFileExt(const FileName: String): String;
begin
Result := SysUtils.ExtractFileExt(FileName);
end;
function _DateTimeToStr(const DateTime: TDateTime): String;
begin
Result := SysUtils.DateTimeToStr(DateTime);
end;
procedure _DecodeDate(Date: TDateTime; var Year, Month, Day: Word);
begin
SysUtils.DecodeDate(Date, Year, Month, Day);
end;
procedure _DecodeTime(Time: TDateTime; var Hour, Min, Sec, MSec: Word);
begin
SysUtils.DecodeTime(Time, Hour, Min, Sec, MSec);
end;
function _EncodeTime(Hour, Min, Sec, MSec: Word): TDateTime;
begin
Result := SysUtils.EncodeTime(Hour, Min, Sec, MSec);
end;
function _StrToDateTime(const S: String): TDateTime;
begin
Result := SysUtils.StrToDateTime(S);
end;
function _StrToDateTime(const S: String; const FormatSettings: TFormatSettings): TDateTime;
begin
Result := SysUtils.StrToDateTime(S, FormatSettings);
end;
function _DirectoryExists(const Name: String): Boolean;
begin
Result := SysUtils.DirectoryExists(Name);
end;
function _IncludeTrailingPathDelimiter(const S: String): String;
begin
Result := SysUtils.IncludeTrailingPathDelimiter(S);
end;
function _ExcludeTrailingPathDelimiter(const S: String): String;
begin
Result := SysUtils.ExcludeTrailingPathDelimiter(S);
end;
function _Now: TDateTime;
begin
Result := SysUtils.Now;
end;
function _Format(const Fmt: String; const Args: array of const): String;
begin
Result := SysUtils.Format(Fmt, Args);
end;
function _FindFirst(const Path: String; Attr: Integer; var F: TSearchRec): Integer;
begin
Result := SysUtils.FindFirst(Path, Attr, F);
end;
function _FindNext(var F: TSearchRec): Integer;
begin
Result := SysUtils.FindNext(F);
end;
procedure _FindClose(var F: TSearchRec);
begin
SysUtils.FindClose(F);
end;
function _FileDateToDateTime(FileDate: Integer): TDateTime;
begin
Result := SysUtils.FileDateToDateTime(FileDate);
end;
function _ExtractFilePath(const FileName: String): String;
begin
Result := SysUtils.ExtractFilePath(FileName);
end;
function _Date : TDateTime;
begin
Result := SysUtils.Date;
end;
function _IntToHex(Value: Integer; Digits: Integer): String;
begin
Result := SysUtils.IntToHex(Value, Digits);
end;
function _IntToHex(Value: Int64; Digits: Integer): String;
begin
Result := SysUtils.IntToHex(Value, Digits);
end;
{$IFDEF COMPILER16_UP}
function _IntToHex(Value: UInt64; Digits: Integer): String;
begin
Result := SysUtils.IntToHex(Value, Digits);
end;
{$ENDIF}
function _FloatToStr(Value: Extended): String;
begin
Result := SysUtils.FloatToStr(Value);
end;
{$IFDEF MSWINDOWS}
function _GetTimeZoneInformation(var lpTimeZoneInformation: TTimeZoneInformation): DWORD;
begin
Result := Windows.GetTimeZoneInformation(lpTimeZoneInformation);
end;
function _GetWindowLong(H: HWND; nIndex: Integer): Longint;
begin
Result := Windows.GetWindowLong(H, nIndex);
end;
function _DefWindowProc(H: HWND; Msg: UINT; ParamW: WPARAM; ParamL: LPARAM): LRESULT;
begin
Result := Windows.DefWindowProc(H, Msg, ParamW, ParamL);
end;
function _GetCurrentThreadId: DWORD;
begin
Result := Windows.GetCurrentThreadId;
end;
function _GetMessage(
var lpMsg: TMsg; H: HWND;
wMsgFilterMin, wMsgFilterMax: UINT): BOOL;
begin
Result := Windows.GetMessage(lpMsg, H, wMsgFilterMin, wMsgFilterMax);
end;
function _TranslateMessage(const lpMsg: TMsg): BOOL;
begin
Result := Windows.TranslateMessage(lpMsg);
end;
function _DispatchMessage(const lpMsg: TMsg): LongInt;
begin
Result := Windows.DispatchMessage(lpMsg);
end;
function _PeekMessage(
var lpMsg: TMsg; H: HWND;
wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): BOOL;
begin
Result := Windows.PeekMessage(lpMsg, H,
wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
end;
function _PostMessage(H: HWND; Msg: UINT; ParamW: WPARAM; ParamL: LPARAM): BOOL;
begin
Result := Windows.PostMessage(H, Msg, ParamW, ParamL);
end;
procedure _EnterCriticalSection(var lpCriticalSection: TRTLCriticalSection);
begin
Windows.EnterCriticalSection(lpCriticalSection);
end;
procedure _LeaveCriticalSection(var lpCriticalSection: TRTLCriticalSection);
begin
Windows.LeaveCriticalSection(lpCriticalSection);
end;
procedure _InitializeCriticalSection(var lpCriticalSection: TRTLCriticalSection);
begin
Windows.InitializeCriticalSection(lpCriticalSection);
end;
procedure _DeleteCriticalSection(var lpCriticalSection: TRTLCriticalSection);
begin
Windows.DeleteCriticalSection(lpCriticalSection);
end;
function _GetClassInfo(
hInstance: HINST; lpClassName: PChar;
var lpWndClass: TWndClass): BOOL;
begin
Result := Windows.GetClassInfo(hInstance, lpClassName, lpWndClass);
end;
function _RegisterClass(const lpWndClass: TWndClass): ATOM; stdcall;
begin
Result := Windows.RegisterClass(lpWndClass);
end;
function _CreateWindowEx(dwExStyle: DWORD; lpClassName: PChar;
lpWindowName: PChar; dwStyle: DWORD; X, Y, nWidth, nHeight: Integer;
hWndParent: HWND; h_Menu: HMENU; hInstance: HINST; lpParam: Pointer): HWND;
begin
Result := Windows.CreateWindowEx(dwExStyle, lpClassName,
lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWndParent, h_Menu, hInstance,
lpParam);
end;
function _DestroyWindow(H: HWND): BOOL;
begin
Result := Windows.DestroyWindow(H);
end;
function _SetWindowLong(H: HWND; nIndex: Integer; dwNewLong: Longint): LongInt;
begin
Result := Windows.SetWindowLong(H, nIndex, dwNewLong);
end;
function _UnregisterClass(lpClassName: PChar; hInstance: HINST): BOOL;
begin
Result := Windows.UnregisterClass(lpClassName, hInstance);
end;
function _FreeLibrary(hLibModule: HMODULE): BOOL;
begin
Result := Windows.FreeLibrary(hLibModule);
end;
function _LoadLibrary(lpLibFileName: PChar): HMODULE;
begin
Result := Windows.LoadLibrary(lpLibFileName);
end;
function _GetProcAddress(hModule: HMODULE; lpProcName: LPCSTR): FARPROC;
begin
Result := Windows.GetProcAddress(hModule, lpProcName);
end;
function _GetTickCount: DWORD;
begin
Result := Windows.GetTickCount;
end;
procedure _Sleep(dwMilliseconds: DWORD);
begin
Windows.Sleep(dwMilliseconds);
end;
function _GetACP: Cardinal; stdcall;
begin
Result := Windows.GetACP;
end;
{$ENDIF}
{$IFNDEF NOFORMS}
function Application : TApplication;
begin
Result := Forms.Application;
end;
{$ENDIF}
{$ENDIF no CLR}
function MakeWord(a, b: Byte): Word;
begin
Result := A or B shl 8;
end;
function MakeLong(a, b: Word): Longint;
begin
Result := A or B shl 16;
end;
function HiWord(L: DWORD): Word;
begin
Result := L shr 16;
end;
end.
|
unit Unit_Persistencia;
interface
uses Unit_DM, Vcl.Dialogs, System.SysUtils, System.Variants;
// Definicoes do Cliente
Type
Dados_Cliente = Record //struct
Cli_Codigo : Integer;
Cli_Nome : String;
Cli_Endereco : String;
Cli_CPF : String;
Cli_Telefone : String;
Cli_Email : String;
Cli_Sexo : Integer;
Cli_EstadoCivil: Integer;
Cli_DataNascimento: String;
End;
Clientes_Cadastrados = Array of Dados_Cliente;
Procedure Grava_Dados_Cliente(Dados_Form : Dados_Cliente;Alterando:Boolean);
Procedure Remove_Cliente(Codigo : Integer);
Function Retorna_Proximo_Codigo:String;
Function Retorna_Dados_Cliente(Codigo : Integer) : Dados_Cliente;
Function Retorna_Clientes_Cadastrados(Condicao:String) : Clientes_Cadastrados;
// Definicoes do Supermercado
Type
Dados_Supermercado = Record
Sup_NomeFantasia : String;
Sup_RazaoSocial : String;
Sup_InscricaoEstadual : String;
Sup_CNPJ : String;
Sup_Endereco : String;
Sup_Lucro : String;
Sup_Telefone : String;
Sup_Email : String;
Sup_NomeResponsavel : String;
Sup_TelefoneResponsavel : String;
End;
Procedure Grava_Dados_Supermercado(Dados_Form : Dados_Supermercado);
Function Recupera_Dados_Supermercado: Dados_Supermercado;
// Definicoes do Produto
Type
Dados_Produto = Record
Prod_Codigo : Integer;
Prod_Descricao : String;
Prod_Estoque : Integer;
Prod_EstoqueMinimo : Integer;
Prod_PrecoCusto : String;
Prod_PrecoVenda : String;
End;
Produtos_Cadastrados = Array of Dados_Produto;
Function Retorna_Proximo_Codigo_Produto : String;
Procedure Grava_Dados_Produto(Dados_Form : Dados_Produto; Alterando:Boolean);
Function Retorna_Produtos_Cadastrados(Condicao:String) : Produtos_Cadastrados;
Function Retorna_Dados_Produto(Codigo : Integer) : Dados_Produto;
Procedure Remove_Produto(Codigo : Integer);
// Definicoes do Fornecedor
Type
Dados_Fornecedor = Record
For_Codigo : Integer;
For_NomeFantasia : String;
For_RazaoSocial : String;
For_InscricaoEstadual: String;
For_CNPJ : String;
For_Endereco : String;
For_Telefone : String;
For_Email: String;
End;
Fornecedores_Cadastrados = Array of Dados_Fornecedor;
Function Retorna_Proximo_Codigo_Fornecedor : String;
Procedure Grava_Dados_Fornecedor(Dados_Form : Dados_Fornecedor; Alterando:Boolean);
Function Retorna_Fornecedores_Cadastrados(Condicao:String) : Fornecedores_Cadastrados;
Function Retorna_Dados_Fornecedor(Codigo : Integer) : Dados_Fornecedor;
Procedure Remove_Fornecedor(Codigo : Integer);
// Definicoes do Caixa
Type
Dados_Transacao = Record //struct
Cai_Codigo : Integer;
Cai_Descricao : String;
Cai_Valor : String;
Cai_Data : String;
Cai_CodigoNota : Integer;
End;
Transacoes_Realizadas = Array of Dados_Transacao;
Function Retorna_Transacoes_Realizadas(Condicao:String) : Transacoes_Realizadas;
Function Retorna_Proximo_Codigo_Transacao : String;
Procedure Grava_Dados_Transacao(Dados_Form : Dados_Transacao);
// Definicoes de Contas a Receber
Type
Dados_ContasReceber = Record //struct
Cr_Codigo : Integer;
Cr_CodigoCliente : Integer;
Cr_Descricao : String;
Cr_Valor : String;
Cr_Data : String;
Cr_CodigoNota : Integer;
End;
Contas_Receber = Array of Dados_ContasReceber;
Function Retorna_Proximo_Codigo_ContaReceber : String;
Function Retorna_Contas_Receber(Condicao:String) : Contas_Receber;
Procedure Grava_Dados_ContaReceber(Dados_Form : Dados_ContasReceber);
// Definicoes de Contas a Pagar
Type
Dados_ContasPagar = Record //struct
Cp_Codigo : Integer;
Cp_CodigoFornecedor : Integer;
Cp_Descricao : String;
Cp_Valor : String;
Cp_Data : String;
Cp_CodigoNota : Integer;
End;
Contas_Pagar = Array of Dados_ContasPagar;
Function Retorna_Proximo_Codigo_ContaPagar : String;
Function Retorna_Contas_Pagar(Condicao:String) : Contas_Pagar;
Procedure Grava_Dados_ContaPagar(Dados_Form : Dados_ContasPagar);
// Definicoes Nota Venda
Type
Dados_NotaVenda = Record
Nv_Codigo : Integer;
Nv_CodigoCliente : Integer;
Nv_ProdutosVendidos : String;
Nv_Data : String;
Nv_ValorTotal: String;
End;
Notas_Venda = Array of Dados_NotaVenda;
Function Retorna_Proximo_Codigo_NotaVenda : String;
Function Retorna_NotasVenda(Condicao:String) : Notas_Venda;
Function Retorna_NotaVenda(Codigo:Integer): Dados_NotaVenda;
Procedure Grava_Dados_NotaVenda(Dados_Form : Dados_NotaVenda);
// Definicoes Nota Compra
Type
Dados_NotaCompra = Record
Nc_Codigo : Integer;
Nc_CodigoFornecedor : Integer;
Nc_ProdutosComprados : String;
Nc_Data : String;
Nc_ValorTotal: String;
Nc_Frete : String;
Nc_Imposto : String;
End;
Notas_Compra = Array of Dados_NotaCompra;
Function Retorna_Proximo_Codigo_NotaCompra : String;
Function Retorna_NotasCompra(Condicao:String) : Notas_Compra;
Function Retorna_NotaCompra(Codigo:Integer): Dados_NotaCompra;
Procedure Grava_Dados_NotaCompra(Dados_Form : Dados_NotaCompra);
//Outras
Procedure Commit;
implementation
Procedure Commit;
Begin
With DM.qryCommit Do
Begin
Close;
SQL.Clear;
SQL.Add('Commit');
Open;
Close;
End;
End;
// Funcoes do Cliente
Function Retorna_Proximo_Codigo:String;
Begin
With DM.qryAux Do
Begin
SQL.Clear;
SQL.Add('Select First 1 Cli_Codigo');
SQL.Add('From Cliente');
SQL.Add('Order By Cli_Codigo Desc');
Open;
FetchAll;
if ((DM.qryAux.RecordCount > 0) And (DM.qryAux['Cli_Codigo'] <> Null))
then Begin
Result := IntToStr(DM.qryAux['Cli_Codigo'] + 1);
End
Else Begin
Result := '1';
End;
End;
End;
Function Retorna_Clientes_Cadastrados(Condicao:String) : Clientes_Cadastrados;
Var
I : Integer;
Begin
With DM.qryCliente Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From Cliente');
SQL.Add(Condicao);
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryCliente.RecordCount > 0
then Begin
for I := 1 to DM.qryCliente.RecordCount Do
Begin
SetLength(Result,Length(Result)+1);
if DM.qryCliente['Cli_Codigo'] <> Null
then Result[I-1].Cli_Codigo := DM.qryCliente['Cli_Codigo']
else Result[I-1].Cli_Codigo := -1;
if DM.qryCliente['Cli_Nome'] <> Null
then Result[I-1].Cli_Nome := DM.qryCliente['Cli_Nome']
else Result[I-1].Cli_Nome := '';
if DM.qryCliente['Cli_Endereco'] <> Null
then Result[I-1].Cli_Endereco := DM.qryCliente['Cli_Endereco']
else Result[I-1].Cli_Endereco := '';
if DM.qryCliente['Cli_CPF'] <> Null
then Result[I-1].Cli_CPF := DM.qryCliente['Cli_CPF']
else Result[I-1].Cli_CPF := '';
if DM.qryCliente['Cli_Telefone'] <> Null
then Result[I-1].Cli_Telefone := DM.qryCliente['Cli_Telefone']
else Result[I-1].Cli_Telefone := '';
if DM.qryCliente['Cli_Email'] <> Null
then Result[I-1].Cli_Email := DM.qryCliente['Cli_Email']
else Result[I-1].Cli_Email := '';
if DM.qryCliente['Cli_Sexo'] <> Null
then Result[I-1].Cli_Sexo := DM.qryCliente['Cli_Sexo']
else Result[I-1].Cli_Sexo := -1;
if DM.qryCliente['Cli_EstadoCivil'] <> Null
then Result[I-1].Cli_EstadoCivil := DM.qryCliente['Cli_EstadoCivil']
else Result[I-1].Cli_EstadoCivil := -1;
if DM.qryCliente['Cli_DataNascimento'] <> Null
then Result[I-1].Cli_DataNascimento := DM.qryCliente['Cli_DataNascimento']
else Result[I-1].Cli_DataNascimento := '';
Next;
End;
End;
End;
End;
Procedure Grava_Dados_Cliente(Dados_Form : Dados_Cliente; Alterando:Boolean);
Begin
if Not(Alterando)
then Begin
With DM.qryCliente Do
Begin
Close;
SQL.Clear;
SQL.Add('Insert Into Cliente Values(');
SQL.Add(IntToStr(Dados_Form.Cli_Codigo)+',');
SQL.Add(QuotedStr(Dados_Form.Cli_Nome)+',');
SQL.Add(QuotedStr(Dados_Form.Cli_Endereco)+',');
SQL.Add(QuotedStr(Dados_Form.Cli_CPF)+',');
SQL.Add(QuotedStr(Dados_Form.Cli_Telefone)+',');
SQL.Add(QuotedStr(Dados_Form.Cli_Email)+',');
SQL.Add(IntToStr(Dados_Form.Cli_Sexo)+',');
SQL.Add(IntToStr(Dados_Form.Cli_EstadoCivil)+',');
SQL.Add(QuotedStr(Dados_Form.Cli_DataNascimento)+')');
//ShowMessage(SQL.Text);
ExecSQL;
Commit;
End;
End
Else Begin
With DM.qryCliente Do
Begin
Close;
SQL.Clear;
SQL.Add('Update Cliente Set');
SQL.Add('Cli_Nome = '+QuotedStr(Dados_Form.Cli_Nome)+',');
SQL.Add('Cli_Endereco = '+QuotedStr(Dados_Form.Cli_Endereco)+',');
SQL.Add('Cli_CPF = '+QuotedStr(Dados_Form.Cli_CPF)+',');
SQL.Add('Cli_Telefone = '+QuotedStr(Dados_Form.Cli_Telefone)+',');
SQL.Add('Cli_Email = '+QuotedStr(Dados_Form.Cli_Email)+',');
SQL.Add('Cli_Sexo = '+IntToStr(Dados_Form.Cli_Sexo)+',');
SQL.Add('Cli_EstadoCivil = '+IntToStr(Dados_Form.Cli_EstadoCivil)+',');
SQL.Add('Cli_DataNascimento = '+QuotedStr(Dados_Form.Cli_DataNascimento));
SQL.Add('Where Cli_Codigo = '+IntToStr(Dados_Form.Cli_Codigo));
ExecSQL;
Commit;
End;
End;
End;
Procedure Remove_Cliente(Codigo : Integer);
Begin
With DM.qryCliente Do
Begin
Close;
SQL.Clear;
SQL.Add('Delete From Cliente ');
SQL.Add('Where Cli_Codigo = '+IntToStr(Codigo));
ExecSQL;
Commit;
End;
End;
Function Retorna_Dados_Cliente(Codigo : Integer) : Dados_Cliente;
Var
I : Integer;
Begin
With DM.qryCliente Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From Cliente');
SQL.Add('Where Cli_Codigo = '+IntToStr(Codigo));
// ExecSQL;
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryCliente.RecordCount > 0
then Begin
for I := 1 to DM.qryCliente.RecordCount Do
Begin
if DM.qryCliente['Cli_Codigo'] <> Null
then Result.Cli_Codigo := DM.qryCliente['Cli_Codigo']
else Result.Cli_Codigo := -1;
if DM.qryCliente['Cli_Nome'] <> Null
then Result.Cli_Nome := DM.qryCliente['Cli_Nome']
else Result.Cli_Nome := '';
if DM.qryCliente['Cli_Endereco'] <> Null
then Result.Cli_Endereco := DM.qryCliente['Cli_Endereco']
else Result.Cli_Endereco := '';
if DM.qryCliente['Cli_CPF'] <> Null
then Result.Cli_CPF := DM.qryCliente['Cli_CPF']
else Result.Cli_CPF := '';
if DM.qryCliente['Cli_Telefone'] <> Null
then Result.Cli_Telefone := DM.qryCliente['Cli_Telefone']
else Result.Cli_Telefone := '';
if DM.qryCliente['Cli_Email'] <> Null
then Result.Cli_Email := DM.qryCliente['Cli_Email']
else Result.Cli_Email := '';
if DM.qryCliente['Cli_Sexo'] <> Null
then Result.Cli_Sexo := DM.qryCliente['Cli_Sexo']
else Result.Cli_Sexo := -1;
if DM.qryCliente['Cli_EstadoCivil'] <> Null
then Result.Cli_EstadoCivil := DM.qryCliente['Cli_EstadoCivil']
else Result.Cli_EstadoCivil := -1;
if DM.qryCliente['Cli_DataNascimento'] <> Null
then Result.Cli_DataNascimento := DM.qryCliente['Cli_DataNascimento']
else Result.Cli_DataNascimento := '';
Next;
End;
End;
End;
End;
// Funcoes do Supermercado
Procedure Grava_Dados_Supermercado(Dados_Form : Dados_Supermercado);
begin
With DM.qrySupermercado Do
Begin
Close;
SQL.Clear;
SQL.Add('Update Supermercado Set');
SQL.Add('Sup_NomeFantasia = '+QuotedStr(Dados_Form.Sup_NomeFantasia)+',');
SQL.Add('Sup_RazaoSocial = '+QuotedStr(Dados_Form.Sup_RazaoSocial)+',');
SQL.Add('Sup_InscricaoEstadual = '+QuotedStr(Dados_Form.Sup_InscricaoEstadual)+',');
SQL.Add('Sup_CNPJ = '+QuotedStr(Dados_Form.Sup_CNPJ)+',');
SQL.Add('Sup_Endereco = '+QuotedStr(Dados_Form.Sup_Endereco)+',');
SQL.Add('Sup_Lucro = '+QuotedStr(Dados_Form.Sup_Lucro)+',');
SQL.Add('Sup_Telefone = '+QuotedStr(Dados_Form.Sup_Telefone)+',');
SQL.Add('Sup_Email = '+QuotedStr(Dados_Form.Sup_Email)+',');
SQL.Add('Sup_NomeResponsavel = '+QuotedStr(Dados_Form.Sup_NomeResponsavel)+',');
SQL.Add('Sup_TelefoneResponsavel = '+QuotedStr(Dados_Form.Sup_TelefoneResponsavel));
SQL.Add('where Sup_CNPJ = '+QuotedStr(Dados_Form.Sup_CNPJ));
// ShowMessage(SQL.Text);
ExecSQL;
Commit;
End;
end;
Function Recupera_Dados_Supermercado;
begin
With DM.qrySupermercado Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From Supermercado');
// ShowMessage(SQL.Text);
//ExecSQL;
Open;
FetchAll; //garante que todos os resultados vieram pra memória
if DM.qrySupermercado['Sup_NomeFantasia'] <> Null
then Result.Sup_NomeFantasia := DM.qrySupermercado['Sup_NomeFantasia']
else Result.Sup_NomeFantasia := '';
if DM.qrySupermercado['Sup_RazaoSocial'] <> Null
then Result.Sup_RazaoSocial := DM.qrySupermercado['Sup_RazaoSocial']
else Result.Sup_RazaoSocial := '';
if DM.qrySupermercado['Sup_InscricaoEstadual'] <> Null
then Result.Sup_InscricaoEstadual := DM.qrySupermercado['Sup_InscricaoEstadual']
else Result.Sup_InscricaoEstadual := '';
if DM.qrySupermercado['Sup_CNPJ'] <> Null
then Result.Sup_CNPJ := DM.qrySupermercado['Sup_CNPJ']
else Result.Sup_CNPJ := '';
if DM.qrySupermercado['Sup_Endereco'] <> Null
then Result.Sup_Endereco := DM.qrySupermercado['Sup_Endereco']
else Result.Sup_Endereco := '';
if DM.qrySupermercado['Sup_Lucro'] <> Null
then Result.Sup_Lucro := DM.qrySupermercado['Sup_Lucro']
else Result.Sup_Lucro := '';
if DM.qrySupermercado['Sup_Telefone'] <> Null
then Result.Sup_Telefone := DM.qrySupermercado['Sup_Telefone']
else Result.Sup_Telefone := '';
if DM.qrySupermercado['Sup_Email'] <> Null
then Result.Sup_Email := DM.qrySupermercado['Sup_Email']
else Result.Sup_Email := '';
if DM.qrySupermercado['Sup_NomeResponsavel'] <> Null
then Result.Sup_NomeResponsavel := DM.qrySupermercado['Sup_NomeResponsavel']
else Result.Sup_NomeResponsavel := '';
if DM.qrySupermercado['Sup_TelefoneResponsavel'] <> Null
then Result.Sup_TelefoneResponsavel := DM.qrySupermercado['Sup_TelefoneResponsavel']
else Result.Sup_TelefoneResponsavel := '';
End;
end;
// Funcoes Produto
Function Retorna_Proximo_Codigo_Produto:String;
Begin
With DM.qryAux Do
Begin
SQL.Clear;
SQL.Add('Select First 1 Prod_Codigo');
SQL.Add('From Produto');
SQL.Add('Order By Prod_Codigo Desc');
Open;
FetchAll;
if ((DM.qryAux.RecordCount > 0) And (DM.qryAux['Prod_Codigo'] <> Null))
then Begin
Result := IntToStr(DM.qryAux['Prod_Codigo'] + 1);
End
Else Begin
Result := '1';
End;
End;
End;
Procedure Grava_Dados_Produto(Dados_Form : Dados_Produto; Alterando:Boolean);
Begin
if Not(Alterando)
then Begin
With DM.qryProduto Do
Begin
Close;
SQL.Clear;
SQL.Add('Insert Into Produto Values(');
SQL.Add(IntToStr(Dados_Form.Prod_Codigo)+',');
SQL.Add(QuotedStr(Dados_Form.Prod_Descricao)+',');
SQL.Add(IntToStr(Dados_Form.Prod_Estoque)+',');
SQL.Add(IntToStr(Dados_Form.Prod_EstoqueMinimo)+',');
SQL.Add(QuotedStr(Dados_Form.Prod_PrecoCusto)+',');
SQL.Add(QuotedStr(Dados_Form.Prod_PrecoVenda)+')');
ExecSQL;
Commit;
End;
End
Else Begin
With DM.qryProduto Do
Begin
Close;
SQL.Clear;
SQL.Add('Update Produto Set');
SQL.Add('Prod_Descricao = '+QuotedStr(Dados_Form.Prod_Descricao)+',');
SQL.Add('Prod_Estoque = '+IntToStr(Dados_Form.Prod_Estoque)+',');
SQL.Add('Prod_EstoqueMinimo = '+IntToStr(Dados_Form.Prod_EstoqueMinimo)+',');
SQL.Add('Prod_PrecoCusto = '+QuotedStr(Dados_Form.Prod_PrecoCusto)+',');
SQL.Add('Prod_PrecoVenda = '+QuotedStr(Dados_Form.Prod_PrecoVenda));
SQL.Add('Where Prod_Codigo = '+IntToStr(Dados_Form.Prod_Codigo));
ExecSQL;
Commit;
End;
End;
End;
Function Retorna_Produtos_Cadastrados(Condicao:String) : Produtos_Cadastrados;
Var
I : Integer;
Begin
With DM.qryProduto Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From Produto');
SQL.Add(Condicao);
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryProduto.RecordCount > 0
then Begin
for I := 1 to DM.qryProduto.RecordCount Do
Begin
SetLength(Result,Length(Result)+1);
if DM.qryProduto['Prod_Codigo'] <> Null
then Result[I-1].Prod_Codigo := DM.qryProduto['Prod_Codigo']
else Result[I-1].Prod_Codigo := -1;
if DM.qryProduto['Prod_Descricao'] <> Null
then Result[I-1].Prod_Descricao := DM.qryProduto['Prod_Descricao']
else Result[I-1].Prod_Descricao := '';
if DM.qryProduto['Prod_Estoque'] <> Null
then Result[I-1].Prod_Estoque := DM.qryProduto['Prod_Estoque']
else Result[I-1].Prod_Estoque := -1;
if DM.qryProduto['Prod_EstoqueMinimo'] <> Null
then Result[I-1].Prod_EstoqueMinimo := DM.qryProduto['Prod_EstoqueMinimo']
else Result[I-1].Prod_EstoqueMinimo := -1;
if DM.qryProduto['Prod_PrecoCusto'] <> Null
then Result[I-1].Prod_PrecoCusto := DM.qryProduto['Prod_PrecoCusto']
else Result[I-1].Prod_PrecoCusto := '';
if DM.qryProduto['Prod_PrecoVenda'] <> Null
then Result[I-1].Prod_PrecoVenda := DM.qryProduto['Prod_PrecoVenda']
else Result[I-1].Prod_PrecoVenda := '';
Next;
End;
End;
End;
End;
Function Retorna_Dados_Produto(Codigo : Integer) : Dados_Produto;
Var
I : Integer;
Begin
With DM.qryProduto Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From Produto');
SQL.Add('Where Prod_Codigo = '+IntToStr(Codigo));
// ExecSQL;
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryProduto.RecordCount > 0
then Begin
for I := 1 to DM.qryProduto.RecordCount Do
Begin
if DM.qryProduto['Prod_Codigo'] <> Null
then Result.Prod_Codigo := DM.qryProduto['Prod_Codigo']
else Result.Prod_Codigo := -1;
if DM.qryProduto['Prod_Descricao'] <> Null
then Result.Prod_Descricao := DM.qryProduto['Prod_Descricao']
else Result.Prod_Descricao := '';
if DM.qryProduto['Prod_Estoque'] <> Null
then Result.Prod_Estoque := DM.qryProduto['Prod_Estoque']
else Result.Prod_Estoque := -1;
if DM.qryProduto['Prod_EstoqueMinimo'] <> Null
then Result.Prod_EstoqueMinimo := DM.qryProduto['Prod_EstoqueMinimo']
else Result.Prod_EstoqueMinimo := -1;
if DM.qryProduto['Prod_PrecoCusto'] <> Null
then Result.Prod_PrecoCusto := DM.qryProduto['Prod_PrecoCusto']
else Result.Prod_PrecoCusto := '';
if DM.qryProduto['Prod_PrecoVenda'] <> Null
then Result.Prod_PrecoVenda := DM.qryProduto['Prod_PrecoVenda']
else Result.Prod_PrecoVenda := '';
Next;
End;
End;
End;
End;
Procedure Remove_Produto(Codigo : Integer);
Begin
With DM.qryProduto Do
Begin
Close;
SQL.Clear;
SQL.Add('Delete From Produto ');
SQL.Add('Where Prod_Codigo = '+IntToStr(Codigo));
ExecSQL;
Commit;
End;
End;
// Funcoes do Fornecedor
Function Retorna_Proximo_Codigo_Fornecedor:String;
Begin
With DM.qryAux Do
Begin
SQL.Clear;
SQL.Add('Select First 1 For_Codigo');
SQL.Add('From Fornecedor');
SQL.Add('Order By For_Codigo Desc');
Open;
FetchAll;
if ((DM.qryAux.RecordCount > 0) And (DM.qryAux['For_Codigo'] <> Null))
then Begin
Result := IntToStr(DM.qryAux['For_Codigo'] + 1);
End
Else Begin
Result := '1';
End;
End;
End;
Procedure Grava_Dados_Fornecedor(Dados_Form : Dados_Fornecedor; Alterando:Boolean);
Begin
if Not(Alterando)
then Begin
With DM.qryFornecedor Do
Begin
Close;
SQL.Clear;
SQL.Add('Insert Into Fornecedor Values(');
SQL.Add(IntToStr(Dados_Form.For_Codigo)+',');
SQL.Add(QuotedStr(Dados_Form.For_NomeFantasia)+',');
SQL.Add(QuotedStr(Dados_Form.For_RazaoSocial)+',');
SQL.Add(QuotedStr(Dados_Form.For_InscricaoEstadual)+',');
SQL.Add(QuotedStr(Dados_Form.For_CNPJ)+',');
SQL.Add(QuotedStr(Dados_Form.For_Endereco)+',');
SQL.Add(QuotedStr(Dados_Form.For_Telefone)+',');
SQL.Add(QuotedStr(Dados_Form.For_Email)+')');
ExecSQL;
Commit;
End;
End
Else Begin
With DM.qryFornecedor Do
Begin
Close;
SQL.Clear;
SQL.Add('Update Fornecedor Set');
SQL.Add('For_NomeFantasia = '+QuotedStr(Dados_Form.For_NomeFantasia)+',');
SQL.Add('For_RazaoSocial = '+QuotedStr(Dados_Form.For_RazaoSocial)+',');
SQL.Add('For_InscricaoEstadual = '+QuotedStr(Dados_Form.For_InscricaoEstadual)+',');
SQL.Add('For_CNPJ = '+QuotedStr(Dados_Form.For_CNPJ)+',');
SQL.Add('For_Endereco = '+QuotedStr(Dados_Form.For_Endereco)+',');
SQL.Add('For_Telefone = '+QuotedStr(Dados_Form.For_Telefone)+',');
SQL.Add('For_Email = '+QuotedStr(Dados_Form.For_Email));
SQL.Add('Where For_Codigo = '+IntToStr(Dados_Form.For_Codigo));
ExecSQL;
Commit;
End;
End;
End;
Function Retorna_Fornecedores_Cadastrados(Condicao:String) : Fornecedores_Cadastrados;
Var
I : Integer;
Begin
With DM.qryFornecedor Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From Fornecedor');
SQL.Add(Condicao);
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryFornecedor.RecordCount > 0
then Begin
for I := 1 to DM.qryFornecedor.RecordCount Do
Begin
SetLength(Result,Length(Result)+1);
if DM.qryFornecedor['For_Codigo'] <> Null
then Result[I-1].For_Codigo := DM.qryFornecedor['For_Codigo']
else Result[I-1].For_Codigo := -1;
if DM.qryFornecedor['For_NomeFantasia'] <> Null
then Result[I-1].For_NomeFantasia := DM.qryFornecedor['For_NomeFantasia']
else Result[I-1].For_NomeFantasia := '';
if DM.qryFornecedor['For_RazaoSocial'] <> Null
then Result[I-1].For_RazaoSocial := DM.qryFornecedor['For_RazaoSocial']
else Result[I-1].For_RazaoSocial := '';
if DM.qryFornecedor['For_InscricaoEstadual'] <> Null
then Result[I-1].For_InscricaoEstadual := DM.qryFornecedor['For_InscricaoEstadual']
else Result[I-1].For_InscricaoEstadual := '';
if DM.qryFornecedor['For_CNPJ'] <> Null
then Result[I-1].For_CNPJ := DM.qryFornecedor['For_CNPJ']
else Result[I-1].For_CNPJ := '';
if DM.qryFornecedor['For_Endereco'] <> Null
then Result[I-1].For_Endereco := DM.qryFornecedor['For_Endereco']
else Result[I-1].For_Endereco := '';
if DM.qryFornecedor['For_Telefone'] <> Null
then Result[I-1].For_Telefone := DM.qryFornecedor['For_Telefone']
else Result[I-1].For_Telefone := '';
if DM.qryFornecedor['For_Email'] <> Null
then Result[I-1].For_Email := DM.qryFornecedor['For_Email']
else Result[I-1].For_Email := '';
Next;
End;
End;
End;
End;
Function Retorna_Dados_Fornecedor(Codigo : Integer) : Dados_Fornecedor;
Var
I : Integer;
Begin
With DM.qryFornecedor Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From Fornecedor');
SQL.Add('Where For_Codigo = '+IntToStr(Codigo));
// ExecSQL;
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryFornecedor.RecordCount > 0
then Begin
for I := 1 to DM.qryFornecedor.RecordCount Do
Begin
if DM.qryFornecedor['For_Codigo'] <> Null
then Result.For_Codigo := DM.qryFornecedor['For_Codigo']
else Result.For_Codigo := -1;
if DM.qryFornecedor['For_NomeFantasia'] <> Null
then Result.For_NomeFantasia := DM.qryFornecedor['For_NomeFantasia']
else Result.For_NomeFantasia := '';
if DM.qryFornecedor['For_RazaoSocial'] <> Null
then Result.For_RazaoSocial := DM.qryFornecedor['For_RazaoSocial']
else Result.For_RazaoSocial := '';
if DM.qryFornecedor['For_InscricaoEstadual'] <> Null
then Result.For_InscricaoEstadual := DM.qryFornecedor['For_InscricaoEstadual']
else Result.For_InscricaoEstadual := '';
if DM.qryFornecedor['For_CNPJ'] <> Null
then Result.For_CNPJ := DM.qryFornecedor['For_CNPJ']
else Result.For_CNPJ := '';
if DM.qryFornecedor['For_Endereco'] <> Null
then Result.For_Endereco := DM.qryFornecedor['For_Endereco']
else Result.For_Endereco := '';
if DM.qryFornecedor['For_Telefone'] <> Null
then Result.For_Telefone := DM.qryFornecedor['For_Telefone']
else Result.For_Telefone := '';
if DM.qryFornecedor['For_Email'] <> Null
then Result.For_Email := DM.qryFornecedor['For_Email']
else Result.For_Email := '';
Next;
End;
End;
End;
End;
Procedure Remove_Fornecedor(Codigo : Integer);
Begin
With DM.qryFornecedor Do
Begin
Close;
SQL.Clear;
SQL.Add('Delete From Fornecedor ');
SQL.Add('Where For_Codigo = '+IntToStr(Codigo));
ExecSQL;
Commit;
End;
End;
// Funcoes do Caixa
Function Retorna_Transacoes_Realizadas(Condicao:String) : Transacoes_Realizadas;
Var
I : Integer;
Begin
With DM.qryCaixa Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From Caixa');
SQL.Add(Condicao);
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryCaixa.RecordCount > 0
then Begin
for I := 1 to DM.qryCaixa.RecordCount Do
Begin
SetLength(Result,Length(Result)+1);
if DM.qryCaixa['Cai_Codigo'] <> Null
then Result[I-1].Cai_Codigo := DM.qryCaixa['Cai_Codigo']
else Result[I-1].Cai_Codigo := -1;
if DM.qryCaixa['Cai_Descricao'] <> Null
then Result[I-1].Cai_Descricao := DM.qryCaixa['Cai_Descricao']
else Result[I-1].Cai_Descricao := '';
if DM.qryCaixa['Cai_Valor'] <> Null
then Result[I-1].Cai_Valor := DM.qryCaixa['Cai_Valor']
else Result[I-1].Cai_Valor := '';
if DM.qryCaixa['Cai_Data'] <> Null
then Result[I-1].Cai_Data := DM.qryCaixa['Cai_Data']
else Result[I-1].Cai_Data := '';
if DM.qryCaixa['Cai_CodigoNota'] <> Null
then Result[I-1].Cai_CodigoNota := DM.qryCaixa['Cai_CodigoNota']
else Result[I-1].Cai_CodigoNota := -1;
Next;
End;
End;
End;
end;
Function Retorna_Proximo_Codigo_Transacao : String;
begin
With DM.qryAux Do
Begin
SQL.Clear;
SQL.Add('Select First 1 Cai_Codigo');
SQL.Add('From Caixa');
SQL.Add('Order By Cai_Codigo Desc');
Open;
FetchAll;
if ((DM.qryAux.RecordCount > 0) And (DM.qryAux['Cai_Codigo'] <> Null))
then Begin
Result := IntToStr(DM.qryAux['Cai_Codigo'] + 1);
End
Else Begin
Result := '1';
End;
End;
end;
Procedure Grava_Dados_Transacao(Dados_Form : Dados_Transacao);
Begin
With DM.qryCaixa Do
Begin
Close;
SQL.Clear;
SQL.Add('Insert Into Caixa Values(');
SQL.Add(IntToStr(Dados_Form.Cai_Codigo)+',');
SQL.Add(QuotedStr(Dados_Form.Cai_Descricao)+',');
SQL.Add(QuotedStr(Dados_Form.Cai_Valor)+',');
SQL.Add(QuotedStr(Dados_Form.Cai_Data)+',');
SQL.Add(IntToStr(Dados_Form.Cai_CodigoNota)+')');
ExecSQL;
Commit;
End;
End;
// Operacoes Contas a Receber
Function Retorna_Contas_Receber(Condicao:String) : Contas_Receber;
Var
I : Integer;
Begin
With DM.qryContasReceber Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From ContasReceber');
SQL.Add(Condicao);
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryContasReceber.RecordCount > 0
then Begin
for I := 1 to DM.qryContasReceber.RecordCount Do
Begin
SetLength(Result,Length(Result)+1);
if DM.qryContasReceber['Cr_Codigo'] <> Null
then Result[I-1].Cr_Codigo := DM.qryContasReceber['Cr_Codigo']
else Result[I-1].Cr_Codigo := -1;
if DM.qryContasReceber['Cr_CodigoCliente'] <> Null
then Result[I-1].Cr_CodigoCliente := DM.qryContasReceber['Cr_CodigoCliente']
else Result[I-1].Cr_CodigoCliente := -1;
if DM.qryContasReceber['Cr_Descricao'] <> Null
then Result[I-1].Cr_Descricao := DM.qryContasReceber['Cr_Descricao']
else Result[I-1].Cr_Descricao := '';
if DM.qryContasReceber['Cr_Valor'] <> Null
then Result[I-1].Cr_Valor := DM.qryContasReceber['Cr_Valor']
else Result[I-1].Cr_Valor := '';
if DM.qryContasReceber['Cr_Data'] <> Null
then Result[I-1].Cr_Data := DM.qryContasReceber['Cr_Data']
else Result[I-1].Cr_Data := '';
if DM.qryContasReceber['Cr_CodigoNota'] <> Null
then Result[I-1].Cr_CodigoNota := DM.qryContasReceber['Cr_CodigoNota']
else Result[I-1].Cr_CodigoNota := -1;
Next;
End;
End;
End;
end;
Function Retorna_Proximo_Codigo_ContaReceber : String;
begin
With DM.qryAux Do
Begin
SQL.Clear;
SQL.Add('Select First 1 Cr_Codigo');
SQL.Add('From ContasReceber');
SQL.Add('Order By Cr_Codigo Desc');
Open;
FetchAll;
if ((DM.qryAux.RecordCount > 0) And (DM.qryAux['Cr_Codigo'] <> Null))
then Begin
Result := IntToStr(DM.qryAux['Cr_Codigo'] + 1);
End
Else Begin
Result := '1';
End;
End;
end;
Procedure Grava_Dados_ContaReceber(Dados_Form : Dados_ContasReceber);
Begin
With DM.qryContasReceber Do
Begin
Close;
SQL.Clear;
SQL.Add('Insert Into ContasReceber Values(');
SQL.Add(IntToStr(Dados_Form.Cr_Codigo)+',');
SQL.Add(IntToStr(Dados_Form.Cr_CodigoCliente)+',');
SQL.Add(QuotedStr(Dados_Form.Cr_Descricao)+',');
SQL.Add(QuotedStr(Dados_Form.Cr_Valor)+',');
SQL.Add(QuotedStr(Dados_Form.Cr_Data)+',');
SQL.Add(IntToStr(Dados_Form.Cr_CodigoNota)+')');
ExecSQL;
Commit;
End;
End;
// Operacoes Contas a Pagar
Function Retorna_Contas_Pagar(Condicao:String) : Contas_Pagar;
Var
I : Integer;
Begin
With DM.qryContasPagar Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From ContasPagar');
SQL.Add(Condicao);
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryContasPagar.RecordCount > 0
then Begin
for I := 1 to DM.qryContasPagar.RecordCount Do
Begin
SetLength(Result,Length(Result)+1);
if DM.qryContasPagar['Cp_Codigo'] <> Null
then Result[I-1].Cp_Codigo := DM.qryContasPagar['Cp_Codigo']
else Result[I-1].Cp_Codigo := -1;
if DM.qryContasPagar['Cp_CodigoFornecedor'] <> Null
then Result[I-1].Cp_CodigoFornecedor := DM.qryContasPagar['Cp_CodigoFornecedor']
else Result[I-1].Cp_CodigoFornecedor := -1;
if DM.qryContasPagar['Cp_Descricao'] <> Null
then Result[I-1].Cp_Descricao := DM.qryContasPagar['Cp_Descricao']
else Result[I-1].Cp_Descricao := '';
if DM.qryContasPagar['Cp_Valor'] <> Null
then Result[I-1].Cp_Valor := DM.qryContasPagar['Cp_Valor']
else Result[I-1].Cp_Valor := '';
if DM.qryContasPagar['Cp_Data'] <> Null
then Result[I-1].Cp_Data := DM.qryContasPagar['Cp_Data']
else Result[I-1].Cp_Data := '';
if DM.qryContasPagar['Cp_CodigoNota'] <> Null
then Result[I-1].Cp_CodigoNota := DM.qryContasPagar['Cp_CodigoNota']
else Result[I-1].Cp_CodigoNota := -1;
Next;
End;
End;
End;
end;
Function Retorna_Proximo_Codigo_ContaPagar : String;
begin
With DM.qryAux Do
Begin
SQL.Clear;
SQL.Add('Select First 1 Cp_Codigo');
SQL.Add('From ContasPagar');
SQL.Add('Order By Cp_Codigo Desc');
Open;
FetchAll;
if ((DM.qryAux.RecordCount > 0) And (DM.qryAux['Cp_Codigo'] <> Null))
then Begin
Result := IntToStr(DM.qryAux['Cp_Codigo'] + 1);
End
Else Begin
Result := '1';
End;
End;
end;
Procedure Grava_Dados_ContaPagar(Dados_Form : Dados_ContasPagar);
Begin
With DM.qryContasPagar Do
Begin
Close;
SQL.Clear;
SQL.Add('Insert Into ContasPagar Values(');
SQL.Add(IntToStr(Dados_Form.Cp_Codigo)+',');
SQL.Add(IntToStr(Dados_Form.Cp_CodigoFornecedor)+',');
SQL.Add(QuotedStr(Dados_Form.Cp_Descricao)+',');
SQL.Add(QuotedStr(Dados_Form.Cp_Valor)+',');
SQL.Add(QuotedStr(Dados_Form.Cp_Data)+',');
SQL.Add(IntToStr(Dados_Form.Cp_CodigoNota)+')');
ExecSQL;
Commit;
End;
End;
// Funcoes Nota Fiscal
Function Retorna_Proximo_Codigo_NotaVenda : String;
begin
With DM.qryAux Do
Begin
SQL.Clear;
SQL.Add('Select First 1 Nv_Codigo');
SQL.Add('From NotaVenda');
SQL.Add('Order By Nv_Codigo Desc');
Open;
FetchAll;
if ((DM.qryAux.RecordCount > 0) And (DM.qryAux['Nv_Codigo'] <> Null))
then Begin
Result := IntToStr(DM.qryAux['Nv_Codigo'] + 1);
End
Else Begin
Result := '1';
End;
End;
end;
Function Retorna_NotasVenda(Condicao:String) : Notas_Venda;
begin
end;
Function Retorna_NotaVenda(Codigo:Integer): Dados_NotaVenda;
Var
I : Integer;
Begin
With DM.qryNotaVenda Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From NotaVenda');
SQL.Add('Where Nv_Codigo = '+IntToStr(Codigo));
// ExecSQL;
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryNotaVenda.RecordCount > 0
then Begin
for I := 1 to DM.qryNotaVenda.RecordCount Do
Begin
if DM.qryNotaVenda['Nv_Codigo'] <> Null
then Result.Nv_Codigo := DM.qryNotaVenda['Nv_Codigo']
else Result.Nv_Codigo := -1;
if DM.qryNotaVenda['Nv_CodigoCliente'] <> Null
then Result.Nv_CodigoCliente := DM.qryNotaVenda['Nv_CodigoCliente']
else Result.Nv_CodigoCliente := -1;
if DM.qryNotaVenda['Nv_ProdutosVendidos'] <> Null
then Result.Nv_ProdutosVendidos := DM.qryNotaVenda['Nv_ProdutosVendidos']
else Result.Nv_ProdutosVendidos := '';
if DM.qryNotaVenda['Nv_Data'] <> Null
then Result.Nv_Data := DM.qryNotaVenda['Nv_Data']
else Result.Nv_Data := '';
if DM.qryNotaVenda['Nv_ValorTotal'] <> Null
then Result.Nv_ValorTotal := DM.qryNotaVenda['Nv_ValorTotal']
else Result.Nv_ValorTotal := '';
Next;
End;
End;
End;
end;
Procedure Grava_Dados_NotaVenda(Dados_Form : Dados_NotaVenda);
begin
With DM.qryNotaVenda Do
Begin
Close;
SQL.Clear;
SQL.Add('Insert Into NotaVenda Values(');
SQL.Add(IntToStr(Dados_Form.Nv_Codigo)+',');
SQL.Add(IntToStr(Dados_Form.Nv_CodigoCliente)+',');
SQL.Add(QuotedStr(Dados_Form.Nv_ProdutosVendidos)+',');
SQL.Add(QuotedStr(Dados_Form.Nv_Data)+',');
SQL.Add(QuotedStr(Dados_Form.Nv_ValorTotal)+')');
ExecSQL;
Commit;
End;
end;
Function Retorna_Proximo_Codigo_NotaCompra : String;
begin
With DM.qryAux Do
Begin
SQL.Clear;
SQL.Add('Select First 1 Nc_Codigo');
SQL.Add('From NotaCompra');
SQL.Add('Order By Nc_Codigo Desc');
Open;
FetchAll;
if ((DM.qryAux.RecordCount > 0) And (DM.qryAux['Nc_Codigo'] <> Null))
then Begin
Result := IntToStr(DM.qryAux['Nc_Codigo'] + 1);
End
Else Begin
Result := '1';
End;
End;
end;
Function Retorna_NotasCompra(Condicao:String) : Notas_Compra;
begin
end;
Function Retorna_NotaCompra(Codigo:Integer): Dados_NotaCompra;
Var
I : Integer;
begin
With DM.qryNotaCompra Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * From NotaCompra');
SQL.Add('Where Nc_Codigo = '+IntToStr(Codigo));
// ExecSQL;
Open;
FetchAll; //garante que todos os resultados vieram pra memória
First;
if DM.qryNotaCompra.RecordCount > 0
then Begin
for I := 1 to DM.qryNotaCompra.RecordCount Do
Begin
if DM.qryNotaCompra['Nc_Codigo'] <> Null
then Result.Nc_Codigo := DM.qryNotaCompra['Nc_Codigo']
else Result.Nc_Codigo := -1;
if DM.qryNotaCompra['Nc_CodigoFornecedor'] <> Null
then Result.Nc_CodigoFornecedor := DM.qryNotaCompra['Nc_CodigoFornecedor']
else Result.Nc_CodigoFornecedor := -1;
if DM.qryNotaCompra['Nc_ProdutosComprados'] <> Null
then Result.Nc_ProdutosComprados := DM.qryNotaCompra['Nc_ProdutosComprados']
else Result.Nc_ProdutosComprados := '';
if DM.qryNotaCompra['Nc_Data'] <> Null
then Result.Nc_Data := DM.qryNotaCompra['Nc_Data']
else Result.Nc_Data := '';
if DM.qryNotaCompra['Nc_ValorTotal'] <> Null
then Result.Nc_ValorTotal := DM.qryNotaCompra['Nc_ValorTotal']
else Result.Nc_ValorTotal := '';
if DM.qryNotaCompra['Nc_Frete'] <> Null
then Result.Nc_Frete := DM.qryNotaCompra['Nc_Frete']
else Result.Nc_Frete := '';
if DM.qryNotaCompra['Nc_Imposto'] <> Null
then Result.Nc_Imposto := DM.qryNotaCompra['Nc_Imposto']
else Result.Nc_Imposto := '';
Next;
End;
End;
End;
end;
Procedure Grava_Dados_NotaCompra(Dados_Form : Dados_NotaCompra);
begin
With DM.qryNotaCompra Do
Begin
Close;
SQL.Clear;
SQL.Add('Insert Into NotaCompra Values(');
SQL.Add(IntToStr(Dados_Form.Nc_Codigo)+',');
SQL.Add(IntToStr(Dados_Form.Nc_CodigoFornecedor)+',');
SQL.Add(QuotedStr(Dados_Form.Nc_ProdutosComprados)+',');
SQL.Add(QuotedStr(Dados_Form.Nc_Data)+',');
SQL.Add(QuotedStr(Dados_Form.Nc_ValorTotal)+',');
SQL.Add(QuotedStr(Dados_Form.Nc_Frete)+',');
SQL.Add(QuotedStr(Dados_Form.Nc_Imposto)+')');
ExecSQL;
Commit;
End;
end;
end.
|
unit EmailOrdering.Views.ErrorForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Grids,
Vcl.ExtCtrls;
type
TErrorDForm = class(TForm)
StringGrid1: TStringGrid;
Button1: TButton;
RichEdit1: TRichEdit;
Panel1: TPanel;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure CreateParams(var Params: TCreateParams); override;
procedure SetErrors(errors: string);
end;
var
ErrorDForm: TErrorDForm;
implementation
{$R *.dfm}
procedure TErrorDForm.Button1Click(Sender: TObject);
begin
self.Close;
end;
procedure TErrorDForm.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
Params.WndParent := 0;
end;
procedure TErrorDForm.FormCreate(Sender: TObject);
var
LIcon:TIcon;
begin
LIcon:= TIcon.Create;
try
LIcon.LoadFromFile('symbol.ico');
StringGrid1.ColCount := 2;
StringGrid1.RowCount := 1;
StringGrid1.ColWidths[1]:= 540;
StringGrid1.Cells[0,0]:= 'Id';
StringGrid1.Cells[1,0]:= 'Error';
self.Icon:= LIcon;
FormStyle:= fsStayOnTop;
self.Constraints.MinHeight := 400;
self.Constraints.MinWidth := 600;
finally
LIcon.Free;
end;
end;
procedure TErrorDForm.SetErrors(errors: string);
var
LStringList: TStringList;
I: Integer;
begin
LStringList := TStringList.Create;
LStringList.Text:= Errors;
try;
self.RichEdit1.Text := format('Error sending email to WDDC due to the following errors:',[]);
for I := 0 to LStringList.Count -1 do
begin
StringGrid1.Cells[0, I + 1] := inttostr(I + 1);
StringGrid1.Cells[1, I + 1] := LStringList[I];
StringGrid1.RowCount := I + 2;
StringGrid1.Row := I + 1;
end;
finally
LStringList.Free;
end;
end;
end.
|
unit uSuporte;
interface
uses uWindows, IdHTTP, Vcl.Forms, System.SysUtils, Vcl.Dialogs;
function getAutorizacaoSuporte(): string;
function getSenhaSuporte(): string;
function fecharAplicacaoSuporte(): Boolean;
function enviarRequisicaoSuporte(codcliente, acesso,
autorizacao: string): Boolean;
implementation
uses uConstantes;
const
NOME_APP_SUPORTE = 'TeamViewer';
function getAutorizacaoSuporte(): string;
begin
Result := getOtherWindowText(NOME_APP_SUPORTE, 'Edit');
end;
function getSenhaSuporte(): string;
begin
Result := getOtherWindowText(NOME_APP_SUPORTE, 'ComboBox');
end;
function fecharAplicacaoSuporte(): Boolean;
begin
terminarProcesso('sp.exe')
end;
function enviarRequisicaoSuporte(codcliente, acesso,
autorizacao: string): Boolean;
const
GET = '?ID_CLIENTE=%s&ACESSO=%s&AUTORIZACAO=%s';
RETORNO = 'OK';
var
httpRetorno: TidHttp;
begin
httpRetorno := TidHttp.Create(Application);
try
acesso := StringReplace(acesso, ' ', '-', [rfReplaceAll]);
Result := httpRetorno.GET(RADIUS_WEB_SERVICE_SUPORTE + Format(GET,
[codcliente, acesso, autorizacao])) = RETORNO;
finally
FreeAndNil(httpRetorno);
end;
end;
end.
|
unit CadastroPessoaForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uPessoa;
type
TfrmCadastroPessoaForm = class(TForm)
edtId: TEdit;
lblId: TLabel;
edtNome: TEdit;
lblNome: TLabel;
lblProfissao: TLabel;
edtProfissao: TEdit;
lblNaturalidade: TLabel;
edtNaturalidade: TEdit;
btnGravar: TButton;
btnSair: TButton;
procedure btnSairClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnGravarClick(Sender: TObject);
private
function GetIsIncluir: Boolean;
function GetPessoa: TPessoa;
property IsIncluir: Boolean read GetIsIncluir;
property Pessoa: TPessoa read GetPessoa;
public
procedure CarregaDados(APessoa: TPessoa);
end;
var
frmCadastroPessoaForm: TfrmCadastroPessoaForm;
implementation
{$R *.dfm}
uses uCliente, uMessageBox, uMJD.Messages, uProtocolo, uJSONPessoa,
uConfig;
procedure TfrmCadastroPessoaForm.btnGravarClick(Sender: TObject);
var Cliente: TCLiente<TPessoa>;
Resposta: TProtocoloResposta;
JSONPessoa: TJSONPessoa;
teste: string;
Pes: TPessoa;
begin
if (edtNome.Text = '') then
begin
MessageBox.MessageOk(rsInformeNome);
if edtNome.CanFocus then
edtNome.SetFocus();
Exit;
end;
JSONPessoa := TJSONPessoa.Create;
teste := JSONPessoa.ObjectToJson(Pessoa);
Pes := JSONPessoa.JsonToObject(teste);
try
Cliente := TCLiente<TPessoa>.Create(Config.Host, Config.Porta);
try
try
if (IsIncluir) then
Resposta := Cliente.ExecuteIncluir(JSONPessoa.ObjectToJson(Pessoa))
else
Resposta := Cliente.ExecuteAlterar(JSONPessoa.ObjectToJson(Pessoa));
if (Resposta.Status = spErro) then
MessageBox.MessageError(Resposta.Mensagem)
else
begin
Close;
ModalResult := mrOk;
end;
except
on E: Exception do
MessageBox.MessageError(E.Message);
end;
finally
Cliente.Free();
end;
finally
JSONPessoa.Free;
end;
end;
procedure TfrmCadastroPessoaForm.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure TfrmCadastroPessoaForm.CarregaDados(APessoa: TPessoa);
begin
edtId.Text := IntToStr(APessoa.Id);
edtNome.Text := APessoa.Nome;
edtProfissao.Text := APessoa.Profissao;
edtNaturalidade.Text := APessoa.Naturalidade;
end;
procedure TfrmCadastroPessoaForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
function TfrmCadastroPessoaForm.GetIsIncluir: Boolean;
begin
Result := (edtId.Text = '');
end;
function TfrmCadastroPessoaForm.GetPessoa: TPessoa;
begin
Result := TPessoa.Create();
try
Result.Id := StrToInt(edtId.Text);
except
Result.Id := 0;
end;
Result.Nome := edtNome.Text;
Result.Profissao := edtProfissao.Text;
Result.Naturalidade := edtNaturalidade.Text;
end;
end.
|
unit View.ParametrosPrazosExtratos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore,
dxSkinsDefaultPainters, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, dxDateRanges,
cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error,
FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxMaskEdit, cxImageComboBox,
cxSpinEdit, dxLayoutControlAdapters, Vcl.Menus, System.Actions, Vcl.ActnList, Vcl.StdCtrls, cxButtons,
Control.FinanceiroPrazosExtratos, Common.ENum;
type
Tview_ParametrosPrazosExtratos = class(TForm)
dxLayoutControl1Group_Root: TdxLayoutGroup;
dxLayoutControl1: TdxLayoutControl;
labelTitle: TcxLabel;
dxLayoutItem1: TdxLayoutItem;
dxLayoutGroup1: TdxLayoutGroup;
dxLayoutGroup2: TdxLayoutGroup;
gridParametrosDBTableView1: TcxGridDBTableView;
gridParametrosLevel1: TcxGridLevel;
gridParametros: TcxGrid;
dxLayoutItem2: TdxLayoutItem;
memTableParametros: TFDMemTable;
memTableParametrosid_registro: TIntegerField;
memTableParametroscod_tipo_extrato: TSmallintField;
memTableParametrosnum_quinzena: TSmallintField;
memTableParametrosnum_dia_inicio: TSmallintField;
memTableParametrosnum_dia_final: TSmallintField;
memTableParametrosnum_dia_pagamento: TSmallintField;
memTableParametrosqtd_dias_prazo_pagamento: TSmallintField;
dsParametros: TDataSource;
gridParametrosDBTableView1id_registro: TcxGridDBColumn;
gridParametrosDBTableView1cod_tipo_extrato: TcxGridDBColumn;
gridParametrosDBTableView1num_quinzena: TcxGridDBColumn;
gridParametrosDBTableView1num_dia_inicio: TcxGridDBColumn;
gridParametrosDBTableView1num_dia_final: TcxGridDBColumn;
gridParametrosDBTableView1num_dia_pagamento: TcxGridDBColumn;
gridParametrosDBTableView1qtd_dias_prazo_pagamento: TcxGridDBColumn;
dxLayoutGroup3: TdxLayoutGroup;
cxButton1: TcxButton;
dxLayoutItem3: TdxLayoutItem;
actionListPrametros: TActionList;
actionFechar: TAction;
cxButton2: TcxButton;
dxLayoutItem4: TdxLayoutItem;
procedure actionFecharExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure memTableParametrosBeforeEdit(DataSet: TDataSet);
procedure memTableParametrosBeforeInsert(DataSet: TDataSet);
procedure memTableParametrosBeforeDelete(DataSet: TDataSet);
procedure memTableParametrosAfterPost(DataSet: TDataSet);
procedure cxButton2Click(Sender: TObject);
private
{ Private declarations }
procedure PopulateData;
function IncludeData(): Boolean;
function UpdateData(): Boolean;
function DeleteData(): Boolean;
function ValidateData(): Boolean;
procedure SetupClass();
public
{ Public declarations }
end;
var
view_ParametrosPrazosExtratos: Tview_ParametrosPrazosExtratos;
FPrazos : TFinanceiroPrazosExtratosControl;
FAcao: TAcao;
implementation
{$R *.dfm}
uses Data.SisGeF;
procedure Tview_ParametrosPrazosExtratos.actionFecharExecute(Sender: TObject);
begin
Close;
end;
procedure Tview_ParametrosPrazosExtratos.cxButton2Click(Sender: TObject);
var
aParam: array of variant;
begin
SetLength(aParam,3);
aParam := ['TIPOQUINZENA',2,2];
if FPrazos.Search(aParam) then
begin
FPrazos.SetupSelf(FPrazos.Prazos.Query);
if FPrazos.MountPeriod(2021,5) then
Beep;
end;
end;
function Tview_ParametrosPrazosExtratos.DeleteData: Boolean;
begin
Result := False;
SetupClass();
Result := FPrazos.Save();
end;
procedure Tview_ParametrosPrazosExtratos.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FPrazos.Free;
Action := caFree;
view_ParametrosPrazosExtratos := nil;
end;
procedure Tview_ParametrosPrazosExtratos.FormShow(Sender: TObject);
begin
labelTitle.Caption := Self.Caption;
FPrazos := TFinanceiroPrazosExtratosControl.Create;
PopulateData;
end;
function Tview_ParametrosPrazosExtratos.IncludeData: Boolean;
begin
Result := False;
SetupClass();
if not ValidateData() then
Exit;
Result := FPrazos.Save();
end;
procedure Tview_ParametrosPrazosExtratos.memTableParametrosAfterPost(DataSet: TDataSet);
begin
if memTableParametros.Tag = -1 then
Exit;
if FAcao = tacIncluir then
begin
if not IncludeData then
Abort;
end
else if FAcao = tacAlterar then
begin
if not UpdateData then
Abort;
end
else if FAcao = tacExcluir then
begin
if not DeleteData then
Abort;
end
else
Application.MessageBox('Alteração gravada.', 'Gravar', MB_OK + MB_ICONINFORMATION);
end;
procedure Tview_ParametrosPrazosExtratos.memTableParametrosBeforeDelete(DataSet: TDataSet);
begin
FAcao := tacExcluir;
end;
procedure Tview_ParametrosPrazosExtratos.memTableParametrosBeforeEdit(DataSet: TDataSet);
begin
FAcao := tacAlterar;
end;
procedure Tview_ParametrosPrazosExtratos.memTableParametrosBeforeInsert(DataSet: TDataSet);
begin
FAcao := tacIncluir;
end;
procedure Tview_ParametrosPrazosExtratos.PopulateData;
var
aParam: array of variant;
begin
SetLength(aParam, 2);
aParam := ['FILTRO',''];
memTableParametros.Active := False;
memTableParametros.Tag := -1;
if FPrazos.Search(aParam) then
begin
memTableParametros.Data := FPrazos.Prazos.Query.Data;
FPrazos.Prazos.Query.Active := False;
FPrazos.Prazos.Query.Connection.Connected := False;
end
else
begin
memTableParametros.Active := True;
end;
Finalize(aParam);
memTableParametros.Tag := 0;
end;
procedure Tview_ParametrosPrazosExtratos.SetupClass();
begin
FPrazos.Prazos.ID := memTableParametrosid_registro.AsInteger;
FPrazos.Prazos.Tipo := memTableParametroscod_tipo_extrato.AsInteger;
FPrazos.Prazos.Quinzena := memTableParametrosnum_quinzena.AsInteger;
FPrazos.Prazos.DiaInicio := memTableParametrosnum_dia_inicio.AsInteger;
FPrazos.Prazos.DiaFinal := memTableParametrosnum_dia_final.AsInteger;
FPrazos.Prazos.DiaPagamento := memTableParametrosnum_dia_pagamento.AsInteger;
FPrazos.Prazos.DiasPrazoPagamento := memTableParametrosqtd_dias_prazo_pagamento.AsInteger;
FPrazos.Prazos.Acao := FAcao;
end;
function Tview_ParametrosPrazosExtratos.UpdateData: Boolean;
begin
Result := False;
SetupClass();
if not ValidateData() then
Exit;
Result := FPrazos.Save();
end;
function Tview_ParametrosPrazosExtratos.ValidateData: Boolean;
var
aParam : array of Variant;
sFiltro: String;
begin
Result := False;
if FPrazos.Prazos.Tipo = 0 then
begin
Application.MessageBox('Informe o tipo de extrato!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FPrazos.Prazos.Quinzena = 0 then
begin
Application.MessageBox('Informe o número da quinzena!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FPrazos.Prazos.DiaInicio = 0 then
begin
Application.MessageBox('Informe o dia de início do período do extrato!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FPrazos.Prazos.DiaFinal = 0 then
begin
Application.MessageBox('Informe o dia de término do período do extrato!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FPrazos.Prazos.DiaPagamento = 0 then
begin
Application.MessageBox('Informe o dia de pagamento desse período do extrato!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FPrazos.Prazos.DiasPrazoPagamento = 0 then
begin
Application.MessageBox('Informe a quantidade de dias de prazo para pagamento a partida da data base!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FPrazos.Prazos.Acao = tacIncluir then
begin
SetLength(aParam, 5);
aParam := ['EXISTE', FPrazos.Prazos.Tipo, FPrazos.Prazos.Quinzena, FPrazos.Prazos.DiaInicio, FPrazos.Prazos.DiaFinal];
if FPrazos.Prazos.Search(aParam) then
begin
Application.MessageBox('Parâmetro já cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING);
FPrazos.Prazos.Query.Active := False;
FPrazos.Prazos.Query.Connection.Connected := False;
Finalize(aParam);
Exit;
end;
end;
Finalize(aParam);
Result := True;
end;
end.
|
unit frm_listadoalumnos;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, db, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Buttons, DBGrids, StdCtrls
,dmGeneral
;
type
{ TfrmListadoAlumnos }
TfrmListadoAlumnos = class(TForm)
btnSalir: TBitBtn;
btnAgregar: TBitBtn;
btnModificar: TBitBtn;
btnEliminar: TBitBtn;
DS_Alumnos: TDatasource;
DBGrid1: TDBGrid;
edBusqueda: TEdit;
Label1: TLabel;
Panel1: TPanel;
Panel2: TPanel;
rgCriterioBusqueda: TRadioGroup;
procedure btnAgregarClick(Sender: TObject);
procedure btnEliminarClick(Sender: TObject);
procedure btnModificarClick(Sender: TObject);
procedure btnSalirClick(Sender: TObject);
procedure edBusquedaKeyPress(Sender: TObject; var Key: char);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
_refCategoria: string;
function GetApyNomAlumnoSeleccionado: string;
function GetidAlumnoSeleccionado: GUID_ID;
procedure PantallaEdicion (idEdicion: GUID_ID);
procedure SetrefCategoria(AValue: string);
public
property idAlumnoSeleccionado: GUID_ID read GetidAlumnoSeleccionado;
property ApyNomAlumnoSeleccionado: string read GetApyNomAlumnoSeleccionado;
property refCategoria: string read _refCategoria write SetrefCategoria;
end;
var
frmListadoAlumnos: TfrmListadoAlumnos;
implementation
{$R *.lfm}
uses
dmalumnos
,frm_alumnoae
;
{ TfrmListadoAlumnos }
procedure TfrmListadoAlumnos.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
// if NOT (fsModal in (sender as TfrmListadoAlumnos).FormState) then //Me fijo si se abrio como modal para no destruirlo
// CloseAction:= caFree;
end;
procedure TfrmListadoAlumnos.btnSalirClick(Sender: TObject);
begin
//Dependiendo de cómo lo abro, lo cierro
// if (fsModal in self.FormState) then
ModalResult:= mrOK
// else
// close;
end;
procedure TfrmListadoAlumnos.edBusquedaKeyPress(Sender: TObject; var Key: char);
begin
if key = #13 then
dm_alumnos.Buscar (edBusqueda.Text, rgCriterioBusqueda.ItemIndex)
end;
procedure TfrmListadoAlumnos.FormCreate(Sender: TObject);
begin
// dm_alumnos:= Tdm_alumnos.Create(self);
// dm_alumnos.ObtenerTodosLosAlumnos;
end;
procedure TfrmListadoAlumnos.FormShow(Sender: TObject);
begin
if _refCategoria = CAT_ALUMNO then
(Sender as TfrmListadoAlumnos).Caption:= 'Alumnos'
else
if _refCategoria = CAT_DOCENTE then
(Sender as TfrmListadoAlumnos).Caption:= 'Docentes';
dm_alumnos.ObtenerTodosLosAlumnos;
end;
function TfrmListadoAlumnos.GetApyNomAlumnoSeleccionado: string;
begin
with DS_Alumnos.DataSet do
begin
if RecordCount > 0 then
Result:= TRIM(FieldByName('cApellidos').asString) + ' ' + TRIM(FieldByName('cNombres').asString)
else
Result:= EmptyStr;
end;
end;
function TfrmListadoAlumnos.GetidAlumnoSeleccionado: GUID_ID;
begin
with DS_Alumnos.DataSet do
begin
if RecordCount > 0 then
Result:= FieldByName('idAlumno').asString
else
Result:= GUIDNULO;
end;
end;
(*******************************************************************************
*** Administra la pantalla de Modificación/Ingreso de un alumno - Docente
********************************************************************************)
procedure TfrmListadoAlumnos.PantallaEdicion(idEdicion: GUID_ID);
var
pantalla: TfrmAlumnoae;
begin
pantalla:= TfrmAlumnoae.Create(self);
try
pantalla.categoria:= refCategoria;
pantalla.idAlumno:= idEdicion;
pantalla.ShowModal;
dm_alumnos.ObtenerTodosLosAlumnos;
finally
pantalla.Free;
end;
end;
procedure TfrmListadoAlumnos.SetrefCategoria(AValue: string);
begin
if _refCategoria=AValue then Exit;
_refCategoria:=AValue;
dm_alumnos.refCategoria:= AValue;
end;
procedure TfrmListadoAlumnos.btnAgregarClick(Sender: TObject);
begin
PantallaEdicion(GUIDNULO);
end;
procedure TfrmListadoAlumnos.btnModificarClick(Sender: TObject);
begin
PantallaEdicion(dm_alumnos.SeleccionTodosLosAlumnos);
end;
(*******************************************************************************
*** Borro un alumno
********************************************************************************)
procedure TfrmListadoAlumnos.btnEliminarClick(Sender: TObject);
begin
if (MessageDlg ('ATENCION', 'Borro el Alumno seleccionado?', mtConfirmation, [mbYes, mbNo],0 ) = mrYes) then
begin
dm_alumnos.Borrar(dm_alumnos.SeleccionTodosLosAlumnos);
dm_alumnos.ObtenerTodosLosAlumnos;
end;
end;
end.
|
unit RegisterWebinarUnit;
interface
uses SysUtils, BaseExampleUnit, EnumsUnit;
type
TRegisterWebinar = class(TBaseExample)
public
function Execute(EMail, FirstName, LastName, Phone, Company: String;
MemberId: integer; Date: TDateTime): boolean;
end;
implementation
function TRegisterWebinar.Execute(EMail, FirstName, LastName, Phone,
Company: String; MemberId: integer; Date: TDateTime): boolean;
var
ErrorString: String;
begin
Result := Route4MeManager.User.RegisterWebinar(EMail, FirstName, LastName,
Phone, Company, MemberId, Date, ErrorString);
WriteLn('');
if (ErrorString = EmptyStr) then
begin
if Result then
WriteLn('RegisterWebinar successfully')
else
WriteLn('RegisterWebinar error');
WriteLn('');
end
else
WriteLn(Format('RegisterWebinar error: "%s"', [ErrorString]));
end;
end.
|
unit mainform;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ddCmdLineUtils, dd_lcHtmlDocReader, l3Filer, EvdWriter,
evNestedDocumentEliminator;
type
TAACMakerForm = class(TForm)
ProgressBar1: TProgressBar;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
f_Filer: TevDOSFiler;
f_Nested: TevNestedDocumentEliminator;
f_Options: TddCmdLine;
f_reader: TlcHTMLDocReader;
f_Writer: TevdNativeWriter;
{ Private declarations }
protected
procedure AazIdle(Sender: TObject; var Done: Boolean);
procedure ConvertFolder;
procedure UpdateProgress;
public
{ Public declarations }
end;
TOptions = class(TddCmdLine)
private
f_DestFolder: string;
f_SrcFolder: string;
protected
procedure Init; override;
public
property DestFolder: string read f_DestFolder write f_DestFolder;
property SrcFolder: string read f_SrcFolder write f_SrcFolder;
end;
var
AACMakerForm: TAACMakerForm;
implementation
uses l3FileUtils, ddFileIterator, l3base;
{$R *.dfm}
procedure TAACMakerForm.AazIdle(Sender: TObject; var Done: Boolean);
begin
application.OnIdle:= nil;
try
ConvertFolder;
except
on E: Exception do
begin
l3System.Exception2Log(E);
MessageDlg(E.Message, mtError, [mbOk], 0);
end
end;
Close;
end;
procedure TAACMakerForm.ConvertFolder;
var
sr: TSearchRec;
begin
if FindFirst(ConcatDirName(TOptions(f_Options).SrcFolder, '*.*'), faDirectory, sr) = 0 then
begin
repeat
if (SR.Name[1] <> '.') and (SR.Attr and faDirectory = faDirectory) then
begin
f_Filer.FileName:= ConcatDirName(TOptions(f_Options).DestFolder, SR.Name) + '.evd';
f_reader.Execute(ConcatDirName(TOptions(f_Options).SrcFolder, SR.Name));
UpdateProgress;
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
end;
procedure TAACMakerForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(f_Nested);
FreeAndNil(f_Filer);
FreeAndNil(f_Writer);
FreeAndNil(f_Options);
FreeAndNil(f_Reader);
end;
procedure TAACMakerForm.FormCreate(Sender: TObject);
begin
f_Options:= TOptions.Create;
f_reader:= TlcHTMLDocReader.Create;
f_Reader.SourceFileName:= ExtractFilePath(Application.ExeName)+'Source.csv';
f_Writer := TevdNativeWriter.Create();
f_Filer := TevDOSFiler.Create();
f_Writer.Filer:= f_Filer;
f_Nested := TevNestedDocumentEliminator.Create();
f_Nested.Generator:= f_Writer;
f_Reader.Generator:= f_Nested;
Application.OnIdle:= AazIdle;
end;
procedure TAACMakerForm.UpdateProgress;
begin
if ProgressBar1.Position = 100 then
ProgressBar1.Position := 0;
ProgressBar1.Position := ProgressBar1.Position + 10;
end;
procedure TOptions.Init;
begin
AddDir('-Src','Root folder', f_SrcFolder);
AddString('-Dest', 'Destination folder', f_DestFolder);
inherited;
end;
end.
|
unit uScript;
interface
uses Classes;
type
TScript = class(TObject)
private
SL: TStringList;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Key(X, Y: Word): string;
function Name(I: Integer): string;
function Value(S: string): string;
procedure Run(X, Y: Word);
procedure LoadFromFile(FileName: string);
procedure SaveToFile(FileName: string);
end;
implementation
uses SysUtils, uBox;
const
LS = '%s=%s';
EX = '.scr';
{ TScript }
procedure TScript.Clear;
begin
SL.Clear
end;
constructor TScript.Create;
begin
SL := TStringList.Create
end;
destructor TScript.Destroy;
begin
SL.Free;
inherited
end;
function TScript.Key(X, Y: Word): string;
begin
Result := Format('%dx%d', [X, Y]);
end;
procedure TScript.LoadFromFile(FileName: string);
begin
FileName := ChangeFileExt(FileName, EX);
if FileExists(FileName) then SL.LoadFromFile(FileName);
end;
procedure TScript.SaveToFile(FileName: string);
begin
FileName := ChangeFileExt(FileName, EX);
SL.SaveToFile(FileName);
end;
function TScript.Name(I: Integer): string;
begin
Result := SL.Names[I];
end;
function TScript.Value(S: string): string;
begin
Result := SL.Values[S];
end;
procedure TScript.Run(X, Y: Word);
begin
Box('SCRIPT');
end;
end.
|
unit InfoCOLLTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoCOLLRecord = record
PLender: String[4];
PLoanNumber: String[18];
PCIndex: String[1];
PModCount: Integer;
PYear: String[2];
PDescription: String[12];
PRVIN: String[17];
PVIN: String[17];
PTitle: String[1];
PTitleDate: String[10];
PCValue: Integer;
PCValueDate: String[10];
PPrint: String[1];
End;
TInfoCOLLClass2 = class
public
PLender: String[4];
PLoanNumber: String[18];
PCIndex: String[1];
PModCount: Integer;
PYear: String[2];
PDescription: String[12];
PRVIN: String[17];
PVIN: String[17];
PTitle: String[1];
PTitleDate: String[10];
PCValue: Integer;
PCValueDate: String[10];
PPrint: String[1];
End;
// function CtoRInfoCOLL(AClass:TInfoCOLLClass):TInfoCOLLRecord;
// procedure RtoCInfoCOLL(ARecord:TInfoCOLLRecord;AClass:TInfoCOLLClass);
TInfoCOLLBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoCOLLRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoCOLL = (InfoCOLLPrimaryKey, InfoCOLLLendDesc, InfoCOLLLendRVIN, InfoCOLLLendYrDesc);
TInfoCOLLTable = class( TDBISAMTableAU )
private
FDFLender: TStringField;
FDFLoanNumber: TStringField;
FDFCIndex: TStringField;
FDFModCount: TIntegerField;
FDFYear: TStringField;
FDFDescription: TStringField;
FDFRVIN: TStringField;
FDFVIN: TStringField;
FDFTitle: TStringField;
FDFTitleDate: TStringField;
FDFCValue: TIntegerField;
FDFCValueDate: TStringField;
FDFPrint: TStringField;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPCIndex(const Value: String);
function GetPCIndex:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPYear(const Value: String);
function GetPYear:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPRVIN(const Value: String);
function GetPRVIN:String;
procedure SetPVIN(const Value: String);
function GetPVIN:String;
procedure SetPTitle(const Value: String);
function GetPTitle:String;
procedure SetPTitleDate(const Value: String);
function GetPTitleDate:String;
procedure SetPCValue(const Value: Integer);
function GetPCValue:Integer;
procedure SetPCValueDate(const Value: String);
function GetPCValueDate:String;
procedure SetPPrint(const Value: String);
function GetPPrint:String;
procedure SetEnumIndex(Value: TEIInfoCOLL);
function GetEnumIndex: TEIInfoCOLL;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoCOLLRecord;
procedure StoreDataBuffer(ABuffer:TInfoCOLLRecord);
property DFLender: TStringField read FDFLender;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFCIndex: TStringField read FDFCIndex;
property DFModCount: TIntegerField read FDFModCount;
property DFYear: TStringField read FDFYear;
property DFDescription: TStringField read FDFDescription;
property DFRVIN: TStringField read FDFRVIN;
property DFVIN: TStringField read FDFVIN;
property DFTitle: TStringField read FDFTitle;
property DFTitleDate: TStringField read FDFTitleDate;
property DFCValue: TIntegerField read FDFCValue;
property DFCValueDate: TStringField read FDFCValueDate;
property DFPrint: TStringField read FDFPrint;
property PLender: String read GetPLender write SetPLender;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PCIndex: String read GetPCIndex write SetPCIndex;
property PModCount: Integer read GetPModCount write SetPModCount;
property PYear: String read GetPYear write SetPYear;
property PDescription: String read GetPDescription write SetPDescription;
property PRVIN: String read GetPRVIN write SetPRVIN;
property PVIN: String read GetPVIN write SetPVIN;
property PTitle: String read GetPTitle write SetPTitle;
property PTitleDate: String read GetPTitleDate write SetPTitleDate;
property PCValue: Integer read GetPCValue write SetPCValue;
property PCValueDate: String read GetPCValueDate write SetPCValueDate;
property PPrint: String read GetPPrint write SetPPrint;
published
property Active write SetActive;
property EnumIndex: TEIInfoCOLL read GetEnumIndex write SetEnumIndex;
end; { TInfoCOLLTable }
TInfoCOLLQuery = class( TDBISAMQueryAU )
private
FDFLender: TStringField;
FDFLoanNumber: TStringField;
FDFCIndex: TStringField;
FDFModCount: TIntegerField;
FDFYear: TStringField;
FDFDescription: TStringField;
FDFRVIN: TStringField;
FDFVIN: TStringField;
FDFTitle: TStringField;
FDFTitleDate: TStringField;
FDFCValue: TIntegerField;
FDFCValueDate: TStringField;
FDFPrint: TStringField;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPCIndex(const Value: String);
function GetPCIndex:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPYear(const Value: String);
function GetPYear:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPRVIN(const Value: String);
function GetPRVIN:String;
procedure SetPVIN(const Value: String);
function GetPVIN:String;
procedure SetPTitle(const Value: String);
function GetPTitle:String;
procedure SetPTitleDate(const Value: String);
function GetPTitleDate:String;
procedure SetPCValue(const Value: Integer);
function GetPCValue:Integer;
procedure SetPCValueDate(const Value: String);
function GetPCValueDate:String;
procedure SetPPrint(const Value: String);
function GetPPrint:String;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoCOLLRecord;
procedure StoreDataBuffer(ABuffer:TInfoCOLLRecord);
property DFLender: TStringField read FDFLender;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFCIndex: TStringField read FDFCIndex;
property DFModCount: TIntegerField read FDFModCount;
property DFYear: TStringField read FDFYear;
property DFDescription: TStringField read FDFDescription;
property DFRVIN: TStringField read FDFRVIN;
property DFVIN: TStringField read FDFVIN;
property DFTitle: TStringField read FDFTitle;
property DFTitleDate: TStringField read FDFTitleDate;
property DFCValue: TIntegerField read FDFCValue;
property DFCValueDate: TStringField read FDFCValueDate;
property DFPrint: TStringField read FDFPrint;
property PLender: String read GetPLender write SetPLender;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PCIndex: String read GetPCIndex write SetPCIndex;
property PModCount: Integer read GetPModCount write SetPModCount;
property PYear: String read GetPYear write SetPYear;
property PDescription: String read GetPDescription write SetPDescription;
property PRVIN: String read GetPRVIN write SetPRVIN;
property PVIN: String read GetPVIN write SetPVIN;
property PTitle: String read GetPTitle write SetPTitle;
property PTitleDate: String read GetPTitleDate write SetPTitleDate;
property PCValue: Integer read GetPCValue write SetPCValue;
property PCValueDate: String read GetPCValueDate write SetPCValueDate;
property PPrint: String read GetPPrint write SetPPrint;
published
property Active write SetActive;
end; { TInfoCOLLTable }
procedure Register;
implementation
procedure TInfoCOLLTable.CreateFields;
begin
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFCIndex := CreateField( 'CIndex' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFYear := CreateField( 'Year' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFRVIN := CreateField( 'RVIN' ) as TStringField;
FDFVIN := CreateField( 'VIN' ) as TStringField;
FDFTitle := CreateField( 'Title' ) as TStringField;
FDFTitleDate := CreateField( 'TitleDate' ) as TStringField;
FDFCValue := CreateField( 'CValue' ) as TIntegerField;
FDFCValueDate := CreateField( 'CValueDate' ) as TStringField;
FDFPrint := CreateField( 'Print' ) as TStringField;
end; { TInfoCOLLTable.CreateFields }
procedure TInfoCOLLTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoCOLLTable.SetActive }
procedure TInfoCOLLTable.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoCOLLTable.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoCOLLTable.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TInfoCOLLTable.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TInfoCOLLTable.SetPCIndex(const Value: String);
begin
DFCIndex.Value := Value;
end;
function TInfoCOLLTable.GetPCIndex:String;
begin
result := DFCIndex.Value;
end;
procedure TInfoCOLLTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TInfoCOLLTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TInfoCOLLTable.SetPYear(const Value: String);
begin
DFYear.Value := Value;
end;
function TInfoCOLLTable.GetPYear:String;
begin
result := DFYear.Value;
end;
procedure TInfoCOLLTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoCOLLTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoCOLLTable.SetPRVIN(const Value: String);
begin
DFRVIN.Value := Value;
end;
function TInfoCOLLTable.GetPRVIN:String;
begin
result := DFRVIN.Value;
end;
procedure TInfoCOLLTable.SetPVIN(const Value: String);
begin
DFVIN.Value := Value;
end;
function TInfoCOLLTable.GetPVIN:String;
begin
result := DFVIN.Value;
end;
procedure TInfoCOLLTable.SetPTitle(const Value: String);
begin
DFTitle.Value := Value;
end;
function TInfoCOLLTable.GetPTitle:String;
begin
result := DFTitle.Value;
end;
procedure TInfoCOLLTable.SetPTitleDate(const Value: String);
begin
DFTitleDate.Value := Value;
end;
function TInfoCOLLTable.GetPTitleDate:String;
begin
result := DFTitleDate.Value;
end;
procedure TInfoCOLLTable.SetPCValue(const Value: Integer);
begin
DFCValue.Value := Value;
end;
function TInfoCOLLTable.GetPCValue:Integer;
begin
result := DFCValue.Value;
end;
procedure TInfoCOLLTable.SetPCValueDate(const Value: String);
begin
DFCValueDate.Value := Value;
end;
function TInfoCOLLTable.GetPCValueDate:String;
begin
result := DFCValueDate.Value;
end;
procedure TInfoCOLLTable.SetPPrint(const Value: String);
begin
DFPrint.Value := Value;
end;
function TInfoCOLLTable.GetPPrint:String;
begin
result := DFPrint.Value;
end;
procedure TInfoCOLLTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Lender, String, 4, N');
Add('LoanNumber, String, 18, N');
Add('CIndex, String, 1, N');
Add('ModCount, Integer, 0, N');
Add('Year, String, 2, N');
Add('Description, String, 12, N');
Add('RVIN, String, 17, N');
Add('VIN, String, 17, N');
Add('Title, String, 1, N');
Add('TitleDate, String, 10, N');
Add('CValue, Integer, 0, N');
Add('CValueDate, String, 10, N');
Add('Print, String, 1, N');
end;
end;
procedure TInfoCOLLTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Lender;LoanNumber;CIndex, Y, Y, N, N');
Add('LendDesc, Lender;Description;Year, N, N, N, N');
Add('LendRVIN, Lender;RVIN, N, N, N, N');
Add('LendYrDesc, Lender;Year;Description, N, N, N, N');
end;
end;
procedure TInfoCOLLTable.SetEnumIndex(Value: TEIInfoCOLL);
begin
case Value of
InfoCOLLPrimaryKey : IndexName := '';
InfoCOLLLendDesc : IndexName := 'LendDesc';
InfoCOLLLendRVIN : IndexName := 'LendRVIN';
InfoCOLLLendYrDesc : IndexName := 'LendYrDesc';
end;
end;
function TInfoCOLLTable.GetDataBuffer:TInfoCOLLRecord;
var buf: TInfoCOLLRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLender := DFLender.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PCIndex := DFCIndex.Value;
buf.PModCount := DFModCount.Value;
buf.PYear := DFYear.Value;
buf.PDescription := DFDescription.Value;
buf.PRVIN := DFRVIN.Value;
buf.PVIN := DFVIN.Value;
buf.PTitle := DFTitle.Value;
buf.PTitleDate := DFTitleDate.Value;
buf.PCValue := DFCValue.Value;
buf.PCValueDate := DFCValueDate.Value;
buf.PPrint := DFPrint.Value;
result := buf;
end;
procedure TInfoCOLLTable.StoreDataBuffer(ABuffer:TInfoCOLLRecord);
begin
DFLender.Value := ABuffer.PLender;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFCIndex.Value := ABuffer.PCIndex;
DFModCount.Value := ABuffer.PModCount;
DFYear.Value := ABuffer.PYear;
DFDescription.Value := ABuffer.PDescription;
DFRVIN.Value := ABuffer.PRVIN;
DFVIN.Value := ABuffer.PVIN;
DFTitle.Value := ABuffer.PTitle;
DFTitleDate.Value := ABuffer.PTitleDate;
DFCValue.Value := ABuffer.PCValue;
DFCValueDate.Value := ABuffer.PCValueDate;
DFPrint.Value := ABuffer.PPrint;
end;
function TInfoCOLLTable.GetEnumIndex: TEIInfoCOLL;
var iname : string;
begin
result := InfoCOLLPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoCOLLPrimaryKey;
if iname = 'LENDDESC' then result := InfoCOLLLendDesc;
if iname = 'LENDRVIN' then result := InfoCOLLLendRVIN;
if iname = 'LENDYRDESC' then result := InfoCOLLLendYrDesc;
end;
procedure TInfoCOLLQuery.CreateFields;
begin
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFCIndex := CreateField( 'CIndex' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFYear := CreateField( 'Year' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFRVIN := CreateField( 'RVIN' ) as TStringField;
FDFVIN := CreateField( 'VIN' ) as TStringField;
FDFTitle := CreateField( 'Title' ) as TStringField;
FDFTitleDate := CreateField( 'TitleDate' ) as TStringField;
FDFCValue := CreateField( 'CValue' ) as TIntegerField;
FDFCValueDate := CreateField( 'CValueDate' ) as TStringField;
FDFPrint := CreateField( 'Print' ) as TStringField;
end; { TInfoCOLLQuery.CreateFields }
procedure TInfoCOLLQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoCOLLQuery.SetActive }
procedure TInfoCOLLQuery.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoCOLLQuery.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoCOLLQuery.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TInfoCOLLQuery.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TInfoCOLLQuery.SetPCIndex(const Value: String);
begin
DFCIndex.Value := Value;
end;
function TInfoCOLLQuery.GetPCIndex:String;
begin
result := DFCIndex.Value;
end;
procedure TInfoCOLLQuery.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TInfoCOLLQuery.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TInfoCOLLQuery.SetPYear(const Value: String);
begin
DFYear.Value := Value;
end;
function TInfoCOLLQuery.GetPYear:String;
begin
result := DFYear.Value;
end;
procedure TInfoCOLLQuery.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoCOLLQuery.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoCOLLQuery.SetPRVIN(const Value: String);
begin
DFRVIN.Value := Value;
end;
function TInfoCOLLQuery.GetPRVIN:String;
begin
result := DFRVIN.Value;
end;
procedure TInfoCOLLQuery.SetPVIN(const Value: String);
begin
DFVIN.Value := Value;
end;
function TInfoCOLLQuery.GetPVIN:String;
begin
result := DFVIN.Value;
end;
procedure TInfoCOLLQuery.SetPTitle(const Value: String);
begin
DFTitle.Value := Value;
end;
function TInfoCOLLQuery.GetPTitle:String;
begin
result := DFTitle.Value;
end;
procedure TInfoCOLLQuery.SetPTitleDate(const Value: String);
begin
DFTitleDate.Value := Value;
end;
function TInfoCOLLQuery.GetPTitleDate:String;
begin
result := DFTitleDate.Value;
end;
procedure TInfoCOLLQuery.SetPCValue(const Value: Integer);
begin
DFCValue.Value := Value;
end;
function TInfoCOLLQuery.GetPCValue:Integer;
begin
result := DFCValue.Value;
end;
procedure TInfoCOLLQuery.SetPCValueDate(const Value: String);
begin
DFCValueDate.Value := Value;
end;
function TInfoCOLLQuery.GetPCValueDate:String;
begin
result := DFCValueDate.Value;
end;
procedure TInfoCOLLQuery.SetPPrint(const Value: String);
begin
DFPrint.Value := Value;
end;
function TInfoCOLLQuery.GetPPrint:String;
begin
result := DFPrint.Value;
end;
function TInfoCOLLQuery.GetDataBuffer:TInfoCOLLRecord;
var buf: TInfoCOLLRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLender := DFLender.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PCIndex := DFCIndex.Value;
buf.PModCount := DFModCount.Value;
buf.PYear := DFYear.Value;
buf.PDescription := DFDescription.Value;
buf.PRVIN := DFRVIN.Value;
buf.PVIN := DFVIN.Value;
buf.PTitle := DFTitle.Value;
buf.PTitleDate := DFTitleDate.Value;
buf.PCValue := DFCValue.Value;
buf.PCValueDate := DFCValueDate.Value;
buf.PPrint := DFPrint.Value;
result := buf;
end;
procedure TInfoCOLLQuery.StoreDataBuffer(ABuffer:TInfoCOLLRecord);
begin
DFLender.Value := ABuffer.PLender;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFCIndex.Value := ABuffer.PCIndex;
DFModCount.Value := ABuffer.PModCount;
DFYear.Value := ABuffer.PYear;
DFDescription.Value := ABuffer.PDescription;
DFRVIN.Value := ABuffer.PRVIN;
DFVIN.Value := ABuffer.PVIN;
DFTitle.Value := ABuffer.PTitle;
DFTitleDate.Value := ABuffer.PTitleDate;
DFCValue.Value := ABuffer.PCValue;
DFCValueDate.Value := ABuffer.PCValueDate;
DFPrint.Value := ABuffer.PPrint;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoCOLLTable, TInfoCOLLQuery, TInfoCOLLBuffer ] );
end; { Register }
function TInfoCOLLBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..13] of string = ('LENDER','LOANNUMBER','CINDEX','MODCOUNT','YEAR','DESCRIPTION'
,'RVIN','VIN','TITLE','TITLEDATE','CVALUE'
,'CVALUEDATE','PRINT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 13) and (flist[x] <> s) do inc(x);
if x <= 13 then result := x else result := 0;
end;
function TInfoCOLLBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftInteger;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftInteger;
12 : result := ftString;
13 : result := ftString;
end;
end;
function TInfoCOLLBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLender;
2 : result := @Data.PLoanNumber;
3 : result := @Data.PCIndex;
4 : result := @Data.PModCount;
5 : result := @Data.PYear;
6 : result := @Data.PDescription;
7 : result := @Data.PRVIN;
8 : result := @Data.PVIN;
9 : result := @Data.PTitle;
10 : result := @Data.PTitleDate;
11 : result := @Data.PCValue;
12 : result := @Data.PCValueDate;
13 : result := @Data.PPrint;
end;
end;
end.
|
unit nscDocumentListTreeView;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Components"
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/rtl/Garant/Components/nscDocumentListTreeView.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<GuiControl::Class>> F1 Базовые определения предметной области::LegalDomain::Components::DocumentListTree::TnscDocumentListTreeView
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
Messages,
bsTypes
{$If defined(Nemesis)}
,
nscTreeView
{$IfEnd} //Nemesis
,
Classes,
ImgList,
l3Interfaces,
Graphics,
vtLister,
Types,
ActiveX,
vtOutlinerWithDragDrop
;
type
TdltGetNodeTypeEvent = function (anIndex: Integer): TbsListNodeType of object;
TnscDocumentListTreeView = class(TnscTreeView)
private
// private fields
f_AllSelected : Boolean;
f_OnGetNodeType : TdltGetNodeTypeEvent;
{* Поле для свойства OnGetNodeType}
private
// private methods
function IsFirstSnippet(aNodeIndex: Integer): Boolean;
function IsDocumentWithSnippets(aNodeIndex: Integer): Boolean;
procedure InternalSetSelected(anItemIndex: Integer;
aValue: Boolean);
function GetNextItem(var anItemIndex: Integer): Boolean;
function GetPrevItem(var anItemIndex: Integer): Boolean;
procedure WMLButtonDown(var Msg: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMRButtonDown(var Msg: TWMRButtonDown); message WM_RBUTTONDOWN;
procedure WMGetText(var Msg: TWMGetText); message WM_GetText;
procedure WMGetTextLength(var Msg: TWMGetTextLength); message WM_GETTEXTLENGTH;
protected
// overridden property methods
procedure pm_SetTopIndex(aValue: LongInt); override;
protected
// overridden protected methods
function DoOnGetItemImageIndex(aItemIndex: LongInt;
var aImages: TCustomImageList): Integer; override;
procedure DoOnGetItemStyle(aItemIndex: Integer;
const aFont: Il3Font;
var aTextBackColor: TColor;
var aItemBackColor: TColor;
var aVJustify: TvtVJustify;
var aFocused: Boolean;
var theImageVertOffset: Integer); override;
function CalcTopIndex(aMaxVisItem: LongInt): LongInt; override;
procedure VlbVScrollPrim(aDelta: Integer); override;
function VlbItemHitTest(aIndex: Integer;
const aPt: TPoint;
fromScreen: Boolean = False): Byte; override;
procedure DoOnGetItemColor(Index: LongInt;
var FG: TColor;
var BG: TColor); override;
function DoOnIsSelected(Index: LongInt): Integer; override;
procedure DoOnSelect(Index: LongInt;
aValue: Integer); override;
procedure DoOnSelectOutRange(First: LongInt;
Last: LongInt;
aSelectState: Integer); override;
function DoDoProcessCommand(Cmd: Tl3OperationCode): Boolean; override;
procedure DoCurrentChanged(aNewCurrent: LongInt;
aOldCurrent: LongInt); override;
procedure DoValidateCurrent(var aIndex: LongInt); override;
function DoOnGetItemIndentEx(anItemIndex: Integer): Integer; override;
{* для каждой ноды можно задать свой "персональный" сдвиг }
function GetSelectedCountForStatusbar: Integer; override;
function NeedDrawSelectionOnItem(aItemIndex: Integer): Boolean; override;
function CanAcceptData(const aData: IDataObject): Boolean; override;
public
// overridden public methods
constructor Create(AOwner: TComponent); override;
procedure SelectItems(aFinish: Integer); override;
{* Создавалась, как ручка для тестов, но немного обобщает логику выделения }
procedure HitTest(const aPt: TPoint;
var aIndex: Integer;
var aItemPart: Byte;
fromScreen: Boolean = False); override;
procedure VlbToggleSelection(Index: LongInt); override;
{* process Ctrl-LMouseBtn }
protected
// protected methods
function GetCurrentText: AnsiString; virtual;
public
// public properties
property OnGetNodeType: TdltGetNodeTypeEvent
read f_OnGetNodeType
write f_OnGetNodeType;
end;//TnscDocumentListTreeView
implementation
uses
l3ControlsTypes,
l3TreeInterfaces,
OvcConst,
Windows,
l3Nodes,
l3MinMax,
SysUtils,
l3Base,
l3String,
evStyleTableTools,
l3Units,
l3ScreenIC,
evdStyles,
DynamicDocListUnit
;
// start class TnscDocumentListTreeView
function TnscDocumentListTreeView.IsFirstSnippet(aNodeIndex: Integer): Boolean;
//#UC START# *51DAD23D01ED_51D56E9F004B_var*
var
l_Node: Il3SimpleNode;
//#UC END# *51DAD23D01ED_51D56E9F004B_var*
begin
//#UC START# *51DAD23D01ED_51D56E9F004B_impl*
Result := False;
if aNodeIndex >= 0 then
if not IsEmpty then
begin
l_Node := TreeStruct.Nodes[aNodeIndex];
if Assigned(l_Node) then
if l_Node.IsFirst then
if Assigned(f_OnGetNodeType)
then Result := f_OnGetNodeType(aNodeIndex) = lntBlock
else Result := l_Node.GetLevel = 2;
end;
//#UC END# *51DAD23D01ED_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.IsFirstSnippet
function TnscDocumentListTreeView.IsDocumentWithSnippets(aNodeIndex: Integer): Boolean;
//#UC START# *51DAD2660297_51D56E9F004B_var*
var
l_Node: Il3SimpleNode;
//#UC END# *51DAD2660297_51D56E9F004B_var*
begin
//#UC START# *51DAD2660297_51D56E9F004B_impl*
{Result := False;
if not IsEmpty then
begin
l_Node := TreeStruct.Nodes[aNodeIndex];
Result := Assigned(l_Node) and (l_Node.GetLevel = 1) and l_Node.HasChild;
end;}
Result := (aNodeIndex >= 0) and IsFirstSnippet(aNodeIndex + 1);
//#UC END# *51DAD2660297_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.IsDocumentWithSnippets
procedure TnscDocumentListTreeView.InternalSetSelected(anItemIndex: Integer;
aValue: Boolean);
//#UC START# *51DFB94B03C1_51D56E9F004B_var*
//#UC END# *51DFB94B03C1_51D56E9F004B_var*
begin
//#UC START# *51DFB94B03C1_51D56E9F004B_impl*
TreeStruct.Select[anItemIndex] := aValue;
InvalidateItem(anItemIndex);
if IsDocumentWithSnippets(anItemIndex) then
InvalidateItem(anItemIndex + 1);
//#UC END# *51DFB94B03C1_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.InternalSetSelected
function TnscDocumentListTreeView.GetNextItem(var anItemIndex: Integer): Boolean;
//#UC START# *51DFB9B50356_51D56E9F004B_var*
var
l_Node, l_Next: Il3SimpleNode;
//#UC END# *51DFB9B50356_51D56E9F004B_var*
begin
//#UC START# *51DFB9B50356_51D56E9F004B_impl*
Result := False;
if IsEmpty or (anItemIndex = f_HighIndex) then
Exit;
l_Node := TreeStruct.Nodes[anItemIndex];
if not Assigned(l_Node) then
Exit;
if l_Node.HasChild then
if TreeStruct.IsExpanded(l_Node) then
begin
if IsDocumentWithSnippets(anItemIndex) then
Inc(anItemIndex, 2)
else
Inc(anItemIndex, 1);
Result := (anItemIndex < Total);
Exit;
end;
l_Next := l_Node.Next;
while Assigned(l_Node) and not Assigned(l_Next) do
begin
l_Node := l_Node.Parent;
if Assigned(l_Node)
then l_Next := l_Node.Next
else l_Next := nil;
end;
Result := Assigned(l_Next);
if Result then
anItemIndex := TreeStruct.GetIndex(l_Next);
//#UC END# *51DFB9B50356_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.GetNextItem
function TnscDocumentListTreeView.GetPrevItem(var anItemIndex: Integer): Boolean;
//#UC START# *51DFBA2F0121_51D56E9F004B_var*
var
l_Prev, l_Parent: Il3SimpleNode;
//#UC END# *51DFBA2F0121_51D56E9F004B_var*
begin
//#UC START# *51DFBA2F0121_51D56E9F004B_impl*
Result := False;
if IsEmpty then
Exit;
if anItemIndex = 0 then
Exit;
l_Prev := TreeStruct.Nodes[anItemIndex - 1];
if not Assigned(l_Prev) then
Exit;
l_Parent := l_Prev.Parent;
while Assigned(l_Parent) do
begin
if not TreeStruct.IsExpanded(l_Parent) then
l_Prev := l_Parent;
l_Parent := l_Parent.Parent;
end;
anItemIndex := TreeStruct.GetIndex(l_Prev);
if IsFirstSnippet(anItemIndex) then
Dec(anItemIndex);
Result := True;
//#UC END# *51DFBA2F0121_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.GetPrevItem
function TnscDocumentListTreeView.GetCurrentText: AnsiString;
//#UC START# *51E01CC7023D_51D56E9F004B_var*
var
l_Node: Il3SimpleNode;
//#UC END# *51E01CC7023D_51D56E9F004B_var*
begin
//#UC START# *51E01CC7023D_51D56E9F004B_impl*
if not IsEmpty then
begin
l_Node := TreeStruct.Nodes[Current];
Result := l3Str(l_Node.Text);
if IsDocumentWithSnippets(Current) and TreeStruct.IsExpanded(l_Node) then
begin
l_Node := l_Node.Child;
Result := Result + #13#10 + l3Str(l_Node.Text);
end;
end else
Result := '';
//#UC END# *51E01CC7023D_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.GetCurrentText
procedure TnscDocumentListTreeView.WMLButtonDown(var Msg: TWMLButtonDown);
//#UC START# *51D7E45A02DB_51D56E9F004B_var*
var
l_Pt: TPoint;
l_ItemIndex: Integer;
l_ParentHeight: Integer;
//#UC END# *51D7E45A02DB_51D56E9F004B_var*
begin
//#UC START# *51D7E45A02DB_51D56E9F004B_impl*
l_Pt := SmallPointToPoint(Msg.Pos);
l_ItemIndex := ItemAtPos(l_Pt, True);
if IsFirstSnippet(l_ItemIndex) then // если кликнули в первое вхождение, то надо перенести клик в родительский документ
begin
l_ParentHeight := GetItemDim(l_ItemIndex - 1).Y;
repeat // сдвигаем координаты клика вверх шагами, равными высоте родительского документа
Msg.Pos.Y := Msg.Pos.Y - l_ParentHeight; // так точно не промахнёмся
l_Pt := SmallPointToPoint(Msg.Pos);
Assert(Msg.Pos.Y > 0);
until ItemAtPos(l_Pt, True) < l_ItemIndex;
end;
inherited;
//#UC END# *51D7E45A02DB_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.WMLButtonDown
procedure TnscDocumentListTreeView.WMRButtonDown(var Msg: TWMRButtonDown);
//#UC START# *51F2344801D4_51D56E9F004B_var*
var
l_Pt: TPoint;
l_ItemIndex: Integer;
//#UC END# *51F2344801D4_51D56E9F004B_var*
begin
//#UC START# *51F2344801D4_51D56E9F004B_impl*
l_Pt := SmallPointToPoint(Msg.Pos);
l_ItemIndex := ItemAtPos(l_Pt, True);
if IsFirstSnippet(l_ItemIndex) then
Msg.Pos.Y := Msg.Pos.Y - GetItemDim(l_ItemIndex).Y - InterRowIndent;
inherited;
//#UC END# *51F2344801D4_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.WMRButtonDown
procedure TnscDocumentListTreeView.WMGetText(var Msg: TWMGetText);
//#UC START# *51E00D2000A7_51D56E9F004B_var*
//#UC END# *51E00D2000A7_51D56E9F004B_var*
begin
//#UC START# *51E00D2000A7_51D56E9F004B_impl*
Msg.Result := StrLen(StrPLCopy(Msg.Text, GetCurrentText, Msg.TextMax - 1));
//#UC END# *51E00D2000A7_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.WMGetText
procedure TnscDocumentListTreeView.WMGetTextLength(var Msg: TWMGetTextLength);
//#UC START# *51E00DAD024C_51D56E9F004B_var*
//#UC END# *51E00DAD024C_51D56E9F004B_var*
begin
//#UC START# *51E00DAD024C_51D56E9F004B_impl*
Msg.Result := Length(GetCurrentText);
//#UC END# *51E00DAD024C_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.WMGetTextLength
constructor TnscDocumentListTreeView.Create(AOwner: TComponent);
//#UC START# *47D1602000C6_51D56E9F004B_var*
//#UC END# *47D1602000C6_51D56E9F004B_var*
begin
//#UC START# *47D1602000C6_51D56E9F004B_impl*
inherited;
ViewOptions := [voShowInterRowSpace,
voShowIcons,
voShowExpandable,
voShowOpenChip,
voDoNotShowFocusRect,
voFullLineSelect];
f_AllSelected := False;
//#UC END# *47D1602000C6_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.Create
function TnscDocumentListTreeView.DoOnGetItemImageIndex(aItemIndex: LongInt;
var aImages: TCustomImageList): Integer;
//#UC START# *508F81110075_51D56E9F004B_var*
const
cDisbledSnippetIcon = 11;
//#UC END# *508F81110075_51D56E9F004B_var*
begin
//#UC START# *508F81110075_51D56E9F004B_impl*
Result := inherited DoOnGetItemImageIndex(aItemIndex, aImages);
if Selected[aItemIndex] then
if Assigned(f_OnGetNodeType) then
begin
if f_OnGetNodeType(aItemIndex) = lntBlock then
Result := cDisbledSnippetIcon;
end else
Assert(False);
//#UC END# *508F81110075_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoOnGetItemImageIndex
procedure TnscDocumentListTreeView.DoOnGetItemStyle(aItemIndex: Integer;
const aFont: Il3Font;
var aTextBackColor: TColor;
var aItemBackColor: TColor;
var aVJustify: TvtVJustify;
var aFocused: Boolean;
var theImageVertOffset: Integer);
//#UC START# *508F825303E4_51D56E9F004B_var*
var
l_Color: TColor;
l_BackColor: TColor;
//#UC END# *508F825303E4_51D56E9F004B_var*
begin
//#UC START# *508F825303E4_51D56E9F004B_impl*
if IsFirstSnippet(aItemIndex) then
inherited DoOnGetItemStyle(aItemIndex - 1, aFont, aTextBackColor, aItemBackColor, aVJustify, aFocused, theImageVertOffset)
else
inherited DoOnGetItemStyle(aItemIndex, aFont, aTextBackColor, aItemBackColor, aVJustify, aFocused, theImageVertOffset);
if Assigned(TreeStruct.Nodes[aItemIndex]) then
if (not IsEmpty) and (TreeStruct.Nodes[aItemIndex].GetLevel > 1) then
begin
l_Color := aFont.ForeColor;
evGetStyleFont(aFont, ev_saSnippet);
if aFocused then
aFont.ForeColor := l_Color;
end;
//#UC END# *508F825303E4_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoOnGetItemStyle
procedure TnscDocumentListTreeView.pm_SetTopIndex(aValue: LongInt);
//#UC START# *515058D60074_51D56E9F004Bset_var*
//#UC END# *515058D60074_51D56E9F004Bset_var*
begin
//#UC START# *515058D60074_51D56E9F004Bset_impl*
if IsFirstSnippet(aValue)
then inherited pm_SetTopIndex(aValue + 1)
else inherited pm_SetTopIndex(aValue);
//#UC END# *515058D60074_51D56E9F004Bset_impl*
end;//TnscDocumentListTreeView.pm_SetTopIndex
function TnscDocumentListTreeView.CalcTopIndex(aMaxVisItem: LongInt): LongInt;
//#UC START# *5151B2C70248_51D56E9F004B_var*
//#UC END# *5151B2C70248_51D56E9F004B_var*
begin
//#UC START# *5151B2C70248_51D56E9F004B_impl*
Result := inherited CalcTopIndex(aMaxVisItem);
if IsFirstSnippet(Result) then
Inc(Result);
//#UC END# *5151B2C70248_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.CalcTopIndex
procedure TnscDocumentListTreeView.VlbVScrollPrim(aDelta: Integer);
//#UC START# *5152B96600E1_51D56E9F004B_var*
var
l_TopIndex: Integer;
//#UC END# *5152B96600E1_51D56E9F004B_var*
begin
//#UC START# *5152B96600E1_51D56E9F004B_impl*
l_TopIndex := TopIndex + aDelta;
if IsFirstSnippet(l_TopIndex) then
begin
if aDelta > 0 then
Inc(l_TopIndex)
else
Dec(l_TopIndex);
TopIndex := Min(Max(l_TopIndex, 0), Total - 1);
end else
inherited;
//#UC END# *5152B96600E1_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.VlbVScrollPrim
function TnscDocumentListTreeView.VlbItemHitTest(aIndex: Integer;
const aPt: TPoint;
fromScreen: Boolean = False): Byte;
//#UC START# *5152C09F00DB_51D56E9F004B_var*
//#UC END# *5152C09F00DB_51D56E9F004B_var*
begin
//#UC START# *5152C09F00DB_51D56E9F004B_impl*
Result := inherited VlbItemHitTest(aIndex, aPt, fromScreen);
//#UC END# *5152C09F00DB_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.VlbItemHitTest
procedure TnscDocumentListTreeView.DoOnGetItemColor(Index: LongInt;
var FG: TColor;
var BG: TColor);
//#UC START# *5152C79F0258_51D56E9F004B_var*
//#UC END# *5152C79F0258_51D56E9F004B_var*
begin
//#UC START# *5152C79F0258_51D56E9F004B_impl*
inherited DoOnGetItemColor(Index, FG, BG);
if Assigned(TreeStruct.Nodes[Index]) then
if (not IsEmpty) and (TreeStruct.Nodes[Index].GetLevel > 1) then
FG := $818386;
//#UC END# *5152C79F0258_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoOnGetItemColor
function TnscDocumentListTreeView.DoOnIsSelected(Index: LongInt): Integer;
//#UC START# *5152C8300174_51D56E9F004B_var*
//#UC END# *5152C8300174_51D56E9F004B_var*
begin
//#UC START# *5152C8300174_51D56E9F004B_impl*
Result := inherited DoOnIsSelected(Index);
if not IsEmpty then
if IsFirstSnippet(Index) then
Result := 0;
//#UC END# *5152C8300174_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoOnIsSelected
procedure TnscDocumentListTreeView.DoOnSelect(Index: LongInt;
aValue: Integer);
//#UC START# *5152C85403DA_51D56E9F004B_var*
var
l_NewNodeIndex: Integer;
l_FullInvalidate: Boolean;
//#UC END# *5152C85403DA_51D56E9F004B_var*
begin
//#UC START# *5152C85403DA_51D56E9F004B_impl*
inherited DoOnSelect(Index, aValue);
l_FullInvalidate := f_AllSelected or (Index = vt_smAllSelect);
f_AllSelected := False;
if Index = vt_smAllSelect then
f_AllSelected := Boolean(aValue)
else
if IsDocumentWithSnippets(Index) then
InvalidateItem(Index + 1);
if l_FullInvalidate then
Invalidate;
//#UC END# *5152C85403DA_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoOnSelect
procedure TnscDocumentListTreeView.DoOnSelectOutRange(First: LongInt;
Last: LongInt;
aSelectState: Integer);
//#UC START# *5152C88400DC_51D56E9F004B_var*
//#UC END# *5152C88400DC_51D56E9F004B_var*
begin
//#UC START# *5152C88400DC_51D56E9F004B_impl*
inherited;
Invalidate;
//#UC END# *5152C88400DC_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoOnSelectOutRange
function TnscDocumentListTreeView.DoDoProcessCommand(Cmd: Tl3OperationCode): Boolean;
//#UC START# *5152C93400EB_51D56E9F004B_var*
var
l_Curr: Integer;
//#UC END# *5152C93400EB_51D56E9F004B_var*
begin
//#UC START# *5152C93400EB_51D56E9F004B_impl*
case Cmd of
ccDown:
begin
Result := True;
l_Curr := Current;
if GetNextItem(l_Curr) then
Current := l_Curr
else
FooterSelected := True;
end;
ccUp:
begin
if FooterSelected then
FooterSelected := False
else
begin
l_Curr := Current;
if GetPrevItem(l_Curr) then
Current := l_Curr;
end;
Result := True;
end;
ccExtendDown:
begin
l_Curr := Current;
Result := GetNextItem(l_Curr);
if Result then
begin
if TreeStruct.Select[l_Curr] then
InternalSetSelected(Current, False)
else
InternalSetSelected(l_Curr, True);
InternalSetCurrent(l_Curr);
VlbMakeItemVisible(l_Curr);
end;
end;
ccExtendUp:
begin
l_Curr := Current;
Result := GetPrevItem(l_Curr);
if Result then
begin
if TreeStruct.Select[l_Curr] then
InternalSetSelected(Current, False)
else
InternalSetSelected(l_Curr, True);
InternalSetCurrent(l_Curr);
VlbMakeItemVisible(l_Curr);
end;
end;
else
Result := inherited DoDoProcessCommand(Cmd);
end;
//#UC END# *5152C93400EB_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoDoProcessCommand
procedure TnscDocumentListTreeView.DoCurrentChanged(aNewCurrent: LongInt;
aOldCurrent: LongInt);
//#UC START# *5152CA8601A6_51D56E9F004B_var*
var
l_Node: Il3SimpleNode;
l_LastSnippetIdx: LongInt;
//#UC END# *5152CA8601A6_51D56E9F004B_var*
begin
//#UC START# *5152CA8601A6_51D56E9F004B_impl*
inherited;
// Костыль: в случае, если последним в списке оказывался документ с одним сниппетом,
// ссылка "показать полный список" не появлялась. Поэтому, здесь
// пытаемся определить, не последний ли документ в списке выбран и не с одним
// ли он сниппетом. Если так - то делаем видимым этот его сниппет, чтобы
// появилась ссылка.
// http://mdp.garant.ru/pages/viewpage.action?pageId=469800200
if IsDocumentWithSnippets(aOldCurrent) then
InvalidateItem(aOldCurrent + 1);
if IsDocumentWithSnippets(aNewCurrent) then
begin
l_Node := TreeStruct.Nodes[aNewCurrent];
if (l_Node.HasChild) and (l_Node.ThisChildrenCount = 1) then
begin
l_LastSnippetIdx := TreeStruct.GetIndex(l_Node.Child);
if (l_LastSnippetIdx = f_HighIndex) then
vlbMakeItemVisible(l_LastSnippetIdx);
end;
InvalidateItem(aNewCurrent + 1);
end;
//#UC END# *5152CA8601A6_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoCurrentChanged
procedure TnscDocumentListTreeView.DoValidateCurrent(var aIndex: LongInt);
//#UC START# *5152CBED028E_51D56E9F004B_var*
//#UC END# *5152CBED028E_51D56E9F004B_var*
begin
//#UC START# *5152CBED028E_51D56E9F004B_impl*
if IsFirstsnippet(aIndex) then
Dec(aIndex);
inherited DoValidateCurrent(aIndex);
//#UC END# *5152CBED028E_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoValidateCurrent
procedure TnscDocumentListTreeView.SelectItems(aFinish: Integer);
//#UC START# *515584B701A0_51D56E9F004B_var*
//#UC END# *515584B701A0_51D56E9F004B_var*
begin
//#UC START# *515584B701A0_51D56E9F004B_impl*
if IsDocumentWithSnippets(aFinish) then
Inc(aFinish);
inherited SelectItems(aFinish);
//#UC END# *515584B701A0_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.SelectItems
procedure TnscDocumentListTreeView.HitTest(const aPt: TPoint;
var aIndex: Integer;
var aItemPart: Byte;
fromScreen: Boolean = False);
//#UC START# *515586660348_51D56E9F004B_var*
//#UC END# *515586660348_51D56E9F004B_var*
begin
//#UC START# *515586660348_51D56E9F004B_impl*
inherited HitTest(aPt, aIndex, aItemPart, fromScreen);
if IsFirstSnippet(aIndex) then
Dec(aIndex);
//#UC END# *515586660348_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.HitTest
procedure TnscDocumentListTreeView.VlbToggleSelection(Index: LongInt);
//#UC START# *51558804036E_51D56E9F004B_var*
//#UC END# *51558804036E_51D56E9F004B_var*
begin
//#UC START# *51558804036E_51D56E9F004B_impl*
if IsFirstSnippet(Index) then
begin
InternalSetSelected(Index, False); // первые сниппеты никогда не выделяем
Dec(Index);
end;
if not (TreeStruct.Select[Index] and (SelectedCount = 1)) then
inherited VlbToggleSelection(Index);
//#UC END# *51558804036E_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.VlbToggleSelection
function TnscDocumentListTreeView.DoOnGetItemIndentEx(anItemIndex: Integer): Integer;
//#UC START# *51D2DC290320_51D56E9F004B_var*
//#UC END# *51D2DC290320_51D56E9F004B_var*
begin
//#UC START# *51D2DC290320_51D56E9F004B_impl*
Result := 0;
if Assigned(TreeStruct.Nodes[anItemIndex]) then
if (not IsEmpty) and (TreeStruct.Nodes[anItemIndex].GetLevel > 1) then
if Assigned(f_OnGetNodeType) then
if f_OnGetNodeType(anItemIndex) = lntBlock then
Result := l3CrtIC.LP2DP(l3PointX(evGetStyleFirstIndent(ev_saSnippet))).X
else
Result := 5;
//#UC END# *51D2DC290320_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.DoOnGetItemIndentEx
function TnscDocumentListTreeView.GetSelectedCountForStatusbar: Integer;
//#UC START# *51DBCA8C0206_51D56E9F004B_var*
//#UC END# *51DBCA8C0206_51D56E9F004B_var*
begin
//#UC START# *51DBCA8C0206_51D56E9F004B_impl*
Result := inherited GetSelectedCountForStatusbar;
//#UC END# *51DBCA8C0206_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.GetSelectedCountForStatusbar
function TnscDocumentListTreeView.NeedDrawSelectionOnItem(aItemIndex: Integer): Boolean;
//#UC START# *51E8006D030E_51D56E9F004B_var*
//#UC END# *51E8006D030E_51D56E9F004B_var*
begin
//#UC START# *51E8006D030E_51D56E9F004B_impl*
if IsFirstSnippet(aItemIndex) then
Dec(aItemIndex);
Result := inherited NeedDrawSelectionOnItem(aItemIndex);
//#UC END# *51E8006D030E_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.NeedDrawSelectionOnItem
function TnscDocumentListTreeView.CanAcceptData(const aData: IDataObject): Boolean;
//#UC START# *51EEB81F017C_51D56E9F004B_var*
var
l_List: IDynList;
//#UC END# *51EEB81F017C_51D56E9F004B_var*
begin
//#UC START# *51EEB81F017C_51D56E9F004B_impl*
if Supports(TreeStruct, IDynList, l_List) and l_List.GetIsSnippet then
Result := False
else
Result := inherited CanAcceptData(aData);
//#UC END# *51EEB81F017C_51D56E9F004B_impl*
end;//TnscDocumentListTreeView.CanAcceptData
end. |
unit evCopyTableCellWidth;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Everest"
// Автор: Инишев Д.А.
// Модуль: "w:/common/components/gui/Garant/Everest/evCopyTableCellWidth.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::CellUtils::TevCopyTableCellWidth
//
// Интсрумент для копирования ширин колонок из одной таблицы в другую.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Everest\evDefine.inc}
interface
uses
l3Interfaces,
nevTools,
evEditorInterfaces,
l3ProtoObject,
evCellsOffsetsList
;
type
TevCopyTableCellWidth = {final} class(Tl3ProtoObject)
{* Интсрумент для копирования ширин колонок из одной таблицы в другую. }
private
// private fields
f_TemplatesArray : TevCellsOffsetsList;
f_TableTag : InevTag;
private
// private methods
procedure RememberRowWidth(const anIterator: IedCellsIterator);
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
// public methods
procedure RememberWidths(const aRange: IedRange); virtual;
procedure ApplyWidths(const aRange: IedRange;
const aProgress: Il3Progress = nil); virtual;
function CanApply: Boolean; virtual;
procedure Clear; virtual;
public
// singleton factory method
class function Instance: TevCopyTableCellWidth;
{- возвращает экземпляр синглетона. }
end;//TevCopyTableCellWidth
implementation
uses
l3Base {a},
nevBase,
evCellsWidthCorrecter
;
// start class TevCopyTableCellWidth
var g_TevCopyTableCellWidth : TevCopyTableCellWidth = nil;
procedure TevCopyTableCellWidthFree;
begin
l3Free(g_TevCopyTableCellWidth);
end;
class function TevCopyTableCellWidth.Instance: TevCopyTableCellWidth;
begin
if (g_TevCopyTableCellWidth = nil) then
begin
l3System.AddExitProc(TevCopyTableCellWidthFree);
g_TevCopyTableCellWidth := Create;
end;
Result := g_TevCopyTableCellWidth;
end;
procedure TevCopyTableCellWidth.RememberRowWidth(const anIterator: IedCellsIterator);
//#UC START# *4F29052701FB_4F28F7160399_var*
//#UC END# *4F29052701FB_4F28F7160399_var*
begin
//#UC START# *4F29052701FB_4F28F7160399_impl*
f_TemplatesArray.Try2RemeberWidths(anIterator);
//#UC END# *4F29052701FB_4F28F7160399_impl*
end;//TevCopyTableCellWidth.RememberRowWidth
procedure TevCopyTableCellWidth.RememberWidths(const aRange: IedRange);
//#UC START# *4F28FC7702ED_4F28F7160399_var*
var
l_Row : IedRow;
l_Table : IedTable;
l_RowsIterator : IedRowsIterator;
l_CellIterator : IedCellsIterator;
//#UC END# *4F28FC7702ED_4F28F7160399_var*
begin
//#UC START# *4F28FC7702ED_4F28F7160399_impl*
if (aRange <> nil) then
begin
l_Table := aRange.Table;
if (l_Table <> nil) then
begin
l_RowsIterator := l_Table.RowsIterator;
if (l_RowsIterator <> nil) then
begin
l_Row := l_RowsIterator.First;
if f_TemplatesArray = nil then
f_TemplatesArray := TevCellsOffsetsList.Create
else
f_TemplatesArray.Clear;
while (l_Row <> nil) do
begin
l_CellIterator := l_Row.CellsIterator;
if l_CellIterator <> nil then
RememberRowWidth(l_CellIterator);
l_Row := l_RowsIterator.Next;
end; // while (l_Row <> nil) do
f_TableTag := l_Table.GetTag;
end; // if (l_RowsIterator <> nil) then
end; // if (l_Table <> nil) then
end; // if (aRange <> nil) then
//#UC END# *4F28FC7702ED_4F28F7160399_impl*
end;//TevCopyTableCellWidth.RememberWidths
procedure TevCopyTableCellWidth.ApplyWidths(const aRange: IedRange;
const aProgress: Il3Progress = nil);
//#UC START# *4F28FC900076_4F28F7160399_var*
var
l_Table: IedTable;
//#UC END# *4F28FC900076_4F28F7160399_var*
begin
//#UC START# *4F28FC900076_4F28F7160399_impl*
if (aRange <> nil) then
begin
l_Table := aRange.Table;
if (l_Table <> nil) and (f_TemplatesArray <> nil) and (f_TemplatesArray.Count > 0) then
begin
if l_Table.GetTag.IsSame(f_TableTag) then
TevCellsWidthCorrecter.DoCorrection(l_Table, nil, True, aProgress)
else
TevCellsWidthCorrecter.DoCorrection(l_Table, f_TemplatesArray, True, aProgress);
end; // if (l_Table <> nil) and (f_TemplatesArray <> nil) and (f_TemplatesArray.Count > 0) then
end; // if (aRange <> nil) then
//#UC END# *4F28FC900076_4F28F7160399_impl*
end;//TevCopyTableCellWidth.ApplyWidths
function TevCopyTableCellWidth.CanApply: Boolean;
//#UC START# *4F28FCC703E7_4F28F7160399_var*
//#UC END# *4F28FCC703E7_4F28F7160399_var*
begin
//#UC START# *4F28FCC703E7_4F28F7160399_impl*
Result := (f_TemplatesArray <> nil) and (f_TemplatesArray.Count > 0);
//#UC END# *4F28FCC703E7_4F28F7160399_impl*
end;//TevCopyTableCellWidth.CanApply
procedure TevCopyTableCellWidth.Clear;
//#UC START# *4F28FCDD00F8_4F28F7160399_var*
//#UC END# *4F28FCDD00F8_4F28F7160399_var*
begin
//#UC START# *4F28FCDD00F8_4F28F7160399_impl*
l3Free(f_TemplatesArray);
f_TableTag := nil;
inherited;
//#UC END# *4F28FCDD00F8_4F28F7160399_impl*
end;//TevCopyTableCellWidth.Clear
procedure TevCopyTableCellWidth.Cleanup;
//#UC START# *479731C50290_4F28F7160399_var*
//#UC END# *479731C50290_4F28F7160399_var*
begin
//#UC START# *479731C50290_4F28F7160399_impl*
l3Free(f_TemplatesArray);
f_TableTag := nil;
inherited;
//#UC END# *479731C50290_4F28F7160399_impl*
end;//TevCopyTableCellWidth.Cleanup
end. |
unit StdBroadcast;
interface
const
tidBroadcast_TV = 'TV';
tidBroadcast_Radio = 'Radio';
tidEnvironment_TV = tidBroadcast_TV;
tidEnvironment_Radio = tidBroadcast_Radio;
procedure RegisterSurfaces;
implementation
uses
Surfaces;
procedure RegisterSurfaces;
begin
TSurface.Create( tidBroadcast_TV, 'TV' );
TSurface.Create( tidBroadcast_Radio, 'Radio' );
end;
end.
|
unit untFiltreSeuilAdaptatif;
interface
uses
StdCtrls, Controls, ExtCtrls, Classes,
untHFiltreImage, untCalcImage, Dialogs, untHFiltreFiltreDigital;
type
TTypeFiltreSeuilAdaptatif = (tfMoyenne, tfMinMax, tfGaussien);
type
TfrmFiltreSeuilAdaptatif = class(TfrmHFiltreFiltreDigital)
rdgTypeFiltre: TRadioGroup;
edtDeviation: TEdit;
lblDeviation: TLabel;
grbCouleurMinimale: TGroupBox;
ShapeCouleur: TShape;
lblRouge: TLabel;
lblVert: TLabel;
lblBleu: TLabel;
lblCouleur: TLabel;
btnSelectionCouleur: TButton;
edtRouge: TEdit;
edtVert: TEdit;
edtBleu: TEdit;
ColorDialog: TColorDialog;
procedure rdgTypeFiltreClick(Sender: TObject);
procedure btnSelectionCouleurClick(Sender: TObject);
procedure edtRougeChange(Sender: TObject);
procedure edtVertChange(Sender: TObject);
procedure edtBleuChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure edtDeviationChange(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
Couleur : TCouleur;
Deviation : Double;
TypeFiltre : TTypeFiltreSeuilAdaptatif;
procedure PrevisualiseResultat; override;
procedure RafraichirCouleur;
end;
procedure CalculerOperation(Image : TCalcImage; CouleurMin : TCouleur; TailleFiltre : Integer; Deviation : Double; TypeFiltre : TTypeFiltreSeuilAdaptatif; var ImageResultat : TCalcImage);
var
frmFiltreSeuilAdaptatif: TfrmFiltreSeuilAdaptatif;
implementation
uses
SysUtils, Forms, Math,
untMDIImage, untPrincipale,
untFiltreMoyenne, untFiltreMinMax, untFiltreGauss, untFiltreSubImageImage, untFiltreAbs, untFiltreSeuil;
{$R *.DFM}
{ TfrmFiltreSeuilAdaptatif }
procedure TfrmFiltreSeuilAdaptatif.PrevisualiseResultat;
var
X, Y : Integer;
X2, Y2 : Integer;
begin
if EnabledOK then // Si l'image est "compatible"
begin
for X := 0 to CalcImagePrevisualisation.TailleX - 1 do
begin
X2 := X * (TfrmMDIImage(Image).CalcImage.TailleX - 1) div (CalcImagePrevisualisation.TailleX - 1); // Calcul le pixel correspondant sur les images d'origines
for Y := 0 to CalcImagePrevisualisation.TailleY - 1 do
begin
Y2 := Y * (TfrmMDIImage(Image).CalcImage.TailleY - 1) div (CalcImagePrevisualisation.TailleY - 1); // Calcul le pixel correspondant sur les images d'origines
CalcImagePrev.Image[X, Y] := TfrmMDIImage(Image).CalcImage.Image[X2, Y2]; // Copie les pixels des images d'origine sur les images de prévisualisation
end;
end;
CalculerOperation(CalcImagePrev, Couleur, TailleFiltre, Deviation, TypeFiltre, CalcImagePrevisualisation); // Calcul l'image résultat de la prévisualisation
AffichePrevisualisation; // Affiche la prévisualisation
end;
end;
procedure TfrmFiltreSeuilAdaptatif.RafraichirCouleur;
begin
ShapeCouleur.Brush.Color := CouleurToColor(Couleur);
ColorDialog.Color := CouleurToColor(Couleur);
PrevisualiseResultat;
end;
procedure TfrmFiltreSeuilAdaptatif.rdgTypeFiltreClick(Sender: TObject);
begin
case rdgTypeFiltre.ItemIndex of // Selon le type de filtre selectionné
0 : TypeFiltre := tfMoyenne;
1 : TypeFiltre := tfMinMax;
2 : TypeFiltre := tfGaussien;
end;
lblDeviation.Visible := rdgTypeFiltre.ItemIndex = 2; // Affiche le paramètre déviation
edtDeviation.Visible := rdgTypeFiltre.ItemIndex = 2; // si le filtre Gaussien est sélectionné
PrevisualiseResultat;
end;
procedure TfrmFiltreSeuilAdaptatif.btnSelectionCouleurClick(
Sender: TObject);
begin
if ColorDialog.Execute then
begin
Couleur.Rouge := ColorDialog.Color and $000000FF; // Calcul les différents
Couleur.Vert := (ColorDialog.Color and $0000FF00) shr 8; // composants de la
Couleur.Bleu := (ColorDialog.Color and $00FF0000) shr 16; // couleur choisie
edtRouge.Text := FloatToStr(Couleur.Rouge);
edtVert.Text := FloatToStr(Couleur.Vert);
edtBleu.Text := FloatToStr(Couleur.Bleu);
RafraichirCouleur;
end;
end;
procedure TfrmFiltreSeuilAdaptatif.edtRougeChange(Sender: TObject);
begin
edtRouge.Text := FormateNombreDecimal(edtRouge.Text, False, Couleur.Rouge);
Application.ProcessMessages;
RafraichirCouleur;
end;
procedure TfrmFiltreSeuilAdaptatif.edtVertChange(Sender: TObject);
begin
edtVert.Text := FormateNombreDecimal(edtVert.Text, False, Couleur.Vert);
Application.ProcessMessages;
RafraichirCouleur;
end;
procedure TfrmFiltreSeuilAdaptatif.edtBleuChange(Sender: TObject);
begin
edtBleu.Text := FormateNombreDecimal(edtBleu.Text, False, Couleur.Bleu);
Application.ProcessMessages;
RafraichirCouleur;
end;
procedure TfrmFiltreSeuilAdaptatif.FormCreate(Sender: TObject);
begin
inherited;
Couleur.Rouge := 50;
Couleur.Vert := 50;
Couleur.Bleu := 50;
TypeFiltre := tfMoyenne;
Deviation := 2;
end;
procedure CalculerOperation(Image : TCalcImage; CouleurMin : TCouleur; TailleFiltre : Integer; Deviation : Double; TypeFiltre : TTypeFiltreSeuilAdaptatif; var ImageResultat : TCalcImage);
var
CouleurS : TCouleur;
begin
case TypeFiltre of // Selon le type de filtre voulu
tfMoyenne : untFiltreMoyenne.CalculerPrevisualisation(Image, TailleFiltre, ImageResultat); // Applique le flou Moyenne à l'image
tfMinMax : untFiltreMinMax.CalculerPrevisualisation(Image, TailleFiltre, ImageResultat); // Applique le flou Min/Max à l'image
tfGaussien : untFiltreGauss.CalculerPrevisualisation(Image, TailleFiltre, Deviation, ImageResultat); // Applique le flou Gaussien à l'image
end;
untFiltreSubImageImage.CalculerOperation(Image, ImageResultat, ImageResultat); // Soustrait les deux images
untFiltreAbs.CalculerOperation(ImageResultat, ImageResultat); // Calcul la valeur absolue du résultat
CouleurS.Rouge := MaxDouble;
CouleurS.Vert := MaxDouble;
CouleurS.Bleu := MaxDouble;
untFiltreSeuil.CalculerOperation(ImageResultat, CouleurMin, CouleurS, ImageResultat); // Affiche les contours
end;
procedure TfrmFiltreSeuilAdaptatif.btnOKClick(Sender: TObject);
begin
inherited;
case TypeFiltre of // Selon le type de filtre voulu
tfMoyenne : TfrmMDIImage(ListeImages.Last).Caption := Format('SeuilAdaptatifMoyenne(%s, %d, RGB(%g, %g, %g))', [TfrmMDIImage(Image).Caption, TailleFiltre, Couleur.Rouge, Couleur.Vert, Couleur.Bleu]); // Affiche le titre de l'image
tfMinMax : TfrmMDIImage(ListeImages.Last).Caption := Format('SeuilAdaptatifMinMax(%s, %d, RGB(%g, %g, %g))', [TfrmMDIImage(Image).Caption, TailleFiltre, Couleur.Rouge, Couleur.Vert, Couleur.Bleu]); // Affiche le titre de l'image
tfGaussien : TfrmMDIImage(ListeImages.Last).Caption := Format('SeuilAdaptatifGauss(%s, %d, %g, RGB(%g, %g, %g))', [TfrmMDIImage(Image).Caption, TailleFiltre, Deviation, Couleur.Rouge, Couleur.Vert, Couleur.Bleu]); // Affiche le titre de l'image
end;
CalculerOperation(TfrmMDIImage(Image).CalcImage, Couleur, TailleFiltre, Deviation, TypeFiltre, TfrmMDIImage(ListeImages.Last).CalcImage); // Calcul le résultat
TfrmMDIImage(ListeImages.Last).AfficheImage; // Affiche le résultat
end;
procedure TfrmFiltreSeuilAdaptatif.edtDeviationChange(Sender: TObject);
begin
edtDeviation.Text := FormateNombreDecimal(edtDeviation.Text, False, Deviation);
Application.ProcessMessages;
PrevisualiseResultat;
end;
end.
|
unit steProcessor;
(*
+--------------------------+
| ┏━┓╺┳╸┏━╸ Simple |
| ┗━┓ ┃ ┣╸ Template |
| ┃ ┃ ┃ Engine |
| ┗━┛ ╹ ┗━╸ for Free Pascal |
+ -------------------------+
*)
{$mode objfpc}{$H+}
// generate output with previously prepared template
interface
uses
Classes, SysUtils, steParser, db;
type
TSTEExpandTagProc = function (const tagParam: string): string of object;
TSTEEvaluateCondProc = function (const ACondName: string): boolean of object;
TSTEExpandTagCallbackInfo = record
Tag : string;
Proc : TSTEExpandTagProc;
end;
TSTEConditionCallbackInfo = record
ConditionName : string;
Proc : TSTEEvaluateCondProc;
end;
type
TSTEProcessor = class
private
FCurrentToken : integer;
FGenerating : boolean; // for handle recursion
FUseDataSetPrefix : boolean; // ise prefixes for dataset names
FDSNamespaceLength : integer;
procedure DisposeValues;
function GetOwnsDatasets : boolean;
procedure SetOwnsDatasets(AValue : boolean);
protected
FOutput : TStream; // not owned
FTemplate : TSTEParsedTemplateData; // template being generated, not owned
FDatasets : TStringList;
FValues : TStringList; //todo: replace with TFPStringHashTable
FExpandTagCallbacks : array of TSTEExpandTagCallbackInfo;
FConditionalCallbacks : array of TSTEConditionCallbackInfo;
procedure ProcessTextToken(token : PSTEParserToken);
procedure ProcessTokens(iEnd : integer);
procedure ProcessIfBlock(token : PSTEParserToken);
procedure ProcessForBlock(token : PSTEParserToken);
procedure ProcessSetBlock(token : PSTEParserToken);
function CheckDSNamespaceDataset(const PrefixedDsName : string; out PureDsName : string) : boolean;
function GetDataset(const dsName : string) : TDataset;
function GetFieldValue(const dsName, fieldName : string; out Value : string) : boolean;
function GetFieldValue(const dsName, fieldName : string; out Value : boolean) : boolean;
function ExpandTag(const tagName, tagParam: string): string; virtual;
function EvaluateIf(const Param : string) : boolean; virtual;
function BeginFor(const Param: string; out data : pointer) : boolean; virtual; // should return true to begin loop
function EndFor(data : pointer) : boolean; virtual; // should return true to stop loop (at EOF)
function CheckTagCallbacks(const tagName, tagParam: string; var Value : string) : boolean;
function CheckConditionalCallbacks(const ACondName: string; var Value : boolean) : boolean;
public
DataSetPrefix : string; // prefix for datasets (for more readable distinction) // set to empty to disable feature
// callback should return false, if tag not handled
OnExpandTag : function (const tagName, tagParam: string; out Value : string) : boolean of object;
UnkownTagFeedback : boolean; // When true (default) all unknown tags echoed to output using UnkownTagFeedbackFormat
// You may want to disable this feature for production
UnkownTagFeedbackFormat : string;
property OwnsDatasets : boolean read GetOwnsDatasets write SetOwnsDatasets;
procedure AddDataset(const dsName : string; ds : TDataset);
//===== todo ? : should be values stored as variant ?
procedure SetValue(const key, value : string);
procedure SetValue(const key : string; const value : boolean);
procedure SetValue(const key : string; const value : integer);
procedure SetValue(const key : string; const value : single);
procedure SetValue(const key : string; const value : double);
procedure AddTagCallback(const tagName : string; ACallbackProc : TSTEExpandTagProc);
procedure AddConditionCallback(const ACondName : string; ACallbackProc : TSTEEvaluateCondProc);
property Output : TStream read FOutput write FOutput;
property Template : TSTEParsedTemplateData read FTemplate write FTemplate;
procedure Generate(ATemplate : TSTEParsedTemplateData; AStream : TStream);
procedure Generate; // to/from prevoiously assigned external OutputStream and prepared Template
constructor Create;
destructor Destroy; override;
end;
implementation
uses strutils;
const
steNumericFieldTypes = [ftInteger, ftSmallint, ftWord, ftFloat, ftAutoInc, ftBCD, ftLargeint];
function TSTEProcessor.ExpandTag(const tagName, tagParam: string): string;
var
i : integer;
dsname : string;
begin
if Assigned(OnExpandTag) then
if OnExpandTag(tagName, tagParam, Result) then
Exit;
if CheckDSNamespaceDataset(tagName, dsname) then begin // try if this is a dataset field
if GetFieldValue(dsname, tagParam, Result) then
Exit;
end else begin
//try callbacks
if CheckTagCallbacks(tagName, tagParam, Result) then
Exit;
//try plain values
if (tagParam = '') then begin
i := FValues.IndexOf(tagName);
if i <> -1 then begin
Result := Pstring(FValues.Objects[i])^;
Exit;
end;
end;
end;
// nothing found
if UnkownTagFeedback then
Result := format( UnkownTagFeedbackFormat, [tagName] ) //echo tag --- for debug purposes
else
Result := '';
end;
function TSTEProcessor.EvaluateIf(const Param: string): boolean;
var
i: Integer;
fldName, dsName : string;
Value : boolean;
const
psep : TSysCharSet = [' '];
begin
Result := false;
//try callbacks
if CheckConditionalCallbacks(Param, Value) then begin
Result := Value;
Exit;
end;
i := FValues.IndexOf(Param);
if i <> -1 then begin
Result := ( PString(FValues.Objects[i])^ <> '' );
end else begin
//------- try dataset
if CheckDSNamespaceDataset(ExtractWord(1, Param, psep), dsName) then begin
fldName := ExtractWord(2, Param, psep);
if fldName = '' then
Exit;
if GetFieldValue(dsName, fldName, Value) then
Result := Value;
end;
end;
end;
function TSTEProcessor.BeginFor(const Param: string; out data: pointer): boolean;
var
ds : TDataSet;
dsname : string;
begin
if CheckDSNamespaceDataset(Param, dsname) then begin
ds := GetDataset(dsname);
Result := ( (ds <> nil) and ds.Active and (not ds.EOF));
data := ds;
end else
Result := false;
end;
function TSTEProcessor.EndFor(data: pointer): boolean;
var
ds : TDataSet;
begin
Result := true;
ds := TDataset(data);
if ds <> nil then begin
ds.Next;
Result := ds.EOF;
end;
//WriteLn('ENDFOR: ', Result);
end;
function TSTEProcessor.CheckTagCallbacks(const tagName, tagParam: string; var Value: string): boolean;
var
i : integer;
begin
Result := false;
for i := Low(FExpandTagCallbacks) to High(FExpandTagCallbacks) do
with FExpandTagCallbacks[i] do begin
if tagName = Tag then begin
Value := Proc(tagParam);
Result := true;
Break;
end;
end;
end;
function TSTEProcessor.CheckConditionalCallbacks(const ACondName : string; var Value : boolean) : boolean;
var
i : integer;
begin
Result := false;
for i := Low(FConditionalCallbacks) to High(FConditionalCallbacks) do
with FConditionalCallbacks[i] do begin
if ACondName = ConditionName then begin
Value := Proc(ACondName);
Result := true;
Break;
end;
end;
end;
procedure TSTEProcessor.ProcessTextToken(token: PSTEParserToken);
var
customTagText : string;
ln : integer;
begin
if token^.Kind = tkPlainText then
FOutput.Write( FTemplate.Source[token^.StartPos], token^.Size )
else
if token^.Kind = tkCustomTag then begin
customTagText := ExpandTag(token^.Tag, token^.Param);
ln := Length(customTagText);
if ln > 0 then
FOutput.Write( customTagText[1], ln);
end;
end;
procedure TSTEProcessor.ProcessTokens(iEnd: integer);
var
token : PSTEParserToken;
begin
if iEnd > (FTemplate.Tokens.Count-1) then
Exit;
while (FCurrentToken <= iEnd) do begin
token := PSTEParserToken(FTemplate.Tokens.Items[FCurrentToken]);
//Writeln('Processing token ', FCurrentToken, '-->', STETokenTagNames[token^.Kind], ' line: ', GetSourceLineNumber(FTemplate.Source, token^.StartPos) );
case token^.Kind of
tkPlainText, tkCustomTag : ProcessTextToken(token);
tkIf :
begin
ProcessIfBlock(token);
Continue;
end;
tkFor : ProcessForBlock(token);
tkSet: ProcessSetBlock(token);
end; // case
inc(FCurrentToken);
end;
end;
procedure TSTEProcessor.ProcessIfBlock(token: PSTEParserToken);
var
linked: PSTEParserToken;
hasElse : boolean;
begin
linked := PSTEParserToken(token^.LinkedToken);
hasElse := linked^.Kind = tkElse;
//WriteLn('IF block, hasElse -- ', hasElse, ' -- line: ', GetSourceLineNumber(FTemplate.Source, token^.StartPos) );
if EvaluateIf(token^.Param) then begin
//WriteLn('IF evaluated as true');
inc(FCurrentToken);
ProcessTokens(linked^.Index);
if hasElse then begin// there is an else block -- skip it
//WriteLn('skipping else block');
linked := PSTEParserToken(linked^.LinkedToken);
FCurrentToken := linked^.Index; // so skip to endif
end;
end else begin
if hasElse then begin // execute else block
FCurrentToken := linked^.Index;
linked := PSTEParserToken(linked^.LinkedToken); //endif
ProcessTokens(linked^.Index);
end else
FCurrentToken := linked^.Index;
end;
end;
procedure TSTEProcessor.ProcessForBlock(token: PSTEParserToken);
var
linked: PSTEParserToken;
data : pointer;
begin
linked := PSTEParserToken(token^.LinkedToken);
//Writeln('FOR, FCurrentToken', FCurrentToken);
if BeginFor(token^.Param, data) then begin
repeat
FCurrentToken := token^.Index+1;
ProcessTokens(linked^.Index);
until EndFor(data);
end;
FCurrentToken := linked^.Index;
end;
procedure TSTEProcessor.ProcessSetBlock(token : PSTEParserToken);
var
textToken: PSTEParserToken;
begin
textToken := PSTEParserToken(FTemplate.Tokens.Items[ token^.Index+1 ]);
SetValue(token^.Param, Copy(FTemplate.Source, textToken^.StartPos, textToken^.Size) );
FCurrentToken := PSTEParserToken(token^.LinkedToken)^.Index;
end;
procedure TSTEProcessor.DisposeValues;
var
i : integer;
begin
for i := 0 to FValues.Count-1 do
Dispose( pstring(FValues.Objects[i]) );
FValues.Free;
end;
function TSTEProcessor.GetOwnsDatasets : boolean;
begin
Result := FDatasets.OwnsObjects;
end;
procedure TSTEProcessor.SetOwnsDatasets(AValue : boolean);
begin
FDatasets.OwnsObjects := AValue;
end;
function TSTEProcessor.CheckDSNamespaceDataset(const PrefixedDsName: string; out PureDsName: string): boolean;
begin
Result := ( FUseDataSetPrefix and (Pos(DataSetPrefix, PrefixedDsName) = 1) ); // try if this is a dataset field
if Result then
PureDsName := Copy(PrefixedDsName, FDSNamespaceLength + 1, Length(PrefixedDsName)-FDSNamespaceLength);
end;
function TSTEProcessor.GetDataset(const dsName: string): TDataset;
var
i : integer;
begin
Result := nil;
i := FDatasets.IndexOf(dsName);
if i <> -1 then
Result := TDataset(FDatasets.Objects[i]);
end;
function TSTEProcessor.GetFieldValue(const dsName, fieldName: string; out Value: string): boolean;
var
ds : TDataSet;
fld : TField;
begin
Result := false;
ds := GetDataset(dsName);
if ds <> nil then begin
fld := ds.FindField(fieldName);
if fld <> nil then begin
if fld.IsBlob then
Value := fld.AsString // Display actual text instead of (MEMO)
else
Value := fld.DisplayText;
Result := true;
end;
end;
end;
function TSTEProcessor.GetFieldValue(const dsName, fieldName: string; out Value: boolean): boolean;
var
fld : TField;
ds : TDataset;
begin
Result := false;
ds := GetDataset(dsName);
if ds = nil then
Exit;
fld := ds.FindField( fieldName );
if fld = nil then
Exit;
Value := false;
Result := true;
if fld.DataType in steNumericFieldTypes then
Value := fld.Value > 0
else
if fld.DataType = ftBoolean then
Value := fld.AsBoolean
else
Value := (fld.AsString <> '');
end;
procedure TSTEProcessor.AddDataset(const dsName: string; ds: TDataset);
begin
FDatasets.AddObject(dsName, TObject(ds));
end;
procedure TSTEProcessor.SetValue(const key, value: string);
var
pValue : PString;
idx : integer;
begin
idx := FValues.IndexOf(key);
if idx = -1 then begin
New(pValue);
pValue^ := value;
FValues.AddObject(key, TObject(pValue) );
end else begin
PString(FValues.Objects[idx])^ := value;
end;
end;
procedure TSTEProcessor.SetValue(const key: string; const value: boolean);
begin
if value then
SetValue(key, '1' )
else
SetValue(key, '' );
end;
procedure TSTEProcessor.SetValue(const key : string; const value : integer);
begin
SetValue(key, intToStr(value) );
end;
procedure TSTEProcessor.SetValue(const key : string; const value : single);
begin
SetValue(key, floatToStr(value) );
end;
procedure TSTEProcessor.SetValue(const key : string; const value : double);
begin
SetValue(key, floatToStr(value) );
end;
procedure TSTEProcessor.AddTagCallback(const tagName : string; ACallbackProc : TSTEExpandTagProc);
var
i : integer;
begin
if ACallbackProc = nil then
raise Exception.CreateFmt('%s: AddTagCallback: unassigned tag callback', [Self.ClassName]);
i := Length(FExpandTagCallbacks);
SetLength(FExpandTagCallbacks, i+1);
FExpandTagCallbacks[i].Tag := tagName;
FExpandTagCallbacks[i].Proc := ACallbackProc;
end;
procedure TSTEProcessor.AddConditionCallback(const ACondName : string; ACallbackProc : TSTEEvaluateCondProc);
var
i : integer;
begin
if ACallbackProc = nil then
raise Exception.CreateFmt('%s: AddTagCallback: unassigned tag callback', [Self.ClassName]);
i := Length(FConditionalCallbacks);
SetLength(FConditionalCallbacks, i+1);
FConditionalCallbacks[i].ConditionName := ACondName;
FConditionalCallbacks[i].Proc := ACallbackProc;
end;
procedure TSTEProcessor.Generate;
begin
if FGenerating then Exit;
FGenerating := true;
try
FUseDataSetPrefix := (DataSetPrefix <> '');
FDSNamespaceLength := Length(DataSetPrefix);
FCurrentToken := 0;
ProcessTokens(FTemplate.Tokens.Count-1);
finally
FGenerating := false;
end;
end;
procedure TSTEProcessor.Generate(ATemplate : TSTEParsedTemplateData; AStream : TStream);
begin
FTemplate := ATemplate;
FOutput := AStream;
Generate;
end;
constructor TSTEProcessor.Create;
begin
FGenerating := false;
SetLength(FExpandTagCallbacks, 0);
SetLength(FConditionalCallbacks, 0);
FOutput := nil;
FTemplate := nil;
OnExpandTag := nil;
FDatasets := TStringList.Create;
FValues := TStringList.Create;
UnkownTagFeedback := true;
UnkownTagFeedbackFormat := '[{%s}]';
DataSetPrefix := 'ds:';
end;
destructor TSTEProcessor.Destroy;
begin
SetLength(FExpandTagCallbacks, 0);
SetLength(FConditionalCallbacks, 0);
FDatasets.Free;
DisposeValues;
inherited Destroy;
end;
end.
|
unit TestFMXCalloutMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Edit, FMX.EditBox,
FMX.SpinBox, FMX.Colors,
FMX.Callout,
FMX.Graphics.INativeCanvas,
FMX.Graphics.NativeCanvas;
type
TForm1 = class(TForm)
Selection1: TSelection;
TopSB: TSpeedButton;
BottomSB: TSpeedButton;
LeftSB: TSpeedButton;
RightSB: TSpeedButton;
XRadiusSpinBox: TSpinBox;
XRadiusLabel: TLabel;
Layout2: TLayout;
YRadiusSpinBox: TSpinBox;
YRadiusLabel: TLabel;
CalloutWidthSpinBox: TSpinBox;
CalloutWidthLabel: TLabel;
CalloutLengthSpinBox: TSpinBox;
CalloutLengthLabel: TLabel;
CalloutOffsetSpinBox: TSpinBox;
CalloutOffsetLabel: TLabel;
CalloutPeakOffsetSpinBox: TSpinBox;
CalloutPeakOffsetLabel: TLabel;
FillColorCB: TComboColorBox;
FillColorLabel: TLabel;
StrokeColorCB: TComboColorBox;
StrokeLabel: TLabel;
ThicknessSpinBox: TSpinBox;
Thickness0Label: TLabel;
NativeDrawSwitch: TSwitch;
Label2: TLabel;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure TopSBClick(Sender: TObject);
procedure XRadiusSpinBoxChangeTracking(Sender: TObject);
procedure YRadiusSpinBoxChangeTracking(Sender: TObject);
procedure CalloutWidthSpinBoxChangeTracking(Sender: TObject);
procedure CalloutLengthSpinBoxChangeTracking(Sender: TObject);
procedure CalloutOffsetSpinBoxChangeTracking(Sender: TObject);
procedure CalloutPeakOffsetSpinBoxChangeTracking(Sender: TObject);
procedure FillColorCBChange(Sender: TObject);
procedure StrokeColorCBChange(Sender: TObject);
procedure ThicknessSpinBoxChangeTracking(Sender: TObject);
procedure NativeDrawSwitchClick(Sender: TObject);
private
FCallout: TFMXCallout;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.FormCreate(Sender: TObject);
begin
FCallout := TFMXCallout.Create(Self);
Selection1.AddObject(FCallout);
FCallout.HitTest := False;
FCallout.Stroke.Cap := TStrokeCap.Round;
FCallout.Stroke.Join := TStrokeJoin.Round;
FCallout.Align := TAlignLayout.Client;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
XRadiusSpinBox.Value := FCallout.XRadius;
YRadiusSpinBox.Value := FCallout.YRadius;
CalloutWidthSpinBox.Value := FCallout.CalloutWidth;
CalloutLengthSpinBox.Value := FCallout.CalloutLength;
CalloutOffsetSpinBox.Value := FCallout.CalloutOffset;
CalloutPeakOffsetSpinBox.Value := FCallout.CalloutPeakOffset;
case FCallout.CalloutPosition of
TCalloutPosition.Top:
TopSB.IsPressed := True;
TCalloutPosition.Bottom:
BottomSB.IsPressed := True;
TCalloutPosition.Left:
LeftSB.IsPressed := True;
TCalloutPosition.Right:
RightSB.IsPressed := True;
end;
FillColorCB.Color := FCallout.Fill.Color;
StrokeColorCB.Color := FCallout.Stroke.Color;
ThicknessSpinBox.Value := FCallout.Stroke.Thickness;
end;
procedure TForm1.NativeDrawSwitchClick(Sender: TObject);
begin
FCallout.NativeDraw := NativeDrawSwitch.IsChecked;
end;
procedure TForm1.XRadiusSpinBoxChangeTracking(Sender: TObject);
begin
FCallout.XRadius := XRadiusSpinBox.Value;
end;
procedure TForm1.YRadiusSpinBoxChangeTracking(Sender: TObject);
begin
FCallout.YRadius := YRadiusSpinBox.Value;
end;
procedure TForm1.CalloutWidthSpinBoxChangeTracking(Sender: TObject);
begin
FCallout.CalloutWidth := CalloutWidthSpinBox.Value;
end;
procedure TForm1.CalloutLengthSpinBoxChangeTracking(Sender: TObject);
begin
FCallout.CalloutLength := CalloutLengthSpinBox.Value;
end;
procedure TForm1.CalloutOffsetSpinBoxChangeTracking(Sender: TObject);
begin
FCallout.CalloutOffset := CalloutOffsetSpinBox.Value;
end;
procedure TForm1.CalloutPeakOffsetSpinBoxChangeTracking(Sender: TObject);
begin
FCallout.CalloutPeakOffset := CalloutPeakOffsetSpinBox.Value;
end;
procedure TForm1.TopSBClick(Sender: TObject);
begin
if Sender = TopSB then
FCallout.CalloutPosition := TCalloutPosition.Top;
if Sender = BottomSB then
FCallout.CalloutPosition := TCalloutPosition.Bottom;
if Sender = LeftSB then
FCallout.CalloutPosition := TCalloutPosition.Left;
if Sender = RightSB then
FCallout.CalloutPosition := TCalloutPosition.Right;
end;
procedure TForm1.FillColorCBChange(Sender: TObject);
begin
FCallout.Fill.Color := FillColorCB.Color;
end;
procedure TForm1.StrokeColorCBChange(Sender: TObject);
begin
FCallout.Stroke.Color := StrokeColorCB.Color;
end;
procedure TForm1.ThicknessSpinBoxChangeTracking(Sender: TObject);
var
s: Single;
begin
FCallout.Stroke.Thickness := ThicknessSpinBox.Value;
s := ThicknessSpinBox.Value / 2;
Selection1.Padding.Rect := RectF(s, s * 2, s, s);
end;
end.
|
{ TODO:
property ShowFilenameInCaption: boolean;
property ShowFilenameWithoutExtInCaption: boolean;
}
{ from http://pp4s.co.uk/main/tu-form2-help-demo-laz.html }
unit htmlfileviewer;
{$mode objfpc}{$H+}
{$R htmlfileviewer.rc} //comment out if no resources used
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Buttons,
FileUtil, IpHtml, LazFileUtils, lclintf, LazHelpHTML,
Windows; //RT_RCDATA
type
TSimpleIpHtml = class(TIpHtml)
public
property OnGetImageX;
end;
{ THelpForm }
THelpForm = class(TForm)
IpHtmlPanel1: TIpHtmlPanel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure HTMLGetImageX(Sender: TIpHtmlNode;const URL: string;var Picture: TPicture);
procedure IpHtmlPanel1HotClick(Sender: TObject);
function GetResTemp: string;
procedure ExtractResources;
procedure DeleteExtractedResources;
private
ResDir: string;
Resources: TStringList;
public
procedure OpenFile(const Filename: string);
procedure OpenResource(const Resourcename : string);
procedure OpenURL(const aURL : string);
end;
const
DS=DirectorySeparator;
var
HelpForm: THelpForm;
implementation
{$R *.lfm}
{ Resources }
function THelpForm.GetResTemp: string;
begin
Result:=GetTempDir(false)+'res-htmlfileviewer'+DS;
end;
procedure THelpForm.DeleteExtractedResources;
var
i: integer;
f: string;
begin
try
for i:=0 to Resources.Count-1 do begin
f:=GetResTemp+Resources.ValueFromIndex[i];
if FileExists(f) then sysutils.DeleteFile(f);
end;
if DirectoryExists(GetResTemp) then
RemoveDir(GetResTemp);
finally
Resources.Free;
end;
end;
procedure THelpForm.ExtractResources;
var
i,q1: integer;
S: TResourceStream;
buff: TStringList;
ResName,ResValue: string;
begin
buff:=TStringList.Create;
Resources:=TStringList.Create;
try
//S:=TResourceStream.Create(HInstance, 'res', RT_RCDATA);
S:=TResourceStream.Create(HInstance, 'htmlfileviewer', PChar(600));
except
ShowMessage('debug error reading resources');
Exit;
end;
try
buff.LoadFromStream(S);
for i:=1 to buff.Count-1 do begin
//ResName:=Trim(Copy(buff[i],1,Pos('RCDATA',buff[i])-2));
ResName:=Trim(Copy(buff[i],1,Pos('600',buff[i])-2));
q1:=buff[i].IndexOf('"');
ResValue:=Trim(Copy(buff[i],q1+2,buff[i].Length-q1-2));
if ResName<>'' then begin
Resources.Add(ResName+'='+ExtractFileName(ResValue));
//ShowMessage('debug file ResName='+ResName+', ResValue='+ResValue);
end;
end;
finally
FreeAndNil(S);
buff.Free;
end;
ForceDirectories(GetResTemp);
try
for i:=0 to Resources.Count-1 do begin
//S:=TResourceStream.Create(HInstance, Resources.Names[i], RT_RCDATA);
S:=TResourceStream.Create(HInstance, Resources.Names[i], PChar(600));
S.SaveToFile(GetResTemp+Resources.ValueFromIndex[i]);
FreeAndNil(S);
end;
finally
FreeAndNil(S);
end;
end;
{ HelpForm }
procedure THelpForm.FormCreate(Sender: TObject);
begin
ResDir:=GetResTemp;
ExtractResources;
end;
procedure THelpForm.FormDestroy(Sender: TObject);
begin
DeleteExtractedResources;
end;
procedure THelpForm.HTMLGetImageX(Sender: TIpHtmlNode; const URL: string;
var Picture: TPicture);
var
PicCreated: boolean;
begin
try
if FileExistsUTF8(ResDir+URL) then
begin
PicCreated := False;
if Picture = nil then
begin
Picture := TPicture.Create;
PicCreated := True;
end;
Picture.LoadFromFile(ResDir+URL);
end;
except
if PicCreated then
Picture.Free;
Picture := nil;
end;
end;
procedure THelpForm.IpHtmlPanel1HotClick(Sender: TObject);
var
NodeA : TIpHtmlNodeA;
i: integer;
s: string;
anchor, filename: string;
begin
if IpHtmlPanel1.HotNode is TIpHtmlNodeA then
begin
NodeA := TIpHtmlNodeA(IpHtmlPanel1.HotNode);
s:=Trim(NodeA.HRef);
i:=Pos('#',s);
if i=0 then begin
if FileExists(ResDir+s) then
OpenFile(ResDir+s)
else
OpenResource(s);
end
else if i=1 then begin
anchor:=Copy(s,2,MaxInt);
IpHtmlPanel1.MakeAnchorVisible(anchor);
end else begin
filename:=Trim(Copy(s,1,i-1));
anchor:=Trim(Copy(s,i+1,MaxInt));
if FileExists(ResDir+filename) then
OpenFile(ResDir+filename)
else
OpenResource(filename);
IpHtmlPanel1.MakeAnchorVisible(anchor);
end;
end;
end;
procedure THelpForm.OpenFile(const Filename : string);
var
fs : TFileStream;
NewHTML : TSimpleIpHtml;
begin
if not FileExists(Filename) then Exit;
HelpForm.Show;
ResDir:=ExtractFilePath(Filename);
try
fs := TFileStream.Create(Filename, fmOpenRead);
try
NewHTML := TSimpleIpHtml.Create; // Note: Will be freed by IpHtmlPanel1
NewHTML.OnGetImageX := @HTMLGetImageX;
NewHTML.LoadFromStream(fs);
finally
fs.Free;
end;
IpHtmlPanel1.SetHtml(NewHTML);
HelpForm.Caption:='Help - '+Filename;
except
on E: Exception do
begin
MessageDlg('Unable to open HTML file', 'HTML File: ' + Filename + #13 +
'Error: ' + E.Message,mtError, [mbCancel], 0);
end;
end;
end;
procedure THelpForm.OpenResource(const Resourcename : string);
begin
if Resources.Count=0 then Exit;
HelpForm.Show;
OpenFile(GetResTemp+Resourcename);
end;
procedure THelpForm.OpenURL(const aURL : string);
begin
// browser lclintf.OpenURL(aURL);
IpHtmlPanel1.OpenURL(aURL);
end;
end.
|
unit SysInfo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TSystemInfoRecord = record
{- Disk Section }
SectorsPerCluster,
BytesPerSector,
FreeClusters,
TotalClusters,
FreeBytes,
TotalBytes : DWORD;
VolumeName,
VolumeSerial,
FileSystemName,
Drives : string;
{- Processor Section }
ProcessorType : string;
ProcessorNum : integer;
ProcessorOemId : integer;
{- Directory Section }
CurrentDir,
SystemDir,
WindowsDir : string;
{- Windows Section }
Version,
Plattform : string;
PlattId : DWORD;
{- Property Section }
UserConName,
ComputerName,
FPU,
UserName,
CompanyName,
CDSerial : string;
end;
TSysInfo = class(TComponent)
private
FSysInfoRec: TSystemInfoRecord;
FOSVerInfo: TOSVersionInfo;
procedure SetSysInfoRec(const Value: TSystemInfoRecord);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
procedure GetOSVersionInfo;
procedure GetDriveNames;
procedure GetDirectories;
procedure GetSystemInfo;
procedure GetDiskInfo;
procedure GetVolumeInfo;
procedure GetCurrentDir;
procedure GetComputerName;
procedure GetRegisterInfo;
procedure GetNetInfo;
procedure ReturnSystemInfo(aStringList: TStrings);
property SysInfoRec: TSystemInfoRecord read FSysInfoRec write SetSysInfoRec;
published
{ Published declarations }
end;
procedure Register;
implementation
uses Registry;
const
CrLf = #13#10;
procedure Register;
begin
RegisterComponents('FFS Common', [TSysInfo]);
end;
{ TSysInfo }
procedure TSysInfo.GetComputerName;
var
Computer : PChar;
CSize : DWORD;
begin
Computer := #0;
CSize := MAX_COMPUTERNAME_LENGTH + 1;
try
GetMem( Computer, CSize );
if Windows.GetComputerName( Computer, CSize ) then
FSysInfoRec.ComputerName := Computer;
finally
FreeMem( Computer );
end;
end;
procedure TSysInfo.GetCurrentDir;
var
BufLen : DWORD;
Buffer : PChar;
begin
BufLen := 0;
GetMem( Buffer, MAX_PATH + 1 );
if Windows.GetCurrentDirectory( BufLen, Buffer ) > 0 then
FSysInfoRec.CurrentDir := Buffer;
FreeMem( Buffer );
end;
procedure TSysInfo.GetDirectories;
var
Names: Pchar;
begin
Names := #0;
try
GetMem( Names, MAX_PATH+1 );
GetSystemDirectory(Names, MAX_PATH+1);
FSysInfoRec.SystemDir := StrPas(Names);
GetWindowsDirectory(Names, MAX_PATH+1);
FSysInfoRec.WindowsDir := StrPas(Names);
finally
FreeMem( Names );
end;
end;
procedure TSysInfo.GetDiskInfo;
var
RootPathName: Pchar;
// SectorsPerCluster,
// BytesPerSector,
// FreeClusters,
// TotalClusters,
// FreeBytes,
// TotalBytes : DWORD;
begin
with fSysInfoRec do begin
RootPathName := Pchar('C:\');
if GetDiskFreeSpace( RootPathName, SectorsPerCluster,
BytesPerSector, FreeClusters,
TotalClusters ) then;
FreeBytes := SectorsPerCluster * BytesPerSector * FreeClusters;
TotalBytes := SectorsPerCluster * BytesPerSector * TotalClusters;
end; {- with }
end;
procedure TSysInfo.GetDriveNames;
var
D1 : set of 0..25;
D2 : integer;
begin
DWORD( D1 ) := Windows.GetLogicalDrives;
with fSysInfoRec do begin
for D2 := 0 to 25 do
if D2 in D1 then
Drives := Drives + Chr( D2 + Ord( 'A' )) + ': ';
end;
end;
procedure TSysInfo.GetNetInfo;
var
BufLen : DWORD;
Buffer : PChar;
begin
BufLen := 32+1;
Buffer := #0;
try
GetMem( Buffer, BufLen );
case WNetGetUser(nil, Buffer, BufLen) of
NO_ERROR: FSysInfoRec.UserConName := Buffer;
ERROR_NOT_CONNECTED: FSysInfoRec.UserConName := 'Not Connected';
ERROR_NO_NETWORK: FSysInfoRec.UserConName := 'No Network';
else FSysInfoRec.UserConName := 'Other Network error';
end;
finally
FreeMem( Buffer );
end; // try
end;
procedure TSysInfo.GetOSVersionInfo;
function Plat(Pl: DWORD): string;
begin
case Pl of
VER_PLATFORM_WIN32s: result := 'Win32s on Windows 3.1';
VER_PLATFORM_WIN32_WINDOWS: result := 'Win32 on Windows 95';
VER_PLATFORM_WIN32_NT: result := 'Windows NT';
else result := '???';
end;
end;
begin
with FOSVerInfo, FSysInfoRec do begin
dwOSVersionInfoSize := SizeOf(FOSVerInfo);
if GetVersionEx(FOSVerInfo) then;
Version := Format('%d.%d (%d.%s)',[dwMajorVersion, dwMinorVersion,
(dwBuildNumber and $FFFF), szCSDVersion]);
Plattform := Plat(dwPlatformId);
PlattID := dwPlatformId;
end;
end;
procedure TSysInfo.GetRegisterInfo;
const
FPPKey = '\hardware\DESCRIPTION\System\FloatingPointProcessor';
var
CurVerKey : PChar;
begin
with fSysInfoRec do begin
case PlattID of
VER_PLATFORM_WIN32_WINDOWS :
CurVerKey := '\SOFTWARE\Microsoft\Windows\CurrentVersion';
VER_PLATFORM_WIN32_NT :
CurVerKey := '\SOFTWARE\Microsoft\Windows NT\CurrentVersion';
else CurVerKey := nil;
end;
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKey(FPPKey, False) then
FPU := 'Yes'
else FPU := 'No';
if OpenKey(CurVerKey, False) then begin
UserName := ReadString('RegisteredOwner');
CompanyName := ReadString('RegisteredOrganization');
if PlattID = VER_PLATFORM_WIN32_WINDOWS then
CDSerial := ReadString('ProductID');
end; {- if }
finally
Free;
end; {- try }
end; {- with }
end;
procedure TSysInfo.GetSystemInfo;
var
LocalSI: TSystemInfo;
const
PROCESSOR_INTEL_386 = 386;
PROCESSOR_INTEL_486 = 486;
PROCESSOR_INTEL_PENTIUM = 586;
PROCESSOR_MIPS_R4000 = 4000;
PROCESSOR_ALPHA_21064 = 21064;
begin
Windows.GetSystemInfo(LocalSI);
with LocalSI, fSysInfoRec do begin
ProcessorOemId := dwOemId;
ProcessorNum := dwNumberOfProcessors;
case dwProcessorType of
PROCESSOR_INTEL_386 : ProcessorType := ' 386';
PROCESSOR_INTEL_486 : ProcessorType := ' 486';
PROCESSOR_INTEL_PENTIUM : ProcessorType := ' Pentium';
PROCESSOR_MIPS_R4000 : ProcessorType := ' MIPS';
PROCESSOR_ALPHA_21064 : ProcessorType := ' ALPHA';
end;
end;
end;
procedure TSysInfo.GetVolumeInfo;
var
lpRootPathName : PChar;
lpVolumeNameBuffer : PChar;
nVolumeNameSize : DWORD;
lpVolumeSerialNumber : DWORD;
lpMaximumComponentLength : DWORD;
lpFileSystemFlags : DWORD;
lpFileSystemNameBuffer : PChar;
nFileSystemNameSize : DWORD;
begin
GetMem( lpVolumeNameBuffer, MAX_PATH + 1 );
GetMem( lpFileSystemNameBuffer, MAX_PATH + 1 );
nVolumeNameSize := MAX_PATH + 1;
nFileSystemNameSize := MAX_PATH + 1;
lpRootPathName := PChar( 'C:\' );
if Windows.GetVolumeInformation( lpRootPathName,
lpVolumeNameBuffer,
nVolumeNameSize,
@lpVolumeSerialNumber,
lpMaximumComponentLength,
lpFileSystemFlags,
lpFileSystemNameBuffer,
nFileSystemNameSize ) then
begin
with fSysInfoRec do begin
VolumeName := lpVolumeNameBuffer;
VolumeSerial := Format('%d',[lpVolumeSerialNumber]);
FileSystemName := lpFileSystemNameBuffer;
end;
end;
FreeMem( lpVolumeNameBuffer );
FreeMem( lpFileSystemNameBuffer );
end;
procedure TSysInfo.ReturnSystemInfo(aStringList: TStrings);
begin
GetDirectories;
GetOSVersionInfo;
GetDriveNames;
GetDiskInfo;
GetSystemInfo;
GetVolumeInfo;
GetCurrentDir;
GetComputerName;
GetRegisterInfo;
GetNetInfo;
with SysInfoRec do begin
aStringList.Add(CrLf+'----------[ WINDOWS & USER ]----------');
aStringList.Add('Computer Name: '+ComputerName);
aStringList.Add('Name: ' + VolumeName + ' - Serial: ' +
VolumeSerial + ' - File System: ' + FileSystemName);
aStringList.Add(Format('Version %s Platform: %s', [Version, Plattform] ));
aStringList.Add('CD Serial No: '+ CDSerial);
aStringList.Add('User Name: '+ UserName);
aStringList.Add('Company Name: '+ CompanyName);
aStringList.Add('User Connection Name: '+ UserConName);
aStringList.Add(CrLf+'----------[ DISK ]----------');
aStringList.Add('Drives: '+Drives);
aStringList.Add('Current Directory: '+CurrentDir);
aStringList.Add('System Directory: '+SysInfoRec.SystemDir);
aStringList.Add('Windows Directory: '+SysInfoRec.WindowsDir);
aStringList.Add(Format('Sectors per Cluster: %.0n', [SectorsPerCluster*1.0]));
aStringList.Add(Format('Bytes per Sector: %.0n', [BytesPerSector*1.0]));
aStringList.Add(Format('Free Clusters: %.0n', [FreeClusters*1.0]));
aStringList.Add(Format('Total Clusters: %.0n', [TotalClusters*1.0]));
aStringList.Add(Format('Total Space: %.0n bytes',[TotalBytes * 1.0]));
aStringList.Add(Format('Free Space: %.0n bytes',[FreeBytes * 1.0]));
aStringList.Add(CrLf+'----------[ CPU ]----------');
aStringList.Add(Format('OEM Id %d', [ProcessorOemId]));
aStringList.Add(Format('Number of processor %d', [ProcessorNum]));
aStringList.Add('Processor Type'+ProcessorType);
aStringList.Add('FPU : '+ FPU);
end;
end;
procedure TSysInfo.SetSysInfoRec(const Value: TSystemInfoRecord);
begin
FSysInfoRec := Value;
end;
end.
|
unit uOrcamentoOcorrenciaVO;
interface
uses
System.Generics.Collections, System.SysUtils, uTableName, uKeyField;
type
[TableName('Orcamento_Ocorrencia')]
TOrcamentoOcorrenciaVO = class
private
FDescricao: string;
FIdUsuario: Integer;
FId: Integer;
FIdOrcamento: Integer;
FData: TDate;
procedure SetData(const Value: TDate);
procedure SetDescricao(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdOrcamento(const Value: Integer);
procedure SetIdUsuario(const Value: Integer);
public
[KeyField('OrcOco_Id')]
property Id: Integer read FId write SetId;
[FieldName('OrcOco_Orcamento')]
property IdOrcamento: Integer read FIdOrcamento write SetIdOrcamento;
[FieldName('OrcOco_Data')]
property Data: TDate read FData write SetData;
[FieldName('OrcOco_Usuario')]
property IdUsuario: Integer read FIdUsuario write SetIdUsuario;
[FieldName('OrcOco_Descricao')]
property Descricao: string read FDescricao write SetDescricao;
end;
TListaOrcamentoOcorrencia = TObjectList<TOrcamentoOcorrenciaVO>;
implementation
{ TOrcamentoOcorrenciaVO }
procedure TOrcamentoOcorrenciaVO.SetData(const Value: TDate);
begin
if Value = 0 then
raise Exception.Create('Informe a Data da Ocorrência!');
FData := Value;
end;
procedure TOrcamentoOcorrenciaVO.SetDescricao(const Value: string);
begin
if Value.Trim = '' then
raise Exception.Create('Informe a Descrição da Ocorrência!');
FDescricao := Value;
end;
procedure TOrcamentoOcorrenciaVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TOrcamentoOcorrenciaVO.SetIdOrcamento(const Value: Integer);
begin
FIdOrcamento := Value;
end;
procedure TOrcamentoOcorrenciaVO.SetIdUsuario(const Value: Integer);
begin
if Value = 0 then
raise Exception.Create('Informe o Usuário da Ocorrência!');
FIdUsuario := Value;
end;
end.
|
Unit Guess;
Interface
Uses
TpCrt,
TpHelp,
TpString;
Procedure InitialTopic(Help : HelpPtr;Var Topic : Word);
{-Tries to guess the initial topic number. The guess is made in the }
{ following order: }
{ 1. If ParamCount <> 0 use ParamStr(1) }
{ 2. The word at the start of the line }
{ }
{ If a word is found a topic number for an exact match is attempted. }
{ If that is unsuccessful an attempt is made to find a match of the }
{ following types: }
{ 1. Truncated, e.g. "SELE" for "SELECT" }
{ }
{ Often more than one topic could match the given string, e.g. "DI" }
{ would match "DIR", "DIRS", "DISKCOMP", and "DISKCOPY". When this }
{ occurs the first (as displayed on the topic menu) matching topic }
{ will be selected. }
{ }
{ If, after all these attempts, no topic is found, zero (0) is }
{ returned as the topic number, which signals the calling procedure }
{ to display the topic menu. }
Implementation
{$F+} { these routines MUST be FAR }
Function TruncMatch(TopicName,ScreenName : String) : Boolean;
{-trys to match truncated words }
Begin
TruncMatch := Pos(StUpCase(ScreenName),StUpCase(TopicName)) = 1;
End;
{$F-} { end of FAR requirement }
Procedure InitialTopic(Help : HelpPtr;Var Topic : Word);
Var
Name : String;
Index : integer;
WStart : integer;
ScreenLine : String;
Begin
If ParamCount > 0
Then Name := ParamStr(1) { get the word from the command line }
Else Begin { get the word from the screen }
FastRead((80 - WhereXAbs + 1),WhereYAbs,WhereXAbs,ScreenLine);
ScreenLine := StUpCase(TrimTrail(ScreenLine));
WriteLn('WhereY is ', WhereY, ' screen line is [', ScreenLine, ']');
Name := '';
Index := 1;
while (not (ScreenLine[Index] in ['A'..'Z'])) and
(Index <= Length(ScreenLine)) do
Inc(Index);
WStart := Index;
if Index <= Length(ScreenLine) then begin
while (ScreenLine[Index] in ['A'..'Z']) and
(Index <= Length(ScreenLine)) do
Inc(Index);
Name := Copy(ScreenLine, WStart, (Index - WStart + 1));
end;
WriteLn('Name is [', Name, ']', ', press any key ...');
ReadLn;
End;
If Name = '' { no word so no topic number }
Then Topic := 0
Else Begin
Topic := FindHelp(Help,Name,NIL); { try an exact match }
{ if that didn't work try for an inexact match }
If Topic = 0 Then Topic := FindHelp(Help,Name,@TruncMatch);
End;
End;
End.
|
unit UAccessDomain;
interface
uses Classes, UAccessBase, UAccessContainer;
type
TSAVAccessDomain = class(TSAVAccessContainer)
private
FGroups: TStringList;
procedure SetGroups(const Value: TStringList);
protected
public
property Groups: TStringList read FGroups write SetGroups;
constructor Create; overload;
constructor Create(aBase: TSAVAccessBase; const aCaption, aSID,
aDescription: string); overload;
destructor Destroy; override;
procedure Save; override;
function Load(aSID: string = ''): Boolean; override;
procedure GetGroups(List: TStrings; const aWithSID: Boolean = False);
procedure GetUsers(List: TStrings);
procedure GetUsersFromAD(List: TStrings);
procedure Clear; override;
procedure Open(aBase: TSAVAccessBase; const aCaption, aSID: string; const
aDescription: string = ''; const aParam: string = ''; const aVersion:
TVersionString = ''); override;
procedure UpdateVersion; override;
end;
implementation
uses SAVLib, SAVLib_DBF, KoaUtils, SysUtils, VKDBFDataSet, VKDBFNTX, VKDBFIndex,
VKDBFSorters, UAccessConstant, MsAD;
{ TSAVAccessDomain }
constructor TSAVAccessDomain.Create;
begin
inherited Create;
ContainerType := 'D';
FGroups := TStringList.Create;
end;
procedure TSAVAccessDomain.Clear;
begin
inherited;
FGroups.Clear;
end;
constructor TSAVAccessDomain.Create(aBase: TSAVAccessBase; const aCaption,
aSID, aDescription: string);
begin
Create;
Open(aBase, aCaption, aSID, aDescription);
Save;
end;
procedure TSAVAccessDomain.GetGroups(List: TStrings; const aWithSID: Boolean =
False);
begin
GetAllGroups(SID, List, aWithSID);
end;
procedure TSAVAccessDomain.GetUsers(List: TStrings);
begin
end;
procedure TSAVAccessDomain.GetUsersFromAD(List: TStrings);
begin
end;
function TSAVAccessDomain.Load(aSID: string): Boolean;
var
table1: TVKDBFNTX;
s: string;
begin
// inherited;
if aSID = '' then
s := SID
else
s := aSID;
table1 := TVKDBFNTX.Create(nil);
SAVLib_DBF.InitOpenDBF(table1, IncludeTrailingPathDelimiter(Bases.JournalsDir)
+ csTableDomains, 64);
table1.Open;
Result := table1.Locate(csFieldSID, s, []);
if Result then
begin
SID := s;
Caption := table1.fieldByName(csFieldCaption).AsString;
Description := table1.FieldByName(csFieldDescription).AsString;
ID := table1.FieldByName(csFieldID).AsInteger;
WorkDir := IncludeTrailingPathDelimiter(Bases.DomainsDir) + SID;
ReadVersion;
end;
table1.Close;
FreeAndNil(table1);
end;
procedure TSAVAccessDomain.Open(aBase: TSAVAccessBase; const aCaption,
aSID, aDescription, aParam: string; const aVersion: TVersionString);
begin
WorkDir := IncludeTrailingPathDelimiter(aBase.DomainsDir) + aSID;
inherited Open(aBase, aCaption, aSID, aDescription, aParam, aVersion);
GetGroups(FGroups, True);
end;
procedure TSAVAccessDomain.Save;
var
table1: TVKDBFNTX;
begin
inherited;
table1 := TVKDBFNTX.Create(nil);
SAVLib_DBF.InitOpenDBF(table1, Bases.JournalsPath + csTableDomains, 66);
with table1.Indexes.Add as TVKNTXIndex do
NTXFileName := Bases.JournalsPath + csIndexDomainName;
with table1.Indexes.Add as TVKNTXIndex do
NTXFileName := Bases.JournalsPath + csIndexDomainVersion;
table1.Open;
if table1.FLock then
begin
if not (table1.Locate(csFieldSID, SID, [])) then
begin
table1.Append;
table1.FieldByName(csFieldSID).AsString := SID;
table1.FieldByName(csFieldID).AsInteger :=
table1.GetNextAutoInc(csFieldID);
end
else
table1.Edit;
table1.FieldByName(csFieldVersion).AsString := GetNewVersion;
Version := table1.FieldByName(csFieldVersion).AsString;
table1.FieldByName(csFieldCaption).AsString := Caption;
table1.FieldByName(csFieldDescription).AsString := Description;
ID := table1.FieldByName(csFieldID).AsInteger;
table1.Post;
table1.UnLock;
end
else
raise Exception.Create(csFLockError + Table1.DBFFileName);
table1.Close;
FreeAndNil(table1);
WorkDir := IncludeTrailingPathDelimiter(Bases.DomainsDir) + SID;
ForceDirectories(WorkDir);
WriteVersion;
end;
procedure TSAVAccessDomain.SetGroups(const Value: TStringList);
begin
FGroups := Value;
end;
destructor TSAVAccessDomain.Destroy;
begin
FreeAndNil(FGroups);
inherited;
end;
procedure TSAVAccessDomain.UpdateVersion;
var
table1: TVKDBFNTX;
begin
inherited;
table1 := TVKDBFNTX.Create(nil);
InitOpenDBF(table1, Bases.JournalsPath + csTableDomains, 66);
with table1.Indexes.Add as TVKNTXIndex do
NTXFileName := Bases.JournalsPath + csIndexDomainVersion;
table1.Open;
if table1.Locate(csFieldSID, SID, []) then
begin
if table1.FLock then
begin
table1.Edit;
table1.FieldByName(csFieldVersion).AsString := Version;
table1.Post;
table1.UnLock;
end
else
raise Exception.Create(csFLockError + Table1.DBFFileName);
end;
table1.Close;
FreeAndNil(table1);
end;
end.
|
program drawTriabgle(input, output);
var
size, spaces, points, lines : integer;
i, j, k : integer;
done : boolean;
{}
begin
done := true;
while(done) do
begin
write('Size: ');
read(size);
if (size mod 2 = 0) then
writeln('The number must be odd.')
else
begin
lines := size - 2;
points := 1;
spaces := (size - 1) div 2;
for i := 0 to lines do
begin
for j := 0 to spaces do
write(' ');
for k := 0 to points - 1 do
write('*');
spaces := spaces - 1;
points := points + 2;
writeln();
end;
done := false;
end;
end;
end.
|
unit konami;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
main_engine,dialogs,sysutils,timer_engine,m6809,cpu_misc;
type
tset_lines=procedure (valor:byte);
cpu_konami=class(cpu_m6809)
public
constructor create(clock:dword;frames_div:word);
procedure run(maximo:single);
procedure change_set_lines(tset_lines_call:tset_lines);
private
set_lines_call:tset_lines;
//Llamadas IRQ
function call_irq:byte;
function call_firq:byte;
//Misc Func
function get_indexed:word;
procedure trf(valor:byte);
procedure trf_ex(valor:byte);
end;
var
konami_0:cpu_konami;
implementation
const
estados_t:array[0..255] of byte=(
//0 1 2 3 4 5 6 7 8 9 a b c d e f
0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 5, 5, 4, 4, // 0
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 10
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 20
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 8, 6, // 30
4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 5, 3, 5, 3, 5, 3, // 40
5, 3, 5, 3, 5, 4, 5, 4, 3, 3, 3, 3, 3, 0, 0, 0, // 50
3, 3, 3, 3, 0, 3, 3, 3, 4, 4, 4, 4, 0, 4, 4, 4, // 60
3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 0, 4, 4, 4, // 70
1, 1, 4, 2, 2, 4, 2, 2, 4, 2, 2, 4, 2, 2, 4, 4, // 80
2, 2, 4, 2, 2, 4, 2, 2, 4, 2, 2, 4, 2, 2, 4, 4, // 90
2, 2, 4, 2, 0, 2, 2, 0, 1, 5, 7, 9, 3, 3, 2, 0, // A0
3, 2, 2,11,21,10, 1, 0, 2, 0, 0, 0, 2, 0, 2, 0, // B0
0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 1, // C0
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // F0
paginacion:array[0..255] of byte=(
//0 1 2 3 4 5 6 7 8 9 a b c d e f
$f,$f,$f,$f,$f,$f,$f,$f, 4, 4, 4, 4, 2, 2, 2, 2, //00
2, 2, 6, 6, 2, 2, 6, 6, 2, 2, 6, 6, 2, 2, 6, 6, //10
2, 2, 6, 6, 2, 2, 6, 6, 2, 2, 6, 6, 2, 2, 6, 6, //20
2, 2, 6, 6, 2, 2, 6, 6, 2, 6, 4, 4, 2, 2, 2, 2, //30
3, 9, 3, 9, 3, 9, 3, 9, 3, 9, 3, 9, 3, 9, 3, 9, //40
3, 9, 3, 9, 3, 9, 3, 9, 4, 4, 4, 4, 4,$f,$f,$f, //50
2, 2, 2, 2,$f, 2, 2, 2, 3, 3, 3, 3,$f, 3, 3, 3, //60
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,$f, 3, 3, 3, //70
0, 0, 4, 0, 0, 4, 0, 0, 4, 0, 0, 4, 0, 0, 4, 0, //80
0, 0, 4, 0, 0, 4, 0, 0, 4, 0, 0, 4, 0, 0, 4, 0, //90
0, 0, 4, 4,$f, 4, 4,$f, 4, 4, 2, 3, 2, 2, 0,$f, //a0
0, 0, 0, 0, 0, 0, 0,$f, 2,$f,$f,$f, 2,$f, 2,$f, //b0
$f,$f, 0, 4, 0, 4, 4, 4,$f, 4, 0, 4, 0, 0, 0, 0, //c0
0,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f, //d0
$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f, //e0
$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f,$f); //f0
constructor cpu_konami.create(clock:dword;frames_div:word);
begin
getmem(self.r,sizeof(reg_m6809));
fillchar(self.r^,sizeof(reg_m6809),0);
self.numero_cpu:=cpu_main_init(clock);
self.clock:=clock;
self.tframes:=(clock/frames_div)/llamadas_maquina.fps_max;
end;
procedure cpu_konami.change_set_lines(tset_lines_call:tset_lines);
begin
self.set_lines_call:=tset_lines_call;
end;
function cpu_konami.call_irq:byte;
begin
self.push_sw(r.pc);
self.push_sw(r.u);
self.push_sw(r.y);
self.push_sw(r.x);
self.push_s(r.dp);
self.push_s(r.d.b);
self.push_s(r.d.a);
r.cc.e:=true;
self.push_s(self.dame_pila);
call_irq:=19;
r.pc:=self.getword($FFF8);
r.cc.i:=true;
if self.pedir_irq=HOLD_LINE then self.pedir_irq:=CLEAR_LINE;
end;
function cpu_konami.call_firq:byte;
begin
r.cc.e:=false;
self.push_sw(r.pc);
self.push_s(self.dame_pila);
call_firq:=10;
r.cc.f:=true;
r.cc.i:=true;
r.pc:=self.getword($FFF6);
if self.pedir_firq=HOLD_LINE then self.pedir_firq:=CLEAR_LINE;
end;
procedure cpu_konami.trf(valor:byte);
var
temp:word;
begin
case (valor and $7) of
$0:temp:=r.d.a; //A
$1:temp:=r.d.b; //B
$2:temp:=r.x; //X
$3:temp:=r.y; //Y
$4:temp:=r.s; //S
$5:temp:=r.u; //U
end;
case ((valor shr 4) and 7) of
$0:r.d.a:=temp; //A
$1:r.d.b:=temp; //B
$2:r.x:=temp; //X
$3:r.y:=temp; //Y
$4:r.s:=temp; //S
$5:r.u:=temp; //U
end;
end;
procedure cpu_konami.trf_ex(valor:byte);
var
temp1,temp2:word;
begin
case (valor and $7) of
$0:temp1:=r.d.a; //A
$1:temp1:=r.d.b; //B
$2:temp1:=r.x; //X
$3:temp1:=r.y; //Y
$4:temp1:=r.s; //S
$5:temp1:=r.u; //U
end;
case ((valor shr 4) and 7) of
$0:temp2:=r.d.a; //A
$1:temp2:=r.d.b; //B
$2:temp2:=r.x; //X
$3:temp2:=r.y; //Y
$4:temp2:=r.s; //S
$5:temp2:=r.u; //U
end;
case (valor and $7) of
$0:r.d.a:=temp2; //A
$1:r.d.b:=temp2; //B
$2:r.x:=temp2; //X
$3:r.y:=temp2; //Y
$4:r.s:=temp2; //S
$5:r.u:=temp2; //U
end;
case ((valor shr 4) and 7) of
$0:r.d.a:=temp1; //A
$1:r.d.b:=temp1; //B
$2:r.x:=temp1; //X
$3:r.y:=temp1; //Y
$4:r.s:=temp1; //S
$5:r.u:=temp1; //U
end;
end;
function cpu_konami.get_indexed:word;
var
iindexed,temp:byte;
origen:pword;
direccion,temp2:word;
begin
iindexed:=self.getbyte(r.pc); //Hay que aņadir 1 estado por cojer un byte...
r.pc:=r.pc+1;
case (iindexed and $70) of
$20:origen:=@r.x;
$30:origen:=@r.y;
$50:origen:=@r.u;
$60:origen:=@r.s;
$70:origen:=@r.pc;
end;
direccion:=$ffff;
case (iindexed and $f7) of
7:begin // =
direccion:=self.getword(r.pc);
r.pc:=r.pc+2;
self.estados_demas:=self.estados_demas+1+2;
end;
$20,$30,$50,$60,$70:begin //reg+
direccion:=origen^;
origen^:=origen^+1;
self.estados_demas:=self.estados_demas+1+2;
end;
$21,$31,$51,$61,$71:begin //reg++
direccion:=origen^;
origen^:=origen^+2;
self.estados_demas:=self.estados_demas+1+3;
end;
$22,$32,$52,$62,$72:begin //-reg
origen^:=origen^-1;
direccion:=origen^;
self.estados_demas:=self.estados_demas+1+3;
end;
$23,$33,$53,$63,$73:begin //--reg
origen^:=origen^-2;
direccion:=origen^;
self.estados_demas:=self.estados_demas+1+3;
end;
$24,$34,$54,$64,$74:begin //reg + deplazamiento 8bits
direccion:=origen^;
temp:=self.getbyte(r.pc);
r.pc:=r.pc+1;
direccion:=direccion+shortint(temp);
self.estados_demas:=self.estados_demas+1+2;
end;
$25,$35,$55,$65,$75:begin //reg + deplazamiento 16bits
direccion:=origen^;
temp2:=self.getword(r.pc);
r.pc:=r.pc+2;
direccion:=direccion+smallint(temp2);
self.estados_demas:=self.estados_demas+5+1;
end;
$26,$36,$56,$66,$76:begin // =
direccion:=origen^;
self.estados_demas:=self.estados_demas+1;
end;
$c4:begin
direccion:=(self.r.dp shl 8)+self.getbyte(r.pc);
r.pc:=r.pc+1;
self.estados_demas:=self.estados_demas+1+1;
end;
$a0,$b0,$d0,$e0,$f0:begin // reg + r.d.a
direccion:=origen^+shortint(r.d.a);
self.estados_demas:=self.estados_demas+1+1;
end;
$a1,$b1,$d1,$e1,$f1:begin //reg + r.d.b
direccion:=origen^+shortint(r.d.b);
self.estados_demas:=self.estados_demas+1+1;
end;
$a7,$b7,$d7,$e7,$f7:begin //reg + r.d.w
direccion:=origen^+smallint(r.d.w);
self.estados_demas:=self.estados_demas+1+4;
end;
else MessageDlg('Indexed desconocido. PC='+inttohex(r.pc,10), mtInformation,[mbOk], 0);
end;
if (iindexed and $8)<>0 then begin
direccion:=self.getword(direccion);
self.estados_demas:=self.estados_demas+2;
end;
get_indexed:=direccion;
end;
//Functions
{$I m6809.inc}
procedure cpu_konami.run(maximo:single);
var
tempb,tempb2,cf,instruccion,numero:byte;
tempw,posicion:word;
templ:dword;
begin
self.contador:=0;
while self.contador<maximo do begin
if self.pedir_reset<>CLEAR_LINE then begin
tempb:=self.pedir_reset;
self.reset;
if tempb=ASSERT_LINE then self.pedir_reset:=ASSERT_LINE;
self.contador:=trunc(maximo);
exit;
end;
self.r.old_pc:=self.r.pc;
self.estados_demas:=0;
if ((self.pedir_firq<>CLEAR_LINE) and not(r.cc.f)) then self.estados_demas:=self.call_firq
else if ((self.pedir_irq<>CLEAR_LINE) and not(r.cc.i)) then self.estados_demas:=self.call_irq;
self.opcode:=true;
instruccion:=self.getbyte(r.pc);
r.pc:=r.pc+1;
self.opcode:=false;
case paginacion[instruccion] of
0:; //implicito 0T
2:begin //inmediato byte
numero:=self.getbyte(r.pc);
r.pc:=r.pc+1;
end;
3:begin //EXTENDED 3T
posicion:=self.getword(r.pc);
r.pc:=r.pc+2;
end;
4:posicion:=self.get_indexed; //INDEXED Los estados T son variables
6:numero:=self.getbyte(get_indexed); //indexado indirecto byte
9:posicion:=self.getword(get_indexed); //indexado indirecto word
$f:MessageDlg('Konami CPU '+inttostr(self.numero_cpu)+' instruccion: '+inttohex(instruccion,2)+' desconocida. PC='+inttohex(r.pc,10)+' OLD_PC='+inttohex(self.r.old_pc,10), mtInformation,[mbOk], 0)
end; //del case!!
case instruccion of
$08:begin //leax 2T
r.x:=posicion;
r.cc.z:=(r.x=0);
end;
$09:begin //leay 2T
r.y:=posicion;
r.cc.z:=(r.y=0);
end;
$0a:r.u:=posicion; //leau 2T
$0b:r.s:=posicion; //leas 2T
$0c:begin //pshs 5T
if (numero and $80)<>0 then begin
self.push_sw(r.pc);
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $40)<>0 then begin
self.push_sw(r.u);
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $20)<>0 then begin
self.push_sw(r.y);
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $10)<>0 then begin
self.push_sw(r.x);
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $8)<>0 then begin
self.push_s(r.dp);
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $4)<>0 then begin
self.push_s(r.d.b);
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $2)<>0 then begin
self.push_s(r.d.a);
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $1)<>0 then begin
self.push_s(self.dame_pila);
self.estados_demas:=self.estados_demas+1;
end;
end;
$0d:begin //pshu 5T
if (numero and $80)<>0 then begin
self.push_uw(r.pc);
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $40)<>0 then begin
self.push_uw(r.s);
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $20)<>0 then begin
self.push_uw(r.y);
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $10)<>0 then begin
self.push_uw(r.x);
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $8)<>0 then begin
self.push_u(r.dp);
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $4)<>0 then begin
self.push_u(r.d.b);
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $2)<>0 then begin
self.push_u(r.d.a);
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $1)<>0 then begin
self.push_u(self.dame_pila);
self.estados_demas:=self.estados_demas+1;
end;
end;
$0e:begin //puls 4T
if (numero and $1)<>0 then begin
self.pon_pila(self.pop_s);
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $2)<>0 then begin
r.d.a:=self.pop_s;
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $4)<>0 then begin
r.d.b:=self.pop_s;
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $8)<>0 then begin
r.dp:=self.pop_s;
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $10)<>0 then begin
r.x:=self.pop_sw;
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $20)<>0 then begin
r.y:=self.pop_sw;
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $40)<>0 then begin
r.u:=self.pop_sw;
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $80)<>0 then begin
r.pc:=self.pop_sw;
self.estados_demas:=self.estados_demas+2;
end;
end;
$0f:begin //pulu 4T
if (numero and $1)<>0 then begin
self.pon_pila(self.pop_u);
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $2)<>0 then begin
r.d.a:=self.pop_u;
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $4)<>0 then begin
r.d.b:=self.pop_u;
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $8)<>0 then begin
r.dp:=self.pop_u;
self.estados_demas:=self.estados_demas+1;
end;
if (numero and $10)<>0 then begin
r.x:=self.pop_uw;
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $20)<>0 then begin
r.y:=self.pop_uw;
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $40)<>0 then begin
r.s:=self.pop_uw;
self.estados_demas:=self.estados_demas+2;
end;
if (numero and $80)<>0 then begin
r.pc:=self.pop_uw;
self.estados_demas:=self.estados_demas+2;
end;
end;
$10,$12:r.d.a:=m680x_ld_st8(numero,@r.cc); //lda 1T
$11,$13:r.d.b:=m680x_ld_st8(numero,@r.cc); //ldb 1T
$14,$16:r.d.a:=m680x_add8(r.d.a,numero,@r.cc); //adda 1T
$15,$17:r.d.b:=m680x_add8(r.d.b,numero,@r.cc); //addb 1T
$18,$1a:r.d.a:=m680x_adc(r.d.a,numero,@r.cc); //adca 1T
$19,$1b:r.d.b:=m680x_adc(r.d.b,numero,@r.cc); //adcb 1T
$1c,$1e:r.d.a:=m680x_sub8(r.d.a,numero,@r.cc); //suba 1T
$1d,$1f:r.d.b:=m680x_sub8(r.d.b,numero,@r.cc); //subb 1T
$20,$22:r.d.a:=m680x_sbc(r.d.a,numero,@r.cc); //sbca 1T
$21,$23:r.d.b:=m680x_sbc(r.d.b,numero,@r.cc); //sbcb 1T
$24,$26:r.d.a:=m680x_and(r.d.a,numero,@r.cc); //anda 1T
$25,$27:r.d.b:=m680x_and(r.d.b,numero,@r.cc); //andb 1T
$28,$2a:m680x_and(r.d.a,numero,@r.cc); //bita 1T
$29,$2b:m680x_and(r.d.b,numero,@r.cc); //bitb 1T
$2c,$2e:r.d.a:=m680x_eor(r.d.a,numero,@r.cc); //eora 1T
$2d,$2f:r.d.b:=m680x_eor(r.d.b,numero,@r.cc); //eorb 1T
$30,$32:r.d.a:=m680x_or(r.d.a,numero,@r.cc); //ora 1T
$31,$33:r.d.b:=m680x_or(r.d.b,numero,@r.cc); //orb 1T
$34,$36:m680x_sub8(r.d.a,numero,@r.cc); //cmpa 1T
$35,$37:m680x_sub8(r.d.b,numero,@r.cc); //cmpb 1T
$38,$39:if @self.set_lines_call<>nil then self.set_lines_call(numero);
$3a:self.putbyte(posicion,m680x_ld_st8(r.d.a,@r.cc)); //sta 1T
$3b:self.putbyte(posicion,m680x_ld_st8(r.d.b,@r.cc)); //stb 1T
$3c:begin //andcc 3T
tempb:=self.dame_pila and numero;
self.pon_pila(tempb);
end;
$3d:begin //orcc 3T
tempb:=self.dame_pila or numero;
self.pon_pila(tempb);
end;
$3e:self.trf_ex(numero); //exg 8T
$3f:self.trf(numero); //trf 4T
$40,$41:r.d.w:=m680x_ld_st16(posicion,@r.cc); //ldd 2T
$42,$43:r.x:=m680x_ld_st16(posicion,@r.cc); //ldx 2T
$44,$45:r.y:=m680x_ld_st16(posicion,@r.cc); //ldy 2T
$46,$47:r.u:=m680x_ld_st16(posicion,@r.cc); //ldu 2T
$48,$49:r.s:=m680x_ld_st16(posicion,@r.cc); //lds 2T
$4a,$4b:m680x_sub16(r.d.w,posicion,@r.cc); //cmpd
$4c,$4d:m680x_sub16(r.x,posicion,@r.cc); //cmpx
$4e,$4f:m680x_sub16(r.y,posicion,@r.cc); //cmpy
$50,$51:m680x_sub16(r.u,posicion,@r.cc); //cmpu
$52,$53:m680x_sub16(r.s,posicion,@r.cc); //cmps
$54,$55:r.d.w:=m680x_add16(r.d.w,posicion,@r.cc); //addd 2T
$56,$57:r.d.w:=m680x_sub16(r.d.w,posicion,@r.cc); //subd 2T
$58:self.putword(posicion,m680x_ld_st16(r.d.w,@r.cc)); //std
$59:self.putword(posicion,m680x_ld_st16(r.x,@r.cc)); //stx
$5a:self.putword(posicion,m680x_ld_st16(r.y,@r.cc)); //sty
$5b:self.putword(posicion,m680x_ld_st16(r.u,@r.cc)); //stu
$5c:self.putword(posicion,m680x_ld_st16(r.s,@r.cc)); //sts
$60:r.pc:=r.pc+shortint(numero); //bra 3T
$61:if not(r.cc.c or r.cc.z) then r.pc:=r.pc+shortint(numero); //bhi 3T
$62:if not(r.cc.c) then r.pc:=r.pc+shortint(numero); //bcc 3T
$63:if not(r.cc.z) then r.pc:=r.pc+shortint(numero); //bne 3T
$65:if not(r.cc.n) then r.pc:=r.pc+shortint(numero); //bpl 3T
$66:if (r.cc.n=r.cc.v) then r.pc:=r.pc+shortint(numero);//bge 3T
$67:if ((r.cc.n=r.cc.v) and not(r.cc.z)) then r.pc:=r.pc+shortint(numero); //bgt 3T
$68:r.pc:=r.pc+smallint(posicion); //lbra 3T
$69:if not(r.cc.c or r.cc.z) then r.pc:=r.pc+smallint(posicion); //lbhi 3T
$6a:if not(r.cc.c) then r.pc:=r.pc+smallint(posicion); //lbcc 3T
$6b:if not(r.cc.z) then r.pc:=r.pc+smallint(posicion); //lbne 3T
$6d:if not(r.cc.n) then r.pc:=r.pc+smallint(posicion); //lbpl 3T
$6e:if (r.cc.n=r.cc.v) then r.pc:=r.pc+smallint(posicion);//lbge 3T
$6f:if ((r.cc.n=r.cc.v) and not(r.cc.z)) then r.pc:=r.pc+smallint(posicion); //lbgt 3T
$70:; //brn 3T
$71:if (r.cc.c or r.cc.z) then r.pc:=r.pc+shortint(numero); //bls 3T
$72:if r.cc.c then r.pc:=r.pc+shortint(numero); //bcs 3T
$73:if r.cc.z then r.pc:=r.pc+shortint(numero); //beq 3T
$74:if r.cc.v then r.pc:=r.pc+shortint(numero); //bvs 3T
$75:if r.cc.n then r.pc:=r.pc+shortint(numero); //bmi 3T
$76:if not(r.cc.n=r.cc.v) then r.pc:=r.pc+shortint(numero);//blt 3T
$77:if not((r.cc.n=r.cc.v) and not(r.cc.z)) then r.pc:=r.pc+shortint(numero); //ble 3T
$78:; //lbrn 3T
$79:if (r.cc.c or r.cc.z) then r.pc:=r.pc+smallint(posicion); //lbls 3T
$7a:if r.cc.c then r.pc:=r.pc+smallint(posicion); //lbcs 3T
$7b:if r.cc.z then r.pc:=r.pc+smallint(posicion); //lbeq 3T
$7d:if r.cc.n then r.pc:=r.pc+smallint(posicion); //lbmi 3T
$7e:if not(r.cc.n=r.cc.v) then r.pc:=r.pc+smallint(posicion);//lblt 3T
$7f:if not((r.cc.n=r.cc.v) and not(r.cc.z)) then r.pc:=r.pc+smallint(posicion); //lble 3T
$80:begin //clra 2T
r.d.a:=0;
r.cc.z:=true;
r.cc.n:=false;
r.cc.v:=false;
r.cc.c:=false;
end;
$81:begin //clrb 2T
r.d.b:=0;
r.cc.z:=true;
r.cc.n:=false;
r.cc.v:=false;
r.cc.c:=false;
end;
$82:begin //clr 4T
self.putbyte(posicion,0);
r.cc.n:=false;
r.cc.v:=false;
r.cc.c:=false;
r.cc.z:=true;
end;
$83:r.d.a:=m680x_com(r.d.a,@r.cc); //coma 2T
$84:r.d.b:=m680x_com(r.d.b,@r.cc); //comb 2T
$85:self.putbyte(posicion,m680x_com(self.getbyte(posicion),@r.cc)); //com 4T
$86:r.d.a:=m680x_neg(r.d.a,@r.cc); //nega 2T
$87:r.d.b:=m680x_neg(r.d.b,@r.cc); //negb 2T
$88:self.putbyte(posicion,m680x_neg(self.getbyte(posicion),@r.cc)); //neg 4T
$89:r.d.a:=m680x_inc(r.d.a,@r.cc); //inca 2T
$8a:r.d.b:=m680x_inc(r.d.b,@r.cc); //incb 2T
$8b:self.putbyte(posicion,m680x_inc(self.getbyte(posicion),@r.cc)); //inc 4T
$8c:r.d.a:=m680x_dec(r.d.a,@r.cc); //deca 2T
$8d:r.d.b:=m680x_dec(r.d.b,@r.cc); //decb 2T
$8e:self.putbyte(posicion,m680x_dec(self.getbyte(posicion),@r.cc)); //dec 4T
$8f:r.pc:=self.pop_sw; //rts 4T
$90:m680x_tst(r.d.a,@r.cc); //tsta 2T
$91:m680x_tst(r.d.b,@r.cc); //tstb 2T
$92:m680x_tst(self.getbyte(posicion),@r.cc); //tst 3T
$93:r.d.a:=m680x_lsr(r.d.a,@r.cc); //lsra 2T
$94:r.d.b:=m680x_lsr(r.d.b,@r.cc); //lsrb 2T
$95:self.putbyte(posicion,m680x_lsr(self.getbyte(posicion),@r.cc)); //lsr 4T
$96:r.d.a:=m680x_ror(r.d.a,@r.cc); //rora 2T
$97:r.d.b:=m680x_ror(r.d.b,@r.cc); //rorb 2T
$98:self.putbyte(posicion,m680x_ror(self.getbyte(posicion),@r.cc)); //ror 4T
$99:r.d.a:=m680x_asr(r.d.a,@r.cc); //asra 2T
$9a:r.d.b:=m680x_asr(r.d.b,@r.cc); //asrb 2T
$9b:self.putbyte(posicion,m680x_asr(self.getbyte(posicion),@r.cc)); //asr 4T
$9c:r.d.a:=m680x_asl(r.d.a,@r.cc); //asla 2T
$9d:r.d.b:=m680x_asl(r.d.b,@r.cc); //aslb 2T
$9e:self.putbyte(posicion,m680x_asl(self.getbyte(posicion),@r.cc)); //asl 4T
$9f:begin //rti 4T
self.pon_pila(self.pop_s);
if r.cc.e then begin //13 T
self.estados_demas:=self.estados_demas+9;
r.d.a:=self.pop_s;
r.d.b:=self.pop_s;
r.dp:=self.pop_s;
r.x:=self.pop_sw;
r.y:=self.pop_sw;
r.u:=self.pop_sw;
end;
r.pc:=self.pop_sw;
end;
$a0:r.d.a:=m680x_rol(r.d.a,@r.cc); //rola 2T
$a1:r.d.b:=m680x_rol(r.d.b,@r.cc); //rolb 2T
$a2:self.putbyte(posicion,m680x_rol(self.getbyte(posicion),@r.cc)); //rol 4T
$a3:self.putword(posicion,m680x_lsr16(self.getword(posicion),@r.cc)); //lsr16
$a5:self.putword(posicion,m680x_asr16(self.getword(posicion),@r.cc)); //asr16
$a6:self.putword(posicion,m680x_asl16(self.getword(posicion),@r.cc)); //asl16
$a8:r.pc:=posicion; //jmp 1T
$a9:begin //jsr 5T
self.push_sw(r.pc);
r.pc:=posicion;
end;
$aa:begin //bsr 7T
self.push_sw(r.pc);
r.pc:=r.pc+shortint(numero);
end;
$ab:begin //lbsr 9T
self.push_sw(r.pc);
r.pc:=r.pc+smallint(posicion);
end;
$ac:begin //decbjnz
tempw:=r.d.b-1;
r.cc.z:=((tempw and $ff)=0);
r.cc.n:=(tempw and $80)<>0;
r.cc.v:=((r.d.b xor 1 xor tempw xor (tempw shr 1)) and $80)<>0;
r.d.b:=tempw;
if not(r.cc.z) then r.pc:=r.pc+shortint(numero);
end;
$ad:begin //decxjnz
templ:=r.x-1;
r.cc.z:=((templ and $ffff)=0);
r.cc.n:=(templ and $8000)<>0;
r.cc.v:=((r.x xor 1 xor templ xor (templ shr 1)) and $8000)<>0;
r.x:=templ;
if not(r.cc.z) then r.pc:=r.pc+shortint(numero);
end;
$b0:r.x:=r.x+r.d.b; //abx 3T
$b1:begin //daa 2T
cf:=0;
tempb:=r.d.a and $f0;
tempb2:=r.d.a and $0f;
if ((tempb2>$09) or r.cc.h) then cf:=cf or $06;
if ((tempb>$80) and (tempb2>$09)) then cf:=cf or $60;
if ((tempb>$90) or r.cc.c) then cf:=cf or $60;
tempw:=cf+r.d.a;
r.cc.v:=false;
r.cc.n:=(tempw and $80)<>0;
r.cc.z:=((tempw and $ff)=0);
r.cc.c:=r.cc.c or ((tempw and $100)<>0);
r.d.a:=tempw;
end;
$b2:begin //sex 2T
r.d.a:=$ff*(r.d.b shr 7);
r.cc.n:=(r.d.w and $8000)<>0;
r.cc.z:=(r.d.w=0);
end;
$b3:begin //mul 11T
r.d.w:=r.d.a*r.d.b;
r.cc.c:=(r.d.w and $80)<>0;
r.cc.z:=(r.d.w=0);
end;
$b4:begin //lmul 21
templ:=r.x*r.y;
r.x:=templ shr 16;
r.y:=templ and $ffff;
r.cc.z:=(templ and $ffffffff)=0;
r.cc.c:=(templ and $8000)<>0;
end;
$b5:begin //divx 10
if r.d.b<>0 then begin
tempw:=r.x div r.d.b;
tempb:=r.x mod r.d.b;
end else begin
tempw:=0;
tempb:=0;
end;
r.x:=tempw;
r.d.b:=tempb;
r.cc.c:=(tempw and $80)<>0;
r.cc.z:=tempw=0;
end;
$b6:while (r.u<>0) do begin //bmove
tempb:=self.getbyte(r.y);
r.y:=r.y+1;
self.putbyte(r.x,tempb);
r.x:=r.x+1;
r.u:=r.u-1;
self.estados_demas:=self.estados_demas+2;
end;
$b8:r.d.w:=m680x_lsrd(r.d.w,numero,@r.cc); //lsrd
$bc:r.d.w:=m680x_asrd(r.d.w,numero,@r.cc); //asrd
$be:r.d.w:=m680x_asld(r.d.w,numero,@r.cc); //asld
$c2:begin //clrd
r.d.w:=0;
r.cc.z:=true;
r.cc.n:=false;
r.cc.v:=false;
r.cc.c:=false;
end;
$c3:begin //clr16
self.putword(posicion,0);
r.cc.z:=true;
r.cc.n:=false;
r.cc.v:=false;
r.cc.c:=false;
end;
$c4:r.d.w:=m680x_neg16(r.d.w,@r.cc); // negd
$c5:self.putword(posicion,m680x_neg16(self.getword(posicion),@r.cc)); // neg16
$c6:r.d.w:=m680x_inc16(r.d.w,@r.cc); //incd
$c7:self.putword(posicion,m680x_inc16(self.getword(posicion),@r.cc)); //inc16
$c9:self.putword(posicion,m680x_dec16(self.getword(posicion),@r.cc)); //dec16
$ca:m680x_tst16(r.d.w,@r.cc); //tstd
$cb:m680x_tst16(self.getword(posicion),@r.cc);
$cc:r.d.a:=m680x_abs8(r.d.a,@r.cc); //absa
$cd:r.d.b:=m680x_abs8(r.d.b,@r.cc); //absb
$ce:r.d.w:=m680x_abs16(r.d.w,@r.cc); //absd
$cf:while (r.u<>0) do begin //bset
self.putbyte(r.x,r.d.a);
r.x:=r.x+1;
r.u:=r.u-1;
self.estados_demas:=self.estados_demas+2;
end;
$d0:while (r.u<>0) do begin //bset2
self.putword(r.x,r.d.w);
r.x:=r.x+2;
r.u:=r.u-1;
self.estados_demas:=self.estados_demas+3;
end;
end;
tempw:=estados_t[instruccion]+self.estados_demas;
self.contador:=self.contador+tempw;
timers.update(tempw,self.numero_cpu);
end; //Del while
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Creation: May 6, 2007
Version: 0.99d ALPHA CODE
Description: TMultipartFtpDownloader is a component to download files using
simultaneous connections to speedup download. The demo make
also use of the TMultiProgressBar (included in ICS) which is
a segmented progress bar.
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2007 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
Updates:
Sep 10, 2007 Added timeout to Size operation
Oct 30, 2010 0.99b In DownloadDocData, fixed call to Seek so that the int64
overloaded version is used.
Oct 31, 2010 0.99c In DownloadDocData, restart the timeout timer.
Renamed protected TMultipartFtpDownloader.FHttp member to
FMyFtp (Breaking change. Not an issue since we are in alpha phase).
Nov 08, 2010 0.99d Arno improved final exception handling, more details
in OverbyteIcsWndControl.pas (V1.14 comments).
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsMultipartFtpDownloader;
{$I OverbyteIcsDefs.inc}
{$IFDEF COMPILER14_UP}
{$IFDEF NO_EXTENDED_RTTI}
{$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
{$ENDIF}
{$ENDIF}
interface
uses
Windows, Messages, SysUtils, Classes, IniFiles,
OverbyteIcsWndControl, OverbyteIcsFtpCli;
type
TFtpBigInt = int64;
TDisplayEvent = procedure (Sender : TObject;
const Msg : String) of object;
TRequestDoneEvent = procedure (Sender : TObject;
ErrorCode : Integer;
const Reason : String) of object;
TProgressAddSegmentEvent = procedure (Sender : TObject;
StartOffset : Int64;
ASpan : Int64;
InitPos : Int64) of Object;
TProgressSetPositionEvent = procedure (Sender : TObject;
Index : Integer;
Position : Int64) of object;
TFtpDocDataEvent = procedure (Sender : TObject;
Data : Pointer;
Len : Integer) of object;
TMyFtpCli = class(TFtpClient)
protected
FDataCount : TFtpBigInt;
FDataMax : TFtpBigInt;
FStartOffset : TFtpBigInt;
FEndOffset : TFtpBigInt;
FIndex : Integer;
FDone : Boolean;
FOnDocData : TFtpDocDataEvent;
procedure LocalStreamWrite(const Buffer; Count : Integer); override;
published
property OnDocData : TFtpDocDataEvent read FOnDocData
write FOnDocData;
end;
TMultipartFtpDownloader = class(TIcsWndControl)
protected
FMyFtp : array of TMyFtpCli;
FPassive : Boolean;
FBinary : Boolean;
FPartCount : Integer;
FPass : String;
FUser : String;
FServer : String;
FFileName : String;
FDir : String;
FPort : String;
FAbortFlag : Boolean;
FPauseFlag : Boolean;
FTimeoutFlag : Boolean;
FStateFileName : String;
FFileStream : TStream;
FContentLength : TFtpBigInt;
FTotalCount : TFtpBigInt;
FPrevCount : TFtpBigInt;
FPrevTick : Cardinal;
FStartTime : TDateTime;
FElapsedTime : TDateTime;
FCurSpeed : Double;
FPercentDone : Double;
FTimeoutValue : Integer; // Milli-seconds
FAssumedSize : TFtpBigInt; // DOESN'T WORK !
FOnDisplay : TDisplayEvent;
FOnRequestDone : TRequestDoneEvent;
FOnProgressAddSegment : TProgressAddSegmentEvent;
FOnProgressSetPosition : TProgressSetPositionEvent;
FOnShowStats : TNotifyEvent;
FMsg_WM_START_MULTI : UINT;
FMsg_WM_PART_DONE : UINT;
Timer1 : TIcsTimer;
TimeoutTimer : TIcsTimer;
procedure AbortComponent; override; { 0.99d }
procedure AllocateMsgHandlers; override;
procedure FreeMsgHandlers; override;
function MsgHandlersCount: Integer; override;
procedure SizeASyncRequestDone(Sender : TObject;
Request : TFtpRequest;
ErrorCode : Word);
procedure SizeSessionClosed(Sender: TObject; ErrCode: Word);
procedure GetASyncRequestDone(Sender : TObject;
Request : TFtpRequest;
ErrorCode : Word);
procedure Display(const Msg: String);
procedure DisplayHandler(Sender : TObject; var Msg: String);
procedure WMStartMulti(var msg: TMessage);
procedure WMPartDone(var msg: TMessage);
procedure WndProc(var MsgRec: TMessage); override;
procedure DownloadRequestDone(Sender : TObject;
Request : TFtpRequest;
ErrorCode : Word);
procedure DownloadDocData(Sender : TObject;
Data : Pointer;
Len : Integer);
procedure CheckDone(ErrCode : Integer; const Reason : String);
procedure Timer1Timer(Sender: TObject);
procedure SizeTimeoutTimerTimer(Sender: TObject);
procedure RestartDownload(MyFtp : TMyFtpCli);
procedure TriggerRequestDone(ErrCode : Integer;
const Reason : String); virtual;
procedure TriggerShowStats; virtual;
procedure TriggerProgressSetPosition(Index : Integer;
Position : Int64); virtual;
procedure TriggerProgressAddSegment(StartOffset, ASpan,
InitPos: Int64); virtual;
procedure LoadStatus;
procedure SaveStatus;
procedure SetStateFileName(const Value: String);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start;
procedure Abort;
procedure Pause;
procedure Resume;
property TotalCount : TFtpBigInt read FTotalCount;
property ContentLength : TFtpBigInt read FContentLength;
property CurSpeed : Double read FCurSpeed;
property ElapsedTime : TDateTime read FElapsedTime;
property PercentDone : Double read FPercentDone;
published
property Server : String read FServer
write FServer;
property Port : String read FPort
write FPort;
property User : String read FUser
write FUser;
property Pass : String read FPass
write FPass;
property Dir : String read FDir
write FDir;
property FileName : String read FFileName
write FFileName;
property Passive : Boolean read FPassive
write FPassive;
property Binary : Boolean read FBinary
write FBinary;
property PartCount : Integer read FPartCount
write FPartCount;
property FileStream : TStream read FFileStream
write FFileStream;
property StateFileName : String read FStateFileName
write SetStateFileName;
property TimeoutValue : Integer read FTimeoutValue
write FTimeoutValue;
property AssumedSize : TFtpBigInt read FAssumedSize
write FAssumedSize;
property OnDisplay : TDisplayEvent read FOnDisplay
write FOnDisplay;
property OnRequestDone : TRequestDoneEvent read FOnRequestDone
write FOnRequestDone;
property OnProgressAddSegment : TProgressAddSegmentEvent
read FOnProgressAddSegment
write FOnProgressAddSegment;
property OnProgressSetPosition : TProgressSetPositionEvent
read FOnProgressSetPosition
write FOnProgressSetPosition;
property OnShowStats : TNotifyEvent
read FOnShowStats
write FOnShowStats;
property OnBgException; { 0.99d }
end;
implementation
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TMultipartFtpDownloader.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
AllocateHWnd;
FTimeoutValue := 30000; // 30 second timeout by default
Timer1 := TIcsTimer.Create(Self);
Timer1.Enabled := FALSE;
Timer1.Interval := 1000;
Timer1.OnTimer := Timer1Timer;
TimeoutTimer := TIcsTimer.Create(Self);
TimeoutTimer.Enabled := FALSE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TMultipartFtpDownloader.Destroy;
var
I : Integer;
begin
for I := 0 to Length(FMyFtp) - 1 do
FreeAndNil(FMyFtp[I]);
SetLength(FMyFtp, 0);
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.Display(const Msg: String);
begin
if Assigned(FOnDisplay) then
FOnDisplay(Self, Msg);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.DisplayHandler(
Sender : TObject;
var Msg : String);
var
FtpCli : TMyFtpCli;
begin
FtpCli := Sender as TMyFtpCli;
Display(Format('%03.3d %s', [FtpCli.FIndex + 1, Msg]));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.Start;
var
I : Integer;
begin
if FPartCount < 1 then
raise ERangeError.Create('PartCount (' + IntToStr(FPartCount) +
') must be positive and not nul');
FAbortFlag := FALSE;
FPauseFlag := FALSE;
FTimeoutFlag := FALSE;
FContentLength := -1;
FTotalCount := 0;
FPrevCount := 0;
FPrevTick := GetTickCount;
FStartTime := Now;
FElapsedTime := 0;
TriggerShowStats;
for I := 0 to Length(FMyFtp) - 1 do
FreeAndNil(FMyFtp[I]);
// First we need to get the size of the file
SetLength(FMyFtp, 1);
FMyFtp[0] := TMyFtpCli.Create(Self);
FMyFtp[0].FIndex := 0;
FMyFtp[0].HostName := FServer;
FMyFtp[0].Port := FPort;
FMyFtp[0].Username := FUser;
FMyFtp[0].Password := FPass;
FMyFtp[0].HostDirName := FDir;
FMyFtp[0].HostFileName := FFileName;
FMyFtp[0].OnDisplay := DisplayHandler;
FMyFtp[0].OnBgException := OnBgException; { 0.99d }
FMyFtp[0].ExceptAbortProc := AbortComponent; { 0.99d }
// We don't need to get a size if we have an assumed size
if FAssumedSize > 0 then begin
FContentLength := FAssumedSize;
PostMessage(Handle, FMsg_WM_START_MULTI, 0, 0);
Exit;
end;
FMyFtp[0].OnRequestDone := SizeASyncRequestDone;
FMyFtp[0].OnSessionClosed := SizeSessionClosed;
FMyFtp[0].OpenAsync;
Display('SizeASync');
TimeoutTimer.OnTimer := SizeTimeoutTimerTimer;
TimeoutTimer.Interval := FTimeoutValue;
TimeoutTimer.Enabled := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// This event handler is called for all operation related to getting file size
procedure TMultipartFtpDownloader.SizeASyncRequestDone(
Sender : TObject;
Request : TFtpRequest;
ErrorCode : Word);
var
FtpCli : TMyFtpCli;
begin
Display('SizeASyncRequestDone');
TimeoutTimer.Enabled := FALSE;
FtpCli := Sender as TMyFtpCli;
if Request = ftpQuitAsync then begin
// We can safely ignore any error here
// We will get an OnSessionClosed event
exit;
end;
if FTimeoutFlag then begin
// ToDo: Check if 426 is correct error code to return
TriggerRequestDone(426, 'Download failed: timeout');
Exit;
end;
if FAbortFlag then begin
Display('Abort has been called');
// ToDo: Check if 426 is correct error code to return
TriggerRequestDone(426, 'Download aborted');
Exit;
end;
if ErrorCode <> 0 then begin
Display('ErrorCode = ' + IntToStr(ErrorCode));
TriggerRequestDone(ErrorCode, 'Download failed');
Exit;
end;
case Request of
ftpOpenAsync: FtpCli.UserAsync;
ftpUserAsync: FtpCli.PassAsync;
ftpPassAsync: FtpCli.CwdAsync;
ftpCwdAsync: FtpCli.SizeAsync;
ftpSizeAsync:
begin
FContentLength := FtpCli.SizeResult;
FtpCli.QuitAsync;
end;
else
Display('Unexpected FTP component state ' + IntToStr(Ord(Request)));
TriggerRequestDone(-1, 'Download failed, internal error');
Exit;
end;
TimeoutTimer.Interval := FTimeoutValue;
TimeoutTimer.Enabled := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.SizeSessionClosed(
Sender : TObject;
ErrCode : Word);
begin
Display('SizeSessionClosed');
if FAbortFlag then begin
Display('Abort has been called');
Exit;
end;
if FContentLength > 0 then begin
// We are happy with a document to get
PostMessage(Handle, FMsg_WM_START_MULTI, 0, 0);
Exit;
end;
if FContentLength = 0 then begin
TriggerRequestDone(0, 'Download success, empty file');
Exit;
end;
TriggerRequestDone(ErrCode, 'Download failed');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.GetASyncRequestDone(
Sender : TObject;
Request : TFtpRequest;
ErrorCode : Word);
var
FtpCli : TMyFtpCli;
begin
Display('GetASyncRequestDone');
if FContentLength > 0 then begin
// We are happy with a document to get
PostMessage(Handle, FMsg_WM_START_MULTI, 0, 0);
Exit;
end;
FtpCli := Sender as TMyFtpCli;
if ErrorCode <> 0 then begin
Display('ErrorCode = ' + IntToStr(ErrorCode));
TriggerRequestDone(ErrorCode, 'Download failed');
Exit;
end;
if FtpCli.StatusCode <> 200 then begin
Display('StatusCode = ' + IntToStr(FtpCli.StatusCode) + ' ' +
FtpCli.LastResponse);
TriggerRequestDone(FtpCli.StatusCode, FtpCli.LastResponse);
Exit;
end;
Display('RequestDone DataCount = ' + IntToStr(FtpCli.FDataCount));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMultipartFtpDownloader.MsgHandlersCount : Integer;
begin
Result := 2 + inherited MsgHandlersCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.AbortComponent; { 0.99d }
begin
try
Abort;
except
end;
inherited;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.AllocateMsgHandlers;
begin
inherited AllocateMsgHandlers;
FMsg_WM_START_MULTI := FWndHandler.AllocateMsgHandler(Self);
FMsg_WM_PART_DONE := FWndHandler.AllocateMsgHandler(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.FreeMsgHandlers;
begin
if Assigned(FWndHandler) then begin
FWndHandler.UnregisterMessage(FMsg_WM_PART_DONE);
FWndHandler.UnregisterMessage(FMsg_WM_START_MULTI);
end;
inherited FreeMsgHandlers;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.WndProc(var MsgRec: TMessage);
begin
try { 0.99d }
with MsgRec do begin
if Msg = FMsg_WM_START_MULTI then
WMStartMulti(MsgRec)
else if Msg = FMsg_WM_PART_DONE then
WMPartDone(MsgRec)
else
inherited WndProc(MsgRec);
end;
except { 0.99d }
on E: Exception do
HandleBackGroundException(E);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.WMStartMulti(var msg: TMessage);
var
Chunk : TFtpBigInt;
Offset : TFtpBigInt;
I : Integer;
MyFtp : TMyFtpCli;
OldFtp : TMyFtpCli;
begin
// Do not destroy current component before having allocated the new
// it still has to purge events from the queue. Chances are that the
// new components handle those events !
OldFtp := FMyFtp[0];
OldFtp.OnRequestDone := nil;
OldFtp.OnSessionClosed := nil;
OldFtp.OnDisplay := nil;
Chunk := FContentLength div FPartCount;
Offset := 0;
SetLength(FMyFtp, FPartCount);
for I := 0 to FPartCount - 1 do begin
FMyFtp[I] := TMyFtpCli.Create(Self);
MyFtp := FMyFtp[I];
MyFtp.FStartOffset := Offset;
if I < (FPartCount - 1) then
MyFtp.FEndOffset := Offset + Chunk
else
MyFtp.FEndOffset := FContentLength;
Offset := Offset + Chunk + 1;
MyFtp.ResumeAt := MyFtp.FStartOffset;
TriggerProgressAddSegment(MyFtp.FStartOffset,
MyFtp.FEndOffset - MyFtp.FStartOffset,
MyFtp.FStartOffset);
MyFtp.FIndex := I;
MyFtp.HostName := FServer;
MyFtp.Port := FPort;
MyFtp.Username := FUser;
MyFtp.Password := FPass;
MyFtp.HostDirName := FDir;
MyFtp.HostFileName := FFileName;
MyFtp.LocalStream := FFileStream;
MyFtp.Passive := FPassive;
MyFtp.Binary := FBinary;
MyFtp.OnRequestDone := DownloadRequestDone;
MyFtp.OnDocData := DownloadDocData;
MyFtp.OnDisplay := DisplayHandler;
MyFtp.OnBgException := OnBgException; { 0.99d }
MyFtp.ExceptAbortProc := AbortComponent; { 0.99d }
MyFtp.FDataCount := 0;
MyFtp.FDone := FALSE;
MyFtp.Options := [ftpNoAutoResumeAt];
//ListBox1.Items.Add('0');
end;
for I := 0 to Length(FMyFtp) - 1 do
FMyFtp[I].OpenASync;
Timer1.Enabled := TRUE;
// Now it is safe to destroy the old component (the one used for Size)
OldFtp.Free;
Display('OpenASync');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.LoadStatus;
const
Default = '0';
var
SectionNames : TStringList;
Cnt : Integer;
I : Integer;
MyFtp : TMyFtpCli;
IniFile : TIniFile;
//Dls : TDownloadState;
begin
for I := 0 to Length(FMyFtp) - 1 do
FreeAndNil(FMyFtp[I]);
SetLength(FMyFtp, 0);
FTotalCount := 0;
FContentLength := 0;
FServer := '';
FPort := '';
FPartCount := 0;
if not FileExists(FStateFileName) then
Exit;
IniFile := TIniFile.Create(FStateFileName);
try
//FFileName := IniFile.ReadString('GLOBAL', 'FileName', '');
FContentLength := StrToInt64Def(IniFile.ReadString('GLOBAL', 'ContentLength', Default), 0);
FServer := IniFile.ReadString('GLOBAL', 'Server', '');
FPort := IniFile.ReadString('GLOBAL', 'Port', '');
FPartCount := IniFile.ReadInteger('GLOBAL', 'PartCount', 1);
SetLength(FMyFtp, FPartCount);
if FPartCount > 0 then begin
SectionNames := TStringList.Create;
try
IniFile.ReadSections(SectionNames);
for I := 0 to SectionNames.Count - 1 do begin
if Copy(SectionNames[I], 1, 5) <> 'PART_' then
Continue;
Cnt := StrToInt(Copy(SectionNames[I], 6, 8));
FMyFtp[Cnt] := TMyFtpCli.Create(Self);
MyFtp := FMyFtp[Cnt];
MyFtp.FIndex := Cnt;
MyFtp.FStartOffset := StrToInt64Def(IniFile.ReadString(SectionNames[I], 'StartOffset', Default), 0);
MyFtp.FEndOffset := StrToInt64Def(IniFile.ReadString(SectionNames[I], 'EndOffset', Default), 0);
MyFtp.FDataCount := StrToInt64Def(IniFile.ReadString(SectionNames[I], 'DataCount', Default), 0);
// MyFtp.FDone := IniFile.ReadBool(SectionNames[I], 'Done', FALSE);
MyFtp.HostName := IniFile.ReadString(SectionNames[I], 'Server', '');
MyFtp.Port := IniFile.ReadString(SectionNames[I], 'Port', '');
MyFtp.OnRequestDone := DownloadRequestDone;
MyFtp.OnDocData := DownloadDocData;
Inc(FTotalCount, MyFtp.FDataCount);
end;
FPrevCount := FTotalCount;
FPrevTick := GetTickCount;
FStartTime := Now;
FElapsedTime := 0;
finally
FreeAndNil(SectionNames);
end;
end;
finally
FreeAndNil(IniFile);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.SaveStatus;
var
SectionNames : TStringList;
I : Integer;
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(FStateFileName);
try
SectionNames := TStringList.Create;
try
IniFile.ReadSections(SectionNames);
for I := 0 to SectionNames.Count - 1 do begin
if Copy(SectionNames[I], 1, 5) = 'PART_' then
IniFile.EraseSection(SectionNames[I]);
end;
finally
FreeAndNil(SectionNames);
end;
IniFile.EraseSection('GLOBAL');
IniFile.WriteString('GLOBAL', 'Server', FServer);
IniFile.WriteString('GLOBAL', 'Port', FPort);
IniFile.WriteString('GLOBAL', 'ContentLength', IntToStr(FContentLength));
IniFile.WriteInteger('GLOBAL', 'PartCount', Length(FMyFtp));
for I := 0 to Length(FMyFtp) - 1 do begin
IniFile.WriteString('PART_' + IntToStr(I), 'StartOffset', IntToStr(FMyFtp[I].FStartOffset));
IniFile.WriteString('PART_' + IntToStr(I), 'EndOffset', IntToStr(FMyFtp[I].FEndOffset));
IniFile.WriteString('PART_' + IntToStr(I), 'DataCount', IntToStr(FMyFtp[I].FDataCount));
IniFile.WriteString('PART_' + IntToStr(I), 'Server', FMyFtp[I].HostName);
IniFile.WriteString('PART_' + IntToStr(I), 'Port', FMyFtp[I].Port);
FMyFtp[I].FDone := (FMyFtp[I].FDataCount >= (FMyFtp[I].FEndOffset - FMyFtp[I].FStartOffset));
end;
finally
FreeAndNil(IniFile);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
type
TOKStatus = record
Rq : TFtpRequest;
St : array [0..4] of Integer;
end;
procedure TMultipartFtpDownloader.DownloadRequestDone(
Sender : TObject;
Request : TFtpRequest;
ErrorCode : Word);
var
FtpCli : TMyFtpCli;
ErrCode : Integer;
Reason : String;
const
OKStatus : array [0..1] of TOKStatus = (
(Rq: ftpOpenAsync; St: (0, 0, 0, 0, 0)),
(Rq: ftpUserAsync; St: (0, 0, 0, 0, 0))
);
begin
FtpCli := Sender as TMyFtpCli;
if FAbortFlag then begin
// We are aborting transfert, just ignore any error
Display(Format('%03.3d %s',
[FtpCli.FIndex + 1, 'Download done : Aborted']));
ErrCode := 503; // 503 is service unavailable
Reason := 'Transfert aborted';
end
else if FPauseFlag then begin
// We are aborting transfert, just ignore any error
Display(Format('%03.3d %s',
[FtpCli.FIndex + 1, 'Download done : Paused']));
ErrCode := 204;
Reason := 'Transfert paused';
end
else if FtpCli.FDone then begin
Display(Format('%03.3d %s',
[FtpCli.FIndex + 1, 'DownloadRequestDone']));
ErrCode := 0; // This part is finished, it is OK
Reason := 'Part finished';
end
else begin
if Request = ftpQuitAsync then begin
// We can safely ignore any error here
Exit;
end;
if ErrorCode <> 0 then begin
Display(Format('%03.3d Download ErrorCode = %d, Msg = %s',
[FtpCli.FIndex + 1,
ErrorCode, FtpCli.LastResponse]));
// RestartDownload(FtpCli);
// Exit;
end;
try
case Request of
ftpOpenAsync: FtpCli.UserAsync;
ftpUserAsync: FtpCli.PassAsync;
ftpPassAsync: FtpCli.CwdAsync;
ftpCwdAsync: FtpCli.TypeSetAsync;
ftpTypeSetAsync: FtpCli.RestGetAsync;
ftpRestGetAsync: FtpCli.GetAsync;
ftpGetAsync: FtpCli.QuitAsync;
else
Display(Format('%03.3d %s %d',
[FtpCli.FIndex + 1,
'Unexpected FTP component state',
Ord(Request)]));
TriggerRequestDone(-1, 'Download failed, internal error');
end;
except
on E:Exception do begin
if Request <> ftpGetAsync then begin
Display(Format('%03.3d %s %s: %s',
[FtpCli.FIndex + 1,
'Download exception =',
E.ClassName, E.Message]));
RestartDownload(FtpCli);
end;
end;
end;
Exit;
end;
CheckDone(ErrCode, Reason);
FtpCli.FDone := TRUE;
if FAbortFlag then begin
// We are aborting transfert, just ignore any error
Display(Format('%03.3d %s',
[FtpCli.FIndex + 1, 'Download done Aborted']));
ErrCode := 503; // 503 is service unavailable
Reason := 'Transfert aborted';
end
else if FPauseFlag then begin
// We are aborting transfert, just ignore any error
Display(Format('%03.3d %s',
[FtpCli.FIndex + 1, 'Download done Paused']));
ErrCode := 204;
Reason := 'Transfert paused';
end
else begin
if ErrorCode = 426 then begin
// 426 is transfert aborted because part is finished
end
else if ErrorCode <> 0 then begin
Display(Format('%03.3d %s %d',
[FtpCli.FIndex + 1,
'Download done ErrorCode =',
ErrorCode]));
RestartDownload(FtpCli);
Exit;
end
else if FtpCli.StatusCode <> 206 then begin
Display(Format('%03.3d %s %d',
[FtpCli.FIndex + 1,
'Download done Status =',
FtpCli.StatusCode]));
RestartDownload(FtpCli);
Exit;
end;
Display(Format('%03.3d %s', [FtpCli.FIndex + 1, 'Download done OK']));
ErrCode := 200;
Reason := 'OK';
end;
CheckDone(ErrCode, Reason);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.CheckDone(
ErrCode : Integer;
const Reason : String);
var
Done : Boolean;
I : Integer;
begin
Done := TRUE;
for I := 0 to Length(FMyFtp) - 1 do
Done := Done and (FMyFtp[I].FDone);
if Done then begin
Timer1.Enabled := FALSE;
Timer1.OnTimer(nil);
Display('All done');
if FPauseFlag then
SaveStatus;
TriggerRequestDone(ErrCode, Reason);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.DownloadDocData(
Sender : TObject;
Data : Pointer;
Len : Integer);
var
FtpCli : TMyFtpCli;
begin
if Len <= 0 then
Exit;
if FPauseFlag then
Exit;
TimeoutTimer.Enabled := FALSE; // Stop timeout timer...
TimeoutTimer.Enabled := TRUE; // and restart timeout timer
FtpCli := Sender as TMyFtpCli;
FFileStream.Seek(FtpCli.FStartOffset + FtpCli.FDataCount,
soBeginning); // Warning: Using soFromBeginning make sthe compiler pick the 32 bit overload !
FFileStream.WriteBuffer(Data^, Len);
FtpCli.FDataCount := FtpCli.FDataCount + Len;
FTotalCount := FTotalCount + Len;
TriggerProgressSetPosition(FtpCli.FIndex,
FtpCli.FStartOffset + FtpCli.FDataCount);
// Todo: Check if that component has finished his range and abort the
// transfer when finished.
if FtpCli.FDataCount > (FtpCli.FEndOffset - FtpCli.FStartOffset) then begin
// Component has finished his part
Display(Format('%03.3d %s',
[FtpCli.FIndex + 1, 'Part done DownloadDocData']));
PostMessage(Handle, FMsg_WM_PART_DONE, 0, LParam(FtpCli));
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.WMPartDone(var msg: TMessage);
var
FtpCli : TMyFtpCli;
begin
FtpCli := TObject(Msg.LParam) as TMyFtpCli;
// Display(Format('%03.3d %s', [FtpCli.FIndex + 1, 'Part done handler']));
if not Assigned(FtpCli) then
Exit;
if FtpCli.FDone then
Exit;
FtpCli.FDone := TRUE;
FtpCli.AbortAsync;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.TriggerProgressSetPosition(
Index : Integer;
Position : Int64);
begin
if Assigned(FOnProgressSetPosition) then
FOnProgressSetPosition(Self, Index, Position);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.TriggerProgressAddSegment(
StartOffset : Int64;
ASpan : Int64;
InitPos : Int64);
begin
if Assigned(FOnProgressAddSegment) then
FOnProgressAddSegment(Self, StartOffset, ASpan, InitPos);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.TriggerShowStats;
begin
if Assigned(FOnShowStats) then
FOnShowStats(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.TriggerRequestDone(
ErrCode : Integer;
const Reason : String);
begin
if Assigned(FOnrequestDone) then
FOnRequestDone(Self, ErrCode, Reason);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.SizeTimeoutTimerTimer(Sender: TObject);
begin
Display('Timeout');
FTimeoutFlag := TRUE;
Abort;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.Timer1Timer(Sender: TObject);
var
FtpCli : TMyFtpCli;
I : Integer;
Done : Boolean;
Tick : Cardinal;
begin
Done := TRUE;
for I := 0 to Length(FMyFtp) - 1 do begin
FtpCli := FMyFtp[I];
Done := Done and (FtpCli.FDone);
end;
Tick := GetTickCount;
FCurSpeed := 8 * (FTotalCount - FPrevCount) / (Tick - FPrevTick);
FElapsedTime := Now - FStartTime;
if FContentLength = 0 then
FPercentDone := 0
else
FPercentDone := 100.0 * FTotalCount / FContentLength;
TriggerShowStats;
FPrevTick := Tick;
FPrevCount := FTotalCount;
if not Done then
Exit;
// Download is finished
Timer1.Enabled := FALSE;
FCurSpeed := 8 * FTotalCount / (FElapsedTime * 86400000);
TriggerShowStats;
FreeAndNil(FFileStream);
Display('Done');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.RestartDownload(MyFtp: TMyFtpCli);
begin
Display('Restarting ' + IntToStr(MyFtp.FIndex + 1));
TriggerProgressSetPosition(MyFtp.FIndex, MyFtp.FStartOffset);
MyFtp.ResumeAt := MyFtp.FStartOffset;
MyFtp.Username := FUser;
MyFtp.Password := FPass;
MyFtp.FDataCount := 0;
MyFtp.FDone := FALSE;
MyFtp.GetASync;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.Abort;
var
FtpCli : TMyFtpCli;
I : Integer;
begin
FAbortFlag := TRUE;
for I := 0 to Length(FMyFtp) - 1 do begin
FtpCli := FMyFtp[I];
FtpCli.Abort;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.Pause;
var
FtpCli : TMyFtpCli;
I : Integer;
begin
if StateFileName = '' then
raise Exception.Create('TMultipartHttpDownloader.Pause: ' +
'No file name specified');
FPauseFlag := TRUE;
for I := 0 to Length(FMyFtp) - 1 do begin
FtpCli := FMyFtp[I];
FtpCli.Abort;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.Resume;
var
FtpCli : TMyFtpCli;
I : Integer;
begin
if StateFileName = '' then
raise Exception.Create('TMultipartHttpDownloader.Resume: ' +
'No file name specified');
FAbortFlag := FALSE;
FPauseFlag := FALSE;
LoadStatus;
for I := 0 to Length(FMyFtp) - 1 do begin
FtpCli := FMyFtp[I];
FtpCli.HostName := FServer;
FtpCli.Port := FPort;
FtpCli.Username := FUser;
FtpCli.Password := FPass;
FtpCli.HostDirName := FDir;
FtpCli.HostFileName := FFileName;
FtpCli.LocalStream := FFileStream;
FtpCli.Passive := FPassive;
FtpCli.Binary := FBinary;
FtpCli.OnRequestDone := DownloadRequestDone;
FtpCli.OnDocData := DownloadDocData;
FtpCli.OnDisplay := DisplayHandler;
FtpCli.FDone := (FtpCli.FDataCount >= (FtpCli.FEndOffset - FtpCli.FStartOffset));
FtpCli.Options := [ftpNoAutoResumeAt];
FtpCli.ResumeAt := FtpCli.FStartOffset + FtpCli.FDataCount;
Display('Resuming ' + IntToStr(I) +
' Offset=' + IntToStr(FtpCli.ResumeAt) +
' DataCount=' + IntToStr(FtpCli.FDataCount));
TriggerProgressAddSegment(FtpCli.FStartOffset,
FtpCli.FEndOffset - FtpCli.FStartOffset,
FtpCli.FStartOffset + FtpCli.FDataCount);
end;
// Start all download which is not done yet
for I := 0 to Length(FMyFtp) - 1 do begin
if not FMyFtp[I].FDone then
FMyFtp[I].OpenASync;
end;
Timer1.Enabled := TRUE;
CheckDone(0, 'OK');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMultipartFtpDownloader.SetStateFileName(const Value: String);
begin
// We use TIniFile which create a file with no path into Windows directory
// Add the current directory specifier to the filename if required.
if ExtractFilePath(Value) = '' then
FStateFileName := '.\' + Value
else
FStateFileName := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMyFtpCli.LocalStreamWrite(const Buffer; Count: Integer);
begin
if Assigned(FOnDocData) then
FOnDocData(Self, @Buffer, Count);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit uGrupos;
interface
type TGrupos = class
private
FGRUPO_DESCRICAO: String;
FGRUPO_CODIGO: Integer;
procedure SetGRUPO_CODIGO(const Value: Integer);
procedure SetGRUPO_DESCRICAO(const Value: String);
public
constructor Create;
destructor Destroy; override;
protected
published
property GRUPO_CODIGO : Integer read FGRUPO_CODIGO write SetGRUPO_CODIGO;
property GRUPO_DESCRICAO : String read FGRUPO_DESCRICAO write SetGRUPO_DESCRICAO;
end;
implementation
{ TGrupos }
constructor TGrupos.Create;
begin
FGRUPO_DESCRICAO := '';
FGRUPO_CODIGO := 0;
end;
destructor TGrupos.Destroy;
begin
inherited;
end;
procedure TGrupos.SetGRUPO_CODIGO(const Value: Integer);
begin
FGRUPO_CODIGO := Value;
end;
procedure TGrupos.SetGRUPO_DESCRICAO(const Value: String);
begin
FGRUPO_DESCRICAO := Value;
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uPrintReportParametersImpl.pas }
{ Описание: Реализация IPrintReportParameters }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uPrintReportParametersImpl;
interface
uses
SysUtils, Classes, uServices;
function CreatePrintReportParameters: IPrintReportParameters;
implementation
type
TPrintReportParameters = class(TInterfacedObject, IPrintReportParameters)
private
FDuplex: TDuplex;
FNumCopy: Integer;
FPaperOrientation: TPaperOrientation;
FPrinterName: string;
FShowPrintDialog: Boolean;
public
function GetDuplex: TDuplex; stdcall;
function GetNumCopy: Integer; stdcall;
function GetPaperOrientation: TPaperOrientation; stdcall;
function GetPrinterName: string; stdcall;
function GetShowPrintDialog: Boolean; stdcall;
procedure SetDuplex(Value: TDuplex); stdcall;
procedure SetNumCopy(Value: Integer); stdcall;
procedure SetPaperOrientation(Value: TPaperOrientation); stdcall;
procedure SetPrinterName(const Value: string); stdcall;
procedure SetShowPrintDialog(Value: Boolean); stdcall;
property Duplex: TDuplex read GetDuplex write SetDuplex;
property NumCopy: Integer read GetNumCopy write SetNumCopy;
property PaperOrientation: TPaperOrientation read GetPaperOrientation write
SetPaperOrientation;
property PrinterName: string read GetPrinterName write SetPrinterName;
property ShowPrintDialog: Boolean read GetShowPrintDialog write
SetShowPrintDialog;
end;
{
**************************** TPrintReportParameters ****************************
}
function TPrintReportParameters.GetDuplex: TDuplex;
begin
Result := FDuplex;
end;
function TPrintReportParameters.GetNumCopy: Integer;
begin
Result := FNumCopy;
end;
function TPrintReportParameters.GetPaperOrientation: TPaperOrientation;
begin
Result := FPaperOrientation;
end;
function TPrintReportParameters.GetPrinterName: string;
begin
Result := FPrinterName;
end;
function TPrintReportParameters.GetShowPrintDialog: Boolean;
begin
Result := FShowPrintDialog;
end;
procedure TPrintReportParameters.SetDuplex(Value: TDuplex);
begin
if FDuplex <> Value then
begin
FDuplex := Value;
end;
end;
procedure TPrintReportParameters.SetNumCopy(Value: Integer);
begin
if FNumCopy <> Value then
begin
FNumCopy := Value;
end;
end;
procedure TPrintReportParameters.SetPaperOrientation(Value: TPaperOrientation);
begin
if FPaperOrientation <> Value then
begin
FPaperOrientation := Value;
end;
end;
procedure TPrintReportParameters.SetPrinterName(const Value: string);
begin
if FPrinterName <> Value then
begin
FPrinterName := Value;
end;
end;
procedure TPrintReportParameters.SetShowPrintDialog(Value: Boolean);
begin
if FShowPrintDialog <> Value then
begin
FShowPrintDialog := Value;
end;
end;
function CreatePrintReportParameters: IPrintReportParameters;
begin
Result := TPrintReportParameters.Create();
end;
end.
|
unit Control.CadastroEmpresa;
interface
uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Control.Sistema, Model.CadastroEmpresa;
type
TCadastroEmpresaControl = class
private
FCadastro : TCadastroEmpresa;
public
constructor Create();
destructor Destroy(); override;
property Cadastro: TCadastroEmpresa read FCadastro write FCadastro;
function GetID(): Integer;
function ValidaCampos(): Boolean;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
end;
implementation
{ TCadastroEmpresaControl }
uses Common.Utils;
constructor TCadastroEmpresaControl.Create;
begin
FCadastro := TCadastroEmpresa.Create;
end;
destructor TCadastroEmpresaControl.Destroy;
begin
FCadastro.Free;
inherited;
end;
function TCadastroEmpresaControl.GetID: Integer;
begin
Result := FCadastro.GetID();
end;
function TCadastroEmpresaControl.Gravar: Boolean;
begin
Result := False;
if not ValidaCampos() then Exit;
Result := FCadastro.Gravar;
end;
function TCadastroEmpresaControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FCadastro.Localizar(aParam);
end;
function TCadastroEmpresaControl.ValidaCampos: Boolean;
var
FDQuery : TFDQuery;
aParam: Array of variant;
begin
try
Result := False;
FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery;
// if FCadastro.ID = 0 then
// begin
// Application.MessageBox('Informe um ID para o cadastro!', 'Atenção', MB_OK + MB_ICONWARNING);
// Exit;
// end;
if FCadastro.Nome.IsEmpty then
begin
Application.MessageBox('Informe o nome do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FCadastro.TipoDoc.IsEmpty then
begin
Application.MessageBox('Informe o tipo de documento do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if not FCadastro.CPFCNPJ.IsEmpty then
begin
if not TUtils.CNPJ(FCadastro.CPFCNPJ) then
begin
Application.MessageBox('Número do CNPJ inválido!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
SetLength(aParam,2);
aParam[0] := 'CPFCNPJ';
aParam[1] := FCadastro.CPFCNPJ;
FDQuery := FCadastro.Localizar(aParam);
Finalize(aParam);
if FDQuery.RecordCount >= 1 then
begin
if FCadastro.Acao = tacIncluir then
begin
Application.MessageBox('CNPJ já cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING);
FDQuery.Close;
Exit;
end;
end;
end;
Result := True;
finally
FDQuery.Free;
end;end;
end.
|
unit AutoMapper.Exceptions;
interface
uses
System.SysUtils
;
type
TAutoMapperException = class(Exception);
TMapperConfigureException = class(TAutoMapperException);
TGetMapItemException = class(TAutoMapperException);
TClassPairCreateExcetion = class(TAutoMapperException);
TTypePairCreateException = class(TAutoMapperException);
resourcestring
CS_MAPPER_CONFIGURATION_ALLREADY = 'The AutoMapper configuration has already been performed.';
CS_GET_MAPITEM_NOT_FOUND = 'MapItem for a pair of objects "%s"->"%s" not found.';
CS_CLASSPAIR_CREATE_SOURCECLASS_NIL = 'Argument SourceClass is nil.';
CS_CLASSPAIR_CREATE_DESTCLASS_NIL = 'Argument DestinationClass is nil.';
implementation
end.
|
unit PascaltypeSettings;
{ Settings for converting IDL-types to Pascal types
Copyright (C) 20120 Joost van der Sluis/CNOC joost@cnoc.nl
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, ValEdit;
type
{ TTypeSettings }
TTypeSettings = class(TForm)
bSaveMap: TButton;
bLoadMap: TButton;
Label1: TLabel;
Label2: TLabel;
OpenDialog: TOpenDialog;
pMapBottom: TPanel;
pCListBottom: TPanel;
pRight: TPanel;
pLeft: TPanel;
SaveDialog: TSaveDialog;
Splitter1: TSplitter;
ValueListEditor1: TValueListEditor;
procedure bLoadMapClick(Sender: TObject);
procedure bSaveMapClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
TypeSettings: TTypeSettings;
implementation
{$R *.lfm}
{ TTypeSettings }
procedure TTypeSettings.bLoadMapClick(Sender: TObject);
begin
if OpenDialog.Execute then
ValueListEditor1.Strings.LoadFromFile(OpenDialog.FileName);
end;
procedure TTypeSettings.bSaveMapClick(Sender: TObject);
begin
if SaveDialog.Execute then
ValueListEditor1.Strings.SaveToFile(SaveDialog.FileName);
end;
end.
|
unit UDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeUIBaseControl,
FMX.TMSNativeUIButton, FMX.TMSNativeUIActionSheet, iOSApi.UIKit, iOSApi.Foundation;
type
TForm1035 = class(TForm)
TMSFMXNativeUIActionSheet1: TTMSFMXNativeUIActionSheet;
TMSFMXNativeUIButton1: TTMSFMXNativeUIButton;
procedure TMSFMXNativeUIButton1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure TMSFMXNativeUIActionSheet1DidDismissWithButtonIndex(
Sender: TObject; AButtonIndex: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1035: TForm1035;
implementation
{$R *.fmx}
procedure TForm1035.FormCreate(Sender: TObject);
begin
TMSFMXNativeUIActionSheet1.CancelButtonTitle := 'Cancel';
TMSFMXNativeUIActionSheet1.DestructiveButtonTitle := 'Delete';
TMSFMXNativeUIActionSheet1.Buttons.Add('Hello World!');
end;
procedure TForm1035.TMSFMXNativeUIActionSheet1DidDismissWithButtonIndex(
Sender: TObject; AButtonIndex: Integer);
var
str: String;
av: UIAlertView;
begin
str := 'Clicked on ' + TMSFMXNativeUIActionSheet1.ButtonTitleAtIndex(AButtonIndex) + ' button';
av := TUIAlertView.Wrap(TUIAlertView.Wrap(TUIAlertView.OCClass.alloc).initWithTitle(NSSTR('Alert'), NSSTR(str), nil, NSSTR('OK'), nil));
av.show;
av.release;
end;
procedure TForm1035.TMSFMXNativeUIButton1Click(Sender: TObject);
begin
TMSFMXNativeUIActionSheet1.ShowFromControl(TMSFMXNativeUIButton1);
end;
end.
|
unit GetOptimizationsUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TGetOptimizations = class(TBaseExample)
public
procedure Execute;
end;
implementation
uses RouteParametersQueryUnit, DataObjectUnit;
procedure TGetOptimizations.Execute;
var
DataObjects: TDataObjectList;
DataObject: TDataObject;
ErrorString: String;
Limit, Offset: integer;
begin
Limit := 10;
Offset := 5;
DataObjects := Route4MeManager.Optimization.Get(Limit, Offset, ErrorString);
try
WriteLn('');
if (DataObjects.Count > 0) then
begin
WriteLn(Format(
'GetOptimizations executed successfully, %d optimizations returned',
[DataObjects.Count]));
WriteLn('');
for DataObject in DataObjects do
WriteLn(Format('Optimization Problem ID: %s', [DataObject.OptimizationProblemId]));
end
else
WriteLn(Format('GetOptimizations error: "%s"', [ErrorString]));
finally
FreeAndNil(DataObjects);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.