text
stringlengths
14
6.51M
unit EnumsUnit; interface uses SysUtils; type TTrackingInfo = ( tiOrderReceived, tiOrderAssignedToRoute, tiPacking, tiLoadedToVehicle, tiOutForDelivery, tiUnknown ); TPeriod = ( pToday, pYesterday, pThismonth, p7days, p14days, p30days, p60days, p90days, pAllTime ); TConfidenceType = ( ctHigh, ctMedium, ctLow, ctUnknown ); TDisplayLocations = ( dlAll, dlRouted, dlUnrouted); TActivityType = ( atUnknown, atDeleteDestination, atInsertDestination, atMarkDestinationDeparted, atMarkDestinationVisited, atMemberCreated, atMemberDeleted, atMemberModified, atMoveDestination, atNoteInsert, atRouteDelete, atRouteOptimized, atRouteOwnerChanged, atUpdateDestinations, atUserMessage, atAreaAdded, atAreaUpdated, atAreaRemoved, atDestinationOutSequence, atDriverArrivedEarly, atDriverArrivedLate, atDriverArrivedOnTime, atGeofenceLeft, atGeofenceEntered); TMemberType = ( mtPrimaryAccount, mtSubAccountAdmin, mtSubAccountRegionalManager, mtSubAccountDispatcher, mtSubAccountPlanner, mtSubAccountDriver, mtSubAccountAnalyst, mtSubAccountVendor, mtSubAccountCustomerService, mtUnknown ); TCompassDirection = ( cdNorth, cdSouth, cdWest, cdEast, cdNorthWest, cdNorthEast, cdSouthWest, cdSouthEast, cdUndefined ); TDirectionEnum = ( dHead, dGoStraight, dTurnLeft, dTurnRight, dTurnSlightLeft, dTurnSlightRight, dTurnSharpLeft, dTurnSharpRight, dRoundaboutLeft, dRoundaboutRight, dUturnLeft, dUturnRight, dRampLeft, dRampRight, dForkLeft, dForkRight, dKeepLeft, dKeepRight, dFerry, dFerryTrain, dMerge, dReachedYourDestination, dUnknown ); TRoutePathOutput = ( rpoPoints, rpoNone, rpoUndefined); TAddressStopType = ( astPickup, astDelivery, astBreak, astMeetup, astUnknown ); TFormatEnum = ( Csv, Serialized, Xml, UndefinedFormat ); TOptimizationParametersFormat = ( opJson, opXml, opSerialized, opFriendly, opCsv, opUndefined ); /// <summary> /// Territory type (circle, rectangle, polygon) /// </summary> TTerritoryType = ( ttCircle, ttPoly, ttRect, ttUndefined ); TStatusUpdateType = ( Pickup, DropOff, NoAnswer, NotFound, NotPaid, Paid, WrongDelivery, WrongAddressRecipient, NotPresent, PartsMissing, ServiceRendered, FollowUp, LeftInformation, SpokeWithDecisionMaker, SpokeWithDecisionInfluencer, CompetitiveAccount, ScheduledFollowUpMeeting, ScheduledLunch, ScheduledProductDemo, ScheduledClinicalDemo, NoOpportunity, Unclassified ); //an optimization problem can be at one state at any given time //every state change invokes a socket notification to the associated member id //every state change invokes a callback webhook event invocation if it was provided during the initial optimization TOptimizationState = ( Initial = 1, MatrixProcessing = 2, Optimizing = 3, Optimized = 4, Error = 5, ComputingDirections = 6 ); HttpMethodType = ( Get, Put, Post, Delete ); TAlgorithmType = ( TSP = 1, //single depot, single driver route VRP = 2, //single depot, multiple driver, no constraints, no time windows, no capacities CVRP_TW_SD = 3, //single depot, multiple driver, capacitated, time windows CVRP_TW_MD = 4, //multiple depot, multiple driver, capacitated, time windows TSP_TW = 5, //single depot, single driver, time windows TSP_TW_CR = 6, //single depot, single driver, time windows, continuous optimization (minimal location shifting) BBCVRP = 7, //shifts addresses from one route to another over time on a recurring schedule NoneAlgorithmType = 8 ); TMetric = ( Euclidean = 1, //measures point to point distance as a straight line Manhattan = 2, //measures point to point distance as taxicab geometry line Geodesic = 3, //measures point to point distance approximating curvature of the earth Matrix = 4, //measures point to point distance by traversing the actual road network Exact_2D = 5, //measures point to point distance using 2d rectilinear distance UndefinedMetric = 6 ); TDeviceType = (Web, IPhone, IPad, AndroidPhone, AndroidTablet, UnknownDevice); TDistanceUnit = (MI, KM, Undefinded); TOptimize = (Distance, Time, TimeWithTraffic, NoneOptimize); TTravelMode = (Driving, Walking, Trucking, UnknownMode); TAvoid = (Highways, Tolls, MinimizeHighways, MinimizeTolls, Empty); TUploadType = (DriverImg, VehicleImg, AddressImg, CsvFile, XlsFile, AnyFile, UnknownUploadType); TVendorSizeType = (vsGlobal, vsRegional, vsLocal); var TDeviceTypeDescription: array[TDeviceType] of String = ('web', 'iphone', 'ipad', 'android_phone', 'android_tablet', 'UnknownDevice'); TDistanceUnitDescription: array[TDistanceUnit] of String = ('mi', 'km', 'undefinded'); TOptimizeDescription: array[TOptimize] of String = ('Distance', 'Time', 'timeWithTraffic', 'None'); TTravelModeDescription: array[TTravelMode] of String = ('Driving', 'Walking', 'Trucking', 'UnknownMode'); TOptimizationDescription: array[TOptimizationState] of String = ('Initial', 'MatrixProcessing', 'Optimizing', 'Optimized', 'Error', 'ComputingDirections'); TUploadTypeDescription: array[TUploadType] of String = ('DRIVER_IMG', 'VEHICLE_IMG', 'ADDRESS_IMG', 'CSV_FILE', 'XLS_FILE', 'ANY_FILE', 'UnknownUploadType'); TStatusUpdateTypeDescription: array[TStatusUpdateType] of String = ('pickup', 'dropoff', 'noanswer', 'notfound', 'notpaid', 'paid', 'wrongdelivery', 'wrongaddressrecipient', 'notpresent', 'parts_missing', 'service_rendered', 'follow_up', 'left_information', 'spoke_with_decision_maker', 'spoke_with_decision_influencer', 'competitive_account', 'scheduled_follow_up_meeting', 'scheduled_lunch', 'scheduled_product_demo', 'scheduled_clinical_demo', 'no_opportunity', 'unclassified'); TTerritoryTypeDescription: array[TTerritoryType] of String = ('circle', 'poly', 'rect', 'Undefined'); TFormatDescription: array[TFormatEnum] of String = ('csv', 'serialized', 'xml', 'UndefinedFormat'); TAddressStopTypeDescription: array[TAddressStopType] of String = ('PICKUP', 'DELIVERY', 'BREAK', 'MEETUP', 'Unknown'); TCompassDirectionDescription: array[TCompassDirection] of String = ('N', 'S', 'W', 'E', 'NW', 'NE', 'SW', 'SE', 'Undefined'); TOptimizationParametersFormatDescription: array[TOptimizationParametersFormat] of String = ('json', 'xml', 'serialized', 'friendly', 'csv', 'undefined'); TAvoidDescription: array[TAvoid] of String = ('Highways', 'Tolls', 'minimizeHighways', 'minimizeTolls', ''); TRoutePathOutputDescription: array[TRoutePathOutput] of String = ('Points', 'None', 'Undefined'); TDirectionDescription: array[TDirectionEnum] of String = ( 'Head', 'Go Straight', 'Turn Left', 'Turn Right', 'Turn Slight Left', 'Turn Slight Right', 'Turn Sharp Left', 'Turn Sharp Right', 'Roundabout Left', 'Roundabout Right', 'Uturn Left', 'Uturn Right', 'Ramp Left', 'Ramp Right', 'Fork Left', 'Fork Right', 'Keep Left', 'Keep Right', 'Ferry', 'Ferry Train', 'Merge', 'Reached Your Destination', 'Unknown'); TManeuverTypeDescription: array[TDirectionEnum] of String = ( 'HEAD', 'GO_STRAIGHT', 'TURN_LEFT', 'TURN_RIGHT', 'TURN_SLIGHT_LEFT', 'TURN_SLIGHT_RIGHT', 'TURN_SHARP_LEFT', 'TURN_SHARP_RIGHT', 'ROUNDABOUT_LEFT', 'ROUNDABOUT_RIGHT', 'UTURN_LEFT', 'UTURN_RIGHT', 'RAMP_LEFT', 'RAMP_RIGHT', 'FORK_LEFT', 'FORK_RIGHT', 'KEEP_LEFT', 'KEEP_RIGHT', 'FERRY', 'FERRY_TRAIN', 'MERGE', 'REACHED_YOUR_DESTINATION', 'Unknown'); TMemberTypeDescription: array[TMemberType] of String = ( 'PRIMARY_ACCOUNT', 'SUB_ACCOUNT_ADMIN', 'SUB_ACCOUNT_REGIONAL_MANAGER', 'SUB_ACCOUNT_DISPATCHER', 'SUB_ACCOUNT_PLANNER', 'SUB_ACCOUNT_DRIVER', 'SUB_ACCOUNT_ANALYST', 'SUB_ACCOUNT_VENDOR', 'SUB_ACCOUNT_CUSTOMER_SERVICE', 'Unknown'); TActivityTypeDescription: array[TActivityType] of String = ( '','delete-destination', 'insert-destination', 'mark-destination-departed', 'mark-destination-visited', 'member-created', 'member-deleted', 'member-modified', 'move-destination', 'note-insert', 'route-delete', 'route-optimized', 'route-owner-changed', 'update-destinations', 'user_message', 'area-added', 'area-updated', 'area-removed', 'destination-out-sequence', 'driver-arrived-early', 'driver-arrived-late', 'driver-arrived-on-time', 'geofence-left', 'geofence-entered'); TDisplayLocationsDescription: array[TDisplayLocations] of String = ( 'all', 'routed', 'unrouted'); TConfidenceTypeDescription: array[TConfidenceType] of String = ( 'high', 'medium', 'low', 'unknown'); TPeriodDescription: array[TPeriod] of String = ('today', 'yesterday', 'thismonth', '7days', '14days', '30days', '60days', '90days', 'all_time'); TTrackingInfoDescription: array[TTrackingInfo] of String = ( 'Order Received', 'Order Assigned to Route', 'Packing', 'Loaded to Vehicle', 'Out for Delivery', 'Unknown'); TVendorSizeTypeDescription: array[TVendorSizeType] of String = ( 'global', 'regional', 'local'); type NullableVendorSizeType = record strict private FValue: TVendorSizeType; FIsNull: boolean; function GetValue: TVendorSizeType; public constructor Create(PValue: TVendorSizeType); class operator Implicit(A: NullableVendorSizeType): TVendorSizeType; class operator Implicit(PValue: TVendorSizeType): NullableVendorSizeType; class operator Equal(A, B: NullableVendorSizeType): boolean; class operator NotEqual(A, B: NullableVendorSizeType): boolean; class function Null: NullableVendorSizeType; static; property Value: TVendorSizeType read GetValue; property IsNull: boolean read FIsNull; function IsNotNull: boolean; end; implementation { NullableVendorSizeType } constructor NullableVendorSizeType.Create(PValue: TVendorSizeType); begin FValue := PValue; FIsNull := False; end; class operator NullableVendorSizeType.Equal(A, B: NullableVendorSizeType): boolean; begin if (A.IsNull <> B.IsNull) then Result := False else if (A.IsNull = B.IsNull) and (A.IsNull) then Result := True else if (A.IsNull = B.IsNull) and (not A.IsNull) then Result := A.Value = B.Value else raise Exception.Create('Непредвиденный вариант сравнения'); end; function NullableVendorSizeType.GetValue: TVendorSizeType; begin if (FIsNull) then raise Exception.Create('Невозможно получить значение - оно равно Null') else Result := FValue; end; class operator NullableVendorSizeType.Implicit( A: NullableVendorSizeType): TVendorSizeType; begin Result := A.Value; end; class operator NullableVendorSizeType.Implicit( PValue: TVendorSizeType): NullableVendorSizeType; begin Result := NullableVendorSizeType.Create(PValue); end; function NullableVendorSizeType.IsNotNull: boolean; begin Result := not IsNull; end; class operator NullableVendorSizeType.NotEqual(A, B: NullableVendorSizeType): boolean; begin Result := not (A = B); end; class function NullableVendorSizeType.Null: NullableVendorSizeType; begin Result.FIsNull := True; end; end.
unit l3Types; {* Базовые типы библиотеки L3. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3Types - } { Начат: 14.04.1998 11:40 } { $Id: l3Types.pas,v 1.142 2016/04/06 20:24:12 lulin Exp $ } // $Log: l3Types.pas,v $ // Revision 1.142 2016/04/06 20:24:12 lulin // - обрабатываем ошибки открытия файла с логом. // // Revision 1.141 2016/03/14 11:35:30 lulin // - перегенерация. // // Revision 1.140 2015/10/29 14:32:46 lulin // - обновляем. // // Revision 1.139 2015/06/03 12:43:16 lulin // - пытаемся разрулить зависимости. // // Revision 1.138 2015/06/02 15:03:56 voba // - переделка итератора по записям. Теперь пустые в подитеративную процедуру не передаются, стопзапись ставится внутри итератора // // Revision 1.137 2014/11/10 14:19:47 lukyanets // Механизм обработки сообщений // // Revision 1.136 2014/10/14 12:35:17 lukyanets // Пишем/читаем все базовые параметры // // Revision 1.135 2014/07/16 15:56:57 lulin // - чистим код и упрощаем наследование. // // Revision 1.134 2014/02/19 15:05:08 lulin // - добавляем эталоны. // // Revision 1.133 2013/04/04 11:33:02 lulin // - портируем. // // Revision 1.132 2013/03/28 17:25:05 lulin // - портируем. // // Revision 1.131 2010/09/21 11:06:56 fireton // - переводим деревья с PAnsiChar на Tl3WString // // Revision 1.130 2009/10/14 08:58:17 voba // - избавляемся от библиотеки mg // -add l3_fmFullShareReadWrite, l3_fmFullShareCreateReadWrite - открытие с расшаренным чтением и записью // // Revision 1.129 2009/07/20 16:44:09 lulin // - убираем из некоторых листьевых параграфов хранение типа конкретного тега, вместо этого "плодим" под каждый тип тега свой тип класса. // // Revision 1.128 2009/07/17 12:42:04 lulin // {RequestLink:141264340}. №7, 32, 33. // // Revision 1.127 2008/10/31 09:51:55 voba // - add type // // Revision 1.126 2008/10/27 08:17:45 voba // - move type TListIndex to l3Types // // Revision 1.125 2008/09/09 15:40:14 lulin // - удалены ненужные свойства. // // Revision 1.124 2008/05/14 11:20:20 narry // - уровень логгирования сообщений // // Revision 1.123 2008/03/28 13:53:45 lulin // - рисуем модель в рамках <K>: 88081637. // // Revision 1.122 2008/03/04 08:28:05 lulin // - <K>: 85721148. // // Revision 1.121 2008/02/28 15:12:11 lulin // - переносим nevTools на модель. // // Revision 1.120 2008/02/21 18:13:28 lulin // - избавляемся от ненужных типов. // // Revision 1.119 2008/02/20 19:01:29 lulin // - удалён ненужный тип. // // Revision 1.118 2008/02/20 18:25:25 lulin // - удалён ненужный тип. // // Revision 1.117 2008/02/20 14:06:42 lulin // - удалены избыточные операции сравнения. // // Revision 1.116 2008/02/19 14:58:59 lulin // - переводим сортировку списков на новые, менее виртуальные, рельсы. // // Revision 1.115 2008/02/13 13:05:29 lulin // - cleanup. // // Revision 1.114 2008/02/12 16:35:59 lulin // - итераторы переехали на примесь. // // Revision 1.113 2008/02/08 19:52:45 lulin // - продолжаем санацию списков. // // Revision 1.112 2007/12/21 15:21:57 lulin // - cleanup. // // Revision 1.111 2007/12/20 15:11:56 lulin // - перегенерация. // // Revision 1.110 2007/12/18 14:04:42 lulin // - избавился от неправильной зависимости. // // Revision 1.109 2007/09/20 17:16:43 lulin // - для сегмента с параграфом возвращаем специальный атомарный шрифт. // // Revision 1.108 2007/09/04 12:54:55 lulin // - при поиске минимизируем вычисление головы списка. // // Revision 1.107 2007/08/30 14:52:26 lulin // - получаем дубликаты только один раз. // // Revision 1.106 2007/08/30 14:00:49 lulin // - при поиске реже вычисляем размер элемента. // // Revision 1.105 2007/08/29 19:09:09 lulin // - упрощаем поиск в списках. // // Revision 1.104 2007/08/29 16:03:03 lulin // - cleanup. // // Revision 1.103 2007/08/09 11:19:29 lulin // - cleanup. // // Revision 1.102 2007/08/02 10:37:10 lulin // - добавлены структуры для оптимизации хранения строк. // // Revision 1.101 2007/07/24 18:14:49 lulin // - собрался первый проект со сгенерированным модулем l3Interfaces. // // Revision 1.100 2007/05/24 09:24:23 lulin // - по-другому идентифицируем комплексную сортировку. // // Revision 1.99 2007/05/24 07:30:52 lulin // - добавлена константа, обозначающая сортировку по нескольким атрибутам. // // Revision 1.98 2007/02/19 15:20:02 lulin // - bug fix: не собирался Архивариус. // // Revision 1.97 2007/01/30 15:24:25 lulin // - текст ноды - теперь более простого типа. // // Revision 1.96 2007/01/17 11:20:20 lulin // - cleanup. // // Revision 1.95 2007/01/12 13:48:16 lulin // - cleanup. // // Revision 1.94 2007/01/11 14:06:33 lulin // - интерфейс шрифта переехал в базовый модуль. // // Revision 1.93 2006/12/10 12:48:41 lulin // - оптимизируем распределение памяти для маленьких кусочков. // // Revision 1.92 2006/12/08 13:25:54 lulin // - сделана возможность управлять полной очисткой данных объекта при укладывании их в кеш. // // Revision 1.91 2006/11/27 10:23:16 lulin // - cleanup. // // Revision 1.90 2006/11/27 08:43:26 lulin // - cleanup. // // Revision 1.89 2006/11/25 14:31:53 lulin // - корректнее записываем текст, который в кодировке, отличной от кодировки записываемого файла. // // Revision 1.88 2006/11/17 15:38:24 voba // - add to Tl3CompareData поле DataSize для _l3_ctRawData для поиска по началу записи // // Revision 1.87 2006/05/02 11:16:27 lulin // - вытерта лишняя процедура сортировки. // // Revision 1.86 2006/05/02 08:45:51 lulin // - вычищен ненужный тип. // // Revision 1.85 2006/04/26 12:16:23 voba // - bug fix: архивирующие потоки не работали над файловыми потоками, отличными от m3. // // Revision 1.84 2006/04/26 09:03:15 voba // - введен режим открытия "по-Опоссуму" - l3_fmCreateReadWrite. // // Revision 1.83 2006/04/25 09:19:02 voba // - add type TSmallIntArray // // Revision 1.82 2006/04/24 12:58:47 lulin // - выпиливаем из списков общую функциональность. // // Revision 1.81 2006/04/12 13:13:39 oman // - change: перевод механизма локализации строк на использование фабрик // - new beh: Локализация nsc // // Revision 1.80 2006/03/06 12:02:29 oman // - new behavior: контроль провисания ресурсов при добавлении объектов в кэш // // Revision 1.79 2005/11/24 17:14:47 demon // - fix: после переноса функциональности на l3Control отъехала // реализация возможности вызова Changing/Changed из DoChanged циклически // // Revision 1.78 2005/11/09 15:28:41 lulin // - базовые интерфейсы перенесены в правильный модуль. // // Revision 1.77 2005/09/14 07:02:28 lulin // - bug fix: исправлена очередная пачка ошибок с редактированием параграфа в Unicode. // // Revision 1.76 2005/08/23 07:17:42 mmorozov // new: Tl3Bool (переехавший Tk2Bool); // // Revision 1.75 2005/06/29 10:30:24 lulin // - введен собственный тип для множества скроллбар'ов - чтобы не такскать везде это виндовое уродство. // // Revision 1.74 2005/05/27 12:06:04 lulin // - убраны лишние зависимости. // // Revision 1.73 2005/05/26 13:19:36 lulin // - new unit: _l3ScreenIC. // // Revision 1.72 2005/03/30 15:56:33 lulin // - TevLocation теперь наследуется от Tk2Tool - базового класса для инструментов тегов. // // Revision 1.71 2005/03/21 10:05:08 lulin // - new interface: _Ik2Type. // // Revision 1.70 2005/02/22 12:27:44 lulin // - рефакторинг работы с Tl3Point и Tl3Rect. // // Revision 1.69 2005/01/20 07:12:54 mmorozov // change: WordOrderNames; // // Revision 1.68 2005/01/19 14:40:05 lulin // - new type: Tl3StringArray. // // Revision 1.67 2004/12/16 08:15:14 mmorozov // new: константы и типы для параметров контекстной фильтрации; // // Revision 1.66 2004/11/19 16:33:17 lulin // - bug fix: съедались двухбуквенные ShortCut'ы. // // Revision 1.65 2004/09/11 14:15:54 lulin // - класс _Tl3InterfacedComponent сделан кешируемым. // // Revision 1.64 2004/09/02 12:30:35 law // - cleanup. // // Revision 1.63 2004/09/02 11:57:04 law // - cleanup. // // Revision 1.62 2004/08/27 10:56:20 law // - new const: l3_fmExclusiveReadWrite. // // Revision 1.61 2004/07/22 14:49:50 law // - new type: _Tl3OperationCode. // // Revision 1.60 2004/06/18 10:15:46 law // - класс _TevTextPara стал крайне аскетичным. // // Revision 1.59 2004/06/08 09:07:04 law // - на Tl3PCharLen добавлены операции эквивалентности. // // Revision 1.58 2004/05/19 14:13:17 voba // -add notify after delete node // // Revision 1.57 2004/05/14 13:29:38 law // - new method: Tl3KeyWords.AddKeyWords. // // Revision 1.56 2004/04/29 14:57:04 law // - bug fix: теперь табуляции корректно обрабатываются и в Unicode строке. // // Revision 1.55 2004/04/26 14:28:24 law // - new behavior: Tl3Filer теперь при чтении посимвольно учитывает кодировку. // - bug fix: в свойство TevMemo.Buffer теперь нормально присваиваются строки с кодировкой Unicode. // // Revision 1.54 2004/04/20 14:53:43 law // - new method: Tl3PCharLen.InitPart. // - remove proc: ev_plAssign. // // Revision 1.53 2004/04/19 16:08:23 law // - new type: _Tl3PCharLenConst. // // Revision 1.52 2004/04/19 14:52:22 law // - new proc: Tl3PCharLen.Shift. // // Revision 1.51 2004/03/05 13:09:48 law // - cleanup. // // Revision 1.50 2003/05/30 12:25:58 law // - change: константы nt* переехали в модуль l3Types. // // Revision 1.49 2003/04/09 13:26:56 law // - new proc version: _l3BFind. // // Revision 1.48 2003/03/13 16:37:21 law // - change: попытка портировать на Builder. // // Revision 1.47 2002/09/24 12:15:59 law // no message // // Revision 1.46 2002/09/02 08:26:52 law // - new tag types: k2_idDictItem, k2_idItemFlag. // - change tag type: k2_idDictRec -> k2_idDictItem для k2_tiClasses, k2_tiTypes, k2_tiKeyWords, k2_tiPrefix. // // Revision 1.45 2002/07/22 13:54:58 law // - rename type: TSetBitType -> Tl3SetBitType. // // Revision 1.44 2002/07/22 13:47:31 law // - new methods: Il3Tree.ChangeExpand, Il3Tree.InsertNode. // // Revision 1.43 2002/07/09 11:12:42 law // - new type: Tl3Inch. // // Revision 1.42 2002/04/19 09:18:28 law // - new const: _l3_ctRawData. // // Revision 1.41 2002/04/03 13:50:39 law // - new const: 3_fmExclusiveWrite, l3_fmExclusiveAppend. // // Revision 1.40 2002/02/21 15:58:15 law // - optimization. // // Revision 1.39 2002/01/17 16:00:00 law // - new type: Tl3MakeLong. // // Revision 1.38 2001/12/27 16:16:52 law // - new const: l3Types.CP_Unicode. // // Revision 1.37 2001/12/27 16:06:34 law // - change: изменен порядок полей Tl3PCharLen. // // Revision 1.36 2001/09/24 11:18:08 law // - bug fix: не обновлялись максимальные размеры вертикального скроллера. // // Revision 1.35 2001/09/11 17:46:36 law // - some new features. // // Revision 1.34 2001/09/04 12:43:47 voba // - bug fix: неописанные типы под Delphi 5. // // Revision 1.33 2001/09/03 08:56:03 law // - bug fix. // // Revision 1.32 2001/09/03 08:42:15 law // - bug fix. // // Revision 1.31 2001/08/31 12:19:58 law // - cleanup: первые шаги к кроссплатформенности. // // Revision 1.30 2001/08/31 08:50:08 law // - cleanup: первые шаги к кроссплатформенности. // // Revision 1.29 2001/08/30 09:58:07 law // - rename type: TDirection -> Tl3Direction. // // Revision 1.28 2001/07/27 15:46:05 law // - comments: xHelpGen. // // Revision 1.27 2001/07/26 15:55:03 law // - comments: xHelpGen. // // Revision 1.26 2001/07/24 12:30:24 law // - comments: xHelpGen. // // Revision 1.25 2001/06/26 13:33:53 law // - comments & cleanup. // // Revision 1.24 2001/04/18 13:25:24 law // - comments: добавлены комментарии для xHelpGen. // // Revision 1.23 2001/04/05 08:55:58 law // - new type: Tl3ClipboardFormats - массив форматов буфера обмена. // // Revision 1.22 2001/03/13 18:44:35 law // - some cleaning, tuning & comments. // // Revision 1.21 2000/12/19 15:52:41 law // - убраны ненужные директивы компиляции. // // Revision 1.20 2000/12/15 15:19:02 law // - вставлены директивы Log. // {$Include l3Define.inc } {$WriteableConst Off } interface uses {$IfDef Delphi6} Types, {$IFDEF LINUX} {$Else LINUX} Windows, ActiveX, {$EndIF LINUX} {$Else Delphi6} Windows, ActiveX, {$EndIf Delphi6} Classes, SysUtils, l3Interfaces ; //////////////////////////////////////////////////////////////////////////////// /// Типы и классы используемые для указания способа работы фильтра ///////////// //////////////////////////////////////////////////////////////////////////////// type Tl3Bool = (l3_bUnknown, l3_bFalse, l3_bTrue); {* Тип для кеширования булевского значения. } type Tl3WordPosition = l3Interfaces.Tl3WordPosition; Tl3TreeLevelDist = l3Interfaces.Tl3TreeLevelDist; Tl3WordOrder = l3Interfaces.Tl3WordOrder; //////////////////////////////////////////////////////////////////////////////// const SB_Vert = Windows.SB_Vert; SB_Horz = Windows.SB_Horz; SB_Both = Windows.SB_Both; type PObject = ^TObject; PIUnknown = ^IUnknown; PInteger = l3Interfaces.PInteger; Tl3Rgn = hRgn; {* Регион. } Long = Longint; {* Самый большой доступный процессорный целый тип со знаком. } Large = Int64; PLarge = ^Large; Int = SmallInt; PLong = ^Long; {$IfNDef Delphi6} PLongInt = Windows.PLongInt; PWord = Windows.PWord; {$EndIf Delphi6} Bool = Boolean; {* Паскалевское логическое значение. } CardinalBool = LongBool; WParam = Windows.WParam; {* Тип для параметра WParam. } LParam = Windows.LParam; {* Тип для параметра LParam. } PBool = ^Bool; PPointer = ^Pointer; PPChar = ^PAnsiChar; Tl3IStatus = HResult; {* Статус, возвращаемый методами интерфейсов. } sInt8 = ShortInt; {* Знаковое 8-битное целое. } uInt8 = Byte; {* Беззнаковое 8-битное целое. } sInt16 = SmallInt; {* Знаковое 16-битное целое. } uInt16 = Word; {* Беззнаковое 16-битное целое. } sInt32 = Long; {* Знаковое 32-битное целое. } uInt32 = Cardinal; {* Беззнаковое 32-битное целое. } Tl3OperationCode = l3Interfaces.Tl3OperationCode; String255 = String[255]; {* Короткая строка. } Tl3Operation = (l3_opDelete, l3_opInsert); {* Операция: |<br> |<ul> | <li><b>l3_opDelete</b> - удаление.</li> | <li><b>l3_opInsert</b> - вставка.</li> |</ul> } Tl3ItemFlag = (l3_ifNone, l3_ifNew, l3_ifDeleted, l3_ifModified); {* Флаг элемента. } TByteSet = set of Byte; {* Множество байт. } TCharSet = l3Interfaces.TCharSet; {* Множество символов. } TCardinalSizeSet = set of 0..SizeOf(Cardinal) * 8 - 1; TLongSizeSet = set of 0..SizeOf(Long) * 8 - 1; Tl3MakeWord = packed record {* Тип для распаковки Word по байтам. } Lo: sInt8; Hi: sInt8; end;{Tl3MakeWord} Tl3MakeLong = packed record {* Тип для распаковки Long по Word. } Lo: uInt16; Hi: uInt16; end;{Tl3MakeWord} Tl3IteratorAction = function(Data: Pointer {на самом деле P<ItemType> для шаблонов}; Index: Long): Bool; register; {* Подитеративная функция. } Tl3FreeAction = function(Data: Pointer): Bool; register; {* Функция для итераторов и нотификаций об освобождении объекта. } Tl3BeforeAddToCacheEvent = procedure of object; {-} Tl3GetClassCacheEntryEvent = function: Pointer of object; {-} Tl3SetClassCacheEntryEvent = procedure(aValue: Pointer) of object; {-} Tl3BoolOp = (l3_boAnd, l3_boOr, l3_boAndNot); {* - операции над множествами} const ntNone = 0; {* - пустая операция. } ntInsert = 1; {* - вставка элемента. } ntDelete = 3; {* - удаление элемента. Вызывается до уничтожения ссылки} ntDeleteDone = 4; {* - удаление элемента. Вызывается после уничтожения ссылки} ntDataChange = 5; {* - изменились элемента. } ntMoveBegin = 6; {* - началось движение элемента. } ntMoveEnd = 7; {* - закончилось движение элемента. } ntClear = 8; {* - очистили структуру данных. } ntClearItem = 9; {* - очистили элемент. } ntChildClear = 10; {* - очистили дочерний элемент. } ntChildInsert = 11; {* - вставлен дочерний элемент. } ntFree = 12; {* - освобождение элемента. } ntCountChange = 13; {* - изменилось количество элементов. } ntChangeItemData = 14; {* - изменились данные элемента. } ntChanging = 15; {* - началось изменение. } ntChanged = 16; {* - закончилось изменение. } ntResortChild = 17; {* - Дочерние элементы изменили взаимное расположение. } type Tl3ClipboardFormat = l3Interfaces.Tl3ClipboardFormat; {* Формат данных буфера обмена. } Tl3ClipboardFormats = l3Interfaces.Tl3ClipboardFormats; {* Набор форматов данных буфера обмена. } Tl3FileMode = (l3_fmRead, l3_fmWrite, l3_fmReadWrite, l3_fmAppend, l3_fmExclusiveReadWrite, l3_fmExclusiveWrite, l3_fmExclusiveAppend, l3_fmCreateReadWrite, l3_fmFullShareReadWrite, l3_fmFullShareCreateReadWrite, l3_fmFullShareRead); {* Режим работы с файлами: |<br> |<ul> | <li><b>l3_fmRead</b> - чтение.</li> | <li><b>l3_fmWrite</b> - запись.</li> | <li><b>l3_fmReadWrite</b> - чтение-запись.</li> | <li><b>l3_fmAppend</b> - добавление в конец.</li> |</ul> } {l3_fmFullShareReadWrite, l3_fmFullShareCreateReadWrite - открытие с расшаренным чтением и записью} const l3_fmWriteMode = [l3_fmWrite, l3_fmReadWrite, l3_fmAppend, l3_fmExclusiveWrite, l3_fmExclusiveAppend, l3_fmCreateReadWrite]; type Tl3ProgressProc = procedure(aState : Byte; aValue : Long; const aMsg : AnsiString = '') of object; {* Процедура индикации. aState - см. piStart. } { If Astate = piStart then AValue=Total Num of item (-1 if not defined), aPercen = 0 If Astate <> piStart and AMsg = '' then No Change Messages; } Tl3Method = packed record {* Тип для распаковки состовляющих указателя на метод. } Code, Data : Pointer; end;{Tl3Method} const CP_ANSI = l3Interfaces.CP_ANSI; {* - константа представляющая кодировку ANSI. } CP_Unicode = l3Interfaces.CP_Unicode; {* - константа представляющая кодировку Unicode. } type Tl3Char = record Case rCodePage : Integer of CP_Unicode : (rWC : WideChar); CP_ANSI : (rAC : AnsiChar); end;//Tl3Char Tl3PCharLenBase = object(Tl3PCharLenPrim) public // public methods function IsLast(aChar: AnsiChar): Boolean; {-} function EQ(const aSt: Tl3PCharLenPrim): Boolean; {-} function Diff(const aSt: Tl3PCharLenPrim): Integer; {-} end;//Tl3PCharLenBase Tl3PCharLen = object(Tl3PCharLenBase) public // public methods procedure Init(aSt: PAnsiChar = nil; aLen: Long = -1; aCodePage: Long = CP_ANSI); {-} procedure InitPart(aSt : PAnsiChar; aStart : Long; aFinish : Long; aCodePage : Long); {-} procedure Shift(aLen: Integer); {-} procedure MoveS(aLen: Integer = 1); {-} end;//Tl3PCharLen Pl3PCharLen = ^Tl3PCharLen; Tl3PCharLenConst = object(Tl3PCharLenBase) end;//Tl3PCharLenConst Tl3PCharRec = packed record rS : PAnsiChar; rAllocated : Boolean; end; Tl3FontIndex = l3Interfaces.Tl3FontIndex; {* Индекс шрифта. } Tl3FontIndexes = l3Interfaces.Tl3FontIndexes; {* Множество индексов шрифта. } Tl3BMTable = array[0..255] of Byte; {* Table used by the Boyer-Moore search routines. } TSmallIntArray = array of SmallInt; {* Динамический массив коротких целых чисел. } TLongArray = array of Long; {* Динамический массив целых чисел. } TStringArray = Tl3StringArray; {* Динамический массив строк. } Tl3Handle = Long; {* Тип целочисленных идентификаторов. Знаковый. Размер не фиксирован. } Tl3Direction = l3Interfaces.Tl3Direction; {* - направление движения. } TListIndex = Integer; {* - индекс элемента списка. } const l3_opExclude = l3_opDelete; {* Исключение. } l3_opInclude = l3_opInsert; {* Включение. } type Tl3MemoryFlag = l3Interfaces.Tl3MemoryFlag; {* Флаг распределения памяти. } Tl3PtrRec = l3Interfaces.Tl3PtrRec; Tl3OperationFlag = (ofInsert, ofDelete, ofModify, ofCanUndo, ofCanRedo); {* Флаг операции. } Tl3OperationFlags = set of Tl3OperationFlag; {* Флаги операции. } Tl3Duplicates = (l3_dupIgnore, l3_dupAccept, l3_dupError, l3_dupAssign, l3_dupChange); {* Операция применимая к совпадающим элементам списка: |<br> |<ul> | <li><b>l3_dupIgnore</b> - игнорировать новый элемент.</li> | <li><b>l3_dupAccept</b> - принять новый элемент.</li> | <li><b>l3_dupError</b> - выдать сообщение об ошибке.</li> | <li><b>l3_dupAssign</b> - присвоить новый элемент старому.</li> | <li><b>l3_dupChange</b> - заменить старый элемент новым.</li> |</ul> } Tl3SortIndex = type SmallInt; {* Индекс сортировки (см. l3_siByID и др). } const l3_siByID = Tl3SortIndex(-7); {* Признак сортировки объектов по "идентификатору". } l3_siUnsorted = Tl3SortIndex(-6); {* Признак отсутствия сортировки. } l3_siCaseUnsensitive = Tl3SortIndex(-5); {* Признак сортировки без учета регистра. } l3_siNative = Tl3SortIndex(-4); {* Признак "родной" сортировки объектов. } type Tl3KW = record rName : String; rID : Integer; end;//Tl3KW Tl3PtrCompareProc = function(A, B: Pointer): Long; {* Прототип сравнения данных по указателям. } Tl3OnCompareItems = function (I, J : Longint) : Longint of object; {-} Tl3CompareAction = l3Interfaces.Tl3CompareAction; {-} Tl3Index = l3Interfaces.Tl3Index; {* Индекс элементов. } {$IfDef Delphi6} {$IFDEF LINUX} IStream = Types.IStream; TStatStg = Types.TStatStg; {$Else LINUX} IStream = ActiveX.IStream; IStorage = ActiveX.IStorage; TStatStg = ActiveX.TStatStg; {$EndIF LINUX} {$Else Delphi6} IStream = ActiveX.IStream; TStatStg = ActiveX.TStatStg; {$EndIf Delphi6} Tl3SetBitType = l3Interfaces.Tl3SetBitType; Tl3PathStr = AnsiString; const l3MinIndex = l3Interfaces.l3MinIndex; {* - минимальный индекс элемента. } l3MaxIndex = l3Interfaces.l3MaxIndex; {* - максимальный индекс элемента. } l3GlyphFontName = '__Glyph__'; {$IfDef Delphi6} RT_RCData = Types.RT_RCDATA; {$IFDEF LINUX} STG_E_INVALIDPOINTER = Types.STG_E_INVALIDPOINTER; STG_E_REVERTED = Types.STG_E_REVERTED; STG_E_INVALIDFUNCTION = Types.STG_E_INVALIDFUNCTION; STG_E_CANTSAVE = Types.STG_E_CANTSAVE; STREAM_SEEK_SET = Types.STREAM_SEEK_SET; STREAM_SEEK_END = Types.STREAM_SEEK_END; STGTY_STREAM = Types.STGTY_STREAM; LOCK_WRITE = Types.LOCK_WRITE; STREAM_SEEK_CUR = Types.STREAM_SEEK_CUR; {$Else LINUX} STG_E_INVALIDPOINTER = Windows.STG_E_INVALIDPOINTER; STG_E_REVERTED = Windows.STG_E_REVERTED; STG_E_INVALIDFUNCTION = Windows.STG_E_INVALIDFUNCTION; STG_E_CANTSAVE = Windows.STG_E_CANTSAVE; STREAM_SEEK_SET = ActiveX.STREAM_SEEK_SET; STREAM_SEEK_END = ActiveX.STREAM_SEEK_END; STGTY_STREAM = ActiveX.STGTY_STREAM; LOCK_WRITE = ActiveX.LOCK_WRITE; STREAM_SEEK_CUR = ActiveX.STREAM_SEEK_CUR; {$EndIF LINUX} {$Else Delphi6} STG_E_INVALIDPOINTER = Windows.STG_E_INVALIDPOINTER; STG_E_REVERTED = Windows.STG_E_REVERTED; STG_E_INVALIDFUNCTION = Windows.STG_E_INVALIDFUNCTION; STG_E_CANTSAVE = Windows.STG_E_CANTSAVE; RT_RCData = Windows.RT_RCDATA; STREAM_SEEK_SET = ActiveX.STREAM_SEEK_SET; STREAM_SEEK_END = ActiveX.STREAM_SEEK_END; STGTY_STREAM = ActiveX.STGTY_STREAM; LOCK_WRITE = ActiveX.LOCK_WRITE; STREAM_SEEK_CUR = ActiveX.STREAM_SEEK_CUR; {$EndIf Delphi6} type EDoChangedAlreadyDone = class(Exception) end;//EDoChangedAlreadyDone const l3_msgAll = 0; l3_msgLevel1 = 1; l3_msgLevel2 = 2; l3_msgLevel3 = 3; l3_msgLevel10 = 10; implementation uses l3String ; // start object Tl3PCharLen procedure Tl3PCharLen.Init(aSt: PAnsiChar = nil; aLen: Long = -1; aCodePage: Long = CP_ANSI); {-} begin S := aSt; if (aLen < 0) then begin if (aCodePage = CP_Unicode) then SLen := l3StrLen(PWideChar(S)) else SLen := l3StrLen(S); end//aLen < 0 else SLen := aLen; SCodePage := aCodePage; end; procedure Tl3PCharLen.InitPart(aSt : PAnsiChar; aStart : Long; aFinish : Long; aCodePage : Long); {-} begin if (aCodePage = CP_Unicode) then S := aSt + aStart * SizeOf(WideChar) else S := aSt + aStart * SizeOf(ANSIChar); if (aFinish > aStart) then SLen := aFinish - aStart else SLen := 0; SCodePage := aCodePage; end; procedure Tl3PCharLen.Shift(aLen: Integer); {-} begin Dec(SLen, aLen); if (SLen < 0) then SLen := 0; {-учитываем конечные пробелы} MoveS(aLen); end; procedure Tl3PCharLen.MoveS(aLen: Integer = 1); {-} begin if (SCodePage = CP_Unicode) then Inc(S, aLen * SizeOf(WideChar)) else Inc(S, aLen * SizeOf(ANSIChar)); end; // start object Tl3PCharLenBase function Tl3PCharLenBase.IsLast(aChar: AnsiChar): Boolean; {-} begin if (SLen <= 0) then Result := false else begin if (SCodePage = CP_Unicode) then Result := (PWideChar(S)[Pred(SLen)] = WideChar(aChar)) else Result := (S[Pred(SLen)] = aChar); end;//SLen <= 0 end; function Tl3PCharLenBase.EQ(const aSt: Tl3PCharLenPrim): Boolean; {-} begin Result := (S = aSt.S) AND (SLen = aSt.SLen) AND (SCodePage = aSt.SCodePage); end; function Tl3PCharLenBase.Diff(const aSt: Tl3PCharLenPrim): Integer; {-} begin Assert(SCodePage = aSt.SCodePage); if (SCodePage = CP_Unicode) then Result := (S - aSt.S) div 2 else Result := (S - aSt.S); end; end.
unit CommandSet; interface uses SysUtils, Device.SMART.List, BufferInterpreter, {$IfDef UNITTEST} Mock.OSFile.IoControl; {$Else} OSFile.Handle, OSFile.IoControl, OS.Handle; {$EndIf} type TCommandSet = class abstract(TIoControlFile) public constructor Create(const FileToGetAccess: String); override; function IdentifyDevice: TIdentifyDeviceResult; virtual; abstract; function SMARTReadData: TSMARTValueList; virtual; abstract; function RAWIdentifyDevice: String; virtual; abstract; function RAWSMARTReadData: String; virtual; abstract; function IsDataSetManagementSupported: Boolean; virtual; abstract; function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; virtual; abstract; function IsExternal: Boolean; virtual; abstract; protected const IdentifyDevicePrefix = 'IdentifyDevice'; SMARTPrefix = 'SMART'; function GetMinimumPrivilege: TCreateFileDesiredAccess; override; end; implementation { TCommandSet } constructor TCommandSet.Create(const FileToGetAccess: String); begin inherited; CreateHandle(FileToGetAccess, GetMinimumPrivilege); end; function TCommandSet.GetMinimumPrivilege: TCreateFileDesiredAccess; begin exit(DesiredReadWrite); end; end.
unit GX_SourceExportOptions; {$I GX_CondDefine.inc} interface uses Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, ColorGrd, SynEdit, Dialogs, GX_BaseForm; type TfmSourceExportOptions = class(TfmBaseForm) pnlSettings: TPanel; dlgBackground: TColorDialog; pnlButtons: TPanel; pnlButtonsRight: TPanel; btnOK: TButton; btnCancel: TButton; pnlCode: TPanel; gbxAttributes: TGroupBox; chkBold: TCheckBox; chkItalic: TCheckBox; chkUnderline: TCheckBox; chkStrikeOut: TCheckBox; cbxAttributes: TComboBox; rbxCopySettings: TRadioGroup; btnBackgroundColor: TButton; btnLoadIde: TButton; lblElement: TLabel; procedure AttributeChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cbxAttributesChange(Sender: TObject); procedure btnLoadIdeClick(Sender: TObject); procedure btnBackgroundColorClick(Sender: TObject); private FSampleEditor: TSynEdit; HiddenGrid: TColorGrid; ColorGrid: TColorGrid; NoChangeEvents: Boolean; function GetColorIndexFromColor(Color: TColor; IsBackground: Boolean): Integer; procedure SynEditSelectionChange(Sender: TObject; Changes: TSynStatusChanges); public BackgroundColor: TColor; property SynSampleEditor: TSynEdit read FSampleEditor write FSampleEditor; end; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, SynEditHighlighter, SynUnicode, GX_SynMemoUtils, GX_VerDepConst, GX_GenericUtils, GX_IdeUtils; {$R *.dfm} procedure TfmSourceExportOptions.FormCreate(Sender: TObject); var i: Integer; GXHighlighter: TGXSyntaxHighlighter; begin // Destroyed with form ColorGrid := TColorGrid.Create(Self); HiddenGrid := TColorGrid.Create(Self); HiddenGrid.Visible := False; HiddenGrid.Parent := Self; with ColorGrid do begin Name := 'ColorGrid'; Parent := gbxAttributes; Left := 9; Top := 17; Width := 100; Height := 100; ClickEnablesColor := True; BackgroundIndex := 15; TabOrder := 0; TabStop := True; OnChange := AttributeChange; end; FSampleEditor := TSynEdit.Create(Self); FSampleEditor.Parent := pnlCode; FSampleEditor.ReadOnly := True; FSampleEditor.Align := alClient; FSampleEditor.Gutter.Width := 0; FSampleEditor.Options := FSampleEditor.Options + [eoNoCaret, eoNoSelection, eoHideShowScrollbars, eoAutoSizeMaxScrollWidth] - [eoScrollPastEof, eoScrollPastEol]; FSampleEditor.OnStatusChange := SynEditSelectionChange; GXHighlighter := GetGXHighlighterForCurrentSourceEditor; SetSynEditHighlighter(FSampleEditor, GXHighlighter); FSampleEditor.Lines.Text := FSampleEditor.Highlighter.SampleSource; if Trim(FSampleEditor.Lines.Text) = '' then FSampleEditor.Lines.Text := 'No sample source available'; if GXHighlighter in [gxpHTML, gxpSQL] then btnLoadIde.Enabled := False; BorderStyle := bsSizeable; Constraints.MinHeight := Height; Constraints.MinWidth := Width; btnLoadIdeClick(Sender); for i := 0 to FSampleEditor.Highlighter.AttrCount - 1 do cbxAttributes.Items.Add(FSampleEditor.Highlighter.Attribute[i].Name); cbxAttributes.ItemIndex := 0; cbxAttributesChange(Self); end; procedure TfmSourceExportOptions.AttributeChange(Sender: TObject); var Attr: TSynHighlighterAttributes; AttrStyle: TFontStyles; begin if NoChangeEvents then Exit; Attr := TSynHighlighterAttributes.Create(cbxAttributes.Items[cbxAttributes.ItemIndex], cbxAttributes.Items[cbxAttributes.ItemIndex]); try AttrStyle := []; Attr.Foreground := ColorGrid.ForegroundColor; Attr.Background := ColorGrid.BackgroundColor; if chkBold.Checked then Include(AttrStyle, fsBold); if chkItalic.Checked then Include(AttrStyle, fsItalic); if chkUnderline.Checked then Include(AttrStyle, fsUnderline); if chkStrikeOut.Checked then Include(AttrStyle, fsStrikeOut); Attr.Style := AttrStyle; FSampleEditor.Highlighter.Attribute[cbxAttributes.ItemIndex].Assign(Attr); FSampleEditor.Refresh; finally FreeAndNil(Attr); end; end; procedure TfmSourceExportOptions.cbxAttributesChange(Sender: TObject); var Attr: TSynHighlighterAttributes; begin Attr := TSynHighlighterAttributes.Create('', ''); try Attr.Assign(FSampleEditor.Highlighter.Attribute[cbxAttributes.ItemIndex]); NoChangeEvents := True; try // Buggy! //ColorGrid.ForegroundIndex := ColorGrid.ColorToIndex(Attr.Foreground); //ColorGrid.BackgroundIndex := ColorGrid.ColorToIndex(Attr.Background); ColorGrid.ForegroundIndex := GetColorIndexFromColor(Attr.Foreground, False); ColorGrid.BackgroundIndex := GetColorIndexFromColor(Attr.Background, True); chkBold.Checked := (fsBold in Attr.Style); chkItalic.Checked := (fsItalic in Attr.Style); chkUnderline.Checked := (fsUnderline in Attr.Style); chkStrikeOut.Checked := (fsStrikeOut in Attr.Style); finally NoChangeEvents := False; AttributeChange(nil); end; finally FreeAndNil(Attr); end; end; procedure TfmSourceExportOptions.btnLoadIdeClick(Sender: TObject); resourcestring ErrorLoadingIDESettings = 'Error loading IDE editor registry settings. You may need to customize your editor highlighter settings before they can be loaded from the registry.'; var UserSettings: TStringList; i: Integer; begin UserSettings := TStringList.Create; try FSampleEditor.Highlighter.EnumUserSettings(UserSettings); for i := UserSettings.Count - 1 downto 0 do begin if StrBeginsWith(GetIDEVersionID, UserSettings[i]) then begin if not FSampleEditor.Highlighter.UseUserSettings(i) then MessageDlg(ErrorLoadingIDESettings, mtError, [mbOK], 0); Break; end; end; finally FreeAndNil(UserSettings); end; end; // Temporary hack, since TColorGrid.ColorToIndex seems buggy? function TfmSourceExportOptions.GetColorIndexFromColor(Color: TColor; IsBackground: Boolean): Integer; var i: Integer; begin for i := 0 to 15 do begin HiddenGrid.ForegroundIndex := i; if ColorToRGB(HiddenGrid.ForegroundColor) = ColorToRGB(Color) then begin Result := HiddenGrid.ForegroundIndex; Exit; end; end; // Fallback for unknown colors {$IFOPT D+}SendDebugError('Source Export: Unknown color requested!');{$ENDIF} if IsBackground then Result := 15 // White else Result := 0; // Black end; procedure TfmSourceExportOptions.SynEditSelectionChange(Sender: TObject; Changes: TSynStatusChanges); var Token: UnicodeString; Attributes: TSynHighlighterAttributes; i: Integer; begin FSampleEditor.GetHighlighterAttriAtRowCol(FSampleEditor.CaretXY, Token, Attributes); if Attributes = nil then Exit; for i := 0 to FSampleEditor.Highlighter.AttrCount - 1 do begin if Attributes.Name = FSampleEditor.Highlighter.Attribute[i].Name then begin cbxAttributes.ItemIndex := i; cbxAttributes.OnChange(Self); Break; end; end; end; procedure TfmSourceExportOptions.btnBackgroundColorClick(Sender: TObject); begin dlgBackground.Color := BackgroundColor; if dlgBackground.Execute then BackgroundColor := dlgBackground.Color; end; end.
unit SensorOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Misc, ComCtrls; type TFormSensorOptions = class(TForm) GroupBox1: TGroupBox; GroupBox2: TGroupBox; BtnOk: TButton; BtnCancel: TButton; BtnApply: TButton; StaticText2: TStaticText; edMinGraphHeight: TEdit; StaticText3: TStaticText; GroupBox3: TGroupBox; StaticText1: TStaticText; edMaxNoDataTime: TEdit; StaticText4: TStaticText; edKilometer: TEdit; edAlphaArc: TComboBox; StaticText5: TStaticText; edAlphaSpy: TComboBox; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; cbHigh: TCheckBox; rbtnHighManual: TRadioButton; rbtnHighAuto: TRadioButton; pnlAutoHigh: TPanel; StaticText8: TStaticText; StaticText6: TStaticText; edHighAlpha: TComboBox; StaticText7: TStaticText; edHighScale: TComboBox; edHighMin: TEdit; edHighMax: TEdit; edHigh: TEdit; cbUseAlpha: TCheckBox; cbLow: TCheckBox; rbtnLowManual: TRadioButton; edLow: TEdit; rbtnLowAuto: TRadioButton; pnlAutoLow: TPanel; StaticText9: TStaticText; StaticText10: TStaticText; edLowAlpha: TComboBox; StaticText11: TStaticText; edLowScale: TComboBox; edLowMin: TEdit; edLowMax: TEdit; procedure BtnOkClick(Sender: TObject); procedure BtnApplyClick(Sender: TObject); private { Private declarations } public { Public declarations } HighValue,HighAlpha,HighScale,HighMin,HighMax:Double; LowValue, LowAlpha, LowScale, LowMin, LowMax :Double; AlphaSpy,AlphaArc:Double; MinGraphHeight:Double; MaxNoDataTime:Integer; Kilometer:Double; function Validate:Boolean; end; var FormSensorOptions: TFormSensorOptions; implementation //uses UFrameGraph; {$R *.DFM} { TFormFPGOptions } function TFormSensorOptions.Validate: Boolean; var AC:TWinControl; begin Result:=False; AC:=ActiveControl; try // High CheckMinMax(HighValue,0.0001,100,edHigh); CheckMinMax(HighAlpha,0,0.9999,edHighAlpha); CheckMinMax(HighScale,2,10,edHighScale); CheckMinMax(HighMin,0,80,edHighMin); CheckMinMax(HighMax,HighMin,80,edHighMax); // Low CheckMinMax(LowValue,0.0001,100,edLow); CheckMinMax(LowAlpha,0,0.9999,edLowAlpha); CheckMinMax(LowScale,2,10,edLowScale); CheckMinMax(LowMin,0,80,edLowMin); CheckMinMax(LowMax,LowMin,80,edLowMax); // Other CheckMinMax(AlphaSpy,0,0.99,edAlphaSpy); CheckMinMax(AlphaArc,0,0.99,edAlphaArc); CheckMinMax(MinGraphHeight,0.05,80,edMinGraphHeight); try MaxNoDataTime:=StrToInt(edMaxNoDataTime.Text); if MaxNoDataTime<0 then ErrorMsg('Значение задержки не может быть отрицательным'); except edMaxNoDataTime.SetFocus; raise; end; CheckMinMax(Kilometer,0,99999,edKilometer); except exit; end; ActiveControl:=AC; Result:=True; end; procedure TFormSensorOptions.BtnOkClick(Sender: TObject); begin if Validate then ModalResult:=mrOk; end; procedure TFormSensorOptions.BtnApplyClick(Sender: TObject); begin if Validate then ModalResult:=mrRetry; end; end.
unit tclists; {$ifdef fpc} {$mode delphi} {$endif} interface uses Classes, SysUtils, Graphics, constants, dbcomponents, tcutils,LCLProc; type {@@ @see TCElementList.ForEachDoPaint } TCElementListPaintCallback = procedure(ACanvas: TCanvas; AElement: PTCElement) of object; TCElementListWriteCallback = procedure(AStream: TStream; AElement: PTCElement) of object; { TCElementList } PTCElementList = ^TCElementList; TCElementList = class(TObject) protected { Element-specific utility methods } {@@ @see #FindElement } function DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; virtual; public Elements: PTCElement; public constructor Create; destructor Destroy; override; { Common utility methods } procedure Clear; function FindElement(Pos: TPoint; var AElement: PTCElement): DWord; procedure ForEachDoPaint(ACanvas: TCanvas; ACallback: TCElementListPaintCallback); procedure ForEachDoWrite(AStream: TStream; ACallback: TCElementListWriteCallback); function GetCount: Cardinal; procedure Insert(AElement: PTCElement); procedure MoveElement(AElement: PTCElement; ADelta: TPoint); procedure Remove(AElement: PTCElement); end; { TCComponentList } TCComponentList = class(TCElementList) protected { Element-specific utility methods } function DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; override; public procedure WriteDebugInfo(); end; { TCWireList } TCWireList = class(TCElementList) protected { Element-specific utility methods } function DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; override; public { Methods specific for wires } procedure MoveWire(AWire: PTCWire; APos: TPoint; APart: DWord); end; { TCTextList } TCTextList = class(TCElementList) protected { Element-specific utility methods } //function DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; override; end; { TCPolylineList } TCPolylineList = class(TCElementList) protected { Element-specific utility methods } function DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; override; public { Methods specific for polylines } procedure AddPoint(APolyline: PTCPolyline; APoint: TPoint); //procedure RemovePoint(APolyline: PTCPolyline; AIndex: Integer); function GetLastPoint(APolyline: PTCPolyline): TPoint; end; { TCRasterImageList } TCRasterImageList = class(TCElementList) protected { Element-specific utility methods } //function DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; override; end; { TCEllipseList } TCEllipseList = class(TCElementList) protected { Element-specific utility methods } //function DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; override; end; implementation { TCElementList } function TCElementList.DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; begin if Pos = AElement^.Pos then Result := ELEMENT_MATCHES else Result := ELEMENT_DOES_NOT_MATCH; end; constructor TCElementList.Create; begin inherited Create; Elements := nil; end; destructor TCElementList.Destroy; begin Clear; inherited Destroy; end; {@@ Clears the list of elements and frees the memory associated with them, efectively reseting the list. } procedure TCElementList.Clear; var AElement, NextElement: PTCElement; begin AElement := Elements; while (AElement <> nil) do begin NextElement := AElement^.Next; FreeMem(AElement); AElement := NextElement; end; Elements := nil; end; {@@ Calls a paint callback for each element on the list } procedure TCElementList.ForEachDoPaint(ACanvas: TCanvas; ACallback: TCElementListPaintCallback); var NextElement: PTCElement; begin if Elements = nil then Exit; NextElement := Elements; while (NextElement <> nil) do begin ACallback(ACanvas, NextElement); NextElement := NextElement^.Next; end; end; procedure TCElementList.ForEachDoWrite(AStream: TStream; ACallback: TCElementListWriteCallback); var NextElement: PTCElement; begin if Elements = nil then Exit; NextElement := Elements; while (NextElement <> nil) do begin ACallback(AStream, NextElement); NextElement := NextElement^.Next; end; end; function TCElementList.GetCount: Cardinal; var AElement: PTCElement; begin Result := 0; AElement := Elements; while AElement <> nil do begin Inc(Result); AElement := AElement^.Next; end; end; procedure TCElementList.Insert(AElement: PTCElement); var LastElement: PTCElement; begin AElement^.Next := nil; AElement^.Previous := nil; { Handles the case where we don't have any items yet } if (Elements = nil) then Elements := AElement else begin { Finds the last item } LastElement := Elements; while LastElement^.Next <> nil do LastElement := LastElement^.Next; { Stablishes the links between the items } LastElement^.Next := AElement; AElement^.Previous := LastElement; end; end; procedure TCElementList.MoveElement(AElement: PTCElement; ADelta: TPoint); begin AElement^.Pos.X := AElement^.Pos.X + ADelta.X; AElement^.Pos.Y := AElement^.Pos.Y + ADelta.Y; end; procedure TCElementList.Remove(AElement: PTCElement); begin if AElement = nil then Exit; if Assigned(AElement^.Previous) then AElement^.Previous^.Next := AElement^.Next; if Assigned(AElement^.Next) then AElement^.Next^.Previous := AElement^.Previous; if (Elements = AElement) then begin Elements := AElement^.Next; if Assigned(AElement^.Next) then AElement^.Next^.Previous := nil; end; Dispose(AElement); end; function TCElementList.FindElement(Pos: TPoint; var AElement: PTCElement): DWord; var NextElement: PTCElement; begin Result := ELEMENT_DOES_NOT_MATCH; if Elements = nil then Exit; NextElement := Elements; while (NextElement <> nil) do begin Result := DoVerifyElementPos(Pos, NextElement); if Result <> ELEMENT_DOES_NOT_MATCH then begin AElement := NextElement; Exit; end; NextElement := NextElement^.Next; end; end; { TCComponentList } function TCComponentList.DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; var AComponent: PTCComponent absolute AElement; ACompHeight, ACompWidth, ABaseCompHeight, ABaseCompWidth: Integer; begin Result := ELEMENT_DOES_NOT_MATCH; vComponentsDatabase.GoToRecByID(AComponent^.TypeID); ACompHeight := vComponentsDatabase.GetHeight(); ACompWidth := vComponentsDatabase.GetWidth(); case AComponent.Orientation of coEast: if (AComponent^.Pos.X < Pos.X) and (Pos.X < AComponent^.Pos.X + ACompWidth) and (AComponent^.Pos.Y < Pos.Y) and (Pos.Y < AComponent^.Pos.Y + ACompHeight) then Result := ELEMENT_MATCHES; coNorth: if (AComponent^.Pos.X < Pos.X) and (Pos.X < AComponent^.Pos.X + ACompHeight) and (AComponent^.Pos.Y - ACompWidth < Pos.Y) and (Pos.Y < AComponent^.Pos.Y) then Result := ELEMENT_MATCHES; coWest: if (AComponent^.Pos.X < Pos.X - ACompWidth) and (Pos.X < AComponent^.Pos.X) and (AComponent^.Pos.Y - ACompHeight < Pos.Y) and (Pos.Y < AComponent^.Pos.Y) then Result := ELEMENT_MATCHES; coSouth: if (AComponent^.Pos.X - ACompHeight< Pos.X) and (Pos.X < AComponent^.Pos.X) and (AComponent^.Pos.Y < Pos.Y) and (Pos.Y < AComponent^.Pos.Y + ACompWidth) then Result := ELEMENT_MATCHES; end; end; procedure TCComponentList.WriteDebugInfo(); var NextComponent: PTCComponent; i: Integer; begin NextComponent := PTCComponent(Elements); i := 0; while (NextComponent <> nil) do begin DebugLn('#Component #' + IntToStr(i) + ' TypeID: ' + NextComponent^.TypeID); NextComponent := PTCComponent(NextComponent^.Next); Inc(i) end; DebugLn(''); end; { TCWireList } function TCWireList.DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; var AWire: PTCWire absolute AElement; begin Result := ELEMENT_DOES_NOT_MATCH; { Verifies PtFrom } if (AWire^.Pos.X = Pos.X) and (AWire^.Pos.Y = Pos.Y) then begin Result := ELEMENT_START_POINT; end { Verifies PtTo } else if (AWire^.PtTo.X = Pos.X) and (AWire^.PtTo.Y = Pos.Y) then begin Result := ELEMENT_END_POINT; end; end; procedure TCWireList.MoveWire(AWire: PTCWire; APos: TPoint; APart: DWord); begin case APart of ELEMENT_START_POINT: AWire^.Pos := APos; ELEMENT_END_POINT: AWire^.PtTo := APos; end; end; { TCTextList } {function TCTextList.DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; var AElementHeight, AElementWidth: Integer; begin Result := ELEMENT_DOES_NOT_MATCH; AElementHeight := 2; AElementWidth := 4; if (AElement^.Pos.X < Pos.X) and (Pos.X < AElement^.Pos.X + AElementWidth) and (AElement^.Pos.Y < Pos.Y) and (Pos.Y < AElement^.Pos.Y + AElementHeight) then Result := ELEMENT_MATCHES; end;} { TCPolylineList } function TCPolylineList.DoVerifyElementPos(Pos: TPoint; AElement: PTCElement): DWord; var APolyline: PTCPolyline absolute AElement; i: Integer; begin Result := ELEMENT_DOES_NOT_MATCH; { Verifies Position } if (APolyline^.Pos.X = Pos.X) and (APolyline^.Pos.Y = Pos.Y) then begin Result := ELEMENT_MATCHES; end { Verifies all other points } else begin for i := 0 to Length(APolyline^.Points) do if APolyline^.Points[i] = Pos then Exit(ELEMENT_MATCHES + i); end; end; procedure TCPolylineList.AddPoint(APolyline: PTCPolyline; APoint: TPoint); begin APolyline^.Points[APolyline^.NPoints] := APoint; Inc(APolyline^.NPoints); end; function TCPolylineList.GetLastPoint(APolyline: PTCPolyline): TPoint; begin if APolyline^.NPoints > 0 then Result := APolyline^.Points[APolyline^.NPoints - 1] else Result := APolyline^.Pos; end; end.
unit UTrieTree; interface uses Windows, SysUtils, UTreeNode, ComCtrls; Type TTrieTree = class private FTree: TNode; public Constructor Create; function IsEmpty: boolean; procedure Push (s: string); function delete(wrd:string):integer; procedure Clear; procedure Print(treeView:TTreeView); procedure pop (s:string); destructor Destroy; end; implementation const N=100; constructor TTrieTree.Create; begin Inherited Create; FTree:=TNode.Create; end; function TTrieTree.IsEmpty: boolean; begin result:=Ftree.IsEmpty; end; procedure TTrieTree.Push(s: string); begin if Ftree= nil then FTree := TNode.Create(); if length(s)>0 then FTree.Push(s,1); end; function TTrieTree.delete(wrd:string):integer; var Arr:array[0..N] of string; i,count:Integer; begin count:=0; FTree.delete(count,Arr,'',wrd); for i:=0 to count-1 do pop(arr[i]); end; procedure TTrieTree.print(treeView:TTreeView); begin treeView.Items.Clear; Ftree.print(treeView, nil); treeView.FullExpand; end; procedure TTrieTree.pop(s:string); begin if Length(s)>0 then FTree.pop(s); end; procedure TTrieTree.Clear; begin if not IsEmpty then FTree.Destroy; end; destructor TTrieTree.Destroy; begin if FTree <> nil then Clear; inherited Destroy; end; end.
unit ufrmPenarikanDeposit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDefault, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, Vcl.Menus, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, System.ImageList, Vcl.ImgList, Datasnap.DBClient, Datasnap.Provider, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, System.Actions, Vcl.ActnList, cxCheckBox, cxGridLevel, cxClasses, cxGridCustomView, Vcl.StdCtrls, cxButtons, Vcl.ComCtrls, Vcl.ExtCtrls, cxPC, dxStatusBar, uDBUtils, ClientModule, uAppUtils, dxCore, cxDateUtils, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, cxMaskEdit, cxCalendar, cxTextEdit, cxMemo, cxCurrencyEdit, uPenarikanDeposit, uSupplier, uDMReport; type TfrmPenarikanDeposit = class(TfrmDefault) lblNoBukti: TLabel; edNoBukti: TcxTextEdit; lblTgl: TLabel; dtTanggal: TcxDateEdit; lblCustomer: TLabel; edKelas: TcxTextEdit; cbbSantri: TcxExtLookupComboBox; lblNominal: TLabel; edNominal: TcxCurrencyEdit; lblKeterangan: TLabel; memKeterangan: TcxMemo; procedure actCetakExecute(Sender: TObject); procedure ActionBaruExecute(Sender: TObject); procedure ActionHapusExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ActionRefreshExecute(Sender: TObject); procedure ActionSimpanExecute(Sender: TObject); procedure cbbSantriPropertiesInitPopup(Sender: TObject); procedure cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); private fcds: TClientDataset; FCDSSantri: tclientDataSet; FPenarikanDeposit: TPenarikanDeposit; function GetCDSSantri: tclientDataSet; function GetPenarikanDeposit: TPenarikanDeposit; procedure InisialisasiCBBSantri; function IsBisaHapus: Boolean; property CDSSantri: tclientDataSet read GetCDSSantri write FCDSSantri; { Private declarations } protected procedure CetakSlip; override; public procedure LoadDataTransaksi(AID : String); override; property PenarikanDeposit: TPenarikanDeposit read GetPenarikanDeposit write FPenarikanDeposit; { Public declarations } end; var frmPenarikanDeposit: TfrmPenarikanDeposit; implementation uses Data.FireDACJSONReflect; {$R *.dfm} procedure TfrmPenarikanDeposit.actCetakExecute(Sender: TObject); begin inherited; CetakSlip; end; procedure TfrmPenarikanDeposit.ActionBaruExecute(Sender: TObject); begin inherited; LoadDataTransaksi(''); end; procedure TfrmPenarikanDeposit.ActionHapusExecute(Sender: TObject); begin inherited; if not IsBisaHapus then Exit; if ClientDataModule.ServerPenarikanDepositClient.Delete(PenarikanDeposit) then begin ActionRefreshExecute(Sender); ActionBaruExecute(Sender); end; end; procedure TfrmPenarikanDeposit.FormCreate(Sender: TObject); begin inherited; InisialisasiCBBSantri; end; procedure TfrmPenarikanDeposit.ActionRefreshExecute(Sender: TObject); begin inherited; if chkKonsolidasi1.Checked then fcds := TDBUtils.DSToCDS(ClientDataModule.ServerLaporanClient.RetrivePenarikanDeposit(dtpAwal.DateTime, dtpAkhir.DateTime, nil), cxGridDBTableOverview) else fcds := TDBUtils.DSToCDS(ClientDataModule.ServerLaporanClient.RetrivePenarikanDeposit(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang), cxGridDBTableOverview); cxGridDBTableOverview.ClearRows; cxGridDBTableOverview.SetDataset(fcds, True); cxGridDBTableOverview.SetVisibleColumns(['ID', 'SANTRI'], False); cxGridDBTableOverview.ApplyBestFit(); end; procedure TfrmPenarikanDeposit.ActionSimpanExecute(Sender: TObject); begin inherited; if not ValidateEmptyCtrl([1]) then Exit else if edNominal.Value <= 0 then begin TAppUtils.Warning('Nominal Harus > 0'); edNominal.SetFocus; Exit; end; PenarikanDeposit.NoBukti := edNoBukti.Text; PenarikanDeposit.Keterangan := memKeterangan.Text; PenarikanDeposit.Nominal := edNominal.Value; PenarikanDeposit.Tanggal := dtTanggal.Date; PenarikanDeposit.Santri := TSupplier.CreateID(cbbSantri.EditValue); if ClientDataModule.ServerPenarikanDepositClient.Save(PenarikanDeposit) then begin if TAppUtils.ConfirmBerhasilSimpanCetakReport('Slip Deposit') then begin actCetakExecute(Sender); end; ActionBaruExecute(Sender); end; end; procedure TfrmPenarikanDeposit.cbbSantriPropertiesInitPopup(Sender: TObject); begin inherited; if Trim(edKelas.Text) = '' then CDSSantri.Filtered := False else begin CDSSantri.Filter := ' kelas = ' + QuotedStr(Trim(edKelas.Text)); CDSSantri.Filtered := True; end; end; procedure TfrmPenarikanDeposit.CetakSlip; var lcds: TFDJSONDataSets; begin with dmReport do begin AddReportVariable('UserCetak', UserAplikasi.UserName); if cxPCData.ActivePageIndex = 0 then lcds := ClientDataModule.ServerPenarikanDepositClient.RetrieveCDSlip(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang, '%') else lcds := ClientDataModule.ServerPenarikanDepositClient.RetrieveCDSlip(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang, PenarikanDeposit.NoBukti); ExecuteReport('Reports/Slip_Penarikan_Deposit' ,lcds); end; end; procedure TfrmPenarikanDeposit.cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin inherited; LoadDataTransaksi(fcds.FieldByName('ID').AsString); cxPCData.ActivePageIndex := 1; end; function TfrmPenarikanDeposit.GetCDSSantri: tclientDataSet; var sSQL: string; begin if FCDSSantri = nil then begin sSQL := 'select Nama,Kode,kelas,ID from TSupplier'; FCDSSantri := TDBUtils.OpenDataset(sSQL); end; Result := FCDSSantri; end; function TfrmPenarikanDeposit.GetPenarikanDeposit: TPenarikanDeposit; begin if FPenarikanDeposit = nil then FPenarikanDeposit := TPenarikanDeposit.Create; Result := FPenarikanDeposit; end; procedure TfrmPenarikanDeposit.InisialisasiCBBSantri; begin cbbSantri.Properties.LoadFromCDS(CDSSantri,'ID','Nama',['ID'],Self); cbbSantri.Properties.SetMultiPurposeLookup; end; function TfrmPenarikanDeposit.IsBisaHapus: Boolean; begin Result := False; if TAppUtils.Confirm('Anda yakin akan menghapus data?') then Result := True; end; procedure TfrmPenarikanDeposit.LoadDataTransaksi(AID : String); begin inherited; if AID = '' then begin edNoBukti.Text := ClientDataModule.ServerPenarikanDepositClient.GenerateNoBukti(dtTanggal.Date, 'PD'); end else begin FreeAndNil(FPenarikanDeposit); FPenarikanDeposit := ClientDataModule.ServerPenarikanDepositClient.Retrieve(AID); edNoBukti.Text := PenarikanDeposit.NoBukti; dtTanggal.Date := PenarikanDeposit.Tanggal; cbbSantri.EditValue := PenarikanDeposit.Santri.ID; edNominal.Value := PenarikanDeposit.Nominal; memKeterangan.Text := PenarikanDeposit.Keterangan; end; end; end.
unit console; {$ifdef fpc}{$mode objfpc}{$H+}{$endif} interface implementation uses {$IFDEF FPC}ZStream, {$ENDIF} strutils,Classes,SysUtils, mat; procedure Showmsg(lStr: string); begin Writeln(lStr); end; {$include common.inc} procedure WriteHelp; var E: string; begin E := extractfilename(ParamStr(0)); writeln('Usage: ',E,'[options] brukerfilename'); writeln(kVers); writeln(' Converts Bruker "subject" or "acqp" MRI images'); writeln('Options:'); writeln(' -a actual size (otherwise x10 scale so animals match human)'); writeln(' -f force conversion of localizer images (multiple slice orientations)'); writeln(' -h show these help instructions'); writeln(' -o output filename'); writeln(' -p append protocol name to output filename'); writeln(' -s append series type ID to output filename'); {$IFDEF FPC}writeln(' -z gz compress images (".nii.gz")');{$ENDIF} writeln(' -v verbose conversion comments'); writeln('Examples:'); {$IFDEF UNIX} writeln(' '+E+' /Users/bruker/mri/1/acqp'); writeln(' '+E+' -v -a /Users/bruker/mri/subject'); writeln(' '+E+' -o /Users/cr/mynifti /Users/bruker/mri/subject'); writeln(' '+E+' "/Users/spaces in filename/subject"'); {$ELSE} writeln(' '+E+' c:\bruker\mri\1\acqp'); writeln(' '+E+' -v -a c:\bruker\mri\1\acqp'); writeln(' '+E+' -o c:\newnifti c:\bruker\mri\1\acqp'); writeln(' '+E+' "c:\spaces in filename\mri\1\acqp"'); {$ENDIF} end; procedure ProcessParamStr; var inFname, outFname, cmd: string; i: integer; FOVx10, verbose, OnlyConvert3D, AppendProtocolName, AppendSeriesTypeID, CompressFile: boolean; begin FOVx10 := true; Verbose := false; AppendProtocolName := false; AppendSeriesTypeID := false; CompressFile := false; OnlyConvert3D := true; outFname := ''; i := 1; while i <= (ParamCount) do begin cmd := ParamStr(i); i := i + 1; if AnsiPos('-', cmd) = 1 then begin if AnsiPos('-a', cmd) = 1 then FOVx10 := false else if AnsiPos('-f', cmd) = 1 then OnlyConvert3D := false else if AnsiPos('-h', cmd) = 1 then WriteHelp else if AnsiPos('-p', cmd) = 1 then AppendProtocolName := true else if AnsiPos('-s', cmd) = 1 then AppendSeriesTypeID := true else if AnsiPos('-z', cmd) = 1 then CompressFile := true else if (AnsiPos('-o', cmd) = 1) and (i <= (ParamCount-1)) then begin outFname := ParamStr(i); i := i + 1; end else if AnsiPos('-v', cmd) = 1 then Verbose := true else showmsg('Unknown command (is this software obsolete?) '+cmd); end else inFname := cmd; end; {$IFNDEF FPC} if CompressFile then begin showmsg('Unable to compress images (solution: recompile with freepascal)'); exit; end; {$ENDIF} BrConvertBatch (inFname, outFname, FOVx10, Verbose, OnlyConvert3D, AppendProtocolName, AppendSeriesTypeID, CompressFile); end; begin {$ifdef fpc} DefaultFormatSettings.DecimalSeparator := '.'; //Bruker will write real numbers as 1.23 not 1,23 {$else} DecimalSeparator := '.'; {$endif} if (ParamCount = 0) then WriteHelp else ProcessParamStr; end.
{ Subroutine SST_R_PAS_INTEGER } module sst_r_pas_INTEGER; define sst_r_pas_integer; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_integer ( {read UNSIGNED_LIT_INTEGER and return value} out ival: sys_int_max_t); {returned integer value} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} token: string_var80_t; {scratch string for number conversion} base: sys_int_machine_t; {number base of integer string} stat: sys_err_t; begin token.max := sizeof(token.str); {init var string} syo_level_down; {down into UNSIGNED_LIT_INTEGER syntax level} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); if tag <> 1 then begin syo_error_tag_unexp (tag, str_h); end; syo_get_tag_string (str_h, token); {get decimal integer or optional base string} string_t_int_max (token, ival, stat); {convert string to integer value} syo_error_abort (stat, str_h, 'sst_pas_read', 'constant_bad', nil, 0); syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); case tag of syo_tag_end_k: begin {token was decimal integer value} end; 1: begin {token was base for next token} base := ival; {save number base to use} syo_get_tag_string (str_h, token); {get integer value string} string_t_int_max_base ( {convert string to integer value} token, {input string} base, {number base of input string} [string_ti_unsig_k], {string is unsigned, null string is error} ival, {output value} stat); syo_error_abort (stat, str_h, 'sst_pas_read', 'constant_bad', nil, 0); end; otherwise syo_error_tag_unexp (tag, str_h); end; syo_level_up; {up from UNSIGNED_LIT_INTEGER syntax level} end;
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StWmDCpy.pas 4.04 *} {*********************************************************} {* SysTools: Class for handling WM_COPYDATA exchanges *} {*********************************************************} {$I StDefine.inc} unit StWmDCpy; interface uses Windows, SysUtils, Messages, Classes, Forms, Controls, Dialogs, StBase; type TStOnDataReceivedEvent = procedure(Sender : TObject; CopyData : TCopyDataStruct) of object; TStWMDataCopy = class(TStComponent) protected {private} { Private declarations } NewWndProc : TFarProc; PrevWndProc : TFarProc; FOnDataReceived : TStOnDataReceivedEvent; procedure AppWndProc(var Msg : TMessage); procedure HookForm(Value : Boolean); protected { Protected declarations } public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; published { Published declarations } property OnDataReceived : TStOnDataReceivedEvent read FOnDataReceived write FOnDataReceived; end; implementation constructor TStWMDataCopy.Create(AOwner : TComponent); begin inherited Create(AOwner); if not (csDesigning in ComponentState) then begin {$WARN SYMBOL_DEPRECATED OFF} NewWndProc := MakeObjectInstance(AppWndProc); {$WARN SYMBOL_DEPRECATED ON} HookForm(True); end; end; destructor TStWMDataCopy.Destroy; begin if Assigned(NewWndProc) then begin HookForm(False); {$WARN SYMBOL_DEPRECATED OFF} FreeObjectInstance(NewWndProc); {$WARN SYMBOL_DEPRECATED ON} end; inherited Destroy; end; procedure TStWMDataCopy.HookForm(Value : Boolean); begin if (not (csDesigning in ComponentState)) and not (csDestroying in ComponentState) then begin if Assigned(PrevWndProc) then Exit; if Value then begin PrevWndProc:= Pointer( SetWindowLong(TForm(Owner).Handle, GWL_WNDPROC, Integer(NewWndProc))) end else if Assigned(PrevWndProc) then begin SetWindowLong(TForm(Owner).Handle, GWL_WNDPROC, Integer(PrevWndProc)); PrevWndProc := nil; end; end; end; procedure TStWMDataCopy.AppWndProc(var Msg : TMessage); var CDS : TCopyDataStruct; begin with Msg do begin if (Msg = WM_COPYDATA) then begin CDS := PCopyDataStruct(Pointer(lParam))^; if (CDS.dwData = WMCOPYID) then begin if (Assigned(FOnDataReceived)) then FOnDataReceived(Self, CDS); end else if Assigned(PrevWndProc) then Result := CallWindowProc(PrevWndProc, TForm(Owner).Handle, Msg, wParam, lParam); end else if Assigned(PrevWndProc) then Result := CallWindowProc(PrevWndProc, TForm(Owner).Handle, Msg, wParam, lParam); end; end; end.
unit ddBreak; // Модуль: "w:\common\components\rtl\Garant\dd\ddBreak.pas" // Стереотип: "SimpleClass" // Элемент модели: "TddBreak" MUID: (51E8EFD50162) {$Include w:\common\components\rtl\Garant\dd\ddDefine.inc} interface uses l3IntfUses , ddDocumentAtom , RTFtypes , ddSectionProperty , ddCustomDestination , k2Interfaces , ddTypes ; type TddBreak = class(TddDocumentAtom) private f_BreakType: TddBreakType; f_SEP: TddSectionProperty; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public function HasDefaultParams: Boolean; procedure Write2Generator(const Generator: Ik2TagGenerator; aNeedProcessRow: Boolean; LiteVersion: TddLiteVersion); override; constructor Create(aDetination: TddCustomDestination); override; function IsBreak: Boolean; override; public property BreakType: TddBreakType read f_BreakType write f_BreakType; property SEP: TddSectionProperty read f_SEP; end;//TddBreak implementation uses l3ImplUses , PageBreak_Const , SectionBreak_Const , k2Tags , l3Interfaces , l3MinMax , SysUtils , ddDocumentProperty //#UC START# *51E8EFD50162impl_uses* //#UC END# *51E8EFD50162impl_uses* ; function TddBreak.HasDefaultParams: Boolean; //#UC START# *53883BAC01A0_51E8EFD50162_var* //#UC END# *53883BAC01A0_51E8EFD50162_var* begin //#UC START# *53883BAC01A0_51E8EFD50162_impl* Result := not SEP.Landscape and (SEP.xaPage = defPageWidth) and (SEP.yaPage = defPageHeight); //#UC END# *53883BAC01A0_51E8EFD50162_impl* end;//TddBreak.HasDefaultParams procedure TddBreak.Write2Generator(const Generator: Ik2TagGenerator; aNeedProcessRow: Boolean; LiteVersion: TddLiteVersion); //#UC START# *518A504F00F5_51E8EFD50162_var* //#UC END# *518A504F00F5_51E8EFD50162_var* begin //#UC START# *518A504F00F5_51E8EFD50162_impl* case BreakType of breakPage : begin Generator.StartChild(k2_typPageBreak); Generator.Finish; end; breakSection: begin Generator.StartChild(k2_typSectionBreak); try Generator.StartTag(k2_tiParas); try if SEP.Landscape then begin Generator.AddIntegerAtom(k2_tiOrientation, Ord(l3_poLandscape)); Generator.AddIntegerAtom(k2_tiHeight, Max(SEP.yaPage, SEP.xaPage)); Generator.AddIntegerAtom(k2_tiWidth, Min(SEP.xaPage, SEP.yaPage)); end else begin Generator.AddIntegerAtom(k2_tiOrientation, Ord(l3_poPortrait)); Generator.AddIntegerAtom(k2_tiHeight, Max(SEP.yaPage, SEP.xaPage)); Generator.AddIntegerAtom(k2_tiWidth, Min(SEP.xaPage, SEP.yaPage)); end; finally Generator.Finish; end;{try..finally} finally Generator.Finish; end; end; end; //#UC END# *518A504F00F5_51E8EFD50162_impl* end;//TddBreak.Write2Generator procedure TddBreak.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_51E8EFD50162_var* //#UC END# *479731C50290_51E8EFD50162_var* begin //#UC START# *479731C50290_51E8EFD50162_impl* FreeAndNil(f_SEP); inherited; //#UC END# *479731C50290_51E8EFD50162_impl* end;//TddBreak.Cleanup constructor TddBreak.Create(aDetination: TddCustomDestination); //#UC START# *51E91BA80051_51E8EFD50162_var* //#UC END# *51E91BA80051_51E8EFD50162_var* begin //#UC START# *51E91BA80051_51E8EFD50162_impl* inherited Create(aDetination); f_SEP := TddSectionProperty.Create; //#UC END# *51E91BA80051_51E8EFD50162_impl* end;//TddBreak.Create function TddBreak.IsBreak: Boolean; //#UC START# *5268D65201D6_51E8EFD50162_var* //#UC END# *5268D65201D6_51E8EFD50162_var* begin //#UC START# *5268D65201D6_51E8EFD50162_impl* Result := True; //#UC END# *5268D65201D6_51E8EFD50162_impl* end;//TddBreak.IsBreak end.
unit flRuleStore; // This Class stores the rules. {$mode objfpc}{$H+} interface uses Classes, SysUtils, fgl; type //TStringList = specialize TList<string>; //TRealList = specialize TList<real>; TStrList = specialize TFPGList<String>; TRealList = specialize TFPGList<Real>; TRuleStore = class(TObject) constructor Create(); function getKeyword(I: integer): string; function getSeed(I: integer): real; function getIncrement(I: integer): real; procedure setKeyword(I: integer; NewValue: string); procedure setSeed(I: integer; NewValue: real); procedure setIncrement(I: integer; NewValue: real); procedure deleteRule(I: integer); procedure addRule(pKeyword: string; pSeed: real; pIncrement: real); function getLength() : Integer; function checkKeyword(pKeyword: String) : Boolean; procedure clear(); end; var keyword: TStrList; seed: TRealList; increment: TRealList; implementation constructor TRuleStore.Create(); begin keyword := TStrList.Create; seed := TRealList.Create; increment := TRealList.Create; end; // Returns keyword[I] function TRuleStore.getKeyword(I: integer): string; begin getKeyword := keyword[I]; end; // Returns seed[I] function TRuleStore.getSeed(I: integer): real; begin getSeed := seed[I] end; // Returns increment[I] function TRuleStore.getIncrement(I: integer): real; begin getIncrement := increment[I]; end; // Sets keyword[I] to NewValue procedure TRuleStore.setKeyword(I: integer; NewValue: string); begin keyword[I] := NewValue; end; // Sets seed[I] to NewValue procedure TRuleStore.setSeed(I: integer; NewValue: real); begin seed[I] := NewValue; end; // Sets increment[I] to NewValue procedure TRuleStore.setIncrement(I: integer; NewValue: real); begin increment[I] := NewValue; end; // Deletes a rule procedure TRuleStore.deleteRule(I: integer); begin keyword.Delete(I); seed.Delete(I); increment.Delete(I); end; // Adds a rule procedure TRuleStore.addRule(pKeyword: string; pSeed: real; pIncrement: real); begin keyword.Add(pKeyword); seed.Add(pSeed); increment.add(pIncrement); end; function TRuleStore.getLength() : Integer; begin getLength := keyword.Count; end; function TRuleStore.checkKeyword(pKeyword: String) : Boolean; var S: String; begin for S in keyword do if S = pKeyword then checkKeyword := False else checkKeyword := True end; procedure TRuleStore.clear(); begin keyword.Clear; seed.Clear; increment.Clear; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@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. * ********************************************************************************************************************** * TERRA_FileManager * Implements the global file manager *********************************************************************************************************************** } Unit TERRA_FileManager; {$I terra.inc} Interface Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF} TERRA_String, TERRA_Utils, TERRA_Resource, TERRA_Collections, TERRA_Stream, TERRA_FileStream, TERRA_Application, TERRA_Hashmap, TERRA_Package; Type ResourceProvider = Class(TERRAObject) Function GetStream(Const Name:TERRAString):Stream; Virtual; Abstract; Function HasStream(Const Name:TERRAString):Boolean; Virtual; Abstract; End; FileLocation = Class(HashMapObject) Public Path:TERRAString; Constructor Create(Const Name, Path:TERRAString); Procedure CopyValue(Other:CollectionObject); Override; End; FileManager = Class(ApplicationComponent) Protected _SourceList:Array Of TERRAString; _SourceCount:Integer; _PathList:Array Of TERRAString; _PathCount:Integer; _PackageList:Array Of Package; _PackageCount:Integer; _ProviderCount:Integer; _Providers:Array Of ResourceProvider; _Locations:HashMap; Public Procedure Init; Override; Class Function Instance:FileManager; Procedure Release; Override; Function SearchResourceFile(FileName:TERRAString):TERRAString; Procedure AddPath(Path:TERRAString); Procedure RemovePath(Path:TERRAString); Function GetPath(Index:Integer):TERRAString; Function AddPackage(FileName:TERRAString):Package; Overload; Function AddPackage(MyPackage:Package):Package; Overload; Procedure AddSource(Source:TERRAString); Procedure RemoveSource(Source:TERRAString); Procedure AddResourceProvider(Provider:ResourceProvider); Procedure DeleteResourceProvider(Provider:ResourceProvider); Procedure RemoveFromCache(FileName:TERRAString); Procedure ExcludeFileFromBackup(Source:FileStream); Function GetPackage(Name:TERRAString; ValidateError:Boolean = True):Package; Function OpenStream(FileName:TERRAString; Mode:Integer = smRead):Stream; // Function OpenPackages(FileName:TERRAString):Boolean; Property PathCount:Integer Read _PathCount; End; Function IsPackageFileName(Const FileName:TERRAString):Boolean; Implementation Uses SysUtils, TERRA_Error, TERRA_Log, {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF} TERRA_OS, TERRA_Image, TERRA_GraphicsManager, TERRA_Color, TERRA_FileUtils, TERRA_MemoryStream; Var _FileManager:ApplicationObject = Nil; Function IsPackageFileName(Const FileName:TERRAString):Boolean; Var I,J:Integer; Begin Result := StringContains('.terra'+PathSeparator, FileName); End; Function SearchFileLocation(P:CollectionObject; UserData:Pointer):Boolean; CDecl; Begin Result := (FileLocation(P).Key = PString(Userdata)^); End; { FileManager } Class Function FileManager.Instance:FileManager; Begin If (_FileManager = Nil) Then _FileManager := InitializeApplicationComponent(FileManager, Nil); Result := FileManager(_FileManager.Instance); End; Procedure FileManager.Init; Begin _Locations := HashMap.Create(256); Self.AddSource(''); End; Procedure FileManager.RemoveFromCache(FileName:TERRAString); Var Location:FileLocation; Begin {$IFNDEF DISABLEFILECACHE} FileName := StringLower(FileName); FileName := GetFileName(FileName, False); Location := FileLocation(_Locations.Search(SearchFileLocation, @FileName)); If Assigned(Location) Then _Locations.Delete(Location); {$ENDIF} End; Procedure FileManager.ExcludeFileFromBackup(Source: FileStream); Begin {$IFDEF IPHONE} (* If (Source.Name<>'') Then ExcludeFileFromCloud(PAnsiChar(Source.Name)); *) {$ENDIF} End; (* Function FileManager.OpenPackages(FileName:TERRAString):Boolean; Type FileEntry = Record Name:TERRAString; Offset:Cardinal; Size:Cardinal; End; Var Source:FileStream; Header:FileHeader; I, Offset, Count:Cardinal; Files:Array Of FileEntry; P:Package; Stream:MemoryStream; Begin Result := False; If Not FileStream.Exists(FileName) Then Exit; Source := FileStream.Open(FileName, smRead); Source.Seek(Source.Size - 8); Source.Read(@Header,4); If (Header <> TERRAHeader) Then Begin ReleaseObject(Source); Exit; End; Source.Read(@Offset, 4); Source.Seek(Offset); Source.Read(@Count, 4); SetLength(Files, Count); For I:=0 To Pred(Count) Do Begin Source.ReadString(Files[I].Name); Source.Read(@Files[I].Offset, 4); Source.Read(@Files[I].Size, 4); End; For I:=0 To Pred(Count) Do Begin Stream := MemoryStream.Create(Files[I].Size); Source.Seek(Files[I].Offset); Source.Read(Stream.Buffer, Files[I].Size); P := Package.Open(Stream); Self.AddPackage(P); End; ReleaseObject(Source) Result := True; End; *) Procedure FileManager.AddResourceProvider(Provider: ResourceProvider); Begin Inc(_ProviderCount); SetLength(_Providers, _ProviderCount); _Providers[Pred(_ProviderCount)] := Provider; End; Procedure FileManager.DeleteResourceProvider(Provider:ResourceProvider); Var I,N:Integer; Begin N := -1; For I:=0 To Pred(_ProviderCount) Do If (_Providers[I] = Provider) Then Begin N := I; Break; End; If (N<0) Then Exit; _Providers[N] := _Providers[Pred(_ProviderCount)]; Dec(_ProviderCount); End; Function FileManager.GetPath(Index: Integer):TERRAString; Begin If (Index>=0) And (Index<_PathCount) Then Result := _PathList[Index] Else Result := ''; End; Procedure FileManager.AddPath(Path:TERRAString); Var I:Integer; // FM:FolderManager; Begin Path := GetOSIndependentFilePath(Path); Path := Path + PathSeparator; {$IFDEF PC} If Not DirectoryExists(Path) Then Begin Log(logWarning, 'FileManager', 'The following path is missing: '+Path); Exit; End; {$ENDIF} For I:=0 To Pred(_PathCount) Do If (_PathList[I] = Path) Then Exit; Log(logDebug, 'FileManager', 'Adding path: '+Path); Inc(_PathCount); SetLength(_PathList, _PathCount); _PathList[Pred(_PathCount)] := Path; (* FM := FolderManager.Instance; If Assigned(FM) Then FM.WatchFolder(Path);*) End; Procedure FileManager.RemovePath(Path:TERRAString); Var I, N:Integer; Begin Path := GetOSIndependentFilePath(Path); Path := Path + PathSeparator; N := -1; For I:=0 To Pred(_PathCount) Do If (_PathList[I] = Path) Then Begin N := I; Break; End; If (N>=0) Then Begin _PathList[N] := _PathList[Pred(_PathCount)]; Dec(_PathCount); End; End; Function FileManager.AddPackage(MyPackage:Package):Package; Begin Result := MyPackage; If MyPackage = Nil Then Exit; Inc(_PackageCount); SetLength(_PackageList, _PackageCount); _PackageList[Pred(_PackageCount)] := MyPackage; Result := _PackageList[Pred(_PackageCount)]; MyPackage.Load(); End; Function FileManager.AddPackage(FileName:TERRAString):Package; Begin If (Pos('.',FileName)<=0) Then FileName := FileName + '.terra'; If FileStream.Exists(FileName) Then Result := Self.AddPackage(Package.Create(FileName)) Else Result := Nil; End; Function FileManager.SearchResourceFile(FileName:TERRAString):TERRAString; Var S:TERRAString; I, J:Integer; Resource:ResourceInfo; Location:FileLocation; Procedure RegisterLocation(); Begin If IsPackageFileName(FileName) Then Exit; Location := FileLocation.Create(FileName, Result); _Locations.Add(Location); End; Begin Result := ''; If (FileName='') Then Exit; FileName := StringLower(FileName); FileName := GetFileName(FileName, False); {$IFDEF DEBUG_FILECACHE}Log(logDebug, 'FileManager', 'Searching for file '+FileName+' in cache');{$ENDIF} {$IFNDEF DISABLEFILECACHE} Location := FileLocation(_Locations.Search(SearchFileLocation, @FileName)); If Assigned(Location) Then Begin {$IFDEF DEBUG_FILECACHE}Log(logDebug, 'FileManager', 'Was found in cache: '+Location.Path);{$ENDIF} Result := Location.Path; Exit; End; {$ENDIF} {$IFDEF DEBUG_FILECACHE}Log(logDebug, 'FileManager', 'Searching for file '+FileName+' in storage');{$ENDIF} For I:=0 To Pred(_ProviderCount) Do Begin If (_Providers[I].HasStream(FileName)) Then Begin Result := FileName; RegisterLocation(); Exit; End; End; If FileStream.Exists(FileName) Then Begin Result := FileName; RegisterLocation(); Exit; End; FileName := GetFileName(FileName, False); For J:=0 To Pred(_SourceCount) Do Begin If _SourceList[J]<>'' Then Log(logDebug,'FileManager', 'Testing source: '+_SourceList[J]); For I:=0 To Pred(_PathCount) Do Begin S := _SourceList[J]+_PathList[I] + FileName; If FileStream.Exists(S) Then Begin Result := S; RegisterLocation(); Exit; End; End; End; For I:=0 To Pred(_PackageCount) Do If Assigned(_PackageList[I]) Then Begin Resource := _PackageList[I].FindResourceByName(FileName); If Assigned(Resource) Then Begin Result := Resource.GetLocation; RegisterLocation(); Exit; End; End; If Assigned(Application.Instance()) And (Application.Instance().TempPath<>'') Then Begin S := Application.Instance().TempPath + PathSeparator + FileName; If FileStream.Exists(S) Then Begin Result := S; RegisterLocation(); Exit; End; End; Result := ''; RegisterLocation(); End; Function FileManager.GetPackage(Name:TERRAString; ValidateError:Boolean):Package; Var I:Integer; Begin Name := GetFileName(StringTrim(Name), True); If (Name='') Then Begin Result := Nil; Exit; End; For I:=0 To Pred(_PackageCount) Do If (StringEquals(_PackageList[I].Name, Name)) Then Begin Result := _PackageList[I]; Exit; End; Result := Nil; If ValidateError Then RaiseError('Could not find package. ['+Name +']'); End; Function FileManager.OpenStream(FileName:TERRAString; Mode:Integer):Stream; Var I:Integer; PackageName,ResourceName:TERRAString; MyPackage:Package; Resource:ResourceInfo; Begin Result:=Nil; Log(logDebug, 'FileManager', 'Searching providers for '+FileName); For I:=0 To Pred(_ProviderCount) Do Begin If (_Providers[I].HasStream(FileName)) Then Begin Result := _Providers[I].GetStream(FileName); Exit; End; End; // load from package If (IsPackageFileName(FileName)) Then Begin I := StringPosReverse(PathSeparator, FileName); PackageName := StringCopy(FileName,1, Pred(I)); ResourceName := StringCopy(FileName, Succ(I), MaxInt); MyPackage := Self.GetPackage(PackageName); Resource := MyPackage.FindResourceByName(ResourceName); If Not Assigned(Resource) Then Begin RaiseError('Resource '+ResourceName+' not found in '+PackageName); Exit; End; Result := MyPackage.LoadResource(Resource); End Else Begin If (FileStream.Exists(FileName)) Then Begin Result := FileStream.Open(FileName, Mode); Exit; End; FileName := GetFileName(FileName, False); FileName := Self.SearchResourceFile(FileName); If (FileName = '') Then Result := Nil Else Begin Log(logDebug, 'FileManager', 'Opening file '+FileName); If (IsPackageFileName(FileName)) Then Result := Self.OpenStream(FileName, Mode) Else Result := MemoryStream.Create(FileName, Mode); //Result := FileStream.Open(FileName,Mode); (* If (Result.Size<=0) Then Begin {$IFDEF PC} Result := OpenStream(FileName, Mode); Halt; {$ENDIF} End;*) Log(logDebug, 'FileManager', 'Open size '+IntToString(Result.Size)); End; End; End; Procedure FileManager.Release; Var I:Integer; Begin For I:=0 To Pred(Self._ProviderCount) Do ReleaseObject(_Providers[I]); For I:=0 To Pred(_PackageCount) Do ReleaseObject(_PackageList[I]); _PackageCount := 0; ReleaseObject(_Locations); _FileManager := Nil; End; Procedure FileManager.AddSource(Source:TERRAString); Var I:Integer; Begin Log(logDebug, 'FileManager', 'Adding source: '+Source); RemoveSource(Source); Inc(_SourceCount); SetLength(_SourceList, _SourceCount); _SourceList[Pred(_SourceCount)] := Source; End; Procedure FileManager.RemoveSource(Source:TERRAString); Var I:Integer; Begin I := 0; While I<_SourceCount Do If (_SourceList[I] = Source) Then Begin _SourceList[I] := _SourceList[Pred(_SourceCount)]; Dec(_SourceCount); End Else Inc(I); End; { FileLocation } Constructor FileLocation.Create(Const Name, Path:TERRAString); Begin Self._Key := StringLower(GetFileName(Name, False)); Self.Path := Path; End; Procedure FileLocation.CopyValue(Other: CollectionObject); Begin Self._Key := FileLocation(Other).Key; Self.Path := FileLocation(Other).Path; End; End.
{ Date Created: 5/25/00 5:01:01 PM } unit InfoDIRYGRUPTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoDIRYGRUPRecord = record PGroup: String[6]; PDescription: String[30]; End; TInfoDIRYGRUPBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoDIRYGRUPRecord end; TEIInfoDIRYGRUP = (InfoDIRYGRUPPrimaryKey); TInfoDIRYGRUPTable = class( TDBISAMTableAU ) private FDFGroup: TStringField; FDFDescription: TStringField; procedure SetPGroup(const Value: String); function GetPGroup:String; procedure SetPDescription(const Value: String); function GetPDescription:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoDIRYGRUP); function GetEnumIndex: TEIInfoDIRYGRUP; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoDIRYGRUPRecord; procedure StoreDataBuffer(ABuffer:TInfoDIRYGRUPRecord); property DFGroup: TStringField read FDFGroup; property DFDescription: TStringField read FDFDescription; property PGroup: String read GetPGroup write SetPGroup; property PDescription: String read GetPDescription write SetPDescription; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoDIRYGRUP read GetEnumIndex write SetEnumIndex; end; { TInfoDIRYGRUPTable } procedure Register; implementation function TInfoDIRYGRUPTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoDIRYGRUPTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoDIRYGRUPTable.GenerateNewFieldName } function TInfoDIRYGRUPTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoDIRYGRUPTable.CreateField } procedure TInfoDIRYGRUPTable.CreateFields; begin FDFGroup := CreateField( 'Group' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; end; { TInfoDIRYGRUPTable.CreateFields } procedure TInfoDIRYGRUPTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoDIRYGRUPTable.SetActive } procedure TInfoDIRYGRUPTable.Validate; begin { Enter Validation Code Here } end; { TInfoDIRYGRUPTable.Validate } procedure TInfoDIRYGRUPTable.SetPGroup(const Value: String); begin DFGroup.Value := Value; end; function TInfoDIRYGRUPTable.GetPGroup:String; begin result := DFGroup.Value; end; procedure TInfoDIRYGRUPTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoDIRYGRUPTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoDIRYGRUPTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Group, String, 6, N'); Add('Description, String, 30, N'); end; end; procedure TInfoDIRYGRUPTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Group, Y, Y, N, N'); end; end; procedure TInfoDIRYGRUPTable.SetEnumIndex(Value: TEIInfoDIRYGRUP); begin case Value of InfoDIRYGRUPPrimaryKey : IndexName := ''; end; end; function TInfoDIRYGRUPTable.GetDataBuffer:TInfoDIRYGRUPRecord; var buf: TInfoDIRYGRUPRecord; begin fillchar(buf, sizeof(buf), 0); buf.PGroup := DFGroup.Value; buf.PDescription := DFDescription.Value; result := buf; end; procedure TInfoDIRYGRUPTable.StoreDataBuffer(ABuffer:TInfoDIRYGRUPRecord); begin DFGroup.Value := ABuffer.PGroup; DFDescription.Value := ABuffer.PDescription; end; function TInfoDIRYGRUPTable.GetEnumIndex: TEIInfoDIRYGRUP; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoDIRYGRUPPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoDIRYGRUPTable, TInfoDIRYGRUPBuffer ] ); end; { Register } function TInfoDIRYGRUPBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PGroup; 2 : result := @Data.PDescription; end; end; end. { InfoDIRYGRUPTable }
unit uBignumArithmetic; interface const DECIMAL_SEPARATOR = '.'; MAX_SIZE = 255; // не более максимального значения TDigit DIGITS_IN_ONE_CELL = 2; // зависит от TDigit: MAX_NUM_IN_ONE_CELL должен входить в диапазон значений TDigit BASE = 10; // фиксированная величина: не изменять MAX_NUM_IN_ONE_CELL = trunc( power(BASE, DIGITS_IN_ONE_CELL) ) - 1; type TDigit = byte; TDigitArr = array[0..MAX_SIZE] of TDigit; TLongReal = record // многоразрядное действительное число intPart: TDigitArr; // целая часть fracPart: TDigitArr; // дробная часть /// Прежде чем начать работать с переменными типа TLongReal, необходимо выполнить этот метод. procedure init(); class function operator <(a, b: TLongReal): boolean; class function operator =(a, b: TLongReal): boolean; end; /// Считывает строку из файла fi. Если строка является многоразрядным числом, то /// число записывается в переменную a, в err записывается false. /// Иначе, в переменную err записывается значение true, значение a неопределено. procedure readTLongReal(fi: text; var a: TLongReal; var err: boolean); /// Записывает многоразрядное число a в файл fo без перевода строки. procedure writeTLongReal(fo: text; a: TLongReal); /// Возвращает сумму многоразрядных чисел a и b в виде многоразрядного числа. /// В случае переполнения суммы значение самого старшего разряда отбрасывается. function addTLongReal(a, b: TLongReal): TLongReal; /// Возвращает модуль разности многоразрядных чисел a и b в виде многоразрядного числа. function absSubTLongReal(a, b: TLongReal): TLongReal; implementation const SIZE = 0; type DynStrArr = array of string; procedure TLongReal.init(); begin intPart[SIZE] := 1; intPart[1] := 0; fracPart[SIZE] := 1; fracPart[1] := 0 end; class function TLongReal.operator <(a, b: TLongReal): boolean; var i: integer; begin result := false; if (a.intPart[SIZE] > b.intPart[SIZE]) or (a = b) then result := false else if a.intPart[SIZE] < b.intPart[SIZE] then result := true else begin for i := a.intPart[SIZE] downto 1 do begin if a.intPart[i] < b.intPart[i] then begin result := true; exit; end else if a.intPart[i] > b.intPart[i] then begin result := false; exit; end; end; for i := 1 to min(a.fracPart[SIZE], b.fracPart[SIZE]) do begin if a.fracPart[i] < b.fracPart[i] then begin result := true; exit; end else if a.fracPart[i] > b.fracPart[i] then begin result := false; exit; end; end; end; end; class function TLongReal.operator =(a, b: TLongReal): boolean; var i: integer; begin result := true; if (a.intPart[SIZE] = b.intPart[SIZE]) and (a.fracPart[SIZE] = b.fracPart[SIZE]) then begin i := 1; while (i <= a.intPart[SIZE]) and result do if a.intPart[i] <> b.intPart[i] then result := false else i += 1; if result then begin i := 1; while (i <= a.fracPart[SIZE]) and result do if a.fracPart[i] <> b.fracPart[i] then result := false else i += 1; end; end else result := false; end; function isValidRealNum(s: string): boolean; var i, j: integer; begin result := true; for i := 1 to length(s) do if not (s[i] in ['0'..'9', DECIMAL_SEPARATOR]) then begin result := false; exit; end; i := pos(DECIMAL_SEPARATOR, s); if (i <> 0) and ( (i+1) <= length(s) ) then begin j := pos(DECIMAL_SEPARATOR, s, i+1); if j > i then result := false; end; end; function split(s, delim: string): DynStrArr; var prevDelimPos, currDelimPos: integer; begin prevDelimPos := 1 - length(delim); currDelimPos := pos(delim, s, prevDelimPos + length(delim)); setlength(result, 0); while currDelimPos <> 0 do begin setlength(result, length(result) + 1); result[high(result)] := copy(s, prevDelimPos + length(delim), currDelimPos - prevDelimPos - length(delim)); prevDelimPos := currDelimPos; currDelimPos := pos(delim, s, prevDelimPos + length(delim)); end; setlength(result, length(result) + 1); result[high(result)] := copy(s, prevDelimPos + length(delim), length(s) - prevDelimPos); end; procedure readTLongReal(fi: text; var a: TLongReal; var err: boolean); const INT = 0; FRAC = 1; var s: string; parts: DynStrArr; i, idx: integer; begin readln(fi, s); s := trim(s); if (length(s) > 0) and isValidRealNum(s) then begin parts := split(s, DECIMAL_SEPARATOR); if length(parts[INT]) > 0 then begin if length(parts[INT]) > (MAX_SIZE * DIGITS_IN_ONE_CELL) then begin err := true; exit; end; // обрезаем незначащие нули в целой части i := 1; while (i < length(parts[INT])) and (parts[INT][i] = '0') do i += 1; parts[INT] := copy(parts[INT], i, length(parts[INT])-i+1); // заполняем массив целой части a.intPart[SIZE] := ceil(length(parts[INT]) / DIGITS_IN_ONE_CELL); idx := length(parts[INT]) + 1; for i := 1 to a.intPart[SIZE] do begin idx -= DIGITS_IN_ONE_CELL; if idx > 0 then a.intPart[i] := strToInt( copy(parts[INT], idx, DIGITS_IN_ONE_CELL) ) else a.intPart[i] := strToInt( copy(parts[INT], 1, DIGITS_IN_ONE_CELL - abs(idx) - 1) ); end; end; // если есть дробная часть if (length(parts) = 2) and (length(parts[FRAC]) > 0) then begin if length(parts[FRAC]) > (MAX_SIZE * DIGITS_IN_ONE_CELL) then begin err := true; exit; end; // обрезаем незначащие нули дробной части i := length(parts[FRAC]); while (i > 1) and (parts[FRAC][i] = '0') do i -= 1; parts[FRAC] := copy(parts[FRAC], 1, i); // "выравнивание" нулями последней ячейки дробной части if (length(parts[FRAC]) mod DIGITS_IN_ONE_CELL) <> 0 then parts[FRAC] += '0'*(DIGITS_IN_ONE_CELL - (length(parts[FRAC]) mod DIGITS_IN_ONE_CELL)); // заполняем массив дробной части a.fracPart[SIZE] := ceil(length(parts[FRAC]) / DIGITS_IN_ONE_CELL); idx := 1; for i := 1 to a.fracPart[SIZE] do begin a.fracPart[i] := strToInt( copy(parts[FRAC], idx, DIGITS_IN_ONE_CELL) ); idx += DIGITS_IN_ONE_CELL; end; end; end else err := true; end; function digitsInNum(a: integer): integer; begin result := 0; if a = 0 then result := 1 else begin while a <> 0 do begin a := a div 10; result += 1; end; end; end; procedure writeTLongReal(fo: text; a: TLongReal); var i: integer; lastFracPartDigit: TDigit; divided: boolean; begin // выводим целую часть write(fo, a.intPart[ a.intPart[SIZE] ]); for i := a.intPart[SIZE] - 1 downto 1 do write(fo, '0'*(DIGITS_IN_ONE_CELL - digitsInNum(a.intPart[i])), a.intPart[i]); // выводим дробную часть write(fo, DECIMAL_SEPARATOR); for i := 1 to a.fracPart[SIZE] - 1 do write(fo, '0'*(DIGITS_IN_ONE_CELL - digitsInNum(a.fracPart[i])), a.fracPart[i]); // опускаем незначащие нули последнего разряда дробной части lastFracPartDigit := a.fracPart[ a.fracPart[SIZE] ]; divided := false; while (lastFracPartDigit <> 0) and ((lastFracPartDigit mod BASE) = 0) do begin lastFracPartDigit := lastFracPartDigit div BASE; divided := true; end; if (lastFracPartDigit = 0) or divided then write(fo, lastFracPartDigit) else write(fo, '0'*(DIGITS_IN_ONE_CELL - digitsInNum(lastFracPartDigit)), lastFracPartDigit); end; function addTLongReal(a, b: TLongReal): TLongReal; var i: integer; curr, carry: TDigit; begin // сумма дробных частей result.fracPart[SIZE] := max(a.fracPart[SIZE], b.fracPart[SIZE]); carry := 0; for i := result.fracPart[SIZE] downto 1 do begin curr := a.fracPart[i] + b.fracPart[i] + carry; carry := 0; if curr > MAX_NUM_IN_ONE_CELL then begin result.fracPart[i] := curr mod (MAX_NUM_IN_ONE_CELL + 1); carry := (curr - result.fracPart[i]) div (MAX_NUM_IN_ONE_CELL + 1); end else result.fracPart[i] := curr; end; // удаление нулевых ячеек из дробной части i := result.fracPart[SIZE]; while (result.fracPart[i] = 0) and (i >= 1) do begin result.fracPart[SIZE] -= 1; i -= 1; end; // сумма целых частей result.intPart[SIZE] := max(a.intPart[SIZE], b.intPart[SIZE]); for i := 1 to result.intPart[SIZE] do begin curr := a.intPart[i] + b.intPart[i] + carry; carry := 0; if curr > MAX_NUM_IN_ONE_CELL then begin result.intPart[i] := curr mod (MAX_NUM_IN_ONE_CELL + 1); carry := (curr - result.intPart[i]) div (MAX_NUM_IN_ONE_CELL + 1); end else result.intPart[i] := curr; end; if carry <> 0 then begin if result.intPart[SIZE] <> MAX_SIZE then begin result.intPart[SIZE] += 1; result.intPart[ result.intPart[SIZE] ] := carry; end else begin // если переполнение // удаляем незначащие нули целой части i := a.intPart[SIZE]; while (i > 1) and (result.intPart[i] = 0) do begin result.intPart[SIZE] -= 1; i -= 1; end; end; end; end; function absSubTLongReal(a, b: TLongReal): TLongReal; var i, j: integer; begin if a = b then begin result.init(); end else begin if a < b then swap(a, b); // b - a result.intPart[SIZE] := a.intPart[SIZE]; result.fracPart[SIZE] := max(a.fracPart[SIZE], b.fracPart[SIZE]); // разность дробных частей for i := max(a.fracPart[SIZE], b.fracPart[SIZE]) downto 1 do begin if a.fracPart[i] < b.fracPart[i] then begin j := i - 1; while (j >= 1) and (a.fracPart[j] = 0) do begin a.fracPart[j] := MAX_NUM_IN_ONE_CELL; j -= 1; end; if j < 1 then begin j := 1; while (j <= a.intPart[SIZE]) and (a.intPart[j] = 0) do begin a.intPart[j] := MAX_NUM_IN_ONE_CELL; j += 1; end; a.intPart[j] -= 1; end else a.fracPart[j] -= 1; result.fracPart[i] := a.fracPart[i] + MAX_NUM_IN_ONE_CELL + 1 - b.fracPart[i]; end else result.fracPart[i] := a.fracPart[i] - b.fracPart[i]; end; // разность целых частей for i := 1 to a.intPart[SIZE] do begin if a.intPart[i] < b.intPart[i] then begin j := i + 1; while (j <= a.intPart[SIZE]) and (a.intPart[j] = 0) do begin a.intPart[j] := MAX_NUM_IN_ONE_CELL; j += 1; end; a.intPart[j] -= 1; result.intPart[i] := a.intPart[i] + MAX_NUM_IN_ONE_CELL + 1 - b.intPart[i]; end else result.intPart[i] := a.intPart[i] - b.intPart[i]; end; // удаление незначащих нулей из целой части i := result.intPart[SIZE]; while (i > 1) and (result.intPart[i] = 0) do begin result.intPart[SIZE] -= 1; i -= 1; end; // удаление незначащих нулей из дробной части i := result.fracPart[SIZE]; while (i > 1) and (result.fracPart[i] = 0) do begin result.fracPart[SIZE] -= 1; i -= 1; end; end; end; end.
unit LS.AndroidTimer; interface uses System.Classes, Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge; type TAndroidTimer = class; TTimerRunnable = class(TJavaLocal, JRunnable) private FTimer: TAndroidTimer; public { JRunnable } procedure run; cdecl; public constructor Create(ATimer: TAndroidTimer); end; TAndroidTimer = class(TObject) private FEnabled: Boolean; FHandler: JHandler; FInterval: Integer; FRunnable: JRunnable; FOnTimer: TNotifyEvent; procedure DoTimer; procedure SetEnabled(const Value: Boolean); procedure SetInterval(const Value: Integer); procedure StartTimer; procedure StopTimer; procedure TimerEvent; public constructor Create; destructor Destroy; override; property Enabled: Boolean read FEnabled write SetEnabled; property Interval: Integer read FInterval write SetInterval; property OnTimer: TNotifyEvent read FOnTimer write FOnTimer; end; implementation // Note: // As per the documentation for postDelayed: // // https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long) // // The runnable's run method is called in the same thread as where postDelayed was called from, so there should be no // need to synchronize { TTimerRunnable } constructor TTimerRunnable.Create(ATimer: TAndroidTimer); begin inherited Create; FTimer := ATimer; end; procedure TTimerRunnable.run; begin FTimer.TimerEvent; end; { TAndroidTimer } constructor TAndroidTimer.Create; begin inherited; FInterval := 1000; FHandler := TJHandler.JavaClass.init; FRunnable := TTimerRunnable.Create(Self); end; destructor TAndroidTimer.Destroy; begin FHandler := nil; FRunnable := nil; inherited; end; procedure TAndroidTimer.DoTimer; begin if Assigned(FOnTimer) then FOnTimer(Self); end; procedure TAndroidTimer.SetEnabled(const Value: Boolean); begin if Value <> FEnabled then begin FEnabled := Value; if FEnabled then StartTimer else StopTimer; end; end; procedure TAndroidTimer.SetInterval(const Value: Integer); begin if Value <> Interval then begin if FEnabled then StopTimer; FInterval := Value; if FEnabled then StartTimer; end; end; procedure TAndroidTimer.StartTimer; begin FHandler.postDelayed(FRunnable, Interval); end; procedure TAndroidTimer.StopTimer; begin FHandler.removeCallbacks(FRunnable); end; procedure TAndroidTimer.TimerEvent; begin DoTimer; StartTimer; end; end.
unit StageOptionPartList; interface uses UIWappedPartUnit, System.Classes, FMX.Controls, UIWrapper_StageEditorUnit, StageOptionPart, SearchOption_Intf; type TStageOptionList = class(TAbsUIWrappedPart) private FChkAutoDetect: TCheckBox; FStageEditor: TUIWrapper_StageEditor; //FAutoStgOpt: TAbsSearchOptionPart; protected procedure ChkAutoDetectCheckedChange(Sender: TObject); public constructor Create(owner: TExpander; autoDetect: TCheckBox; stageEditor: TUIWrapper_StageEditor); destructor Destroy; //procedure Add(stageOpt: TStageOption); //procedure Remove(stageOpt: TStageOption); function Count: Integer; function GetStageOption(index: Integer): TStageOptionPart; function GetValues(key: String): String; override; procedure SetValues(key, val: String); override; end; implementation uses HashedOptionPart, System.SysUtils; { TStageOptionList } //procedure TStageOptionList.Add(stageOpt: TStageOption); //begin // FList.Add( @stageOpt ); //end; procedure TStageOptionList.ChkAutoDetectCheckedChange(Sender: TObject); begin FStageEditor.SetEnabled( not FChkAutoDetect.IsChecked ); end; function TStageOptionList.Count: Integer; begin result := FStageEditor.Count; end; constructor TStageOptionList.Create(owner: TExpander; autoDetect: TCheckBox; stageEditor: TUIWrapper_StageEditor); begin Init( owner ); FChkAutoDetect := autoDetect; FStageEditor := stageEditor; FChkAutoDetect.OnChange := ChkAutoDetectCheckedChange; end; //procedure TStageOptionList.Remove(stageOpt: TStageOption); //begin // FList.Remove( @stageOpt ); //end; procedure TStageOptionList.SetValues(key, val: String); var bSetVal: Boolean; begin bSetVal := false; if key = 'autodetect' then begin bSetVal := val = 'firebird'; FChkAutoDetect.IsChecked := bSetVal; FChkAutoDetect.Enabled := bSetVal; end; end; destructor TStageOptionList.Destroy; begin //FAutoStgOpt.Free; end; function TStageOptionList.GetStageOption(index: Integer): TStageOptionPart; begin result := FStageEditor.GetStageOption( index ); end; function TStageOptionList.GetValues(key: String): String; begin //result := FAutoStgOpt.GetValues( key ); end; end.
unit LevelFunctions; interface uses SysUtils, Dialogs, Functions, Classes; type TFieldType = (ftUndefined, ftFullSpace, ftEmpty, ftRed, ftYellow, ftGreen); TFieldState = (fsUndefined, fsLocked, fsAvailable, fsOccupied); TGameMode = (gmUndefined, gmNormal, gmDiagonal); TLevelError = (leUndefined, leNone, leInvalidElement, leEmptyBoard, leRowInvalidLength, leUnsupportedVersion, leUnsupportedMode); TGoalStatus = (gsUndefined, gsNoGoal, gsMultipleStonesRemaining, gsLastStoneInGoalRed, gsLastStoneInGoalYellow, gsLastStoneInGoalGreen, gsLastStoneOutsideGoal); TCoord = record X: integer; // fields. not pixels Y: integer; // fields. not pixels end; TField = record Indent: integer; // half steps FieldType: TFieldType; Goal: Boolean; Data: TObject; // can be used to hold VCL references. Is not cloned when calling CloneMatrix! function FieldState: TFieldState; end; TPlayGroundMatrix = record Fields: array of array of TField; public procedure InitFieldArray(width, height: integer); function MatrixHasGoal: boolean; function GoalStatus(StonesRemaining: integer): TGoalStatus; function GoalFieldType: TFieldType; function MatrixWorth: integer; procedure ClearMatrix(FreeVCL: boolean); function CloneMatrix: TPlayGroundMatrix; function FieldState(x, y: integer): TFieldState; overload; function FieldState(c: TCoord): TFieldState; overload; function CanJump(SourceX, SourceY, DestX, DestY: integer; DiagonalOK: boolean): boolean; overload; function CanJump(Source, Dest: TCoord; DiagonalOK: boolean): boolean; overload; function CanJump(SourceX, SourceY: integer; DiagonalOK: boolean): boolean; overload; function CanJump(Source: TCoord; DiagonalOK: boolean): boolean; overload; function CanJump(DiagonalOK: boolean): boolean; overload; function IndexToCoord(index: integer): TCoord; function CoordToIndex(coord: TCoord): integer; overload; function CoordToIndex(x, y: integer): integer; overload; function Width: integer; function Height: integer; end; TLevel = class(TObject) private FStringList: TStringList; procedure Load(ABoardFile: string); function GetGameMode: TGameMode; public constructor Create(ABoardFile: string); destructor Destroy; override; procedure FillPlaygroundMatrix(var matrix: TPlayGroundMatrix; ShowErrors: boolean); function CheckLevelIntegrity: TLevelError; overload; function CheckLevelIntegrity(ShowErrors: boolean): TLevelError; overload; property GameMode: TGameMode read GetGameMode; end; function FieldTypeWorth(t: TFieldType): integer; implementation uses Constants; function FieldTypeWorth(t: TFieldType): integer; begin if t = ftGreen then result := WORTH_GREEN else if t = ftYellow then result := WORTH_YELLOW else if t = ftRed then result := WORTH_RED else result := 0; end; { TPlayGroundMatrix } function TPlayGroundMatrix.MatrixHasGoal: boolean; var x, y: integer; begin result := false; for x := Low(Fields) to High(Fields) do begin for y := Low(Fields[x]) to High(Fields[x]) do begin result := result or Fields[x,y].Goal; end; end; end; function TPlayGroundMatrix.GoalStatus(StonesRemaining: integer): TGoalStatus; var ft: TFieldType; begin if not MatrixHasGoal then result := gsNoGoal else if StonesRemaining > 1 then Result := gsMultipleStonesRemaining else begin ft := GoalFieldType; if ft = ftRed then result := gsLastStoneInGoalRed else if ft = ftYellow then result := gsLastStoneInGoalYellow else if ft = ftGreen then result := gsLastStoneInGoalGreen else result := gsUndefined; end; end; function TPlayGroundMatrix.GoalFieldType: TFieldType; var x, y: integer; begin result := ftEmpty; // Damit der Compiler nicht meckert for x := Low(Fields) to High(Fields) do begin for y := Low(Fields[x]) to High(Fields[x]) do begin if Fields[x,y].Goal then result := Fields[x,y].FieldType end; end; end; function TPlayGroundMatrix.Height: integer; begin if Length(Fields) = 0 then result := 0 else result := Length(Fields[0]); end; function TPlayGroundMatrix.IndexToCoord(index: integer): TCoord; begin result.X := index mod Width; result.Y := index div Width; end; procedure TPlayGroundMatrix.InitFieldArray(width, height: integer); var x, y: integer; begin SetLength(Fields, width, height); for x := Low(Fields) to High(Fields) do begin for y := Low(Fields[x]) to High(Fields[x]) do begin Fields[x,y].FieldType := ftUndefined end; end; end; function TPlayGroundMatrix.MatrixWorth: integer; var x, y: integer; begin result := 0; for x := Low(Fields) to High(Fields) do begin for y := Low(Fields[x]) to High(Fields[x]) do begin Inc(result, FieldTypeWorth(Fields[x,y].FieldType)); end; end; end; function TPlayGroundMatrix.Width: integer; begin result := Length(Fields); end; function TPlayGroundMatrix.CanJump(Source: TCoord; DiagonalOK: boolean): boolean; begin result := CanJump(Source.X, Source.Y, DiagonalOK); end; function TPlayGroundMatrix.CanJump(Source, Dest: TCoord; DiagonalOK: boolean): boolean; begin result := CanJump(Source.X, Source.Y, Dest.X, Dest.Y, DiagonalOK); end; procedure TPlayGroundMatrix.ClearMatrix(FreeVCL: boolean); var x, y: integer; begin if FreeVCL then begin for x := Low(Fields) to High(Fields) do begin for y := Low(Fields[x]) to High(Fields[x]) do begin if Assigned(Fields[x,y].Data) then Fields[x,y].Data.Free; end; end; end; SetLength(Fields, 0, 0); end; function TPlayGroundMatrix.CloneMatrix: TPlayGroundMatrix; var x, y: integer; begin SetLength(result.Fields, Length(Fields)); for x := Low(Fields) to High(Fields) do begin SetLength(result.Fields[x], Length(Fields[x])); for y := Low(Fields[x]) to High(Fields[x]) do begin result.Fields[x,y].FieldType := Fields[x,y].FieldType; result.Fields[x,y].Goal := Fields[x,y].Goal; result.Fields[x,y].Data := Fields[x,y].Data; end; end; end; function TPlayGroundMatrix.CoordToIndex(x, y: integer): integer; begin result := x + y * Width; end; function TPlayGroundMatrix.FieldState(c: TCoord): TFieldState; begin result := FieldState(c.X, c.Y); end; function TPlayGroundMatrix.CoordToIndex(coord: TCoord): integer; begin result := CoordToIndex(coord.X, coord.Y); end; function TPlayGroundMatrix.FieldState(x, y: integer): TFieldState; begin result := fsUndefined; if (x < Low(Fields)) or (x > High(Fields)) then exit; if (y < Low(Fields[x])) or (y > High(Fields[x])) then exit; result := Fields[x,y].FieldState; end; function TPlayGroundMatrix.CanJump(SourceX, SourceY, DestX, DestY: integer; DiagonalOK: boolean): boolean; begin result := false; // Check 1: Ist das Zielfeld überhaupt leer? if FieldState(DestX, DestY) <> fsAvailable then exit; // Check 2: Befindet sich ein Stein zwischen Source und Destination und ist der Abstand 2? if DiagonalOK then begin if (SourceX-2 = DestX) and (SourceY-2 = DestY) and (FieldState(SourceX-1, SourceY-1) = fsOccupied) then result := true; if (SourceX-2 = DestX) and (SourceY+2 = DestY) and (FieldState(SourceX-1, SourceY+1) = fsOccupied) then result := true; if (SourceX+2 = DestX) and (SourceY-2 = DestY) and (FieldState(SourceX+1, SourceY-1) = fsOccupied) then result := true; if (SourceX+2 = DestX) and (SourceY+2 = DestY) and (FieldState(SourceX+1, SourceY+1) = fsOccupied) then result := true; end; if (SourceX+2 = DestX) and (SourceY = DestY) and (FieldState(SourceX+1, SourceY ) = fsOccupied) then result := true; if (SourceX-2 = DestX) and (SourceY = DestY) and (FieldState(SourceX-1, SourceY ) = fsOccupied) then result := true; if (SourceX = DestX) and (SourceY+2 = DestY) and (FieldState(SourceX , SourceY+1) = fsOccupied) then result := true; if (SourceX = DestX) and (SourceY-2 = DestY) and (FieldState(SourceX , SourceY-1) = fsOccupied) then result := true; end; function TPlayGroundMatrix.CanJump(SourceX, SourceY: integer; DiagonalOK: boolean): boolean; begin if FieldState(SourceX, SourceY) <> fsOccupied then begin result := false; exit; end; result := true; if CanJump(SourceX, SourceY, SourceX+2, SourceY, DiagonalOK) then exit; if CanJump(SourceX, SourceY, SourceX-2, SourceY, DiagonalOK) then exit; if CanJump(SourceX, SourceY, SourceX, SourceY+2, DiagonalOK) then exit; if CanJump(SourceX, SourceY, SourceX, SourceY-2, DiagonalOK) then exit; if DiagonalOK then begin if CanJump(SourceX, SourceY, SourceX-2, SourceY-2, DiagonalOK) then exit; if CanJump(SourceX, SourceY, SourceX+2, SourceY-2, DiagonalOK) then exit; if CanJump(SourceX, SourceY, SourceX-2, SourceY+2, DiagonalOK) then exit; if CanJump(SourceX, SourceY, SourceX+2, SourceY+2, DiagonalOK) then exit; end; result := false; end; function TPlayGroundMatrix.CanJump(DiagonalOK: boolean): boolean; var x, y: integer; begin result := false; for x := Low(Fields) to High(Fields) do begin for y := Low(Fields[x]) to High(Fields[x]) do begin if CanJump(x, y, DiagonalOK) then begin result := true; break; end; if result then break; end; end; end; { TLevel } const NUM_HEADERS = 2; constructor TLevel.Create(ABoardFile: string); begin inherited Create; FStringList := TStringList.Create; Load(ABoardFile); end; destructor TLevel.Destroy; begin FreeAndNil(FStringList); inherited; end; function TLevel.GetGameMode: TGameMode; begin if LowerCase(FStringList.Strings[1]) = 'mode: normal' then result := gmNormal else if LowerCase(FStringList.Strings[1]) = 'mode: diagonal' then result := gmDiagonal else result := gmUndefined; end; procedure TLevel.Load(ABoardFile: string); var i: Integer; begin FStringList.Clear; FStringList.LoadFromFile(ABoardFile); // Remove whitespaces and empty lines for i := FStringList.Count-1 downto NUM_HEADERS do begin FStringList.Strings[i] := StringReplace(FStringList.Strings[i], ' ', '', [rfReplaceAll]); if FStringList.Strings[i] = '' then FStringList.Delete(i); end; end; procedure TLevel.FillPlaygroundMatrix(var matrix: TPlayGroundMatrix; ShowErrors: boolean); var i: integer; t: TFieldType; err: TLevelError; y: Integer; x: Integer; Line: string; lch, uch: char; ch: char; width: Integer; height: Integer; lineIndent: Integer; begin // Zuerst nach Fehlern suchen err := CheckLevelIntegrity(ShowErrors); if err <> leNone then exit; // Breite feststellen if FStringList.Count > NUM_HEADERS then begin Line := FStringList.Strings[NUM_HEADERS]; Line := StringReplace(Line, '.', '', [rfReplaceAll]); width := Length(Line); end else width := 0; // Höhe feststellen height := FStringList.Count - NUM_HEADERS; // Nun Matrix aufbauen matrix.ClearMatrix(true); matrix.InitFieldArray(width, height); for i := NUM_HEADERS to FStringList.Count-1 do begin y := i - NUM_HEADERS; Line := FStringList.Strings[i]; lineIndent := DotsAtBeginning(Line) - DotsAtEnd(Line); Line := StringReplace(Line, '.', '', [rfReplaceAll]); for x := 0 to Length(Line)-1 do begin ch := Line[x+1]; lch := LowerCase(ch)[1]; uch := UpperCase(ch)[1]; t := ftUndefined; case lch of '*': t := ftFullSpace; 'e': t := ftEmpty; 'r': t := ftRed; 'y': t := ftYellow; 'g': t := ftGreen; end; matrix.Fields[x,y].Indent := lineIndent; matrix.Fields[x,y].FieldType := t; matrix.Fields[x,y].Goal := (ch = uch) and (ch <> lch); end; end; end; function TLevel.CheckLevelIntegrity(ShowErrors: boolean): TLevelError; resourcestring LNG_LVL_INVALID_ELEMENT = 'Level invalid: There are invalid elements in the file.'+#13#10#13#10+'Valid elements are r/R, y/Y, g/G, e/E, . and *.'; LNG_LVL_UNSUPPORTED_VERSION = 'Level format invalid: Version not supported.'; LNG_LVL_UNSUPPORTED_MODE = 'Level format invalid: Mode not supported.'; LNG_LVL_EMPTY_BOARD = 'Level invalid: Board is empty.'; LNG_LVL_INVALID_LENGTH = 'Level invalid: Lines don''t have an equal amount of elements.'; begin result := CheckLevelIntegrity; if ShowErrors then begin case result of leNone: ; leInvalidElement: MessageDlg(LNG_LVL_INVALID_ELEMENT, mtError, [mbOk], 0); leUnsupportedVersion: MessageDlg(LNG_LVL_UNSUPPORTED_VERSION, mtError, [mbOk], 0); leUnsupportedMode: MessageDlg(LNG_LVL_UNSUPPORTED_MODE, mtError, [mbOk], 0); leEmptyBoard: MessageDlg(LNG_LVL_EMPTY_BOARD, mtError, [mbOk], 0); leRowInvalidLength: MessageDlg(LNG_LVL_INVALID_LENGTH, mtError, [mbOk], 0); end; end; end; function TLevel.CheckLevelIntegrity: TLevelError; var tmp: string; i: Integer; Line: string; firstLine: string; thisLine: string; begin result := leNone; // Check 1: Ist der Header OK? if LowerCase(FStringList.Strings[0]) <> 'version 2' then begin result := leUnsupportedVersion; exit; end; if ((LowerCase(FStringList.Strings[1]) <> 'mode: normal') and (LowerCase(FStringList.Strings[1]) <> 'mode: diagonal')) then begin result := leUnsupportedMode; exit; end; // Check 2: Ist das Brett leer? tmp := ''; for i := NUM_HEADERS to FStringList.Count-1 do tmp := tmp + FStringList.Strings[i]; if Trim(StringReplace(tmp, '.', '', [rfReplaceAll])) = '' then begin result := leEmptyBoard; exit; end; // Check 3: Geht das Level nicht in einem Quadrat oder Rechteck auf? firstLine := StringReplace(FStringList.Strings[NUM_HEADERS], '.', '', [rfReplaceAll]); for i := NUM_HEADERS to FStringList.Count-1 do begin thisLine := StringReplace(FStringList.Strings[i], '.', '', [rfReplaceAll]); if Length(thisLine) <> Length(firstLine) then begin result := leRowInvalidLength; // at row y = i-NUM_HEADERS exit; end; end; // Check 4: Gibt es ungültige Elemente in den Zeilen? for i := NUM_HEADERS to FStringList.Count-1 do begin Line := FStringList.Strings[i]; Line := StringReplace(Line, '.', '', [rfReplaceAll]); Line := StringReplace(Line, '*', '', [rfReplaceAll]); Line := StringReplace(Line, 'r', '', [rfReplaceAll, rfIgnoreCase]); Line := StringReplace(Line, 'y', '', [rfReplaceAll, rfIgnoreCase]); Line := StringReplace(Line, 'g', '', [rfReplaceAll, rfIgnoreCase]); Line := StringReplace(Line, 'e', '', [rfReplaceAll, rfIgnoreCase]); if Length(Line) > 0 then begin result := leInvalidElement; // at row y = i-NUM_HEADERS Exit; end; end; // Check 5: Kann im Level gesprungen werden? { Wird hier nicht abgeprüft, da dafür zuerst der PlayGround gebaut sein muss. Es ist außerdem eher ein logischer Fehler, kein Fehler in der Levelstruktur! } end; { TField } function TField.FieldState: TFieldState; begin result := fsUndefined; case FieldType of ftFullSpace: result := fsLocked; ftEmpty: result := fsAvailable; ftGreen: result := fsOccupied; ftYellow: result := fsOccupied; ftRed: result := fsOccupied; end; end; end.
unit Parsers.Excel.Resources.KSR; interface uses SysUtils, Classes, GsDocument, Parsers.Excel, Parsers.Abstract, StrUtils; type TResourceExcelRow = class(TExcelRowWrapper) public function GetOKPCode: string; function GetCaption: string; function GetMeasure: string; function IsChapter: Boolean; function IsRow: Boolean; function GetChapterPriority(Caption: string): Integer; function GetChapterCode: string; function GetRowCode: string; end; TResourceKRSParser = class (TExcelParser<TGsDocument, TResourceExcelRow>) private FMode: Integer; FChapter: TGsAbstractContainer; protected function DoGetDocument: TGsDocument; override; procedure DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); override; procedure DoParseRow(AExcelRow: TResourceExcelRow; ARowIndex: Integer; ADocument: TGsDocument); override; function GetDescription: string; override; function GetLogFileName: string; override; public constructor Create(AMode: Integer); reintroduce; end; implementation const FM_MATERIAL = 0; FM_MACHINE = 1; { TResourceExcelRow } function TResourceExcelRow.GetCaption: string; begin Result := Self.FilledValues[2]; end; function TResourceExcelRow.GetChapterCode: string; var p: Integer; I: Integer; Caption: string; begin Result := ''; Caption := FirstValue; p := Pos(':', Caption); if (p > 0) then begin for I := p downto 1 do if (Caption[I] = '.') or (Caption[I] = ' ') then Break; Result := System.Copy(Caption, I + 1, P - I - 1); end; end; function TResourceExcelRow.GetChapterPriority(Caption: string): Integer; begin if AnsiStartsText('Книга ', Caption) then Result := CP_PART else if AnsiStartsText('Часть ', Caption) then Result := CP_PART + 1 else if AnsiStartsText('Раздел ', Caption) then Result := CP_PART + 2 else if AnsiStartsText('Группа ', Caption) then Result := CP_PART + 3 else Result := CP_STATIC; end; function TResourceExcelRow.GetMeasure: string; begin Result := Self.FilledValues[3]; end; function TResourceExcelRow.GetOKPCode: string; begin Result := Self.FilledValues[0]; end; function TResourceExcelRow.GetRowCode: string; begin Result := FilledValues[1]; end; function TResourceExcelRow.IsChapter: Boolean; begin Result := Self.FilledValuesCount = 1; end; function TResourceExcelRow.IsRow: Boolean; var S: TStringList; begin S := TStringList.Create; try S.Delimiter := '.'; S.DelimitedText := FilledValues[0]; Result := S.Count = 3; finally S.Free; end; end; { TResourceKRSParser } constructor TResourceKRSParser.Create(AMode: Integer); begin inherited Create(); FMode := AMode; end; function TResourceKRSParser.DoGetDocument: TGsDocument; begin Result := TGsDocument.Create; Result.DocumentType := dtBaseData; FChapter := Result.Chapters; case FMode of FM_MATERIAL: Result.BaseDataType := bdtMaterial; FM_MACHINE: Result.BaseDataType := bdtMachine; end; Result.TypeName := ''; end; procedure TResourceKRSParser.DoParseRow(AExcelRow: TResourceExcelRow; ARowIndex: Integer; ADocument: TGsDocument); var Row: TGsRow; begin if AExcelRow.IsChapter then begin FChapter := TGsDocument.CreateChapterByPriority(FChapter, AExcelRow.GetChapterPriority(AExcelRow.FirstValue)); TGsChapter(FChapter).Code := AExcelRow.GetChapterCode(); TGsChapter(FChapter).Caption := AExcelRow.FirstValue; TGsChapter(FChapter).ChapterType := ctChapter; TGsChapter(FChapter).NumberFormative := False; end else if AExcelRow.IsRow then begin Row := TGsRow.Create(ADocument); Row.Code := AExcelRow.GetRowCode; Row.Caption := AExcelRow.GetCaption; Row.Measure := AExcelRow.GetMeasure; Row.Attributes[Ord(eaOKP)] := AExcelRow.GetOKPCode; FChapter.Add(Row); end; end; procedure TResourceKRSParser.DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); begin inherited DoParseSheet(AExcelSheet, ADocument); ADocument.SaveToFile(ChangeFileExt(AExcelSheet.Owner.FileName, '-'+AExcelSheet.Name + '.xml')); end; function TResourceKRSParser.GetDescription: string; begin Result := 'Импорт ресурсов для базы ГЭСН в новой кодировке КСР'; end; function TResourceKRSParser.GetLogFileName: string; begin Result := 'import.resources.ksr.log'; end; end.
unit BowlingScore; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GameUnit, ExtCtrls; type TfrmBowlingGame = class(TForm) Memo1: TMemo; Label1: TLabel; btnNewGame: TButton; gbAddPlayer: TGroupBox; edAddPlayer: TLabeledEdit; btnAddPlayer: TButton; gbScoring: TGroupBox; cbxPlayers: TComboBox; Label2: TLabel; edNoPins: TLabeledEdit; btnAddScore: TButton; btGetAllStats: TButton; cbxRandom: TCheckBox; cbxDisplayInSingleLine: TCheckBox; cbxDisplayLastTwoFrames: TCheckBox; procedure btnNewGameClick(Sender: TObject); procedure btnAddPlayerClick(Sender: TObject); procedure btnAddScoreClick(Sender: TObject); procedure gbAddPlayerExit(Sender: TObject); procedure btGetAllStatsClick(Sender: TObject); procedure edAddPlayerEnter(Sender: TObject); procedure edNoPinsEnter(Sender: TObject); procedure cbxRandomClick(Sender: TObject); private { Private declarations } ATSBowlingGame: IBowlingGame; procedure AdvancePlayer; procedure IsGameOver; public { Public declarations } end; var frmBowlingGame: TfrmBowlingGame; implementation {$R *.dfm} procedure TfrmBowlingGame.btnAddPlayerClick(Sender: TObject); var iIndex: Integer; begin if Length(Trim(edAddPlayer.Text))>0 then begin cbxDisplayInSingleLine.Enabled := False; ATSBowlingGame.AddPlayer(edAddPlayer.Text, cbxDisplayInSingleLine.Checked); iIndex := cbxPlayers.Items.Add(edAddPlayer.Text); edAddPLayer.Text := ''; cbxPlayers.ItemIndex := iIndex; gbScoring.Enabled := True; end; end; procedure TfrmBowlingGame.btnAddScoreClick(Sender: TObject); var NoPins: Integer; bDone: Boolean; iTry: Integer; begin gbAddPlayer.Enabled := False; ATSBowlingGame.SetDisplayLastTwoFrames(cbxDisplayLastTwoFrames.Checked); if cbxRandom.Checked then begin bDone := False; iTry := 0; repeat Inc(iTry); NoPins := 1+Random(10); try OutputDebugString(pChar(Format('Tries %d) NoPins: %d', [iTry, NoPins]))); ATSBowlingGame.AddRoll(cbxPlayers.Text, NoPins); edNoPins.Text := ''; Memo1.Lines.Add(ATSBowlingGame.GetPlayersLastFrameStats(cbxPlayers.ItemIndex)); bDone := True; except // do nothing end; until (iTry = 100) oR bDone; if bDone then begin AdvancePlayer; IsGameOver; if gbScoring.Enabled then FocusControl(edNoPins); SendMessage(Memo1.Handle, EM_LINESCROLL, 0,Memo1.Lines.Count); end; end else if Length(Trim(edNoPins.Text))>0 then begin NoPins := StrToIntDef(edNoPins.Text, -1); if (NoPins=-1) then begin edNoPins.Text := 'Number please'; edNoPins.SelectAll; end else begin try ATSBowlingGame.AddRoll(cbxPlayers.Text, NoPins); edNoPins.Text := ''; Memo1.Lines.Add(ATSBowlingGame.GetPlayersLastFrameStats(cbxPlayers.ItemIndex)); finally AdvancePlayer; IsGameOver; if gbScoring.Enabled then FocusControl(edNoPins); SendMessage(Memo1.Handle, EM_LINESCROLL, 0,Memo1.Lines.Count); end; end; end; end; procedure TfrmBowlingGame.btnNewGameClick(Sender: TObject); begin if NOT Assigned(ATSBowlingGame) then ATSBowlingGame := BowlingGame; ATSBowlingGame.StartGame; cbxDisplayInSingleLine.Enabled := True; gbAddPlayer.Enabled := True; Memo1.Clear; edAddPlayer.Text := ''; edNoPins.Text := ''; cbxPlayers.Clear; btnAddPlayer.Default := true; FocusControl(edAddPlayer) end; procedure TfrmBowlingGame.cbxRandomClick(Sender: TObject); var hours, mins, secs, milliSecs : Word; begin DecodeTime(now, hours, mins, secs, milliSecs); RandSeed := milliSecs; end; procedure TfrmBowlingGame.btGetAllStatsClick(Sender: TObject); begin ATSBowlingGame.SetDisplayLastTwoFrames(cbxDisplayLastTwoFrames.Checked); Memo1.Lines.Text := ATSBowlingGame.GetAllPlayersStats; Memo1.Lines.Add('Player totals:'); Memo1.Lines.Add(ATSBowlingGame.GetAllPlayersTotals); end; procedure TfrmBowlingGame.edAddPlayerEnter(Sender: TObject); begin btnAddPlayer.Default := true; FocusControl(edAddPlayer) end; procedure TfrmBowlingGame.edNoPinsEnter(Sender: TObject); begin btnAddPlayer.Default := False; btnAddScore.Default := True; FocusControl(edNoPins); end; procedure TfrmBowlingGame.AdvancePlayer; var FrameNo: Integer; begin if ATSBowlingGame.IsCurrentFrameComplete(cbxPlayers.Text) then begin if ((cbxPlayers.ItemIndex + 1) = cbxPlayers.Items.Count) then cbxPlayers.ItemIndex := 0 else cbxPlayers.ItemIndex := cbxPlayers.ItemIndex + 1; FrameNo := ATSBowlingGame.GetPlayersCurrentFrameNo(cbxPlayers.Text)+1; if FrameNo > 10 then FrameNo := 10; gbScoring.Caption := Format('Scoring frame: %d', [FrameNo]); end; end; procedure TfrmBowlingGame.IsGameOver; var NoGamesOver: Integer; bPlayerGameOver: Boolean; begin if ATSBowlingGame.IsGameOver(cbxPlayers.ItemIndex) then begin NoGamesOver := 1; bPlayerGameOver := false; repeat if ((cbxPlayers.ItemIndex + 1) = cbxPlayers.Items.Count) then begin cbxPlayers.ItemIndex := 0; NoGamesOver := 0; end else cbxPlayers.ItemIndex := cbxPlayers.ItemIndex + 1; bPlayerGameOver := ATSBowlingGame.IsGameOver(cbxPlayers.ItemIndex); if bPlayerGameOver then Inc(NoGamesOver); Application.ProcessMessages; until (not bPlayerGameOver) or (NoGamesOver >= (cbxPlayers.Items.Count)); if NoGamesOver = (cbxPlayers.Items.Count) then begin edNoPins.Text := 'Game Over'; Memo1.Lines.Add(edNoPins.Text); Memo1.Lines.Add(Format('%sPlayer totals:', [#$0D#$0A])); Memo1.Lines.Add(ATSBowlingGame.GetAllPlayersTotals); gbScoring.Enabled := False; end; end; end; procedure TfrmBowlingGame.gbAddPlayerExit(Sender: TObject); begin cbxPlayers.ItemIndex := 0; gbScoring.Caption := Format('Scoring frame: %d', [ATSBowlingGame.GetPlayersCurrentFrameNo(cbxPlayers.Text)+1]); if gbScoring.Enabled then FocusControl(edNoPins); end; end.
unit BrowseFolder platform; {.$DEFINE USE_FILECTRL_FUNCTIONS} // not recommended! {$DEFINE USE_FORMS} // important interface uses Windows, SysUtils, ShlObj, ActiveX {$IFDEF USE_FILECTRL_FUNCTIONS}, FileCtrl{$ENDIF} {$IFDEF USE_FORMS}, Forms{$ENDIF}; function MySelectDirectory(AMsg: string): string; implementation {$IFNDEF USE_FILECTRL_FUNCTIONS} { This code shows the SelectDirectory dialog with additional expansions: - an edit box, where the user can type the path name, - also files can appear in the list, - a button to create new directories. Dieser Code zeigt den SelectDirectory-Dialog mit zusätzlichen Erweiterungen: - eine Edit-Box, wo der Benutzer den Verzeichnisnamen eingeben kann, - auch Dateien können in der Liste angezeigt werden, - eine Schaltfläche zum Erstellen neuer Verzeichnisse. Ref: http://www.swissdelphicenter.ch/de/showcode.php?id=1802 MODIFIED for AutoSFX! } function AdvSelectDirectory(const Caption: string; const Root: WideString; var Directory: string; EditBox: Boolean = False; ShowFiles: Boolean = False; AllowCreateDirs: Boolean = True): Boolean; // callback function that is called when the dialog has been initialized //or a new directory has been selected // Callback-Funktion, die aufgerufen wird, wenn der Dialog initialisiert oder //ein neues Verzeichnis selektiert wurde function SelectDirCB(Wnd: HWND; uMsg: UINT; lParam, lpData: lParam): Integer; stdcall; var PathName: array[0..MAX_PATH] of Char; begin case uMsg of // BFFM_INITIALIZED: SendMessage(Wnd, BFFM_SETSELECTION, Ord(True), Integer(lpData)); // include the following comment into your code if you want to react on the //event that is called when a new directory has been selected // binde den folgenden Kommentar in deinen Code ein, wenn du auf das Ereignis //reagieren willst, das aufgerufen wird, wenn ein neues Verzeichnis selektiert wurde BFFM_SELCHANGED: begin SHGetPathFromIDList(PItemIDList(lParam), @PathName); if PathName = '' then begin SendMessage(Wnd, BFFM_ENABLEOK, 0, 0); end; // the directory "PathName" has been selected // das Verzeichnis "PathName" wurde selektiert end; end; Result := 0; end; var {$IFDEF USE_FORMS} WindowList: Pointer; {$ENDIF} BrowseInfo: TBrowseInfo; Buffer: PChar; RootItemIDList, ItemIDList: PItemIDList; ShellMalloc: IMalloc; IDesktopFolder: IShellFolder; Eaten, Flags: LongWord; const // necessary for some of the additional expansions // notwendig für einige der zusätzlichen Erweiterungen BIF_USENEWUI = $0040; BIF_NOCREATEDIRS = $0200; begin Result := False; if not DirectoryExists(Directory) then Directory := ''; FillChar(BrowseInfo, SizeOf(BrowseInfo), 0); if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then begin Buffer := ShellMalloc.Alloc(MAX_PATH); try RootItemIDList := nil; if Root <> '' then begin SHGetDesktopFolder(IDesktopFolder); IDesktopFolder.ParseDisplayName({$IFDEF USE_FORMS}Application.Handle{$ELSE}0{$ENDIF}, nil, POleStr(Root), Eaten, RootItemIDList, Flags); end; OleInitialize(nil); with BrowseInfo do begin hwndOwner := {$IFDEF USE_FORMS}Application.Handle{$ELSE}0{$ENDIF}; pidlRoot := RootItemIDList; pszDisplayName := Buffer; lpszTitle := PChar(Caption); // defines how the dialog will appear: // legt fest, wie der Dialog erscheint: ulFlags := BIF_RETURNONLYFSDIRS or BIF_USENEWUI or BIF_EDITBOX * Ord(EditBox) or BIF_BROWSEINCLUDEFILES * Ord(ShowFiles) or BIF_NOCREATEDIRS * Ord(not AllowCreateDirs); lpfn := @SelectDirCB; if Directory <> '' then lParam := Integer(PChar(Directory)); end; {$IFDEF USE_FORMS} WindowList := DisableTaskWindows(0); {$ENDIF} try ItemIDList := ShBrowseForFolder(BrowseInfo); finally {$IFDEF USE_FORMS} EnableTaskWindows(WindowList); {$ENDIF} end; Result := ItemIDList <> nil; if Result then begin ShGetPathFromIDList(ItemIDList, Buffer); ShellMalloc.Free(ItemIDList); Directory := Buffer; end; finally ShellMalloc.Free(Buffer); end; end; end; {$ENDIF} function MySelectDirectory(AMsg: string): string; begin {$IFNDEF USE_FILECTRL_FUNCTIONS} if not AdvSelectDirectory(AMsg, '', result, False, False, True) then begin result := ''; Exit; end; {$ELSE} // Nicht so gut: "Arbeitsplatz" etc nicht ausgegraut if not SelectDirectory(AMsg, '', result, [sdNewUi, sdNewFolder]) then begin result := ''; Exit; end; {$ENDIF} // Optional result := IncludeTrailingPathDelimiter(result); result := ExpandUNCFileName(result); end; end.
object fmGrepSearch: TfmGrepSearch Left = 311 Top = 189 BorderStyle = bsDialog Caption = 'Grep Search' ClientHeight = 563 ClientWidth = 486 Color = clBtnFace Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Tahoma' Font.Style = [] KeyPreview = True OldCreateOrder = True Position = poScreenCenter Scaled = False ShowHint = True OnClose = FormClose OnCreate = FormCreate DesignSize = ( 486 563) PixelsPerInch = 96 TextHeight = 14 object lblFind: TLabel Left = 14 Top = 12 Width = 66 Height = 14 Alignment = taRightJustify Caption = '&Text to find' FocusControl = cbText end object cbText: TComboBox Left = 85 Top = 8 Width = 394 Height = 22 Anchors = [akLeft, akTop, akRight] DropDownCount = 15 ItemHeight = 14 TabOrder = 0 OnKeyDown = ComboKeyDown end object gbxOptions: TGroupBox Left = 8 Top = 40 Width = 227 Height = 145 Caption = 'Options' TabOrder = 1 DesignSize = ( 227 145) object cbCaseSensitive: TCheckBox Left = 10 Top = 18 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = '&Case sensitive' TabOrder = 0 end object cbForms: TCheckBox Left = 10 Top = 58 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Search for&m files' TabOrder = 2 end object cbWholeWord: TCheckBox Left = 10 Top = 38 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = '&Whole word' TabOrder = 1 end object cbRegEx: TCheckBox Left = 10 Top = 98 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Regular e&xpression' TabOrder = 4 end object cbSQLFiles: TCheckBox Left = 10 Top = 78 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Search S&QL files' TabOrder = 3 end end object gbxWhere: TGroupBox Left = 252 Top = 40 Width = 227 Height = 145 Anchors = [akLeft, akTop, akRight] Caption = 'Files' TabOrder = 2 DesignSize = ( 227 145) object rbAllProjFiles: TRadioButton Left = 10 Top = 58 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'All files in &project' Checked = True TabOrder = 2 TabStop = True OnClick = rbDirectoriesClick end object rbOpenFiles: TRadioButton Left = 10 Top = 78 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = '&Open project files' TabOrder = 3 OnClick = rbDirectoriesClick end object rbDirectories: TRadioButton Left = 10 Top = 98 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = '&Directories' TabOrder = 4 OnClick = rbDirectoriesClick end object rbCurrentOnly: TRadioButton Left = 10 Top = 18 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Current &file' TabOrder = 0 OnClick = rbDirectoriesClick end object rbAllProjGroupFiles: TRadioButton Left = 10 Top = 38 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'All files in project &group' TabOrder = 1 OnClick = rbDirectoriesClick end object rbResults: TRadioButton Left = 10 Top = 119 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Pre&vious search result files' TabOrder = 5 OnClick = rbDirectoriesClick end end object gbxContentTypes: TGroupBox Left = 8 Top = 192 Width = 227 Height = 102 Caption = 'Delphi Code Content Types' TabOrder = 3 DesignSize = ( 227 102) object cbGrepCode: TCheckBox Left = 10 Top = 18 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Code' TabOrder = 0 OnClick = cbGrepCodeClick end object cbGrepStrings: TCheckBox Left = 10 Top = 38 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Strings' TabOrder = 1 OnClick = cbGrepStringsClick end object cbGrepComments: TCheckBox Left = 10 Top = 58 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Comments' TabOrder = 2 OnClick = cbGrepCommentsClick end end object gbxUnitSections: TGroupBox Left = 252 Top = 192 Width = 227 Height = 102 Anchors = [akLeft, akTop, akRight] Caption = 'Delphi Code Sections' TabOrder = 4 DesignSize = ( 227 102) object cbSectionInterface: TCheckBox Left = 10 Top = 18 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Interface' TabOrder = 0 OnClick = cbSectionInterfaceClick end object cbSectionImplementation: TCheckBox Left = 10 Top = 38 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Implementation' TabOrder = 1 OnClick = cbSectionImplementationClick end object cbSectionInitialization: TCheckBox Left = 10 Top = 58 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Initialization' TabOrder = 2 OnClick = cbSectionInitializationClick end object cbSectionFinalization: TCheckBox Left = 10 Top = 78 Width = 210 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Finalization' TabOrder = 3 OnClick = cbSectionFinalizationClick end end object gbxDirectories: TGroupBox Left = 8 Top = 300 Width = 471 Height = 133 Anchors = [akLeft, akTop, akRight] Caption = 'Directory Search' TabOrder = 5 DesignSize = ( 471 133) object lblMasks: TLabel Left = 25 Top = 84 Width = 53 Height = 14 Alignment = taRightJustify Caption = 'File mas&ks' FocusControl = cbMasks end object lblDirectory: TLabel Left = 21 Top = 26 Width = 57 Height = 14 Alignment = taRightJustify Caption = 'Di&rectories' FocusControl = cbDirectory end object lblExcludeDirs: TLabel Left = 13 Top = 55 Width = 65 Height = 14 Alignment = taRightJustify Caption = 'Exclude Dirs' FocusControl = cbExcludedDirs end object cbMasks: TComboBox Left = 84 Top = 80 Width = 352 Height = 22 Anchors = [akLeft, akTop, akRight] DropDownCount = 15 ItemHeight = 14 TabOrder = 3 OnKeyDown = ComboKeyDown end object cbInclude: TCheckBox Left = 84 Top = 106 Width = 376 Height = 17 Anchors = [akLeft, akTop, akRight] Caption = 'Search su&bdirectories' TabOrder = 4 end object cbDirectory: TComboBox Left = 84 Top = 22 Width = 352 Height = 22 Anchors = [akLeft, akTop, akRight] DropDownCount = 15 ItemHeight = 14 TabOrder = 0 OnDropDown = cbDirectoryDropDown OnKeyDown = ComboKeyDown end object btnBrowse: TButton Left = 437 Top = 22 Width = 20 Height = 20 Hint = 'Select Directory' Anchors = [akTop, akRight] Caption = '...' ParentShowHint = False ShowHint = True TabOrder = 1 OnClick = btnBrowseClick end object cbExcludedDirs: TComboBox Left = 84 Top = 51 Width = 352 Height = 22 Anchors = [akLeft, akTop, akRight] DropDownCount = 15 ItemHeight = 14 TabOrder = 2 OnDropDown = cbExcludedDirsDropDown OnKeyDown = ComboKeyDown end end object pnlBottom: TPanel Left = 0 Top = 530 Width = 486 Height = 33 Align = alBottom TabOrder = 7 DesignSize = ( 486 33) object btnOK: TButton Left = 241 Top = 2 Width = 75 Height = 25 Anchors = [akTop, akRight] Caption = 'OK' Default = True TabOrder = 2 OnClick = btnOKClick end object btnCancel: TButton Left = 321 Top = 2 Width = 75 Height = 25 Anchors = [akTop, akRight] Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 3 end object btnHelp: TButton Left = 401 Top = 2 Width = 75 Height = 25 Anchors = [akTop, akRight] Caption = 'Help' TabOrder = 4 OnClick = btnHelpClick end object btnSearch: TButton Left = 89 Top = 2 Width = 75 Height = 25 Caption = 'Search' TabOrder = 1 Visible = False OnClick = btnOKClick end object btnOptions: TButton Left = 8 Top = 2 Width = 75 Height = 25 Caption = 'Options' TabOrder = 0 OnClick = btnOptionsClick end end object rgSaveOption: TRadioGroup Left = 8 Top = 439 Width = 471 Height = 86 Anchors = [akLeft, akTop, akRight] Caption = 'Save Search History' ItemIndex = 1 Items.Strings = ( 'Save parameters and results' 'Only save parameters' 'Do not save') ParentShowHint = False ShowHint = False TabOrder = 6 end object timHintTimer: TTimer Interval = 2000 OnTimer = timHintTimerTimer Left = 160 Top = 232 end end
unit AutoMapper.Mapper; interface uses AutoMapper.ConfigurationProvider , AutoMapper.MapEngine , AutoMapper.Exceptions , AutoMapper.CfgMapper , AutoMapper.MappingExpression , System.SysUtils ; type TConfigurationProvider = AutoMapper.ConfigurationProvider.TConfigurationProvider; TMapperSetting = AutoMapper.CfgMapper.TMapperSetting; TMapperSettings = AutoMapper.CfgMapper.TMapperSettings; TActionConfigurationProvider = reference to procedure(const Arg1: TConfigurationProvider); TMapper = class strict private class var FInstance: TMapper; class destructor Destroy; private FActionCfg: TActionConfigurationProvider; FConfiguration: TConfigurationProvider; FMapEngine: TMapEngine; FCfgMapper: TCfgMapper; public /// <summary> /// Execute a mapping from the source object/record to a new destination object/record. /// </summary> /// <typeparam name="TSource">Source type to use, regardless of the runtime type.</typeparam> /// <typeparam name="TDestination">Destination type to create.</typeparam> /// <param name="source">Source object/record to map from.</param> /// <returns>Mapped destination object/record.</returns> function Map<TSource; TDestination>(const source: TSource): TDestination; overload; /// <summary> /// Execute a mapping from the source object/record to a new destination object/record using a custom expression. /// </summary> /// <typeparam name="TSource">Source type to use, regardless of the runtime type.</typeparam> /// <typeparam name="TDestination">Destination type to create.</typeparam> /// <param name="source">Source object/record to map from.</param> /// <param name="MapExpression">Custom expression for mapping.</param> /// <returns>Mapped destination object/record.</returns> function Map<TSource; TDestination>(const source: TSource; const MapExpression: TMapExpression<TSource, TDestination>): TDestination; overload; /// <summary> /// Execute a mapping from the source object to a new destination object/record without specifying the source type. /// </summary> /// <typeparam name="TDestination">Destination type to create.</typeparam> /// <param name="source">Source object to map from.</param> /// <returns>Mapped destination object/record.</returns> /// <remarks> /// To use this method, you must explicitly configure the source-destination mapping.<br/> /// The source can only be a class. /// </remarks> function Map<TDestination>(const source: TObject): TDestination; overload; /// <summary> /// Execute a mapping from the source object to a new destination object/record without specifying the source type using a custom expression. /// </summary> /// <typeparam name="TDestination">Destination type to create.</typeparam> /// <param name="source">Source object to map from.</param> /// <returns>Mapped destination object/record.</returns> /// <remarks> /// To use this method, you must explicitly configure the source-destination mapping.<br/> /// The source can only be a class. /// </remarks> function Map<TDestination>(const source: TObject; const MapExpression: TMapExpression<TObject, TDestination>): TDestination; overload; ///<summary>Instance of Mapper</summary> class function GetInstance: TMapper; /// <summary>Mapper Configuration.</summary> /// <param name="cfg">Mapper Configuration Provider.</param> /// <remarks> /// Here you can specify automatic mapping,<br/> /// explicitly create a source-destination map pair<br/> /// and specify an expression for them. /// </remarks> class procedure Configure(const cfg: TActionConfigurationProvider); ///<summary>Number of configured source-destination pairs.</summary> class function CountMapPair: integer; /// <summary>Reset the mapper</summary> class procedure Reset; end; var ///<summary>Instance of Mapper</summary> Mapper: TMapper; implementation function TMapper.Map<TDestination>(const source: TObject): TDestination; begin Result := FMapEngine.Map<TDestination>(source); end; function TMapper.Map<TSource, TDestination>(const source: TSource): TDestination; begin Result := FMapEngine.Map<TSource, TDestination>(source); end; class procedure TMapper.Configure(const cfg: TActionConfigurationProvider); begin if Assigned(FInstance.FActionCfg) or Assigned(FInstance.FConfiguration) or Assigned(FInstance.FMapEngine) then raise TMapperConfigureException.Create(CS_MAPPER_CONFIGURATION_ALLREADY); FInstance.FActionCfg := cfg; FInstance.FCfgMapper := TCfgMapper.Create; FInstance.FConfiguration := TConfigurationProvider.Create(FInstance.FCfgMapper); FInstance.FActionCfg(FInstance.FConfiguration); FInstance.FMapEngine := TMapEngine.Create(FInstance.FCfgMapper); end; class procedure TMapper.Reset; begin if Assigned(FInstance.FMapEngine) then FInstance.FMapEngine.Free; FInstance.FMapEngine := nil; if Assigned(FInstance.FConfiguration) then FInstance.FConfiguration.Free; FInstance.FConfiguration := nil; if Assigned(FInstance.FCfgMapper) then FInstance.FCfgMapper.Free; FInstance.FCfgMapper := nil; if Assigned(FInstance.FActionCfg) then FInstance. FActionCfg := nil; end; class function TMapper.GetInstance: TMapper; begin If FInstance = nil Then begin FInstance := TMapper.Create; end; Result := FInstance; end; class function TMapper.CountMapPair: integer; begin if (not Assigned(FInstance.FCfgMapper)) then exit(0); result := FInstance.FCfgMapper.Count; end; class destructor TMapper.Destroy; begin Reset; if Assigned(TMapper.FInstance) then TMapper.FInstance.Free; end; function TMapper.Map<TDestination>(const source: TObject; const MapExpression: TMapExpression<TObject, TDestination>): TDestination; begin result := FMapEngine.Map<TDestination>(source, MapExpression); end; function TMapper.Map<TSource, TDestination>(const source: TSource; const MapExpression: TMapExpression<TSource, TDestination>): TDestination; begin result := FMapEngine.Map<TSource, TDestination>(source, MapExpression); end; initialization Mapper := TMapper.GetInstance; end.
unit EditionsContainerKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы EditionsContainer } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Editions\EditionsContainerKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "EditionsContainerKeywordsPack" MUID: (D5B3150A2046) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtProportionalPanel , vtSizeablePanel , vtPanel ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , EditionsContainer_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_EditionsContainer = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы EditionsContainer ---- *Пример использования*: [code] 'aControl' форма::EditionsContainer TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_EditionsContainer Tkw_EditionsContainer_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EditionsContainer_Control_BackgroundPanel Tkw_EditionsContainer_Control_BackgroundPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EditionsContainer_Control_BackgroundPanel_Push Tkw_EditionsContainer_Control_pnLeft = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола pnLeft ---- *Пример использования*: [code] контрол::pnLeft TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EditionsContainer_Control_pnLeft Tkw_EditionsContainer_Control_pnLeft_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола pnLeft ---- *Пример использования*: [code] контрол::pnLeft:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EditionsContainer_Control_pnLeft_Push Tkw_EditionsContainer_Control_pnRight = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола pnRight ---- *Пример использования*: [code] контрол::pnRight TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EditionsContainer_Control_pnRight Tkw_EditionsContainer_Control_pnRight_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола pnRight ---- *Пример использования*: [code] контрол::pnRight:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EditionsContainer_Control_pnRight_Push TkwEditionsContainerFormBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TEditionsContainerForm.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; aEditionsContainerForm: TEditionsContainerForm): TvtProportionalPanel; {* Реализация слова скрипта .TEditionsContainerForm.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEditionsContainerFormBackgroundPanel TkwEditionsContainerFormPnLeft = {final} class(TtfwPropertyLike) {* Слово скрипта .TEditionsContainerForm.pnLeft } private function pnLeft(const aCtx: TtfwContext; aEditionsContainerForm: TEditionsContainerForm): TvtSizeablePanel; {* Реализация слова скрипта .TEditionsContainerForm.pnLeft } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEditionsContainerFormPnLeft TkwEditionsContainerFormPnRight = {final} class(TtfwPropertyLike) {* Слово скрипта .TEditionsContainerForm.pnRight } private function pnRight(const aCtx: TtfwContext; aEditionsContainerForm: TEditionsContainerForm): TvtPanel; {* Реализация слова скрипта .TEditionsContainerForm.pnRight } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEditionsContainerFormPnRight function Tkw_Form_EditionsContainer.GetString: AnsiString; begin Result := 'EditionsContainerForm'; end;//Tkw_Form_EditionsContainer.GetString class function Tkw_Form_EditionsContainer.GetWordNameForRegister: AnsiString; begin Result := 'форма::EditionsContainer'; end;//Tkw_Form_EditionsContainer.GetWordNameForRegister function Tkw_EditionsContainer_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_EditionsContainer_Control_BackgroundPanel.GetString class procedure Tkw_EditionsContainer_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtProportionalPanel); end;//Tkw_EditionsContainer_Control_BackgroundPanel.RegisterInEngine class function Tkw_EditionsContainer_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_EditionsContainer_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_EditionsContainer_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_EditionsContainer_Control_BackgroundPanel_Push.DoDoIt class function Tkw_EditionsContainer_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_EditionsContainer_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_EditionsContainer_Control_pnLeft.GetString: AnsiString; begin Result := 'pnLeft'; end;//Tkw_EditionsContainer_Control_pnLeft.GetString class procedure Tkw_EditionsContainer_Control_pnLeft.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtSizeablePanel); end;//Tkw_EditionsContainer_Control_pnLeft.RegisterInEngine class function Tkw_EditionsContainer_Control_pnLeft.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnLeft'; end;//Tkw_EditionsContainer_Control_pnLeft.GetWordNameForRegister procedure Tkw_EditionsContainer_Control_pnLeft_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('pnLeft'); inherited; end;//Tkw_EditionsContainer_Control_pnLeft_Push.DoDoIt class function Tkw_EditionsContainer_Control_pnLeft_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnLeft:push'; end;//Tkw_EditionsContainer_Control_pnLeft_Push.GetWordNameForRegister function Tkw_EditionsContainer_Control_pnRight.GetString: AnsiString; begin Result := 'pnRight'; end;//Tkw_EditionsContainer_Control_pnRight.GetString class procedure Tkw_EditionsContainer_Control_pnRight.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_EditionsContainer_Control_pnRight.RegisterInEngine class function Tkw_EditionsContainer_Control_pnRight.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnRight'; end;//Tkw_EditionsContainer_Control_pnRight.GetWordNameForRegister procedure Tkw_EditionsContainer_Control_pnRight_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('pnRight'); inherited; end;//Tkw_EditionsContainer_Control_pnRight_Push.DoDoIt class function Tkw_EditionsContainer_Control_pnRight_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnRight:push'; end;//Tkw_EditionsContainer_Control_pnRight_Push.GetWordNameForRegister function TkwEditionsContainerFormBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; aEditionsContainerForm: TEditionsContainerForm): TvtProportionalPanel; {* Реализация слова скрипта .TEditionsContainerForm.BackgroundPanel } begin Result := aEditionsContainerForm.BackgroundPanel; end;//TkwEditionsContainerFormBackgroundPanel.BackgroundPanel class function TkwEditionsContainerFormBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TEditionsContainerForm.BackgroundPanel'; end;//TkwEditionsContainerFormBackgroundPanel.GetWordNameForRegister function TkwEditionsContainerFormBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtProportionalPanel); end;//TkwEditionsContainerFormBackgroundPanel.GetResultTypeInfo function TkwEditionsContainerFormBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEditionsContainerFormBackgroundPanel.GetAllParamsCount function TkwEditionsContainerFormBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TEditionsContainerForm)]); end;//TkwEditionsContainerFormBackgroundPanel.ParamsTypes procedure TkwEditionsContainerFormBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwEditionsContainerFormBackgroundPanel.SetValuePrim procedure TkwEditionsContainerFormBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_aEditionsContainerForm: TEditionsContainerForm; begin try l_aEditionsContainerForm := TEditionsContainerForm(aCtx.rEngine.PopObjAs(TEditionsContainerForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aEditionsContainerForm: TEditionsContainerForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aEditionsContainerForm)); end;//TkwEditionsContainerFormBackgroundPanel.DoDoIt function TkwEditionsContainerFormPnLeft.pnLeft(const aCtx: TtfwContext; aEditionsContainerForm: TEditionsContainerForm): TvtSizeablePanel; {* Реализация слова скрипта .TEditionsContainerForm.pnLeft } begin Result := aEditionsContainerForm.pnLeft; end;//TkwEditionsContainerFormPnLeft.pnLeft class function TkwEditionsContainerFormPnLeft.GetWordNameForRegister: AnsiString; begin Result := '.TEditionsContainerForm.pnLeft'; end;//TkwEditionsContainerFormPnLeft.GetWordNameForRegister function TkwEditionsContainerFormPnLeft.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtSizeablePanel); end;//TkwEditionsContainerFormPnLeft.GetResultTypeInfo function TkwEditionsContainerFormPnLeft.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEditionsContainerFormPnLeft.GetAllParamsCount function TkwEditionsContainerFormPnLeft.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TEditionsContainerForm)]); end;//TkwEditionsContainerFormPnLeft.ParamsTypes procedure TkwEditionsContainerFormPnLeft.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству pnLeft', aCtx); end;//TkwEditionsContainerFormPnLeft.SetValuePrim procedure TkwEditionsContainerFormPnLeft.DoDoIt(const aCtx: TtfwContext); var l_aEditionsContainerForm: TEditionsContainerForm; begin try l_aEditionsContainerForm := TEditionsContainerForm(aCtx.rEngine.PopObjAs(TEditionsContainerForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aEditionsContainerForm: TEditionsContainerForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(pnLeft(aCtx, l_aEditionsContainerForm)); end;//TkwEditionsContainerFormPnLeft.DoDoIt function TkwEditionsContainerFormPnRight.pnRight(const aCtx: TtfwContext; aEditionsContainerForm: TEditionsContainerForm): TvtPanel; {* Реализация слова скрипта .TEditionsContainerForm.pnRight } begin Result := aEditionsContainerForm.pnRight; end;//TkwEditionsContainerFormPnRight.pnRight class function TkwEditionsContainerFormPnRight.GetWordNameForRegister: AnsiString; begin Result := '.TEditionsContainerForm.pnRight'; end;//TkwEditionsContainerFormPnRight.GetWordNameForRegister function TkwEditionsContainerFormPnRight.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEditionsContainerFormPnRight.GetResultTypeInfo function TkwEditionsContainerFormPnRight.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEditionsContainerFormPnRight.GetAllParamsCount function TkwEditionsContainerFormPnRight.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TEditionsContainerForm)]); end;//TkwEditionsContainerFormPnRight.ParamsTypes procedure TkwEditionsContainerFormPnRight.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству pnRight', aCtx); end;//TkwEditionsContainerFormPnRight.SetValuePrim procedure TkwEditionsContainerFormPnRight.DoDoIt(const aCtx: TtfwContext); var l_aEditionsContainerForm: TEditionsContainerForm; begin try l_aEditionsContainerForm := TEditionsContainerForm(aCtx.rEngine.PopObjAs(TEditionsContainerForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aEditionsContainerForm: TEditionsContainerForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(pnRight(aCtx, l_aEditionsContainerForm)); end;//TkwEditionsContainerFormPnRight.DoDoIt initialization Tkw_Form_EditionsContainer.RegisterInEngine; {* Регистрация Tkw_Form_EditionsContainer } Tkw_EditionsContainer_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_EditionsContainer_Control_BackgroundPanel } Tkw_EditionsContainer_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_EditionsContainer_Control_BackgroundPanel_Push } Tkw_EditionsContainer_Control_pnLeft.RegisterInEngine; {* Регистрация Tkw_EditionsContainer_Control_pnLeft } Tkw_EditionsContainer_Control_pnLeft_Push.RegisterInEngine; {* Регистрация Tkw_EditionsContainer_Control_pnLeft_Push } Tkw_EditionsContainer_Control_pnRight.RegisterInEngine; {* Регистрация Tkw_EditionsContainer_Control_pnRight } Tkw_EditionsContainer_Control_pnRight_Push.RegisterInEngine; {* Регистрация Tkw_EditionsContainer_Control_pnRight_Push } TkwEditionsContainerFormBackgroundPanel.RegisterInEngine; {* Регистрация EditionsContainerForm_BackgroundPanel } TkwEditionsContainerFormPnLeft.RegisterInEngine; {* Регистрация EditionsContainerForm_pnLeft } TkwEditionsContainerFormPnRight.RegisterInEngine; {* Регистрация EditionsContainerForm_pnRight } TtfwTypeRegistrator.RegisterType(TypeInfo(TEditionsContainerForm)); {* Регистрация типа TEditionsContainerForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtProportionalPanel)); {* Регистрация типа TvtProportionalPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtSizeablePanel)); {* Регистрация типа TvtSizeablePanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
unit stopwatch_lib; interface type TStopWatch=class private ftms: Integer; frun: Boolean; st_time: TDateTime; function get_current_value: Integer; public procedure reset; procedure start; procedure stop; property tms: Integer read get_current_value; property running: Boolean read frun; end; // Tend:=now; // msec:=MilliSecondsBetween(Tst,Tend); // lblTime.Caption:=intToStr(msec); implementation uses sysutils,DateUtils; procedure TStopWatch.reset; begin ftms:=0; st_time:=Now; end; procedure TStopWatch.start; begin if not frun then begin frun:=true; st_time:=Now; end; end; procedure TStopWatch.stop; begin if frun then begin ftms:=ftms+MilliSecondsBetween(st_time,Now); frun:=false; end; end; function TStopWatch.get_current_value: Integer; begin if frun then result:=ftms+MilliSecondsBetween(st_time,Now) else result:=ftms; end; end.
unit Mat.Settings; interface uses IniFiles, SysUtils, DBGrids, UnitMain, System.Classes; type TSettingsFile = class(Tinifile) public procedure LoadSettingsColumns(DBGrid: TDBGrid); procedure SaveSettingsColumns(DBGrid: TDBGrid); procedure LoadSettingsOther; procedure SaveSettingsOther; end; var FSettingsFile: TSettingsFile; implementation uses Mat.Constants, Mat.AnalysisProcessor; procedure TSettingsFile.LoadSettingsColumns(DBGrid: TDBGrid); var i: integer; begin if SectionExists(DBGrid.Name) then begin for i := 0 to DBGrid.Columns.Count - 1 do DBGrid.Columns[i].Width := ReadInteger(DBGrid.Name, COLUMN_SECTION_NAME + inttostr(i), 100); end; end; procedure TSettingsFile.SaveSettingsColumns(DBGrid: TDBGrid); var i: integer; begin for i := 0 to DBGrid.Columns.Count - 1 do WriteInteger(DBGrid.Name, COLUMN_SECTION_NAME + inttostr(i), DBGrid.Columns[i].Width); end; procedure TSettingsFile.LoadSettingsOther; begin if SectionExists(FOLDER_SECTION_NAME) then begin FAnalysisProcessor.LastFolder := ReadString(FOLDER_SECTION_NAME, LAST_FOLDER_SECTION_NAME, ExtractFilePath(ParamStr(0))); end; end; procedure TSettingsFile.SaveSettingsOther; begin WriteString(FOLDER_SECTION_NAME, LAST_FOLDER_SECTION_NAME, FAnalysisProcessor.LastFolder); end; initialization FSettingsFile := TSettingsFile.Create(ExtractFilePath(ParamStr(0)) + SETTINGS_FOLDER + SETTINGS_FILE_NAME); finalization FreeAndNil(FSettingsFile); end.
//////////////////////////////////////////////////////////////////////////////// // FFormModule.pas // MTB communication library // MTB module config form // (c) Petr Travnik (petr.travnik@kmz-brno.cz), // Jan Horacek (jan.horacek@kmz-brno.cz), // Michal Petrilak (engineercz@gmail.com) //////////////////////////////////////////////////////////////////////////////// { LICENSE: Copyright 2015-2018 Petr Travnik, Michal Petrilak, Jan Horacek 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. } { DESCRIPTION: TFormModules is a class representing MTB module configuration form. } unit FFormModule; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TFormModule = class(TForm) gb_1: TGroupBox; gb_2: TGroupBox; gb_3: TGroupBox; rg_delay: TRadioGroup; cbIR0: TCheckBox; cbIR1: TCheckBox; cbIR2: TCheckBox; cbIR3: TCheckBox; cbSCOM0: TCheckBox; cbSCOM1: TCheckBox; cbSCOM2: TCheckBox; cbSCOM3: TCheckBox; B_Save: TButton; B_Cancel: TButton; E_nazev_desky: TEdit; L_nazev_desky: TLabel; Label1: TLabel; L_FWVersion: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure B_CancelClick(Sender: TObject); procedure B_SaveClick(Sender: TObject); private ledIN: Array[0..15] of TShape; ledOUT: Array[0..15] of TShape; textIN: Array[0..15] of TLabel; textOUT: Array[0..15] of TLabel; OpenModule:Integer; public procedure OpenForm(module: Integer); procedure RefreshStates(); procedure OnChange(Sender:TObject); end; var FormModule: TFormModule; implementation uses FFormConfig, MTBusb, LibCML; {$R *.dfm} //////////////////////////////////////////////////////////////////////////////// procedure TFormModule.FormCreate(Sender: TObject); var i: Integer; begin for i := 0 to 15 do begin ledIN[i] := TShape.Create(Self); with ledIN[i] do begin Parent := gb_1; Left := 15 + (i div 8) * 130; Top := 20 + (i mod 8) * 20; Width := 15; Height := 10; Hint := 'Vstup '+IntToStr(i); Brush.Color := clGray; end; textIN[i] := TLabel.Create(Self); with textIN[i] do begin Parent := gb_1; Left := ledIN[i].Left + 20; Top := ledIN[i].Top; Caption := IntToStr(i); end; ledOUT[i] := TShape.Create(Self); with ledOUT[i] do begin Parent := gb_2; Left := 15 + (i div 8) * 130; Top := 20 + (i mod 8) * 20; Width := 15; Height := 10; Hint := 'Výstup '+IntToStr(i); Brush.Color := clGray; end; textOUT[i] := TLabel.Create(Self); with textOUT[i] do begin Parent := gb_2; Left := ledOUT[i].Left + 20; Top := ledOUT[i].Top; Caption := IntToStr(i); end; end; end;//procedure procedure TFormModule.FormDestroy(Sender: TObject); var i: Integer; begin for i := 0 to 15 do begin ledIN[i].Free; ledOUT[i].Free; textIN[i].Free; textOUT[i].Free; end; end; procedure TFormModule.OpenForm(module: Integer); var i: Cardinal; conf:TModulConfigGet; typ:TModulType; begin Self.OpenModule := module; conf := MTBdrv.GetModuleCfg(module); typ := MTBdrv.GetModuleType(module); i := conf.CFGdata[0] AND $0F; cbSCOM0.Checked := (i AND 1) > 0; cbSCOM1.Checked := (i AND 2) > 0; cbSCOM2.Checked := (i AND 4) > 0; cbSCOM3.Checked := (i AND 8) > 0; rg_delay.ItemIndex := (conf.CFGdata[1] AND $0F); i := (conf.CFGdata[2] AND $0F); cbIR0.Checked := (i AND 1) > 0; cbIR1.Checked := (i AND 2) > 0; cbIR2.Checked := (i AND 4) > 0; cbIR3.Checked := (i AND 8) > 0; E_nazev_desky.Text := conf.CFGpopis; L_FWVersion.Caption := conf.CFGfw; cbSCOM0.Visible := ((typ = TModulType.idMTB_UNI_ID) or (typ = TModulType.idMTB_UNIOUT_ID) or (typ = TModulType.idMTB_TTL_ID) or (typ = TModulType.idMTB_TTLOUT_ID) or (typ = TModulType.idNone)); cbSCOM1.Visible := cbSCOM0.Visible; cbSCOM2.Visible := cbSCOM0.Visible; cbSCOM3.Visible := cbSCOM0.Visible; cbIR0.Visible := ((typ = TModulType.idMTB_UNI_ID) or (typ = TModulType.idNone)); cbIR1.Visible := cbIR0.Visible; cbIR2.Visible := cbIR0.Visible; cbIR3.Visible := cbIR0.Visible; FormModule.Caption := 'Konfigurace modulu '+IntToStr(Module); Self.RefreshStates(); Self.Show(); end; procedure TFormModule.RefreshStates(); var data:Word; i: Integer; cl: TColor; begin if (Self.OpenModule = 0) then Exit(); cbSCOM0.Enabled := (not MTBdrv.Scanning); cbSCOM1.Enabled := (not MTBdrv.Scanning); cbSCOM2.Enabled := (not MTBdrv.Scanning); cbSCOM3.Enabled := (not MTBdrv.Scanning); cbIR0.Enabled := (not MTBdrv.Scanning); cbIR1.Enabled := (not MTBdrv.Scanning); cbIR2.Enabled := (not MTBdrv.Scanning); cbIR3.Enabled := (not MTBdrv.Scanning); rg_delay.Enabled := (not MTBdrv.Scanning); data := MTBdrv.GetIModule(Self.OpenModule); for i := 0 to 15 do begin if (MTBdrv.Scanning) then if ((data shr i) and $01 = 1) then cl := clLime else cl := clRed else cl := clGray; ledIN[i].Brush.Color := cl; end;//for i data := MTBdrv.GetOModule(Self.OpenModule); for i := 0 to 15 do begin if (MTBdrv.Scanning) then if ((data shr i) and $01 = 1) then cl := clLime else cl := clRed else cl := clGray; ledOUT[i].Brush.Color := cl; end; end; procedure TFormModule.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin Self.OpenModule := 0; CanClose := false; Hide; end; procedure TFormModule.B_CancelClick(Sender: TObject); begin Self.Close; end; procedure TFormModule.B_SaveClick(Sender: TObject); var B0: integer; B1: integer; B2: integer; begin Screen.Cursor := crHourGlass; B0 := 0; B2 := 0; if (cbSCOM0.Checked) then B0 := B0 OR 1; if (cbSCOM1.Checked) then B0 := B0 OR 2; if (cbSCOM2.Checked) then B0 := B0 OR 4; if (cbSCOM3.Checked) then B0 := B0 OR 8; MTBdrv.WrCfgData.CFGdata[0] := B0; B1 := rg_delay.ItemIndex; MTBdrv.WrCfgData.CFGdata[1] := B1; if (cbIR0.Checked) then B2 := B2 OR 1; if (cbIR1.Checked) then B2 := B2 OR 2; if (cbIR2.Checked) then B2 := B2 OR 4; if (cbIR3.Checked) then B2 := B2 OR 8; MTBdrv.WrCfgData.CFGdata[2] := B2; MTBdrv.WrCfgData.CFGpopis := Self.E_nazev_desky.Text; MTBdrv.SetModuleCfg(OpenModule); FormConfig.UpdateModulesList(); Screen.Cursor := crDefault; Self.Close; end; //vola se pri zmene MTB portu - zajistuje aktualni stav vstupu a vystupu procedure TFormModule.OnChange(Sender:TObject); begin if (Self.Showing) then Self.RefreshStates; end;//procedure //////////////////////////////////////////////////////////////////////////////// initialization finalization FreeAndNil(FormModule); end.
unit uLogArquivo; interface uses SysUtils, Classes, Windows; type TTipoLog = (tlcInformation, tlcError, tlcWarning, tlcDebug); ILogArquivo = interface ['{23E1C114-AFAC-4CC3-B5FB-8248459C31CE}'] function NomeArquivo: String; procedure Info(ATexto: String); procedure Erro(ATexto: String); procedure Warn(ATexto: String); procedure Debug(ATexto: String); end; TLogArquivo = class(TInterfacedObject, ILogArquivo) private FFileName: String; // FStreamWriter: TStreamWriter; FSeq: SmallInt; procedure DoLog(ATexto: String; ATipoLog: TTipoLog); procedure SetFileName; function GetSizeOfFile(FileName: string): Int64; public constructor Create; function NomeArquivo: String; procedure Info(ATexto: String); procedure Erro(ATexto: String); procedure Warn(ATexto: String); procedure Debug(ATexto: String); end; const K = Int64(1024); M = K * K; G = K * M; T = K * G; var LOGCriticalSection: TRTLCriticalSection; function Log: ILogArquivo; implementation var _Log: ILogArquivo; function Log: ILogArquivo; begin Result := _Log; end; { TLogArquivo } procedure TLogArquivo.SetFileName; var FileSize: Int64; begin if Trim(FFileName) = '' then begin // Verificando se existe a pasta LOG, dentro da pasta que fica o .exe if not DirectoryExists(ExtractFilePath(ParamStr(0)) + 'LOG') then ForceDirectories(ExtractFilePath(ParamStr(0)) + 'LOG'); FFileName := ExtractFilePath(ParamStr(0)) + 'LOG\' + ExtractFileName(ParamStr(0)); FFileName := ChangeFileExt(FFileName, '.000.log'); FSeq := 0; end; if FileExists(FFileName) then begin FileSize := GetSizeOfFile(FFileName); if FileSize > (M * 5) then begin Inc(FSeq); FFileName := ExtractFilePath(ParamStr(0)) + 'LOG\' + ExtractFileName(ParamStr(0)); FFileName := ChangeFileExt(FFileName, '.' + FormatFloat('000', FSeq) + '.log'); SetFileName; end; end; end; constructor TLogArquivo.Create; begin inherited; SetFileName; end; procedure TLogArquivo.Debug(ATexto: String); begin DoLog(ATexto, tlcDebug); end; procedure TLogArquivo.DoLog(ATexto: String; ATipoLog: TTipoLog); const sTipoLog: array [0 .. 3] of string = ('INFO', 'ERROR', 'WARN', 'DEBUG'); var FStreamWriter: TStreamWriter; begin EnterCriticalSection(LOGCriticalSection); FStreamWriter := nil; try try FStreamWriter := TStreamWriter.Create(FFileName, True, TEncoding.UTF8); FStreamWriter.WriteLine(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', now) + ' [' + Format('%-10.10s', [sTipoLog[Ord(ATipoLog)]]) + '] ' + ATexto); except end; finally FStreamWriter.Free; LeaveCriticalSection(LOGCriticalSection); SetFileName; end; end; procedure TLogArquivo.Erro(ATexto: String); begin DoLog(ATexto, tlcError); end; procedure TLogArquivo.Info(ATexto: String); begin DoLog(ATexto, tlcInformation); end; function TLogArquivo.NomeArquivo: String; begin Result := FFileName; end; procedure TLogArquivo.Warn(ATexto: String); begin DoLog(ATexto, tlcWarning); end; function TLogArquivo.GetSizeOfFile(FileName: string): Int64; var Handle: Integer; begin EnterCriticalSection(LOGCriticalSection); try Handle := FileOpen(FileName, fmOpenRead); Result := 0; if Handle <> -1 then begin try Result := FileSeek(Handle, Int64(0), 2); finally FileClose(Handle); end; end; finally LeaveCriticalSection(LOGCriticalSection); end; end; initialization InitializeCriticalSection(LOGCriticalSection); _Log := TLogArquivo.Create; finalization DeleteCriticalSection(LOGCriticalSection); end.
unit Utils.Functions; interface uses Vcl.ExtCtrls,RTTI, vcl.controls,System.classes,Vcl.StdCtrls, vcl.forms,Generics.collections, System.UITypes; Type TGenericObject<T: class> = class public class function CreateObject: T; end; function Iif(Contition: Boolean; ValueTrue, ValueFalse : Variant):Variant;overload; procedure LimpaCampos(Container :TCustomControl; Ignorar: array of TComponent);overload; procedure LimpaCampos(Container :TForm; Ignorar: array of TComponent);overload; function ZeroEsquerda(pValor: string; pQtd: integer): string; procedure DesablePanel (var aPanel : TPanel); procedure EnablePanel (var aPanel : TPanel; aColor: TColor); implementation function Iif(Contition: Boolean; ValueTrue, ValueFalse : Variant):Variant; begin if Contition then Result := ValueTrue else Result := ValueFalse; end; procedure LimpaCampos(Container :TCustomControl; Ignorar: array of TComponent);overload; var i: Integer; contador: Integer; IgnoraComp: Boolean; j: Integer; begin for i := 0 to Container.ComponentCount - 1 do begin IgnoraComp := false; for contador := 0 to High(Ignorar) do begin if Container.Components[i] = Ignorar[contador] then begin IgnoraComp := true; break; end; end; if IgnoraComp then Continue; if (Container.Components[i] is TEdit) then begin TEdit(Container.Components[i]).Text := ''; end else if (Container.Components[i] is TMemo) then begin TMemo(Container.Components[i]).Lines.Clear; end else if (Container.Components[i] is TComboBox) then begin TComBoBox(Container.Components[i]).ItemIndex := -1; end; end; end; procedure LimpaCampos(Container :TForm; Ignorar: array of TComponent);overload; var i: Integer; contador: Integer; IgnoraComp: Boolean; j: Integer; begin for i := 0 to Container.ComponentCount - 1 do begin IgnoraComp := false; for contador := 0 to High(Ignorar) do begin if Container.Components[i] = Ignorar[contador] then begin IgnoraComp := true; break; end; end; if IgnoraComp then Continue; if (Container.Components[i] is TEdit) then begin TEdit(Container.Components[i]).Text := ''; end else if (Container.Components[i] is TMemo) then begin TMemo(Container.Components[i]).Lines.Clear; end else if (Container.Components[i] is TComboBox) then begin TComBoBox(Container.Components[i]).ItemIndex := -1; end; end; end; function ZeroEsquerda(pValor: string; pQtd: integer): string; var i, vTam: integer; vAux: string; begin vAux := pValor; vTam := length( pValor ); pValor := ''; for i := 1 to pQtd - vTam do pValor := '0' + pValor; vAux := pValor + vAux; result := vAux; end; procedure DesablePanel (var aPanel : TPanel); begin with aPanel do begin Enabled := false; Color := $00C7C3BE; Cursor := crNo; end; end; procedure EnablePanel (var aPanel : TPanel; aColor: TColor); begin with aPanel do begin Enabled := True; Color := aColor; Cursor := crHandPoint; end; end; { TGenericObject<T> } class function TGenericObject<T>.CreateObject: T; var Contexto: TRttiContext; Tipo: TRttiType; Value: TValue; Obj: TObject; begin // Criando Objeto via RTTI para chamar o envento OnCreate no Objeto Contexto := TRttiContext.Create; try Tipo := Contexto.GetType(TClass(T)); Value := Tipo.GetMethod('Create').Invoke(Tipo.AsInstance.MetaclassType, []); Result := T(Value.AsObject); finally Contexto.Free; end; end; end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> } unit threadcopyfile; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TThreadUnit } TThreadCopyFile = class(TThread) private FStatus: string; FName: string; procedure Update; procedure OnTerminate; protected procedure Execute; override; public property Status: string Read FStatus Write FStatus; property Name: string Read FName Write FName; constructor Create(CreateSuspended: Boolean); end; implementation uses Unit1; { TThreadUnit } procedure TThreadCopyFile.OnTerminate; begin Form1.Memo1.Append(Name+': Terminated'); end; procedure TThreadCopyFile.Update; begin Form1.Memo1.Append(Status); end; procedure TThreadCopyFile.Execute; const nLoops=20000; var i,j: integer; aSource, aTarget: TextFile; aLine: string; begin { simulate copying a large file } Status:=Name+': Start'; Synchronize(@Update); AssignFile(aSource, GetCurrentDir+'\unit1.pas'); AssignFile(aTarget, GetCurrentDir+'\largefile.txt'); try Rewrite(aTarget); finally CloseFile(aTarget); end; for i:=1 to nLoops do begin if Terminated then break; if j>1000 then begin Status:=Name+': Loop '+i.ToString+' of '+nLoops.ToString; Synchronize(@Update); j:=0; end else Inc(j); try Reset(aSource); Append(aTarget); while not Eof(aSource) do begin Readln(aSource, aLine); Writeln(aTarget, aLine); end; finally CloseFile(aSource); CloseFile(aTarget); end; end; Synchronize(@OnTerminate); end; constructor TThreadCopyFile.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); FreeOnTerminate := False; end; end.
unit SumToText; interface function ConvertSumToText(AValue: real): string; implementation uses SysUtils ; function Propis(Value: int64): string; var Rend: boolean; ValueTemp: int64; procedure Num(Value: byte); begin case Value of 1: if Rend = true then Result := Result + 'один ' else Result := Result + 'одна '; 2: if Rend = true then Result := Result + 'два ' else Result := Result + 'две '; 3: Result := Result + 'три '; 4: Result := Result + 'четыре '; 5: Result := Result + 'пять '; 6: Result := Result + 'шесть '; 7: Result := Result + 'семь '; 8: Result := Result + 'восемь '; 9: Result := Result + 'девять '; 10: Result := Result + 'десять '; 11: Result := Result + 'одиннадцать '; 12: Result := Result + 'двенадцать '; 13: Result := Result + 'тринадцать '; 14: Result := Result + 'четырнадцать '; 15: Result := Result + 'пятнадцать '; 16: Result := Result + 'шестнадцать '; 17: Result := Result + 'семнадцать '; 18: Result := Result + 'восемнадцать '; 19: Result := Result + 'девятнадцать '; end end; procedure Num10(Value: byte); begin case Value of 2: Result := Result + 'двадцать '; 3: Result := Result + 'тридцать '; 4: Result := Result + 'сорок '; 5: Result := Result + 'пятьдесят '; 6: Result := Result + 'шестьдесят '; 7: Result := Result + 'семьдесят '; 8: Result := Result + 'восемьдесят '; 9: Result := Result + 'девяносто '; end; end; procedure Num100(Value: byte); begin case Value of 1: Result := Result + 'сто '; 2: Result := Result + 'двести '; 3: Result := Result + 'триста '; 4: Result := Result + 'четыреста '; 5: Result := Result + 'пятьсот '; 6: Result := Result + 'шестьсот '; 7: Result := Result + 'семьсот '; 8: Result := Result + 'восемьсот '; 9: Result := Result + 'девятьсот '; end end; procedure Num00; begin Num100(ValueTemp div 100); ValueTemp := ValueTemp mod 100; if ValueTemp < 20 then Num(ValueTemp) else begin Num10(ValueTemp div 10); ValueTemp := ValueTemp mod 10; Num(ValueTemp); end; end; procedure NumMult(Mult: int64; s1, s2, s3: string); var ValueRes: int64; begin if Value >= Mult then begin ValueTemp := Value div Mult; ValueRes := ValueTemp; Num00; if ValueTemp = 1 then Result := Result + s1 else if (ValueTemp > 1) and (ValueTemp < 5) then Result := Result + s2 else Result := Result + s3; Value := Value - Mult * ValueRes; end; end; begin if (Value = 0) then Result := 'ноль' else begin Result := ''; Rend := true; NumMult(1000000000000, 'триллион ', 'триллиона ', 'триллионов '); NumMult(1000000000, 'миллиард ', 'миллиарда ', 'миллиардов '); NumMult(1000000, 'миллион ', 'миллиона ', 'миллионов '); Rend := false; NumMult(1000, 'тысяча ', 'тысячи ', 'тысяч '); Rend := true; ValueTemp := Value; Num00; end; end; procedure Fst(S: string; Var S1: string; Var S2: string; Var S3: string); var pos: integer; begin S1 := ''; S2 := ''; S3 := ''; pos := 1; while ((pos <= Length(S))and(S[pos] <> ';'))do begin S1 := S1 + S[pos]; inc(pos); end; inc(pos); while ((pos <= Length(S))and(S[pos] <> ';'))do begin S2 := S2 + S[pos]; inc(pos); end; inc(pos); while ((pos <= Length(S))and(S[pos] <> ';'))do begin S3 := S3 + S[pos]; inc(pos); end; inc(pos); end; function Ruble(Value: int64; Skl: string): string; var hk10, hk20: integer; Skl1,Skl2,Skl3: string; begin Fst(Skl,Skl1,Skl2,Skl3); hk10 := Value mod 10; hk20 := Value mod 100; if (hk20 > 10) and (hk20 < 20) then result := result + Skl3 else if (hk10 = 1) then result := result + Skl1 else if (hk10 > 1) and (hk10 < 5) then result := result + Skl2 else result := result + Skl3; end; function Kopeika(Value: integer; Skp: string): string; var hk10, hk20: integer; Skp1,Skp2,Skp3: string; begin Fst(Skp,Skp1,Skp2,Skp3); hk10 := Value mod 10; hk20 := Value mod 100; if (hk20 > 10) and (hk20 < 20) then result := result + Skp3 else if (hk10 = 1) then result := result + Skp1 else if (hk10 > 1) and (hk10 < 5) then result := result + Skp2 else result := result + Skp3; end; function ConvertSumToText(AValue: real): string; var i: byte; begin i := (Round(Frac(AValue) * 100)); result := Propis(Trunc(AValue)) + ' ' + Ruble(Trunc(AValue), 'рубль;рубля;рублей' ) + ' ' + IntToStr(i div 10) + IntToStr(i mod 10) + ' ' + Kopeika(i, 'копейка;копейки;копеек'); end; end.
unit TestForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SpeedBmp; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDblClick(Sender: TObject); procedure FormPaint(Sender: TObject); private { Private declarations } public { Public declarations } fBitmap : TSpeedBitmap; fTextDrawn : boolean; end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin fBitmap := TSpeedBitmap.CreateSized(ClientWidth, ClientHeight, 16); end; procedure TForm1.FormDblClick(Sender: TObject); const msg : string = 'This is a fucking test'; begin with fBitmap.Canvas do begin Font.Color := clRed; Windows.TextOut(Handle, 0, 0, pchar(msg), length(msg)); end; fTextDrawn := true; Invalidate; end; procedure TForm1.FormPaint(Sender: TObject); begin if fTextDrawn then fBitmap.ClipDraw(Canvas, 0, 0, ClientRect); end; end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.BitString; interface uses Classes, SysUtils; type TBitStringWriter = class(TObject) private FValue: string; FBuffer: uint32; FBufferSize: integer; public property Value: string read FValue; public constructor Create; destructor Destroy; override; procedure Flush; procedure Write(x: uint32; bits: integer); end; TBitStringReader = class(TObject) private FValue: string; FValueIter: integer; FBuffer: uint32; FBufferSize: integer; FEOF: boolean; function GetAvailableBits: integer; public property EOF: boolean read FEOF; property AvailableBits: integer read GetAvailableBits; public constructor Create(input: string); destructor Destroy; override; procedure Reset; function Read(bits: integer): uint32; end; implementation { TBitStringWriter } constructor TBitStringWriter.Create; begin FBuffer := 0; FBufferSize := 0; FValue := ''; end; destructor TBitStringWriter.Destroy; begin inherited; end; procedure TBitStringWriter.Flush; begin // C++ is pain while (FBufferSize > 0) do begin FValue := FValue + chr(FBuffer and 255); FBuffer := FBuffer shr 8; FBufferSize := FBufferSize - 8; end; FBufferSize := 0; end; procedure TBitStringWriter.Write(x: uint32; bits: integer); begin FBuffer := FBuffer or (x shl FBufferSize); FBufferSize := FBufferSize + bits; while (FBufferSize >= 8) do begin FValue := FValue + chr(FBuffer and 255); FBuffer := FBuffer shr 8; FBufferSize := FBufferSize - 8; end; end; { TBitStringReader } constructor TBitStringReader.Create(input: string); begin FValue := input; FBuffer := 0; FBufferSize := 0; FEOF := False; FValueIter := 1; end; destructor TBitStringReader.Destroy; begin inherited; end; function TBitStringReader.GetAvailableBits: integer; begin if FEOF then Result := 0 else begin Result := FBufferSize + 8 * (Length(FValue) - FValueIter + 1); end; end; function TBitStringReader.Read(bits: integer): uint32; var lValueByte: byte; begin if (FBufferSize < bits) then begin if (FValueIter <= Length(FValue)) then begin lValueByte := Ord(FValue[FValueIter]); FBuffer := FBuffer or (lValueByte shl FBufferSize); // C++ is pain Inc(FValueIter); FBufferSize := FBufferSize + 8; end else begin FEOF := True; end; end; Result := FBuffer and ((1 shl bits) - 1); FBuffer := FBuffer shr bits; FBufferSize := FBufferSize - bits; if (FBufferSize <= 0) and (FValueIter > Length(FValue)) then begin FEOF := True; end; end; procedure TBitStringReader.Reset; begin FBuffer := 0; FBufferSize := 0; end; end.
unit AppConfigBaseTest; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "DailyTest" // Модуль: "w:/common/components/rtl/Garant/Daily/AppConfigBaseTest.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Tests::DailyTest::AppConfig::TAppConfigBaseTest // // Тесты на работу конфигурации // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Daily\TestDefine.inc.pas} interface {$If defined(nsTest) AND not defined(NoScripts)} uses ddAppConfigTypes {$If defined(nsTest) AND not defined(NoVCM)} , EmptyFormTest {$IfEnd} //nsTest AND not NoVCM , ddConfigStorages, Types ; {$IfEnd} //nsTest AND not NoScripts {$If defined(nsTest) AND not defined(NoScripts)} type TAppConfigBaseTest = {abstract} class(TEmptyFormTest) {* Тесты на работу конфигурации } private // private fields f_Config : TddAppConfigNode; f_ConfigStorage : IddConfigStorage; protected // overridden protected methods procedure Cleanup; override; {$If defined(nsTest) AND not defined(NoVCM)} function FormExtent: TPoint; override; {* Размеры формы } {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} procedure FormMade(const aForm: _FormClass_); override; {$IfEnd} //nsTest AND not NoVCM function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } {$If defined(nsTest) AND not defined(NoVCM)} procedure CheckControl; override; {$IfEnd} //nsTest AND not NoVCM end;//TAppConfigBaseTest {$IfEnd} //nsTest AND not NoScripts implementation {$If defined(nsTest) AND not defined(NoScripts)} uses SysUtils, ddAppConfigUtils, ConfigStorageStub, Windows, Messages, vtCheckBox, TestFrameWork, ddAppConfigTypesModelPart ; {$IfEnd} //nsTest AND not NoScripts {$If defined(nsTest) AND not defined(NoScripts)} // start class TAppConfigBaseTest procedure TAppConfigBaseTest.Cleanup; //#UC START# *4B2F40FD0088_51D52B6301DD_var* //#UC END# *4B2F40FD0088_51D52B6301DD_var* begin //#UC START# *4B2F40FD0088_51D52B6301DD_impl* FreeAndNil(f_Config); f_ConfigStorage := nil; inherited; //#UC END# *4B2F40FD0088_51D52B6301DD_impl* end;//TAppConfigBaseTest.Cleanup {$If defined(nsTest) AND not defined(NoVCM)} function TAppConfigBaseTest.FormExtent: TPoint; //#UC START# *4C08CF700318_51D52B6301DD_var* //#UC END# *4C08CF700318_51D52B6301DD_var* begin //#UC START# *4C08CF700318_51D52B6301DD_impl* Result.X := 400; Result.Y := 200; //#UC END# *4C08CF700318_51D52B6301DD_impl* end;//TAppConfigBaseTest.FormExtent {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} procedure TAppConfigBaseTest.FormMade(const aForm: _FormClass_); //#UC START# *4C08D61F0231_51D52B6301DD_var* //#UC END# *4C08D61F0231_51D52B6301DD_var* begin //#UC START# *4C08D61F0231_51D52B6301DD_impl* inherited; f_ConfigStorage := TConfigStorageStub.Make; f_Config := MakeNode('Config', 'Настройки', False, MakeBoolean('CheckBoolean', 'Проверочное булевское значение', False, nil)); f_Config.LabelTop := False; IddConfigNode(f_Config).CreateFrame(aForm.WorkSpace, 0); f_Config.Load(f_ConfigStorage); IddConfigNode(f_Config).SetControlValues(False); //#UC END# *4C08D61F0231_51D52B6301DD_impl* end;//TAppConfigBaseTest.FormMade {$IfEnd} //nsTest AND not NoVCM function TAppConfigBaseTest.GetFolder: AnsiString; {-} begin Result := 'AppConfig'; end;//TAppConfigBaseTest.GetFolder function TAppConfigBaseTest.GetModelElementGUID: AnsiString; {-} begin Result := '51D52B6301DD'; end;//TAppConfigBaseTest.GetModelElementGUID {$If defined(nsTest) AND not defined(NoVCM)} procedure TAppConfigBaseTest.CheckControl; //#UC START# *51D5464D033C_51D52B6301DD_var* var l_CheckBox: TvtCheckBox; //#UC END# *51D5464D033C_51D52B6301DD_var* begin //#UC START# *51D5464D033C_51D52B6301DD_impl* l_CheckBox := (f_Config.Items[0].Control as TvtCheckBox); Check(SendMessage(l_CheckBox.Handle, BM_GETCHECK, 0, 0) = BST_CHECKED); //#UC END# *51D5464D033C_51D52B6301DD_impl* end;//TAppConfigBaseTest.CheckControl {$IfEnd} //nsTest AND not NoVCM {$IfEnd} //nsTest AND not NoScripts end.
unit Define_AnalysisUpsDowns; interface uses Define_DealItem, Define_Price, StockDayDataAccess; type PRT_AnalysisUpsDowns = ^TRT_AnalysisUpsDowns; TRT_AnalysisUpsDowns = record StockItem: PRT_DealItem; UpDownTrueStatus: TRT_UpDownStatus; UpDownViewStatus: TRT_UpDownStatus; UpTrueDays: Integer; // 事实上涨天数 ( 收盘 > 昨收盘 ) UpViewDays: Integer; // 看起来上涨天数 ( 收盘 > 开盘 ) UpTrueRate: double; UpTrueBeginPrice: TRT_PricePack; UpTrueEndPrice: TRT_PricePack; UpViewRate: double; UpViewBeginPrice: TRT_PricePack; UpViewEndPrice: TRT_PricePack; UpMaxTrueDays: Integer; UpMaxViewDays: Integer; DownTrueDays: Integer; // 事实下跌天数 ( 收盘 < 昨收盘 ) DownViewDays: Integer; // 看起来下跌天数 ( 收盘 < 开盘 ) DownTrueRate: double; DownTrueBeginPrice: TRT_PricePack; DownTrueEndPrice: TRT_PricePack; DownViewRate: double; DownViewBeginPrice: TRT_PricePack; DownViewEndPrice: TRT_PricePack; DownMaxTrueDays: Integer; DownMaxViewDownDays: Integer; end; PStock_AnalysisUpsDowns = ^TStock_AnalysisUpsDowns; TStock_AnalysisUpsDowns = record StockCode: TDealCodePack; CurrentUpDownStatus: TStore_UpDownStatus; CurrentContinueTrueUpDays: Integer; // 事实上涨天数 ( 收盘 > 昨收盘 ) CurrentContinueViewUpDays: Integer; // 看起来上涨天数 ( 收盘 > 开盘 ) MaxContinueTrueUpDays: Integer; MaxContinueViewUpDays: Integer; CurrentContinueTrueDownDays: Integer; // 事实下跌天数 ( 收盘 < 昨收盘 ) CurrentContinueViewDownDays: Integer; // 看起来下跌天数 ( 收盘 < 开盘 ) MaxContinueTrueDownDays: Integer; MaxContinueViewDownDays: Integer; end; procedure ComputeAnalysisUpsDowns(AStockItem: PRT_DealItem; AnalysisData: PRT_AnalysisUpsDowns; ADataAccess: TStockDayDataAccess); implementation uses define_stock_quotes; procedure ComputeAnalysisUpsDowns(AStockItem: PRT_DealItem; AnalysisData: PRT_AnalysisUpsDowns; ADataAccess: TStockDayDataAccess); var i: integer; tmpQuoteDay: PRT_Quote_M1_Day; tmpNextDayPrice: PRT_PricePack_Range; tmpUpTrueStatus: Byte; tmpUpViewStatus: Byte; tmpDownTrueStatus: Byte; tmpDownViewStatus: Byte; begin if nil = ADataAccess then exit; if 0 < ADataAccess.RecordCount then begin tmpQuoteDay := ADataAccess.RecordItem[ADataAccess.RecordCount - 1]; //if tmpQuoteDay.DealDateTime.Value + 4 > now then begin AnalysisData.UpDownTrueStatus := udNone; AnalysisData.UpDownViewStatus := udNone; tmpUpTrueStatus := 0; tmpUpViewStatus := 0; tmpDownTrueStatus := 0; tmpDownViewStatus := 0; tmpNextDayPrice := nil; for i := ADataAccess.RecordCount - 1 downto 0 do begin if (2 = tmpUpTrueStatus) and (2 = tmpUpViewStatus) and (2 = tmpDownTrueStatus) and (2 = tmpDownViewStatus) then begin if nil <> tmpQuoteDay then begin end; Break; end; tmpQuoteDay := ADataAccess.RecordItem[i]; if tmpQuoteDay.PriceRange.PriceClose.Value > tmpQuoteDay.PriceRange.PriceOpen.Value then begin if 0 = tmpUpViewStatus then begin tmpUpViewStatus := 1; end; if 1 = tmpDownViewStatus then begin tmpDownViewStatus := 2; end; if 1 = tmpUpViewStatus then begin if AnalysisData.UpDownViewStatus = udNone then AnalysisData.UpDownViewStatus := udUp; Inc(AnalysisData.UpViewDays); end; end; if tmpQuoteDay.PriceRange.PriceClose.Value < tmpQuoteDay.PriceRange.PriceOpen.Value then begin if 0 = tmpDownViewStatus then begin tmpDownViewStatus := 1; end; if 1 = tmpUpViewStatus then begin tmpUpViewStatus := 2; end; if 1 = tmpDownViewStatus then begin if AnalysisData.UpDownViewStatus = udNone then AnalysisData.UpDownViewStatus := udDown; Inc(AnalysisData.DownViewDays); end; end; if nil <> tmpNextDayPrice then begin if tmpQuoteDay.PriceRange.PriceClose.Value > tmpNextDayPrice.PriceClose.Value then begin // 下跌 if 0 = tmpDownTrueStatus then begin tmpDownTrueStatus := 1; end; if 1 = tmpUpTrueStatus then begin tmpUpTrueStatus := 2; end; if 1 = tmpDownTrueStatus then begin if AnalysisData.UpDownTrueStatus = udNone then AnalysisData.UpDownTrueStatus := udDown; Inc(AnalysisData.DownTrueDays); end; end; if tmpQuoteDay.PriceRange.PriceClose.Value < tmpNextDayPrice.PriceClose.Value then begin // 上涨 if 0 = tmpUpTrueStatus then begin tmpUpTrueStatus := 1; end; if 1 = tmpDownTrueStatus then begin tmpDownTrueStatus := 2; end; if 1 = tmpUpTrueStatus then begin if AnalysisData.UpDownTrueStatus = udNone then AnalysisData.UpDownTrueStatus := udUp; Inc(AnalysisData.UpTrueDays); end; end; end; tmpNextDayPrice := @tmpQuoteDay.PriceRange; end; end; end; end; end.
unit eeBaseTypes; { Библиотека "Эверест" } { Автор: Люлин А.В. © } { Модуль: eeBaseTypes - } { Начат: 28.05.2003 19:02 } { $Id: eeBaseTypes.pas,v 1.4 2011/04/14 16:19:23 lulin Exp $ } // $Log: eeBaseTypes.pas,v $ // Revision 1.4 2011/04/14 16:19:23 lulin // {RequestLink:257822128}. // // Revision 1.3 2003/07/09 13:10:30 law // - new behavior: в событие _OnMouseAction теперь передается параметр aWasSelection. // // Revision 1.2 2003/05/29 18:30:16 law // - bug fix: восстановлена реакция редактора на события мышью. // // Revision 1.1 2003/05/28 16:15:20 law // - change: отрезал ee.dll. // {$I eeDefine.inc } interface uses Windows, eeInterfaces ; type TeeMouseActionEvent = function (aSender : TObject; const aHotSpot : IeeHotSpot; aButton : TeeMouseButton; anAction : TeeMouseAction; Keys : TeeShiftState; aWasSelection : Windows.Bool {; var NeedAsyncLoop : Bool}): Windows.Bool of object; {* - событие для реакции на операцию мышью. } implementation end.
unit fmuCustomerInfo; {$I defines.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AtrPages, StdCtrls, ToolCtrlsEh, GridsEh, DBGridEh, DBCtrls, DBCtrlsEh, Mask, Buttons, ExtCtrls, DB, FIBDataSet, pFIBDataSet, Menus, DBGridEhToolCtrls, DBAxisGridsEh, PrjConst, EhLibVCL, System.UITypes, DBGridEhGrouping, DynVarsEh, FIBDatabase, pFIBDatabase, System.Actions, Vcl.ActnList, dnSplitter, CnErrorProvider; type TapgCustomerInfo = class(TA4onPage) dsContacts: TpFIBDataSet; srcContacts: TDataSource; pnlInfo: TPanel; Label11: TLabel; lblPN: TLabel; Label6: TLabel; Label5: TLabel; Label3: TLabel; lblPREG: TLabel; Label10: TLabel; Label2: TLabel; Label1: TLabel; edtPASSPORT_NUMBER: TDBEditEh; dbeACCOUNT_NO: TDBEditEh; edtPASP_REG: TDBEditEh; DBDateTimeEditCONTRACT_DATE: TDBDateTimeEditEh; DBDateTimeEditEh1: TDBDateTimeEditEh; DBEdit9: TDBEditEh; edFIO: TEdit; edtAddress: TEdit; memState: TDBMemoEh; pmRecalc: TPopupMenu; N2: TMenuItem; ds: TDataSource; pnlAddInfo: TPanel; Splitter1: TdnSplitter; pnlDP: TPanel; sbRecalc: TSpeedButton; gbSaldo: TGroupBox; DBTextDebt: TDBText; pnlPrepay: TPanel; dbtxtPrepay: TDBText; pnlContacts: TPanel; dbgrdhContacts: TDBGridEh; GroupBox2: TGroupBox; memCustNotice: TDBMemoEh; trRead: TpFIBTransaction; trWrite: TpFIBTransaction; actlst1: TActionList; actMakeCall: TAction; pnlBtns: TPanel; lbl5: TLabel; btnCall: TSpeedButton; lbl1: TLabel; btnCAdd: TSpeedButton; btnCdel: TSpeedButton; lbl2: TLabel; btnSaveNotice: TButton; lblBD: TLabel; edBIRTHDAY: TDBDateTimeEditEh; edtBP: TDBEditEh; dnSplitter1: TdnSplitter; btnCEdit: TSpeedButton; actCAdd: TAction; actCEdit: TAction; actCDel: TAction; CnErrors: TCnErrorProvider; lblPR: TLabel; edtPASSPORT_REGISTRATION: TDBEditEh; procedure srcCustomerDataChange(Sender: TObject; Field: TField); procedure memCustNoticeExit(Sender: TObject); procedure N2Click(Sender: TObject); procedure sbRecalcClick(Sender: TObject); procedure dsContactsNewRecord(DataSet: TDataSet); procedure dsContactsBeforePost(DataSet: TDataSet); procedure dbgrdhContactsExit(Sender: TObject); procedure srcContactsUpdateData(Sender: TObject); procedure FormResize(Sender: TObject); procedure dbgrdhContactsDblClick(Sender: TObject); procedure actMakeCallExecute(Sender: TObject); procedure btnSaveNoticeClick(Sender: TObject); procedure memCustNoticeKeyPress(Sender: TObject; var Key: Char); procedure actCAddExecute(Sender: TObject); procedure actCEditExecute(Sender: TObject); procedure actCDelExecute(Sender: TObject); procedure dbgrdhContactsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); private { Private declarations } FSaveNotice: String; fVisibleColumns: Integer; FCheckPassport: Boolean; procedure RecalcCustomer(const CUSTOMER_ID: Int64); procedure dsCustomers_Refresh; procedure SaveContact; procedure SaveNotice; public procedure InitForm; override; procedure OpenData; override; procedure CloseData; override; class function GetPageName: string; override; end; implementation uses DM, pFIBQuery, Typinfo, MAIN, ContactForma; {$R *.dfm} const clc_PE = 64; // Подъезд'/'этаж Город function PropertyExists(aObject: TObject; const aPropertyName: String): Boolean; begin Result := (GetPropInfo(aObject.ClassInfo, aPropertyName) <> nil); end; class function TapgCustomerInfo.GetPageName: string; begin Result := rsInformation; end; procedure TapgCustomerInfo.InitForm; var vVisibleSum: Boolean; vAsBalance: Boolean; vVisiblePassport: Boolean; vDec: Integer; DispNum: string; i: Integer; begin if TryStrToInt(dmMain.GetIniValue('FONT_SIZE'), i) then begin memCustNotice.Font.Size := i; memCustNotice.Font.Name := dmMain.GetIniValue('FONT_NAME'); end; dsContacts.DataSource := FDataSource; ds.DataSet := FDataSource.DataSet; {$IFNDEF DEMOVERSION} if Assigned(FGrid) then sbRecalc.PopupMenu := pmRecalc; {$ENDIF} { for i := 0 to pnlInfo.ControlCount - 1 do begin if PropertyExists(pnlInfo.Controls[i], 'DataSource') then SetObjectProp(pnlInfo.Controls[i],'DataSource',FDataSource); end; } // actCustomerEdit.Enabled := (ds.RecordCount>0) and actCustomerAdd.Enabled; // actCustomerDelete.Enabled := (ds.RecordCount>0) and (dmMain.AllowedAction(rght_Customer_del) or dmMain.AllowedAction(rght_Customer_full)); vVisibleSum := (dmMain.AllowedAction(rght_Customer_Debt)) or (dmMain.AllowedAction(rght_Customer_full)); vVisiblePassport := (dmMain.AllowedAction(rght_Customer_add)) or (dmMain.AllowedAction(rght_Customer_edit)) or (dmMain.AllowedAction(rght_Customer_full)); // просмотр сумм vAsBalance := (dmMain.GetSettingsValue('SHOW_AS_BALANCE') = '1'); // пеня vDec := dmMain.GetSettingsValue('FEE_ROUND'); if vDec > 0 then DispNum := '#,##0.00' else DispNum := '#,##0'; gbSaldo.Visible := vVisibleSum; if vVisibleSum then begin if vAsBalance then begin gbSaldo.Caption := rsBALANCE; DBTextDebt.DataField := 'BALANCE'; // DBTextDebt.DisplayFormat := DispNum; end else begin gbSaldo.Caption := rsSALDO; DBTextDebt.DataField := 'DEBT_SUM'; end; end; if not(TryStrToInt(dmMain.GetIniValue('COLUMNS'), fVisibleColumns)) then begin fVisibleColumns := 0; end; edBIRTHDAY.Visible := vVisiblePassport; edtPASSPORT_REGISTRATION.Visible := vVisiblePassport; edtPASSPORT_NUMBER.Visible := vVisiblePassport; edtPASP_REG.Visible := vVisiblePassport; lblBD.Visible := vVisiblePassport; lblPR.Visible := vVisiblePassport; lblPN.Visible := vVisiblePassport; lblPREG.Visible := vVisiblePassport; if not vVisiblePassport then begin memState.Top := edtAddress.Top + edtAddress.Height + 4; end; sbRecalc.Visible := (dmMain.AllowedAction(rght_Customer_AddSrv)) or (dmMain.AllowedAction(rght_Customer_full)); dbgrdhContacts.ReadOnly := not(dmMain.AllowedAction(rght_Customer_edit) or dmMain.AllowedAction(rght_Customer_full)); memCustNotice.ReadOnly := not(dmMain.AllowedAction(rght_Customer_edit) or dmMain.AllowedAction(rght_Customer_full)); {$IFNDEF DEMOVERSION} sbRecalc.PopupMenu := pmRecalc; {$ENDIF} end; procedure TapgCustomerInfo.memCustNoticeExit(Sender: TObject); begin SaveNotice; end; procedure TapgCustomerInfo.memCustNoticeKeyPress(Sender: TObject; var Key: Char); begin btnSaveNotice.Visible := (FSaveNotice <> memCustNotice.Lines.Text); end; procedure TapgCustomerInfo.SaveNotice; begin if (not FDataSource.DataSet.Active) or (FDataSource.DataSet.RecordCount = 0) then exit; if FSaveNotice <> memCustNotice.Lines.Text then begin FSaveNotice := memCustNotice.Lines.Text; with TpFIBQuery.Create(Nil) do try DataBase := dmMain.dbTV; Transaction := dmMain.trWriteQ; SQL.Text := 'UPDATE Customer SET Notice = :Notice WHERE (Customer_Id = :Customer_Id)'; ParamByName('Notice').AsString := FSaveNotice; ParamByName('Customer_Id').AsInt64 := FDataSource.DataSet['Customer_id']; Transaction.StartTransaction; ExecQuery; Transaction.Commit; FDataSource.DataSet.Refresh; finally Free; end; end; btnSaveNotice.Visible := (FSaveNotice <> memCustNotice.Lines.Text); end; procedure TapgCustomerInfo.N2Click(Sender: TObject); {$IFNDEF DEMOVERSION} var Save_Cursor: TCursor; i: Integer; {$ENDIF} begin {$IFNDEF DEMOVERSION} Save_Cursor := Screen.Cursor; Screen.Cursor := crHourGlass; { Show hourglass cursor } try if FGrid.SelectedRows.Count = 0 then begin FGrid.DataSource.DataSet.First; while not FGrid.DataSource.DataSet.Eof do begin RecalcCustomer(FGrid.DataSource.DataSet['customer_id']); Application.ProcessMessages; FGrid.DataSource.DataSet.Next; end; end else begin for i := 0 to FGrid.SelectedRows.Count - 1 do begin FGrid.DataSource.DataSet.Bookmark := FGrid.SelectedRows[i]; RecalcCustomer(FGrid.DataSource.DataSet['customer_id']); Application.ProcessMessages; end; end; finally Screen.Cursor := Save_Cursor; { Always restore to normal } end {$ENDIF} end; procedure TapgCustomerInfo.RecalcCustomer(const CUSTOMER_ID: Int64); begin with TpFIBQuery.Create(Self) do try DataBase := dmMain.dbTV; Transaction := dmMain.trWriteQ; Transaction.StartTransaction; SQL.Text := 'EXECUTE PROCEDURE FULL_RECALC_CUSTOMER(:CUST)'; ParamByName('CUST').AsInt64 := CUSTOMER_ID; ExecQuery; Transaction.Commit; dsCustomers_Refresh; finally Free; end end; procedure TapgCustomerInfo.dsContactsNewRecord(DataSet: TDataSet); begin dsContacts['CUSTOMER_ID'] := FDataSource.DataSet['CUSTOMER_ID']; dsContacts['Cc_type'] := 0; dsContacts['Cc_Notify'] := 1; end; procedure TapgCustomerInfo.dsCustomers_Refresh; begin FDataSource.DataSet.Refresh; FSaveNotice := memCustNotice.Lines.Text; end; procedure TapgCustomerInfo.OpenData; begin dsContacts.Open; FSaveNotice := memCustNotice.Lines.Text; end; procedure TapgCustomerInfo.sbRecalcClick(Sender: TObject); var b: TDateTime; Save_Cursor: TCursor; begin Save_Cursor := Screen.Cursor; b := Now(); Screen.Cursor := crSQLWait; try RecalcCustomer(FDataSource.DataSet['CUSTOMER_ID']); finally Screen.Cursor := Save_Cursor; end; b := b - Now(); ShowMessage(Format(rsCalculateComplite, [TimeToStr(b)])); end; procedure TapgCustomerInfo.srcCustomerDataChange(Sender: TObject; Field: TField); var ds: TDataSet; s: string; begin ds := FDataSource.DataSet; s := ds.FieldByName('SURNAME').AsString; if not ds.FieldByName('FIRSTNAME').IsNull then s := s + ' ' + ds.FieldByName('FIRSTNAME').AsString; if not ds.FieldByName('MIDLENAME').IsNull then s := s + ' ' + ds.FieldByName('MIDLENAME').AsString; edFIO.Text := s; s := ds.FieldByName('STREET_SHORT').AsString + ' ' + ds.FieldByName('STREET_NAME').AsString + rsHouse + ds.FieldByName('HOUSE_NO').AsString; if not ds.FieldByName('Flat_no').IsNull then s := s + rsFlatShort + ds.FieldByName('Flat_no').AsString; if (fVisibleColumns and clc_PE) <> 0 then begin if (ds.FieldDefs.IndexOf('Area_Name') >= 0) and (not ds.FieldByName('Area_Name').IsNull) then s := ds.FieldByName('Area_Name').AsString + ' ' + s; end; edtAddress.Text := s; if ds.FieldByName('Notice').IsNull then memCustNotice.Lines.Text := '' else memCustNotice.Lines.Text := ds.FieldByName('Notice').AsString; FSaveNotice := memCustNotice.Lines.Text; pnlPrepay.Visible := False; if not ds.FieldByName('PREPAY').IsNull then pnlPrepay.Visible := (ds.FieldByName('PREPAY').AsCurrency > 0); if not ds.FieldByName('HIS_COLOR').IsNull then try Self.Color := StringToColor(ds.FieldByName('HIS_COLOR').Value); except Self.Color := clBtnFace end else Self.Color := clBtnFace; if FCheckPassport then begin if (not ds.FieldByName('JURIDICAL').IsNull) and (ds['JURIDICAL'] = 0) then begin if (ds.FieldByName('PASSPORT_VALID').IsNull) then CnErrors.Dispose(edtPASSPORT_NUMBER) else if ds['PASSPORT_VALID'] = 0 then CnErrors.SetError(edtPASSPORT_NUMBER, rsPassportNotValid, iaMiddleLeft, bsNeverBlink) else if ds['PASSPORT_VALID'] = -1 then CnErrors.SetError(edtPASSPORT_NUMBER, rsError + '. ' + rsNeedPassportCheck, iaMiddleLeft, bsNeverBlink) else CnErrors.Dispose(edtPASSPORT_NUMBER); end else CnErrors.Dispose(edtPASSPORT_NUMBER); end; end; procedure TapgCustomerInfo.actCAddExecute(Sender: TObject); var Contact: TContact; begin if not(dmMain.AllowedAction(rght_Customer_edit) or dmMain.AllowedAction(rght_Customer_full)) then exit; if not dsContacts.Active then dsContacts.Open; Contact.cID := -1; if EditContact(Contact) then begin dsContacts.Insert; dsContacts['CUSTOMER_ID'] := FDataSource.DataSet['CUSTOMER_ID']; dsContacts['CC_TYPE'] := Contact.cID; dsContacts['CC_VALUE'] := Contact.Contact; dsContacts['CC_NOTICE'] := Contact.Notice; dsContacts['Cc_Notify'] := Contact.Notify; dsContacts['O_Name'] := Contact.cType; dsContacts.Post; dbgrdhContacts.SetFocus; end end; procedure TapgCustomerInfo.actCDelExecute(Sender: TObject); var s: String; begin if not(dmMain.AllowedAction(rght_Customer_edit) or dmMain.AllowedAction(rght_Customer_full)) then exit; if (not dsContacts.Active) or (dsContacts.RecordCount = 0) then exit; if not dsContacts.FieldByName('CC_VALUE').IsNull then s := Format(rsDeleteWithName, [dsContacts.FieldByName('CC_VALUE').AsString]) else s := rsContactDelete; if MessageDlg(s, mtConfirmation, [mbYes, mbNo], 0) = mrYes then dsContacts.Delete; end; procedure TapgCustomerInfo.actCEditExecute(Sender: TObject); var Contact: TContact; begin if not(dmMain.AllowedAction(rght_Customer_edit) or dmMain.AllowedAction(rght_Customer_full)) then exit; if (not dsContacts.Active) then dsContacts.Open; if dsContacts.RecordCount > 0 then begin Contact.cID := dsContacts['CC_TYPE']; if not dsContacts.FieldByName('CC_VALUE').IsNull then Contact.Contact := dsContacts['CC_VALUE'] else Contact.Contact := ''; if not dsContacts.FieldByName('CC_NOTICE').IsNull then Contact.Notice := dsContacts['CC_NOTICE'] else Contact.Notice := ''; if not dsContacts.FieldByName('Cc_Notify').IsNull then Contact.Notify := dsContacts['Cc_Notify'] else Contact.Notify := 0; if not dsContacts.FieldByName('O_Name').IsNull then Contact.cType := dsContacts['O_Name'] else Contact.cType := ''; end else Contact.cID := -1; if EditContact(Contact) then begin if dsContacts.RecordCount > 0 then dsContacts.Edit else dsContacts.Insert; dsContacts['CUSTOMER_ID'] := FDataSource.DataSet['CUSTOMER_ID']; dsContacts['CC_TYPE'] := Contact.cID; dsContacts['CC_VALUE'] := Contact.Contact; dsContacts['CC_NOTICE'] := Contact.Notice; dsContacts['Cc_Notify'] := Contact.Notify; dsContacts['O_Name'] := Contact.cType; dsContacts.Post; dbgrdhContacts.SetFocus; end end; procedure TapgCustomerInfo.actMakeCallExecute(Sender: TObject); begin if (dsContacts.RecordCount = 0) or (dsContacts.FieldByName('CC_TYPE').IsNull) or (dsContacts.FieldByName('CC_VALUE').IsNull) then exit; A4MainForm.MakeCall(dsContacts['CC_TYPE'], dsContacts['CC_VALUE']); end; procedure TapgCustomerInfo.btnSaveNoticeClick(Sender: TObject); begin SaveNotice; end; procedure TapgCustomerInfo.CloseData; begin dsContacts.Close; end; procedure TapgCustomerInfo.dsContactsBeforePost(DataSet: TDataSet); begin if dsContacts.State in [dsInsert, dsEdit] then if (dsContacts.FieldByName('CC_VALUE').IsNull) or (Trim(dsContacts.FieldByName('CC_VALUE').AsString) = '') then Abort; end; procedure TapgCustomerInfo.dbgrdhContactsDblClick(Sender: TObject); begin actMakeCallExecute(Sender); end; procedure TapgCustomerInfo.dbgrdhContactsExit(Sender: TObject); begin SaveContact; end; procedure TapgCustomerInfo.dbgrdhContactsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ActiveControl = dbgrdhContacts then begin case Key of VK_INSERT: actCAdd.Execute; VK_DELETE: actCDel.Execute; VK_F2: actCEdit.Execute; VK_RETURN: actMakeCall.Execute; end; end; end; procedure TapgCustomerInfo.SaveContact; begin if dsContacts.State in [dsInsert, dsEdit] then dsContacts.Post; end; procedure TapgCustomerInfo.srcContactsUpdateData(Sender: TObject); begin if dsContacts.State in [dsInsert, dsEdit] then if (dsContacts.FieldByName('CC_VALUE').IsNull) or (Trim(dsContacts.FieldByName('CC_VALUE').AsString) = '') then dsContacts.Cancel; end; procedure TapgCustomerInfo.FormResize(Sender: TObject); begin memState.Height := Self.Height - memState.Top - 5; end; procedure TapgCustomerInfo.FormShow(Sender: TObject); begin FCheckPassport := True; // (dmMain.GetSettingsValue('KEY_MVD') <> ''); end; end.
unit LUX.GPU.Vulkan.Comman; interface //#################################################################### ■ uses System.Generics.Collections, vulkan_core; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TVkCommans<TVkPooler_:class> = class; TVkComman<TVkPooler_:class> = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkComman TVkComman<TVkPooler_:class> = class private protected _Pooler :TVkPooler_; _Handle :VkCommandBuffer; ///// アクセス function GetHandle :VkCommandBuffer; procedure SetHandle( const Handle_:VkCommandBuffer ); ///// メソッド procedure CreateHandle; procedure DestroHandle; public constructor Create; overload; constructor Create( const Pooler_:TVkPooler_ ); overload; destructor Destroy; override; ///// プロパティ property Pooler :TVkPooler_ read _Pooler; property Handle :VkCommandBuffer read GetHandle write SetHandle; ///// メソッド procedure BeginRecord; procedure EndRecord; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkCommans TVkCommans<TVkPooler_:class> = class( TObjectList<TVkComman<TVkPooler_>> ) private type TVkComman_ = TVkComman<TVkPooler_>; protected _Pooler :TVkPooler_; public constructor Create( const Pooler_:TVkPooler_ ); destructor Destroy; override; ///// プロパティ property Pooler :TVkPooler_ read _Pooler; ///// メソッド function Add :TVkComman_; overload; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses LUX.GPU.Vulkan; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkComman //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkComman<TVkPooler_>.GetHandle :VkCommandBuffer; begin if not Assigned( _Handle ) then CreateHandle; Result := _Handle; end; procedure TVkComman<TVkPooler_>.SetHandle( const Handle_:VkCommandBuffer ); begin if Assigned( _Handle ) then DestroHandle; _Handle := Handle_; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TVkComman<TVkPooler_>.CreateHandle; var B :VkCommandBufferAllocateInfo; begin (* DEPENDS on init_swapchain_extension() and init_command_pool() *) with B do begin sType := VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; pNext := nil; commandPool := TVkPooler( _Pooler ).Handle; level := VK_COMMAND_BUFFER_LEVEL_PRIMARY; commandBufferCount := 1; end; Assert( vkAllocateCommandBuffers( TVkPooler( _Pooler ).Device.Handle, @B, @_Handle ) = VK_SUCCESS ); end; procedure TVkComman<TVkPooler_>.DestroHandle; var Bs :array [ 0..1-1 ] of VkCommandBuffer; begin Bs[0] := _Handle; vkFreeCommandBuffers( TVkPooler( _Pooler ).Device.Handle, TVkPooler( _Pooler ).Handle, 1, @Bs[0] ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkComman<TVkPooler_>.Create; begin inherited; _Handle := nil; end; constructor TVkComman<TVkPooler_>.Create( const Pooler_:TVkPooler_ ); begin Create; _Pooler := Pooler_; TVkPooler( _Pooler ).Commans.Add( TVkComman( Self ) ); end; destructor TVkComman<TVkPooler_>.Destroy; begin Handle := nil; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TVkComman<TVkPooler_>.BeginRecord; var B :VkCommandBufferBeginInfo; begin (* DEPENDS on init_command_buffer() *) with B do begin sType := VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; pNext := nil; flags := 0; pInheritanceInfo := nil; end; Assert( vkBeginCommandBuffer( Handle, @B ) = VK_SUCCESS ); end; procedure TVkComman<TVkPooler_>.EndRecord; begin Assert( vkEndCommandBuffer( Handle ) = VK_SUCCESS ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkCommans //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkCommans<TVkPooler_>.Create( const Pooler_:TVkPooler_ ); begin inherited Create; _Pooler := Pooler_; end; destructor TVkCommans<TVkPooler_>.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TVkCommans<TVkPooler_>.Add :TVkComman_; begin Result := TVkComman_.Create( _Pooler ); end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit MFichas.Model.Item; interface uses System.SysUtils, MFichas.Model.Item.Interfaces, MFichas.Model.Item.Metodos.Factory, MFichas.Model.Item.Iterator, MFichas.Model.Item.Metodos.GravarNoBanco, MFichas.Model.Entidade.VENDAITENS, MFichas.Model.Venda.Interfaces; type TModelItem = class(TInterfacedObject, iModelItem, iModelItemMetodos) private [weak] FParent : iModelVenda; FIterator: iModelItemIterator; FEntidade: TVENDAITENS; constructor Create(AParent: iModelVenda); public destructor Destroy; override; class function New(AParent: iModelVenda): iModelItem; function Metodos : iModelItemMetodos; function Entidade : TVENDAITENS; overload; function Entidade(AEntidade: TVENDAITENS): iModelItem; overload; function Iterator : iModelItemIterator; function GravarNoBanco : iModelItemGravarNoBanco; function ValorTotal : Currency; //METODOS function Vender : iModelItemMetodosVender; function Cancelar : iModelItemMetodosCancelar; function Devolver : iModelItemMetodosDevolver; function &End : iModelItem; end; implementation { TModelItem } function TModelItem.&End: iModelItem; begin Result := Self; end; function TModelItem.Entidade: TVENDAITENS; begin Result := FEntidade; end; function TModelItem.Entidade(AEntidade: TVENDAITENS): iModelItem; begin Result := Self; FEntidade := AEntidade; end; function TModelItem.Cancelar: iModelItemMetodosCancelar; begin Result := TModelItemMetodosFactory.New.Cancelar(Self); end; constructor TModelItem.Create(AParent: iModelVenda); begin FParent := AParent; FIterator := TModelItemIterator.New(Self); FEntidade := TVENDAITENS.Create; end; destructor TModelItem.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; {$ENDIF} inherited; end; function TModelItem.Devolver: iModelItemMetodosDevolver; begin Result := TModelItemMetodosFactory.New.Devolver(Self, FParent); end; function TModelItem.GravarNoBanco: iModelItemGravarNoBanco; begin Result := TModelItemMetodosGravarNoBanco.New(Self); end; function TModelItem.Iterator: iModelItemIterator; begin Result := FIterator; end; function TModelItem.Metodos: iModelItemMetodos; begin Result := Self; end; class function TModelItem.New(AParent: iModelVenda): iModelItem; begin Result := Self.Create(AParent); end; function TModelItem.ValorTotal: Currency; var LItem: TVENDAITENS; begin Result := 0; while FIterator.hasNext do begin LItem := FIterator.Next.Entidade; Result := Result + (LItem.PRECO * LItem.QUANTIDADE); end; end; function TModelItem.Vender: iModelItemMetodosVender; begin Result := TModelItemMetodosFactory.New.Vender(Self, FParent); end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Math, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, DPF.iOS.BaseControl, DPF.iOS.Common, iOSapi.CoreGraphics, iOSApi.UIKit, iOSApi.QuartzCore, iOSapi.Foundation, iOSapi.CoreText, iOSapi.CocoaTypes, Macapi.CoreFoundation, DPF.iOS.UIView, DPF.iOS.UISlider, DPF.iOS.UIButton; type TFDrawingNative = class( TForm ) DPFUIView1: TDPFUIView; DPFUIView2: TDPFUIView; DPFSlider1: TDPFSlider; DPFButton1: TDPFButton; procedure FormShow( Sender: TObject ); procedure DPFUIView1TouchesBegan( Sender: TObject; const Location: DPFNSPoint; const PreviousLocation: DPFNSPoint ); procedure DPFUIView1TouchesMoved( Sender: TObject; const Location: DPFNSPoint; const PreviousLocation: DPFNSPoint ); procedure DPFUIView1TouchesEnded( Sender: TObject; const TapCount: Integer; const Location: DPFNSPoint; const PreviousLocation: DPFNSPoint ); procedure DPFUIView1DrawRect( Sender: TObject; Rect: DPFNSRect ); procedure DPFSlider1Changed( Sender: TObject; CurValue: Single ); procedure DPFButton1Click( Sender: TObject ); private { Private declarations } lineColor : UIColor; DEFAULT_BACKGROUND_COLOR: UIColor; isEmpty: Boolean; lineWidth : Single; previousPoint1: DPFNSPoint; previousPoint2: DPFNSPoint; currentPoint : DPFNSPoint; path: CGMutablePathRef; protected procedure PaintRects( const UpdateRects: array of TRectF ); override; public { Public declarations } end; var FDrawingNative: TFDrawingNative; implementation {$R *.fmx} const kPointMinDistance = 5; kPointMinDistanceSquared = kPointMinDistance * kPointMinDistance; // --------------------------------------------------------------------------- function midPoint( p1: DPFNSPoint; p2: DPFNSPoint ): DPFNSPoint; begin Result.x := ( p1.x + p2.x ) * 0.5; Result.y := ( p1.y + p2.y ) * 0.5; end; // --------------------------------------------------------------------------- procedure TFDrawingNative.DPFButton1Click( Sender: TObject ); begin path := CGPathCreateMutable( ); DPFUIView1.GetUIView.setNeedsDisplay; end; // --------------------------------------------------------------------------- procedure TFDrawingNative.DPFSlider1Changed( Sender: TObject; CurValue: Single ); begin lineWidth := CurValue; end; // --------------------------------------------------------------------------- procedure TFDrawingNative.DPFUIView1DrawRect( Sender: TObject; Rect: DPFNSRect ); var context: CGContextRef; begin // [self.backgroundColor set]; // UIRectFill(rect); context := UIGraphicsGetCurrentContext( ); CGContextAddPath( context, path ); CGContextSetLineCap( context, kCGLineCapRound ); CGContextSetLineWidth( context, self.lineWidth ); CGContextSetStrokeColorWithColor( context, self.lineColor.CGColor ); CGContextStrokePath( context ); isEmpty := False; end; procedure TFDrawingNative.DPFUIView1TouchesBegan( Sender: TObject; const Location: DPFNSPoint; const PreviousLocation: DPFNSPoint ); begin previousPoint1 := PreviousLocation; previousPoint2 := PreviousLocation; currentPoint := Location; DPFUIView1TouchesMoved( Sender, Location, PreviousLocation ); end; // --------------------------------------------------------------------------- procedure TFDrawingNative.DPFUIView1TouchesMoved( Sender: TObject; const Location, PreviousLocation: DPFNSPoint ); var mid1, mid2, point: DPFNSPoint; dx, dy : CGFloat; subpath : CGMutablePathRef; bounds : CGRect; drawBox : CGRect; begin point := Location; // check if the point is farther than min dist from previous dx := point.x - currentPoint.x; dy := point.y - currentPoint.y; if ( ( dx * dx + dy * dy ) < kPointMinDistanceSquared ) then Exit; previousPoint2 := previousPoint1; previousPoint1 := previousLocation; currentPoint := location; mid1 := midPoint( previousPoint1, previousPoint2 ); mid2 := midPoint( currentPoint, previousPoint1 ); subpath := CGPathCreateMutable( ); CGPathMoveToPoint( subpath, nil, mid1.x, mid1.y ); CGPathAddQuadCurveToPoint( subpath, nil, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y ); bounds := CGPathGetBoundingBox( subpath ); CGPathAddPath( path, nil, subpath ); CGPathRelease( subpath ); drawBox := bounds; drawBox.origin.x := drawBox.origin.x - self.lineWidth * 2.0; drawBox.origin.y := drawBox.origin.y - self.lineWidth * 2.0; drawBox.size.width := drawBox.size.width + self.lineWidth * 4.0; drawBox.size.height := drawBox.size.height + self.lineWidth * 4.0; DPFUIView1.GetUIView.setNeedsDisplayInRect( drawBox ); end; // --------------------------------------------------------------------------- procedure TFDrawingNative.DPFUIView1TouchesEnded( Sender: TObject; const TapCount: Integer; const Location: DPFNSPoint; const PreviousLocation: DPFNSPoint ); begin { } end; // --------------------------------------------------------------------------- procedure TFDrawingNative.FormShow( Sender: TObject ); begin lineWidth := 5.0; lineColor := TUIColor.Wrap( TUIColor.OCClass.blackColor ); DEFAULT_BACKGROUND_COLOR := TUIColor.Wrap( TUIColor.OCClass.whiteColor ); path := CGPathCreateMutable( ); end; // ----------------------------------------------------------------------------- procedure TFDrawingNative.PaintRects( const UpdateRects: array of TRectF ); begin { } end; // ----------------------------------------------------------------------------- end.
{******************************************************************************* 作者: dmzn@163.com 2009-7-8 描述: 方案管理 *******************************************************************************} unit UFormEditPlan; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, UDataModule, UBgFormBase, UTransPanel, cxGraphics, dxLayoutControl, cxMCListBox, StdCtrls, cxPC, cxDropDownEdit, cxMaskEdit, cxButtonEdit, cxMemo, cxContainer, cxEdit, cxTextEdit, cxControls; type TfFormEditPlan = class(TfBgFormBase) dxLayout1: TdxLayoutControl; BtnOK: TButton; BtnExit: TButton; EditName: TcxTextEdit; EditMemo: TcxMemo; EditID: TcxButtonEdit; EditPlan: TcxComboBox; EditSkin: TcxComboBox; EditDate: TcxTextEdit; EditMan: TcxTextEdit; wPage: TcxPageControl; cxSheet1: TcxTabSheet; Label1: TLabel; Label2: TLabel; EditInfo: TcxTextEdit; InfoItems: TcxComboBox; BtnAdd: TButton; BtnDel: TButton; ListInfo1: TcxMCListBox; cxSheet2: TcxTabSheet; Label3: TLabel; Label4: TLabel; ProductItmes: TcxComboBox; BtnAdd2: TButton; BtnDel2: TButton; EditReason: TcxMemo; ListProduct1: TcxMCListBox; dxLayoutGroup1: TdxLayoutGroup; dxGroup1: TdxLayoutGroup; dxLayout1Group3: TdxLayoutGroup; dxLayout1Item3: TdxLayoutItem; dxLayout1Item5: TdxLayoutItem; dxLayout1Group4: TdxLayoutGroup; dxLayout1Item4: TdxLayoutItem; dxLayout1Item12: TdxLayoutItem; dxLayout1Group5: TdxLayoutGroup; dxLayout1Item14: TdxLayoutItem; dxLayout1Item13: TdxLayoutItem; dxLayout1Item6: TdxLayoutItem; dxLayout1Item15: TdxLayoutItem; dxLayoutGroup2: TdxLayoutGroup; dxLayoutItem1: TdxLayoutItem; dxLayout1Item2: TdxLayoutItem; EditPlanList: TcxComboBox; dxLayout1Item1: TdxLayoutItem; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnExitClick(Sender: TObject); procedure BtnAddClick(Sender: TObject); procedure BtnDelClick(Sender: TObject); procedure BtnAdd2Click(Sender: TObject); procedure BtnDel2Click(Sender: TObject); procedure ListProduct1Click(Sender: TObject); procedure ListInfo1Click(Sender: TObject); procedure EditIDPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure BtnOKClick(Sender: TObject); procedure EditPlanListPropertiesChange(Sender: TObject); private { Private declarations } FMemberID: string; //会员编号 FSkinType: string; //皮肤标识 FDisplayRect: TRect; //显示区域 FPrefixID: string; //前缀编号 FIDLength: integer; //前缀长度 FDataInfoChanged,FDataProductChanged: Boolean; //数据变动 procedure InitFormData(const nID: string); //初始化数据 function SaveData: Boolean; //保存数据 public { Public declarations } FDataChanged: Boolean; //数据变动 end; function ShowPlanEditForm(const nMemberID,nSkinType: string; const nRect: TRect): TForm; //入口函数 implementation {$R *.dfm} uses IniFiles, ULibFun, UFormCtrl, UAdjustForm, USysGrid, USysDB, USysConst, USysFun, USysGobal; var gForm: TForm = nil; //------------------------------------------------------------------------------ //Date: 2009-7-3 //Parm: 会员号;皮肤标识;显示区域 //Desc: 在nRect区域显示方案管理窗口 function ShowPlanEditForm(const nMemberID,nSkinType: string; const nRect: TRect): TForm; begin Result := gForm; if Assigned(gForm) then Exit; gForm := TfFormEditPlan.Create(gForm); Result := gForm; with TfFormEditPlan(Result) do begin Position := poDesigned; Left := nRect.Left + Round((nRect.Right - nRect.Left - Width) /2 ); Top := nRect.Top + Round((nRect.Bottom - nRect.Top - Height) /2 ); FMemberID := nMemberID; FSkinType := nSkinType; FDisplayRect := nRect; FDataChanged := False; InitFormData(''); if not Showing then Show; end; end; procedure TfFormEditPlan.FormCreate(Sender: TObject); var nIni: TIniFile; begin inherited; nIni := TIniFile.Create(gPath + sFormConfig); try LoadMCListBoxConfig(Name, ListInfo1, nIni); LoadMCListBoxConfig(Name, ListProduct1, nIni); FPrefixID := nIni.ReadString(Name, 'IDPrefix', 'FA'); FIDLength := nIni.ReadInteger(Name, 'IDLength', 8); finally nIni.Free; end; AdjustCtrlData(Self); ResetHintAllCtrl(Self, 'T', sTable_Plan); end; procedure TfFormEditPlan.FormClose(Sender: TObject; var Action: TCloseAction); var nIni: TIniFile; begin inherited; if Action <> caFree then Exit; gForm := nil; ReleaseCtrlData(Self); if Assigned(gOnCloseActiveForm) then gOnCloseActiveForm(Self); nIni := TIniFile.Create(gPath + sFormConfig); try SaveMCListBoxConfig(Name, ListInfo1, nIni); SaveMCListBoxConfig(Name, ListProduct1, nIni); finally nIni.Free; end; end; procedure TfFormEditPlan.BtnExitClick(Sender: TObject); begin CloseForm; end; //------------------------------------------------------------------------------ //Desc: 初始化界面 procedure TfFormEditPlan.InitFormData(const nID: string); var nStr: string; begin EditMan.Text := gSysParam.FUserName; EditDate.Text := DateTime2Str(Now); if InfoItems.Properties.Items.Count < 1 then begin InfoItems.Clear; nStr := MacroValue(sQuery_SysDict, [MI('$Table', sTable_SysDict), MI('$Name', sFlag_PlanItem)]); //数据字典中护理方案信息项 with FDM.QueryTemp(nStr) do begin First; while not Eof do begin InfoItems.Properties.Items.Add(FieldByName('D_Value').AsString); Next; end; end; end; if EditSkin.Properties.Items.Count < 1 then begin nStr := 'T_ID=Select T_ID,T_Name From ' + sTable_SkinType; FDM.FillStringsData(EditSkin.Properties.Items, nStr, -1, '、'); AdjustCXComboBoxItem(EditSkin, False); SetCtrlData(EditSkin, FSkinType); end; if EditPlan.Properties.Items.Count < 1 then begin nStr := 'B_ID=Select B_ID,B_Text From %s Where B_Group=''%s'''; nStr := Format(nStr, [sTable_BaseInfo, sFlag_PlanItem]); FDM.FillStringsData(EditPlan.Properties.Items, nStr, -1, '、'); AdjustCXComboBoxItem(EditPlan, False); end; if EditPlanList.Properties.Items.Count < 1 then begin nStr := 'P_ID=Select P_ID,P_Name From %s'; nStr := Format(nStr, [sTable_Plan]); FDM.FillStringsData(EditPlanList.Properties.Items, nStr, -1, '、'); AdjustStringsItem(EditPlanList.Properties.Items, False); end; if ProductItmes.Properties.Items.Count < 1 then begin nStr := 'P_ID=Select P_ID, P_Name, ' + ' (Select B_Text From $Base a Where a.B_ID=t.P_Type) as P_TName,' + ' (Select P_Name From $Plant b Where b.P_ID=t.P_Plant) as P_PName ' + 'From $Pro t'; nStr := MacroValue(nStr, [MI('$Base', sTable_BaseInfo),MI('$Plant', sTable_Plant), MI('$Pro', sTable_Product)]); FDM.FillStringsData(ProductItmes.Properties.Items, nStr); AdjustCXComboBoxItem(ProductItmes, False); end; if nID <> '' then begin FDataInfoChanged := False; FDataProductChanged := False; nStr := 'Select * From %s Where P_ID=''%s'''; nStr := Format(nStr, [sTable_Plan, nID]); LoadDataToCtrl(FDM.QueryTemp(nStr), Self, ''); ListInfo1.Clear; nStr := MacroValue(sQuery_ExtInfo, [MI('$Table', sTable_ExtInfo), MI('$Group', sFlag_PlanItem), MI('$ID', nID)]); //扩展信息 with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin First; while not Eof do begin nStr := FieldByName('I_Item').AsString + ListInfo1.Delimiter + FieldByName('I_Info').AsString; ListInfo1.Items.Add(nStr); Next; end; end; nStr := 'Select E_Product, E_Memo, ' + ' (Select P_Name From $Pro Where P_ID=E_Product) as E_PName ' + 'From $Plan Where E_Plan=''$ID'''; nStr := MacroValue(nStr, [MI('$Pro', sTable_Product), MI('$Plan', sTable_PlanExt), MI('$ID', nID)]); ListProduct1.Clear; with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin First; while not Eof do begin nStr := FieldByName('E_Product').AsString + ListInfo1.Delimiter + FieldByName('E_PName').AsString + ListInfo1.Delimiter + FieldByName('E_Memo').AsString + ' '; ListProduct1.Items.Add(nStr); Next; end; end; end; end; //Desc: 添加信息项 procedure TfFormEditPlan.BtnAddClick(Sender: TObject); begin InfoItems.Text := Trim(InfoItems.Text); if InfoItems.Text = '' then begin ListInfo1.SetFocus; FDM.ShowMsg('请填写 或 选择有效的信息项', sHint); Exit; end; EditInfo.Text := Trim(EditInfo.Text); if EditInfo.Text = '' then begin EditInfo.SetFocus; FDM.ShowMsg('请填写有效的信息内容', sHint); Exit; end; ListInfo1.Items.Add(InfoItems.Text + ListInfo1.Delimiter + EditInfo.Text); FDataInfoChanged := True; end; //Desc: 删除信息项 procedure TfFormEditPlan.BtnDelClick(Sender: TObject); var nIdx: integer; begin if ListInfo1.ItemIndex < 0 then begin FDM.ShowMsg('请选择要删除的内容', sHint); Exit; end; nIdx := ListInfo1.ItemIndex; ListInfo1.Items.Delete(ListInfo1.ItemIndex); FDataInfoChanged := True; if nIdx >= ListInfo1.Count then Dec(nIdx); ListInfo1.ItemIndex := nIdx; FDM.ShowMsg('信息项已删除', sHint); end; //Desc: 查看信息 procedure TfFormEditPlan.ListInfo1Click(Sender: TObject); var nStr: string; nPos: integer; begin if ListInfo1.ItemIndex > -1 then begin nStr := ListInfo1.Items[ListInfo1.ItemIndex]; nPos := Pos(ListInfo1.Delimiter, nStr); InfoItems.Text := Copy(nStr, 1, nPos - 1); System.Delete(nStr, 1, nPos + Length(ListInfo1.Delimiter) - 1); EditInfo.Text := nStr; end; end; //Desc: 增加产品 procedure TfFormEditPlan.BtnAdd2Click(Sender: TObject); var nStr: string; nList: TStrings; begin if ProductItmes.ItemIndex < 0 then begin ProductItmes.SetFocus; FDM.ShowMsg('请选择有效的产品', sHint); Exit; end; nList := TStringList.Create; try nStr := ProductItmes.Properties.Items[ProductItmes.ItemIndex]; if not SplitStr(nStr, nList, 4, '|') then begin FDM.ShowMsg('无效的产品记录', sHint); Exit; end; nStr := GetCtrlData(ProductItmes) + ListProduct1.Delimiter + nList[1] + ListProduct1.Delimiter + EditReason.Text + ' '; ListProduct1.Items.Add(nStr); FDataProductChanged := True; finally nList.Free; end; end; //Desc: 删除产品 procedure TfFormEditPlan.BtnDel2Click(Sender: TObject); var nIdx: integer; begin if ListProduct1.ItemIndex < 0 then begin FDM.ShowMsg('请选择要删除的产品', sHint); Exit; end; nIdx := ListProduct1.ItemIndex; ListProduct1.Items.Delete(ListProduct1.ItemIndex); FDataProductChanged := True; if nIdx >= ListProduct1.Count then Dec(nIdx); ListProduct1.ItemIndex := nIdx; FDM.ShowMsg('已成功删除', sHint); end; //Desc: 查看明细 procedure TfFormEditPlan.ListProduct1Click(Sender: TObject); var nStr: string; nList: TStrings; begin nList := nil; if ListProduct1.ItemIndex > -1 then try nList := TStringList.Create; nStr := ListProduct1.Items[ListProduct1.ItemIndex]; if SplitStr(nStr, nList, 3, ListProduct1.Delimiter) then begin SetCtrlData(ProductItmes, nList[0]); EditReason.Text := Trim(nList[2]); end; finally if Assigned(nList) then nList.Free; end; end; //Desc: 随机编号 procedure TfFormEditPlan.EditIDPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin EditMan.Text := gSysParam.FUserID; EditDate.Text := DateTime2Str(Now); SetCtrlData(EditSkin, FSkinType); EditID.Text := FDM.GetRandomID(FPrefixID, FIDLength); end; procedure TfFormEditPlan.EditPlanListPropertiesChange(Sender: TObject); begin InitFormData(GetCtrlData(EditPlanList)); end; //------------------------------------------------------------------------------ //Desc: 保存数据 function TfFormEditPlan.SaveData: Boolean; var nIsNew: Boolean; nList: TStrings; i,nCount: integer; nStr,nSQL: string; begin Result := True; nStr := 'Select * From %s Where P_ID=''%s'''; nStr := Format(nStr, [sTable_Plan, EditID.Text]); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin if not (gSysParam.FIsAdmin or (FieldByName('P_Man').AsString = gSysParam.FUserName)) then Exit; if EditID.Text <> GetCtrlData(EditPlanList) then begin EditID.SetFocus; FDM.ShowMsg('该编号已经被使用', sHint); Exit; end else nIsNew := False; end else begin nIsNew := True; FDataInfoChanged := True; FDataProductChanged := True; EditMan.Text := gSysParam.FUserID; EditDate.Text := DateTime2Str(Now); end; nList := nil; FDM.ADOConn.BeginTrans; try nStr := 'P_ID=''' + EditID.Text + ''''; nSQL := MakeSQLByForm(Self, sTable_Plan, nStr, nIsNew, nil); FDM.ExecuteSQL(nSQL); if gSysDBType = dtAccess then begin nSQL := 'Insert Into %s(S_Table, S_Field, S_Value) ' + 'Values(''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_Plan, 'P_ID', EditID.Text]); FDM.ExecuteSQL(nSQL); end; //记录变更 if FDataInfoChanged then begin if not nIsNew then begin nSQL := 'Delete From %s Where I_Group=''%s'' and I_ItemID=''%s'''; nSQL := Format(nSQL, [sTable_ExtInfo, sFlag_PlanItem, EditID.Text]); FDM.ExecuteSQL(nSQL); end; nList := TStringList.Create; nCount := ListInfo1.Items.Count - 1; nSQL := 'Insert Into %s(I_Group, I_ItemID, I_Item, I_Info) ' + 'Values(''%s'', ''%s'', ''%s'', ''%s'')'; //xxxxx for i:=0 to nCount do begin nStr := ListInfo1.Items[i]; if not SplitStr(nStr, nList, 2, ListInfo1.Delimiter) then Continue; nStr := Format(nSQL, [sTable_ExtInfo, sFlag_PlanItem, EditID.Text, nList[0], nList[1]]); FDM.ExecuteSQL(nStr); end; if gSysDBType = dtAccess then begin nSQL := 'Insert Into %s(S_Table, S_Field, S_Value, S_ExtField, S_ExtValue) ' + 'Values(''%s'', ''%s'', ''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_ExtInfo, 'I_ItemID', EditID.Text, 'I_Group', sFlag_PlanItem]); FDM.ExecuteSQL(nSQL); end; //记录变更 end; if FDataProductChanged then begin if not nIsNew then begin nSQL := 'Delete From %s Where E_Plan=''%s'''; nSQL := Format(nSQL, [sTable_PlanExt, EditID.Text]); FDM.ExecuteSQL(nSQL); end; if not Assigned(nList) then nList := TStringList.Create; nCount := ListProduct1.Items.Count - 1; nSQL := 'Insert Into %s(E_Plan, E_Product, E_Memo) ' + 'Values(''%s'', ''%s'', ''%s'')'; //xxxxx for i:=0 to nCount do begin nStr := ListProduct1.Items[i]; if not SplitStr(nStr, nList, 3, ListProduct1.Delimiter) then Continue; nStr := Format(nSQL, [sTable_PlanExt, EditID.Text, nList[0], nList[2]]); FDM.ExecuteSQL(nStr); end; if gSysDBType = dtAccess then begin nSQL := 'Insert Into %s(S_Table, S_Field, S_Value) ' + 'Values(''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_PlanExt, 'E_Plan', EditID.Text]); FDM.ExecuteSQL(nSQL); end; //记录变更 end; if gSysParam.FGroupID = IntToStr(cBeauticianGroup) then nStr := gSysParam.FBeautyID else nStr := gSysParam.FUserID; nSQL := 'Insert Into %s(U_PID, U_MID, U_BID, U_Date) ' + ' Values(''%s'', ''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_PlanUsed, EditID.Text, FMemberID, nStr, DateTime2Str(Now)]); FDM.ExecuteSQL(nSQL); if gSysDBType = dtAccess then begin nSQL := 'Insert Into %s(S_Table, S_Field, S_Value) ' + 'Values(''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_PlanUsed, 'U_PID', EditID.Text]); FDM.ExecuteSQL(nSQL); end; //记录变更 FreeAndNil(nList); FDM.ADOConn.CommitTrans; FDM.ShowMsg('数据已保存', sHint); except Result := False; FreeAndNil(nList); FDM.ADOConn.RollbackTrans; FDM.ShowMsg('保存分析结果失败', '未知原因'); end; end; //Desc: 保存 procedure TfFormEditPlan.BtnOKClick(Sender: TObject); begin EditID.Text := Trim(EditID.Text); if EditID.Text = '' then begin EditID.SetFocus; FDM.ShowMsg('请填写有效的方案编号', sHint); Exit; end; EditName.Text := Trim(EditName.Text); if EditName.Text = '' then begin EditName.SetFocus; FDM.ShowMsg('请填写有效的方案名称', sHint); Exit; end; if SaveData then begin FDataChanged := True; CloseForm; end; end; end.
{ Routines to create various SST expressions for use in syntax parsing * functions. } module sst_r_syn_exp; define sst_r_syn_exp_ichar; define sst_r_syn_exp_pfunc; define sst_r_syn_exp_exp2; %include 'sst_r_syn.ins.pas'; { ******************************************************************************** * * Function SST_R_SYN_EXP_ICHAR * * Create the SST expression that is the value of the function SYN_P_ICHAR. * The function returns a pointer to the newly-created expression. This * function must be called when a syntax parsing function is being written, * since it references that functions call argument. } function sst_r_syn_exp_ichar: {create SST expression for SYN_P_ICHAR value} sst_exp_p_t; {pointer to the new expression descriptor} val_param; var exp_p: sst_exp_p_t; {pointer to expression being built} proc_p: sst_proc_p_t; {pointer to called procedure descriptor} arg_p: sst_proc_arg_p_t; {pointer to call argument} begin { * Create the call argument descriptor. } sst_mem_alloc_scope ( {create the empty descriptor} sizeof(arg_p^), arg_p); arg_p^ := sym_ichar_p^.proc.first_arg_p^; {init from template} arg_p^.next_p := nil; {there is no following argument} arg_p^.exp_p := exp_syn_p; {pointer to SYN argument value expression} { * Create desciptor for the function call. } sst_mem_alloc_scope ( {create called routine descriptor} sizeof(proc_p^), proc_p); proc_p^ := sym_ichar_p^.proc; {initialize called function from template} proc_p^.first_arg_p := arg_p; {point to first (and only) call argument} { * Create the expression for the value of the called function. } sst_mem_alloc_scope ( {create expression descriptor} sizeof(exp_p^), exp_p); exp_p^.str_h.first_char.crange_p := nil; exp_p^.dtype_p := sym_int_p^.dtype_dtype_p; {expression type is machine integer} exp_p^.dtype_hard := true; {data type is known and fixed} exp_p^.val_eval := true; {attempted to resolve value} exp_p^.val_fnd := false; {fixed value not found} exp_p^.rwflag := [sst_rwflag_read_k]; {expression is read-only} exp_p^.term1.next_p := nil; {there is no next term} exp_p^.term1.op2 := sst_op2_none_k; {no operator with previous term} exp_p^.term1.op1 := sst_op1_none_k; {no unary operator applying to this term} exp_p^.term1.ttype := sst_term_func_k; {term is the value of a function} exp_p^.term1.str_h.first_char.crange_p := nil; exp_p^.term1.dtype_p := exp_p^.dtype_p; {same data type as whole expression} exp_p^.term1.dtype_hard := true; {data type is known and fixed} exp_p^.term1.val_eval := true; {tried to resolve value} exp_p^.term1.val_fnd := false; {not a known fixed value} exp_p^.term1.rwflag := [sst_rwflag_read_k]; {term is read-only} exp_p^.term1.func_var_p := var_ichar_p; {"variable" reference for calling the function} exp_p^.term1.func_proc_p := proc_p; {point to function call descriptor} exp_p^.term1.func_proct_p := {point to the procedure template} addr(sym_ichar_p^.proc); sst_r_syn_exp_ichar := exp_p; {return pointer to the function result expression} end; { ******************************************************************************** * * Function SST_R_SYN_EXP_PFUNC (SYM) * * Create the expression that is the value of a syntax parsing function. SYM * is the function symbol. Such functions always take the SYN argument, and * return TRUE of FALSE depending on whether the input stream matched the * syntax template. } function sst_r_syn_exp_pfunc ( {create expression for value of syn parsing func} in var sym: sst_symbol_t) {syntax parsing funtion symbol} :sst_exp_p_t; {pointer to expression referencing the function} val_param; var exp_p: sst_exp_p_t; {pointer to expression being built} proc_p: sst_proc_p_t; {pointer to called procedure descriptor} arg_p: sst_proc_arg_p_t; {pointer to call argument} begin { * Create the call argument descriptor. } sst_mem_alloc_scope ( {create the empty descriptor} sizeof(arg_p^), arg_p); arg_p^ := sym.proc.first_arg_p^; {init from template} arg_p^.next_p := nil; {there is no following argument} arg_p^.exp_p := exp_syn_p; {pointer to SYN argument value expression} { * Create desciptor for the function call. } sst_mem_alloc_scope ( {create called routine descriptor} sizeof(proc_p^), proc_p); proc_p^ := sym.proc; {initialize called function from template} proc_p^.first_arg_p := arg_p; {point to first (and only) call argument} { * Create the expression for the value of the called function. } sst_mem_alloc_scope ( {create expression descriptor} sizeof(exp_p^), exp_p); exp_p^.str_h.first_char.crange_p := nil; exp_p^.dtype_p := sym.proc_dtype_p; {expression dtype is function return dtype} exp_p^.dtype_hard := true; {data type is known and fixed} exp_p^.val_eval := true; {attempted to resolve value} exp_p^.val_fnd := false; {fixed value not found} exp_p^.rwflag := [sst_rwflag_read_k]; {expression is read-only} exp_p^.term1.next_p := nil; {there is no next term} exp_p^.term1.op2 := sst_op2_none_k; {no operator with previous term} exp_p^.term1.op1 := sst_op1_none_k; {no unary operator applying to this term} exp_p^.term1.ttype := sst_term_func_k; {term is the value of a function} exp_p^.term1.str_h.first_char.crange_p := nil; exp_p^.term1.dtype_p := exp_p^.dtype_p; {same data type as whole expression} exp_p^.term1.dtype_hard := true; {data type is known and fixed} exp_p^.term1.val_eval := true; {tried to resolve value} exp_p^.term1.val_fnd := false; {not a known fixed value} exp_p^.term1.rwflag := [sst_rwflag_read_k]; {term is read-only} exp_p^.term1.func_var_p := {"variable" reference for calling the function} sst_r_syn_var_proc (sym); exp_p^.term1.func_proc_p := proc_p; {point to function call descriptor} exp_p^.term1.func_proct_p := {point to the procedure template} addr(sym.proc); sst_r_syn_exp_pfunc := exp_p; {return pointer to the function value expression} end; { ******************************************************************************** * * Subrtoutine SST_R_SYN_EXP_EXP2 (EXP1, EXP1, OP, EXP_P) * * Create the expression resulting from combining two sub-expressions. EXP1 * and EXP2 are the two sub-expressions. OP is the operator between them. * EXP_P is returned pointing to the new combined expression. } procedure sst_r_syn_exp_exp2 ( {exp from operation on two sub-exp} in var exp1: sst_exp_t; {first sub-expression} in var exp2: sst_exp_t; {second sub-expression} in op: sst_op2_k_t; {operator between the two sub-expressions} out exp_p: sst_exp_p_t); {returned pointer to new combined expression} val_param; var dtype_p: sst_dtype_p_t; {pnt to data type of combined expression} term_p: sst_exp_term_p_t; {second term of combined expression} begin case op of {which operator ?} sst_op2_eq_k, sst_op2_ne_k, sst_op2_ge_k, sst_op2_le_k, sst_op2_lt_k, sst_op2_and_k, sst_op2_or_k, sst_op2_andthen_k, sst_op2_orelse_k, sst_op2_in_k: begin {operators that always result in BOOLEAN} dtype_p := sst_dtype_bool_p; end; otherwise writeln ('INTERNAL ERROR: Operator with ID ', ord(op), ' not supported'); writeln ('in SST_R_SYN_EXP_EXP2.'); sys_bomb; end; sst_mem_alloc_scope ( {create combined expression descriptor} sizeof(exp_p^), exp_p); exp_p^.str_h.first_char.crange_p := nil; exp_p^.dtype_p := dtype_p; {data type of whole expression} exp_p^.dtype_hard := true; {data type is known and fixed} exp_p^.val_eval := true; {indicated attempted to evaluate} exp_p^.val_fnd := false; {no fixed value found} exp_p^.rwflag := [sst_rwflag_read_k]; {expression is read-only} exp_p^.term1.op2 := sst_op2_none_k; {no operation with previous term} exp_p^.term1.op1 := sst_op1_none_k; {no unary operation on this term} exp_p^.term1.ttype := sst_term_exp_k; {this term is an expression} exp_p^.term1.str_h.first_char.crange_p := nil; exp_p^.term1.dtype_p := exp1.dtype_p; {data type of this term} exp_p^.term1.dtype_hard := true; {data type is known and fixed} exp_p^.term1.val_eval := true; {tried to evaluate fixed value} exp_p^.term1.val_fnd := false; {no fixed value} exp_p^.term1.rwflag := [sst_rwflag_read_k]; {term is read-only} exp_p^.term1.exp_exp_p := addr(exp1); {the expression that is this term} sst_mem_alloc_scope ( {create descriptor for second term} sizeof(term_p^), term_p); exp_p^.term1.next_p := term_p; {link second term to after first} term_p^.next_p := nil; {this is last term in expression} term_p^.op2 := op; {operation between prev term and this} term_p^.op1 := sst_op1_none_k; {no unary operation on this term} term_p^.ttype := sst_term_exp_k; {this term is an expression} term_p^.str_h.first_char.crange_p := nil; term_p^.dtype_p := exp2.dtype_p; {data type of this term} term_p^.dtype_hard := true; {data type is known and fixed} term_p^.val_eval := true; {tried to evaluate fixed value} term_p^.val_fnd := false; {no fixed value} term_p^.rwflag := [sst_rwflag_read_k]; {term is read-only} term_p^.exp_exp_p := addr(exp2); {the expression that is this term} end;
unit GX_CodeFormatterBookmarks; // stores the bookmarks while the source file is being reformatted // Original Author: Thomas Mueller (http://www.dummzeuch.de) interface uses SysUtils, Classes; type TBookmark = class private fLine: Integer; fNumber: Integer; public constructor Create(_Number, _Line: Integer); property Number: Integer read fNumber; property Line: Integer read fLine; end; TBookmarks = class private function GetCount: Integer; function GetItems(_Idx: Integer): TBookmark; protected fList: TList; public constructor Create; destructor Destroy; override; procedure Add(_Number, _Line: Integer); procedure Clear; property Items[_Idx: Integer]: TBookmark read GetItems; default; property Count: Integer read GetCount; end; TBookmarkHandler = class private FBookmarks: TBookmarks; public constructor Create; destructor Destroy; override; procedure SaveBookmarks; procedure RestoreBookmarks; end; implementation uses ToolsApi; { TBookmark } constructor TBookmark.Create(_Number, _Line: Integer); begin inherited Create; fNumber := _Number; fLine := _Line; end; { TBookmarks } constructor TBookmarks.Create; begin inherited; fList := TList.Create; end; destructor TBookmarks.Destroy; var i: Integer; begin if Assigned(fList) then begin for i := 0 to fList.Count - 1 do TBookmark(fList[i]).Free; fList.Free; fList := nil; end; inherited; end; procedure TBookmarks.Add(_Number, _Line: Integer); begin fList.Add(TBookmark.Create(_Number, _Line)) end; function TBookmarks.GetCount: Integer; begin Result := fList.Count; end; function TBookmarks.GetItems(_Idx: Integer): TBookmark; begin Result := fList[_Idx]; end; procedure TBookmarks.Clear; var i: Integer; begin for i := 0 to fList.Count - 1 do TBookmark(fList[i]).Free; fList.Clear; end; { TBookmarkHandler } constructor TBookmarkHandler.Create; begin inherited Create; FBookmarks := TBookmarks.Create; end; destructor TBookmarkHandler.Destroy; begin FBookmarks.Free; inherited; end; procedure TBookmarkHandler.SaveBookmarks; var EditorService: IOTAEditorServices; SourceEditor: IOTASourceEditor; EditView: IOTAEditView; i: Integer; BmPos: TOTACharPos; begin FBookmarks.Clear; if BorlandIDEServices.QueryInterface(IOTAEditorServices, EditorService) <> S_OK then Exit; SourceEditor := EditorService.GetTopBuffer; if not Assigned(SourceEditor) then Exit; EditView := SourceEditor.GetEditView(0); if not Assigned(EditView) then Exit; for i := 0 to 19 do begin BmPos := EditView.BookmarkPos[i]; if BmPos.Line <> 0 then FBookmarks.Add(i, BmPos.Line); end; end; procedure TBookmarkHandler.RestoreBookmarks; var EditorService: IOTAEditorServices; SourceEditor: IOTASourceEditor; EditView: IOTAEditView; SaveCursorPos: TOTAEditPos; BmEditPos: TOTAEditPos; i: Integer; begin if not BorlandIDEServices.QueryInterface(IOTAEditorServices, EditorService) = S_OK then Exit; SourceEditor := EditorService.GetTopBuffer; if not Assigned(SourceEditor) then Exit; EditView := SourceEditor.GetEditView(0); if not Assigned(EditView) then Exit; SaveCursorPos := EditView.GetCursorPos; try for i := 0 to FBookmarks.Count - 1 do begin BmEditPos.Line := FBookmarks[i].Line; BmEditPos.Col := 1; EditView.SetCursorPos(BmEditPos); EditView.BookmarkToggle(FBookmarks[i].Number); end; finally EditView.SetCursorPos(SaveCursorPos); end; EditView.Paint; SourceEditor.show; FBookmarks.Clear; end; end.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcCryptoUtils.pas } { File version: 5.01 } { Description: Crypto utils } { } { Copyright: Copyright (c) 2008-2021, David J Butler } { All rights reserved. } { This file is licensed under the BSD License. } { See http://www.opensource.org/licenses/bsd-license.php } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND } { CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED } { WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED } { WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A } { PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL } { THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, } { INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR } { CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF } { USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) } { HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER } { IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING } { NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE } { USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE } { POSSIBILITY OF SUCH DAMAGE. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2020/12/29 5.01 Create flcCryptoUtils from Cipher units. } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$INCLUDE flcCrypto.inc} unit flcCryptoUtils; interface uses SysUtils, flcStdTypes; { } { Secure memory clear } { Used to clear keys and other sensitive data from memory. } { Memory is overwritten with zeros before releasing reference. } { } procedure SecureClearBuf(var Buf; const BufSize: NativeInt); procedure SecureClearBytes(var B: TBytes); procedure SecureClearStrB(var S: RawByteString); procedure SecureClearStrU(var S: UnicodeString); procedure SecureClearStr(var S: String); implementation {$IFNDEF SupportStringRefCount} uses flcUtils; {$ENDIF} { } { Secure memory clear } { } procedure SecureClearBuf(var Buf; const BufSize: NativeInt); begin if BufSize <= 0 then exit; FillChar(Buf, BufSize, #$00); end; procedure SecureClearBytes(var B: TBytes); var L : NativeInt; begin L := Length(B); if L = 0 then exit; SecureClearBuf(Pointer(B)^, L); SetLength(B, 0); end; procedure SecureClearStrB(var S: RawByteString); var L : NativeInt; begin L := Length(S); if L = 0 then exit; if StringRefCount(S) > 0 then SecureClearBuf(PByteChar(S)^, L); SetLength(S, 0); end; procedure SecureClearStrU(var S: UnicodeString); var L : NativeInt; begin L := Length(S); if L = 0 then exit; if StringRefCount(S) > 0 then SecureClearBuf(PWideChar(S)^, L * SizeOf(WideChar)); S := ''; end; procedure SecureClearStr(var S: String); var L : NativeInt; begin L := Length(S); if L = 0 then exit; if StringRefCount(S) > 0 then SecureClearBuf(PChar(S)^, L * SizeOf(Char)); S := ''; end; end.
unit csExport; interface {$Include CsDefine.inc} uses Classes, daTypes, dtIntf, CsDataPipe, csProcessTask, CsTaskTypes, dt_Sab, k2Base, csExportTaskPrim ; type TcsExport = class(TcsExportTaskPrim) private f_DocSab: ISab; procedure pm_SetDocSab(Value: ISab); protected function RequireDelivery: Boolean; override; procedure Cleanup; override; function GetDescription: AnsiString; override; procedure DoLoadFrom(aStream: TStream; aIsPipe: Boolean); override; function pm_GetTaskFolder: AnsiString; override; public constructor Create(aUserID: TdaUserID); override; {$If defined(AppServerSide)} procedure RunEnded(const aServices: IcsRunTaskServices); override; {$IfEnd defined(AppServerSide)} procedure MakeSab; procedure DoSaveTo(aStream: TStream; aIsPipe: Boolean); override; procedure DoWriteResult(aPipe: TcsDataPipe); {overload; }override; function DefaultDescription: AnsiString; function DeliverySourceFolder: AnsiString; override; function DeliveryTargetFolder: AnsiString; override; property DocSab: ISab read f_DocSab write pm_SetDocSab; end;//TcsExport implementation uses l3TempMemoryStream, daSchemeConsts, SysUtils, ddUtils, L3FileUtils, dt_Types, DT_DictConst, dt_Doc, DT_Const, daInterfaces, k2Tags, Task_Const, ExportTask_Const ; { ****************************** TcsExport ******************************* } constructor TcsExport.Create(aUserID: TdaUserID); begin inherited; VersionW := 4; ToRegion:= cUndefDictID; FormulaAsPicture:= False; end; procedure TcsExport.Cleanup; begin f_DocSab:= nil; inherited; end; function TcsExport.GetDescription: AnsiString; var l_SR: TSearchRec; l_Mask, l_Descript: AnsiString; l_Total, l_Count: Int64; begin Result := 'Экспорт '; if TepDivideBy(SeparateFiles) = divTopic then Result:= Result + 'по документам, ' else begin if DocumentFileNameMask <> '' then Result := Result + SysUtils.Format('%s, ', [DocumentFileNameMask]); if TepDivideBy(SeparateFiles) = divSize then Result := Result + SysUtils.Format('размер части: %s, ', [Bytes2Str(OutputFileSize)]); end; Result := Result + SysUtils.Format('папка: %s, формат: %s', [ExportDirectory, SupportFileTypeNames[TepSupportFileType(OutFileType)]]); if ExportDocImage then Result := Result + ', с графическими образами'; end; procedure TcsExport.DoLoadFrom(aStream: TStream; aIsPipe: Boolean); var l_Value : Integer; begin inherited; //with aStream do begin AnnoTopicFileName := ReadString(aStream); DiapasonType := TDiapType(ReadInteger(aStream)); DocID := ReadInteger(aStream); DocumentFileNameMask := ReadString(aStream); ExportAnnoTopics := ReadBoolean(aStream); ExportDirectory := ReadString(aStream); ExportDocImage := ReadBoolean(aStream); ExportDocument := ReadBoolean(aStream); ExportEmptyKW := ReadBoolean(aStream); ExportKW := ReadBoolean(aStream); ExportRTFBody := ReadBoolean(aStream); Family := ReadInteger(aStream); InternalFormat := ReadBoolean(aStream); KWFileName := ReadString(aStream); MultiUser := ReadBoolean(aStream); l_Value := ReadInteger(aStream); if l_Value > 0 then begin //f_SABStream.Seek(0, 0); {l_Value := }SABStream.CopyFrom(aStream, l_Value); //f_SABStream.Seek(0, 0); end; if not aIsPipe then // Нельзя использовать HyTech в другой нити :( begin (*TODO: extracted code f_DocSab:= MakeValueSet(DocumentServer(CurrentFamily).FileTbl, fID_Fld, SABStream); f_DocSab.Sort; *) //MakeSab; end; // not aIsPipe ObjTopicFileName := ReadString(aStream); OnlyStructure := ReadBoolean(aStream); OutFileType := TepSupportFileType(ReadInteger(aStream)); OutputFileSize := ReadInteger(aStream); ReferenceFileNameMask := ReadString(aStream); SeparateFiles := TepDivideBy(ReadInteger(aStream)); ToRegion := ReadCardinal(aStream); ExportReferences := ExportDocument; ExportEditions := False; FormulaAsPicture:= False; if Version > 1 then ExportReferences := ReadBoolean(aStream); if Version > 2 then ExportEditions := ReadBoolean(aStream); if Version > 3 then FormulaAsPicture := ReadBoolean(aStream); end; // with aStream end; procedure TcsExport.MakeSab; begin f_DocSab:= MakeValueSet(DocumentServer(CurrentFamily).FileTbl, fID_Fld, SABStream); f_DocSab.Sort; end; procedure TcsExport.pm_SetDocSab(Value: ISab); begin f_DocSab := Value; end; function TcsExport.pm_GetTaskFolder: AnsiString; begin Result := ConcatDirName(TaggedData.StrA[k2_attrTaskFolder], 'Export\' + TaskID); end; procedure TcsExport.DoSaveTo(aStream: TStream; aIsPipe: Boolean); var l_Value : Integer; begin inherited; WriteString(aStream, AnnoTopicFileName); WriteInteger(aStream, Ord(DiapasonType)); WriteInteger(aStream, DocID); WriteString(aStream, DocumentFileNameMask); WriteBoolean(aStream, ExportAnnoTopics); WriteString(aStream, ExportDirectory); WriteBoolean(aStream, ExportDocImage); WriteBoolean(aStream, ExportDocument); WriteBoolean(aStream, ExportEmptyKW); WriteBoolean(aStream, ExportKW); WriteBoolean(aStream, ExportRTFBody); writeInteger(aStream, Family); WriteBoolean(aStream, InternalFormat); WriteString(aStream, KWFileName); WriteBoolean(aStream, MultiUser); //if not aIsPipe and (DocSab <> nil) and not DocSab.IsEmpty then // dtOutSabToStream(DocSab, SABStream); (* %<---Потом нужно удалить--->% *) l_Value := SABStream.Size; WriteInteger(aStream, l_Value); //f_SABStream.Seek(0, 0); SABStream.CopyTo(aStream, l_Value); //aStream.CopyFrom(f_SABStream, l_Value); //f_SABStream.Seek(0, 0); (*=======================*) WriteString(aStream, ObjTopicFileName); WriteBoolean(aStream, OnlyStructure); WriteInteger(aStream, Ord(OutFileType)); WriteInteger(aStream, OutputFileSize); WriteString(aStream, ReferenceFileNameMask); WriteInteger(aStream, Ord(SeparateFiles)); WriteCardinal(aStream, ToRegion); if Version > 1 then WriteBoolean(aStream, ExportReferences); if Version > 2 then begin WriteBoolean(aStream, ExportEditions); end; if Version > 3 then begin WriteBoolean(aStream, FormulaAsPicture); end; end; procedure TcsExport.DoWriteResult(aPipe: TcsDataPipe); begin aPipe.WriteFolder(TaskFolder); //PureDir(TaskFolder); //RemoveDir(TaskFolder); end; function TcsExport.RequireDelivery: Boolean; begin Result := User <> usServerService; end; {$If defined(AppServerSide)} procedure TcsExport.RunEnded(const aServices: IcsRunTaskServices); begin f_DocSab := nil; inherited; end; {$IfEnd defined(AppServerSide)} function TcsExport.DefaultDescription: AnsiString; begin Result := GetDescription; end; function TcsExport.DeliverySourceFolder: AnsiString; begin Result := TaskFolder; end; function TcsExport.DeliveryTargetFolder: AnsiString; begin Result := ExportDirectory; end; end.
unit AbastecimentoHelper; interface uses Abastecimento; type TAbastecimentoHelper = class helper for TAbastecimento private function GetValorImposto: Double; function GetValorTotal: Double; public property ValorImposto: Double read GetValorImposto; property ValorTotal: Double read GetValorTotal; end; implementation { TAbastecimentoHelper } function TAbastecimentoHelper.GetValorImposto: Double; begin Result := ((Valor * 13) / 100); end; function TAbastecimentoHelper.GetValorTotal: Double; begin Result := Valor + ValorImposto; end; end.
{ GDAX/Coinbase-Pro client library Copyright (c) 2018 mr-highball Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit gdax.api; {$i gdax.inc} interface uses Classes, SysUtils, gdax.api.consts, gdax.api.types, {$IFDEF FPC} internetaccess {$ELSE} //could probably use internetaccess, but need to check. if so, //fpc class could just be used for delphi and should just "work" System.Net.HttpClientComponent {$ENDIF}; type { TBaseGDAXRestApiImpl } TBaseGDAXRestApiImpl = class(TInterfacedObject,IGDAXRestAPI) strict private FAuthenticator:IGDAXAuthenticator; protected function GetAuthenticator: IGDAXAuthenticator; function GetPostBody: String; function GetSupportedOperations: TRestOperations; procedure SetAuthenticator(Const AValue: IGDAXAuthenticator); function GetEndpoint(Const AOperation:TRestOperation) : String;virtual;abstract; function GetHeadersForOperation(Const AOperation:TRestOperation; Const AHeaders:TStrings;Out Error:String):Boolean;virtual; function DoDelete(Const AEndpoint:String;Const AHeaders:TStrings; Out Content:String;Out Error:String):Boolean;virtual;abstract; function DoGet(Const AEndpoint:String;Const AHeaders:TStrings; Out Content:String;Out Error:String):Boolean;virtual;abstract; function DoPost(Const AEndPoint:String;Const AHeaders:TStrings;Const ABody:String; Out Content:String;Out Error:String):Boolean;virtual;abstract; function DoGetSupportedOperations:TRestOperations;virtual;abstract; function DoGetPostBody:String;virtual; function DoGetSuccess(Const AHTTPStatusCode:Integer;Out Error:String):Boolean;virtual; function DoLoadFromJSON(Const AJSON:String;Out Error:String):Boolean;virtual; public property SupportedOperations: TRestOperations read GetSupportedOperations; property Authenticator: IGDAXAuthenticator read GetAuthenticator write SetAuthenticator; property PostBody : String read GetPostBody; function Post(Out Content:String;Out Error:String):Boolean; function Get(Out Content:String;Out Error:String):Boolean; function Delete(Out Content:String;Out Error:String):Boolean; function LoadFromJSON(Const JSON:String;Out Error:String):Boolean; constructor Create;virtual; destructor Destroy; override; end; (* meta class for gdax base *) TBaseGDAXRestApiImplClass = class of TBaseGDAXRestApiImpl; {$IFDEF FPC} (* free pascal implementation of a base gdax api *) { TFPCRestAPI } TFPCRestAPI = class(TBaseGDAXRestApiImpl) strict private procedure TransferReaction(sender: TInternetAccess; var method: string; var url: TDecodedUrl; var data: TInternetAccessDataBlock; var reaction: TInternetAccessReaction); strict protected function DoDelete(Const AEndpoint: string; Const AHeaders: TStrings; Out Content:String;out Error: string): Boolean; override; function DoPost(Const AEndPoint: string; Const AHeaders: TStrings; Const ABody: string; Out Content:String;out Error: string): Boolean; override; function DoGet(Const AEndpoint: string; Const AHeaders: TStrings; Out Content:String;out Error: string): Boolean; override; public constructor Create; override; destructor Destroy; override; end; {$ELSE} (* delphi rest api will most likely need some overhauling to even compile, have not tested... *) TDelphiRestAPI = class(TBaseGDAXRestApiImpl) strict private FClient: TNetHTTPClient; strict protected function DoDelete(Const AEndpoint: string; Const AHeaders: TStrings; Out Content:String;out Error: string): Boolean; override; function DoPost(Const AEndPoint: string; Const AHeaders: TStrings; Const ABody: string; Out Content:String;out Error: string): Boolean; override; function DoGet(Const AEndpoint: string; Const AHeaders: TStrings; Out Content:String;out Error: string): Boolean; override; public constructor Create; override; destructor Destroy; override; end; {$ENDIF} (* actual base class depending on compiler for api endpoints *) TGDAXRestApi = {$IFDEF FPC} TFPCRestAPI {$ELSE} TDelphiRestAPI {$ENDIF}; { TGDAXPagedApi } (* for endpoints that are paged, inherit from this base class *) TGDAXPagedApi = class(TGDAXRestApi,IGDAXPaged) strict private FLastAfterID:Integer; FLastBeforeID:Integer; FMoving:Boolean; FMovingParams:String; procedure ExtractPageIDs(Const AHeaders:TStrings); protected function GetLastAfterID: Integer; function GetLastBeforeID: Integer; strict protected function DoMove(Const ADirection:TGDAXPageDirection;Out Error:String; Const ALastBeforeID,ALastAfterID:Integer; Const ALimit:TPageLimit=0):Boolean;virtual; function DoGet(Const AEndpoint: string; Const AHeaders: TStrings; out Content: String; out Error: string): Boolean; override; function GetMovingParameters:String; public property LastBeforeID:Integer read GetLastBeforeID; property LastAfterID:Integer read GetLastAfterID; function Move(Const ADirection:TGDAXPageDirection;Out Error:String; Const ALastBeforeID,ALastAfterID:Integer; Const ALimit:TPageLimit=0):Boolean;overload; function Move(Const ADirection:TGDAXPageDirection; Const ALimit:TPageLimit=0):Boolean;overload; function Move(Const ADirection:TGDAXPageDirection;Out Error:String; Const ALimit:TPageLimit=0):Boolean;overload; end; implementation uses {$IFDEF FPC} {$IFDEF MSWINDOWS} w32internetaccess {$ELSE} {$IFDEF ANDROID} androidinternetaccess {$ELSE} synapseinternetaccess {$ENDIF} {$ENDIF} {$ELSE} System.Generics.Collections, System.Net.UrlClient, System.Net.HttpClient {$ENDIF}; { TGDAXPagedApi } function TGDAXPagedApi.GetLastAfterID: Integer; begin Result:=FLastAfterID; end; function TGDAXPagedApi.GetLastBeforeID: Integer; begin Result:=FLastBeforeID end; procedure TGDAXPagedApi.ExtractPageIDs(Const AHeaders: TStrings); var I:Integer; begin //find if we have before cursor I:=AHeaders.IndexOfName(CB_BEFORE); if I>=0 then FLastBeforeID:=StrToIntDef(AHeaders.ValueFromIndex[I],0) //if no before cursor, we won't have an after else Exit; //now look for after cursor I:=AHeaders.IndexOfName(CB_AFTER); if I>=0 then FLastAfterID:=StrToIntDef(AHeaders.ValueFromIndex[I],0); end; function TGDAXPagedApi.DoMove(Const ADirection: TGDAXPageDirection;out Error: String; Const ALastBeforeID,ALastAfterID:Integer; Const ALimit: TPageLimit): Boolean; var LContent:String; begin Result:=False; try FMoving:=True; FMovingParams:=''; //direction first case ADirection of pdAfter: FMovingParams:=URL_PAGE_AFTER + '=' + IntToStr(ALastAfterID); pdBefore: FMovingParams:=URL_PAGE_BEFORE + '=' + IntToStr(ALastBeforeID); end; //next if we have a limit if ALimit>0 then FMovingParams:=FMovingParams + '&' + URL_PAGE_LIMIT + IntToStr(ALimit); //the child class needs to use GetMovingParameters method for now, //perhaps later will change Result:=Get(LContent,Error); except on E:Exception do Error:=E.Message; end; end; function TGDAXPagedApi.DoGet(Const AEndpoint: string; Const AHeaders: TStrings; out Content: String; out Error: string): Boolean; begin Result:=inherited DoGet(AEndpoint, AHeaders, Content, Error); ExtractPageIDs(AHeaders); //if a call to Move was made, then reset until next call if FMoving then FMoving:=False; end; function TGDAXPagedApi.GetMovingParameters: String; begin if not FMoving then Result:='' else Result:=FMovingParams; end; function TGDAXPagedApi.Move(Const ADirection: TGDAXPageDirection;Out Error:String; Const ALastBeforeID, ALastAfterID: Integer; Const ALimit: TPageLimit): Boolean; begin Result:=False; try //use id's provided by caller Result:=DoMove(ADirection,Error,ALastBeforeID,ALastAfterID,ALimit); except on E:Exception do Error:=E.Message; end; end; function TGDAXPagedApi.Move(Const ADirection: TGDAXPageDirection; Const ALimit: TPageLimit): Boolean; var LError:String; begin Result:=Move(ADirection,LError,ALimit); end; function TGDAXPagedApi.Move(Const ADirection: TGDAXPageDirection; out Error: String; Const ALimit: TPageLimit): Boolean; begin Result:=False; //make a call to the base move with private id's Result:=Move(ADirection,Error,FLastBeforeID,FLastAfterID,ALimit); end; { TGDAXRestApi } constructor TBaseGDAXRestApiImpl.Create; begin end; function TBaseGDAXRestApiImpl.Delete(out Content: String; out Error: String): Boolean; var LHeaders: TStringList; LEndpoint: String; begin Result:=False; if not (roDelete in SupportedOperations) then begin Error:=Format(E_UNSUPPORTED,['delete',Self.ClassName]); Exit; end; LHeaders:=TStringList.Create; try if not GetHeadersForOperation(roDelete,LHeaders,Error) then Exit; LEndpoint:=BuildFullEndpoint(GetEndpoint(roDelete),Authenticator.Mode); Result:=DoDelete( LEndpoint, LHeaders, Content, Error ); finally LHeaders.Free; end; end; destructor TBaseGDAXRestApiImpl.Destroy; begin //nil our reference FAuthenticator:=nil; inherited Destroy; end; function TBaseGDAXRestApiImpl.DoGetPostBody: String; begin Result:=''; end; function TBaseGDAXRestApiImpl.DoGetSuccess(const AHTTPStatusCode: Integer; out Error: String): Boolean; begin Result:=False; if (AHTTPStatusCode>=200) and (AHTTPStatusCode<=299) then begin Result:=True; Exit; end; Error:=Format('invalid web status code %d',[AHTTPStatusCode]); end; function TBaseGDAXRestApiImpl.DoLoadFromJSON(const AJSON: String; out Error: String): Boolean; begin //nothing to load from Error:=''; Result:=True; end; function TBaseGDAXRestApiImpl.Get(out Content: String; out Error: String): Boolean; var LHeaders: TStringList; LEndpoint: String; begin Result:=False; if not (roGet in SupportedOperations) then begin Error:=Format(E_UNSUPPORTED,['get',Self.ClassName]); Exit; end; LHeaders:=TStringList.Create; try if not GetHeadersForOperation(roGet,LHeaders,Error) then Exit; LEndpoint:=BuildFullEndpoint(GetEndpoint(roGet),Authenticator.Mode); Result:=DoGet( LEndpoint, LHeaders, Content, Error ); if Result and (not DoLoadFromJSON(Content,Error)) then begin Result:=False; Exit; end; finally LHeaders.Free; end; end; function TBaseGDAXRestApiImpl.GetAuthenticator: IGDAXAuthenticator; begin Result:=FAuthenticator; end; function TBaseGDAXRestApiImpl.GetPostBody: String; begin Result:=DoGetPostBody; end; function TBaseGDAXRestApiImpl.GetSupportedOperations: TRestOperations; begin Result:=DoGetSupportedOperations; end; procedure TBaseGDAXRestApiImpl.SetAuthenticator(const AValue: IGDAXAuthenticator); begin FAuthenticator:=AValue; end; function TBaseGDAXRestApiImpl.GetHeadersForOperation( const AOperation: TRestOperation; const AHeaders: TStrings; out Error: String): Boolean; var LEpoch:Integer; LSignature:String; begin Result:=False; try if not Assigned(Authenticator) then begin Error:='authenticator is invalid'; Exit; end; //generate the signature LSignature:=Authenticator.GenerateAccessSignature( AOperation, GetEndpoint(AOperation), LEpoch, DoGetPostBody ); //using signature and time, build the headers for the request Authenticator.BuildHeaders( AHeaders, LSignature, LEpoch ); Result:=True; except on E: Exception do Error:=E.Message; end; end; function TBaseGDAXRestApiImpl.LoadFromJSON(const JSON: String; out Error: String ): Boolean; begin Result:=DoLoadFromJSON(JSON,Error); end; function TBaseGDAXRestApiImpl.Post(out Content: String; out Error: String): Boolean; var LHeaders: TStringList; LBody: string; LEndpoint: String; begin Result:=False; if not (roPost in SupportedOperations) then begin Error:=Format(E_UNSUPPORTED,['post',Self.ClassName]); Exit; end; LHeaders:=TStringList.Create; try if not GetHeadersForOperation(roPost,LHeaders,Error) then Exit; LEndpoint:=BuildFullEndpoint(GetEndpoint(roPost),Authenticator.Mode); LBody:=DoGetPostBody; Result:=DoPost( LEndpoint, LHeaders, LBody, Content, Error ); if Result and (not DoLoadFromJSON(Content,Error)) then begin Result:=False; Exit; end; finally LHeaders.Free; end; end; {$IFNDEF FPC} { TDelphiRestAPI } constructor TDelphiRestAPI.Create; begin inherited; FClient:=TNetHTTPClient.Create(nil); FClient.ContentType:='application/json; charset=utf-8'; FClient.UserAgent:=USER_AGENT_MOZILLA; end; destructor TDelphiRestAPI.Destroy; begin FClient.Free; inherited; end; function TDelphiRestAPI.DoDelete(Const AEndpoint: string; Const AHeaders: TStrings; Out Content:String;out Error: string): Boolean; var LHeaders:TArray<TNameValuePair>; I: Integer; LResp: IHTTPResponse; begin Result:=False; try SetLength(LHeaders,AHeaders.Count); for I := 0 to Pred(AHeaders.Count) do LHeaders[I]:=TNameValuePair.Create(AHeaders.Names[I],AHeaders.ValueFromIndex[I]); LResp:=FClient.Delete( AEndpoint, nil, LHeaders ); Content:=LResp.ContentAsString(); Result:=DoGetSuccess(LResp.StatusCode,Error); //this will provide a more specific error if (not Result) and (LResp.StatusText<>'') then Error:=LResp.StatusText; except on E: Exception do Error:=E.Message; end; end; function TDelphiRestAPI.DoGet(Const AEndpoint: string; Const AHeaders: TStrings; Out Content:String;out Error: string): Boolean; var LHeaders:TArray<TNameValuePair>; I: Integer; LResp: IHTTPResponse; LJSON:TJSONVariantData; begin Result:=False; try SetLength(LHeaders,AHeaders.Count); for I := 0 to Pred(AHeaders.Count) do LHeaders[I]:=TNameValuePair.Create(AHeaders.Names[I],AHeaders.ValueFromIndex[I]); LResp:=FClient.Get( AEndpoint, nil, LHeaders ); Content:=LResp.ContentAsString(); Result:=DoGetSuccess(LResp.StatusCode,Error); //this will provide a more specific error if (not Result) then begin if LJSON.FromJSON(Content) and (LJSON.NameIndex('message')>-1) then Error:=LJSON.Value['message'] else if Error='' then Error:=LResp.StatusText; end; except on E: Exception do Error:=E.Message; end; end; function TDelphiRestAPI.DoPost(Const AEndPoint: string; Const AHeaders: TStrings; Const ABody: string; Out Content:String;out Error: string): Boolean; var LHeaders:TArray<TNameValuePair>; I: Integer; LResp: IHTTPResponse; LBody:TStringStream; begin Result:=False; try SetLength(LHeaders,AHeaders.Count); for I := 0 to Pred(AHeaders.Count) do LHeaders[I]:=TNameValuePair.Create(AHeaders.Names[I],AHeaders.ValueFromIndex[I]); LBody:=TStringStream.Create(ABody); try LResp:=FClient.Post( AEndpoint, LBody, nil, LHeaders ); Content:=LResp.ContentAsString(); Result:=DoGetSuccess(LResp.StatusCode,Error); //this will provide a more specific error if (not Result) and (LResp.StatusText<>'') then Error:=LResp.StatusText; finally LBody.Free; end; except on E: Exception do Error:=E.Message; end; end; {$ELSE} { TFPCRestAPI } procedure TFPCRestAPI.TransferReaction(sender: TInternetAccess; var method: string; var url: TDecodedUrl; var data: TInternetAccessDataBlock; var reaction: TInternetAccessReaction); begin reaction:=TInternetAccessReaction.iarAccept; end; function TFPCRestAPI.DoDelete(Const AEndpoint: string; Const AHeaders: TStrings; out Content: String; out Error: string): Boolean; var LClient:TInternetAccess; begin Result:=False; LClient:=defaultInternetAccessClass.create(); try try //take control of determining success LClient.OnTransferReact:=TransferReaction; //add all headers to client LClient.additionalHeaders.AddStrings(AHeaders,True); //delete and capture response (will throw exception of failure) Content:=LClient.request(OP_DELETE,AEndPoint,''); //check response status code, otherwise error details will be in the body if not DoGetSuccess(LClient.lastHTTPResultCode,Error) then begin Error:=Error + sLineBreak + Content; Exit; end; AHeaders.Clear; AHeaders.AddStrings(LClient.lastHTTPHeaders); Result:=True; except on E:Exception do Error:=E.Message; end; finally LClient.Free; end; end; function TFPCRestAPI.DoPost(Const AEndPoint: string; Const AHeaders: TStrings; Const ABody: string; out Content: String; out Error: string): Boolean; var LClient:TInternetAccess; begin Result:=False; LClient:=defaultInternetAccessClass.create(); try try //take control of determining success LClient.OnTransferReact:=TransferReaction; //add all headers to client LClient.additionalHeaders.AddStrings(AHeaders,True); //post and capture response (will throw exception of failure) Content:=LClient.post(AEndPoint,ABody); //check response status code, otherwise error details will be in the body if not DoGetSuccess(LClient.lastHTTPResultCode,Error) then begin Error:=Error + sLineBreak + Content; Exit; end; AHeaders.Clear; AHeaders.AddStrings(LClient.lastHTTPHeaders); Result:=True; except on E:Exception do Error:=E.Message; end; finally LClient.Free; end; end; function TFPCRestAPI.DoGet(Const AEndpoint: string; Const AHeaders: TStrings; out Content: String; out Error: string): Boolean; var LClient:TInternetAccess; begin Result:=False; LClient:=defaultInternetAccessClass.create(); try try //take control of determining success LClient.OnTransferReact:=TransferReaction; //add all headers to client LClient.additionalHeaders.AddStrings(AHeaders,True); //get and capture response (will throw exception if failure) Content:=LClient.get(AEndPoint); //check response status code, otherwise error details will be in the body if not DoGetSuccess(LClient.lastHTTPResultCode,Error) then begin Error:=Error + sLineBreak + Content; Exit; end; AHeaders.Clear; AHeaders.AddStrings(LClient.lastHTTPHeaders); Result:=True; except on E:Exception do Error:=E.Message; end; finally LClient.Free; end; end; constructor TFPCRestAPI.Create; begin inherited Create; end; destructor TFPCRestAPI.Destroy; begin inherited Destroy; end; {$ENDIF} initialization {$IFDEF FPC} {$IFDEF MSWINDOWS} defaultInternetAccessClass:=TW32InternetAccess; {$ELSE} {$IFDEF ANDROID} defaultInternetAccessClass:=TAndroidInternetAccessClass; {$ELSE} defaultInternetAccessClass:=TSynapseInternetAccess; {$ENDIF} {$ENDIF} {$ENDIF} end.
unit OptionsHandler; interface uses Classes, VoyagerInterfaces, VoyagerServerInterfaces, Controls, OptionsHandlerViewer, Protocol, JukeBox, ChatHandler; type TMetaOptionsHandler = class( TInterfacedObject, IMetaURLHandler ) // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; end; TOptionsHandler = class( TInterfacedObject, IURLHandler, IPlayList, IPrivacyHandler ) private constructor Create; destructor Destroy; override; private fControl : TOptionsHandlerView; fClientView : IClientView; fMasterURLHandler : IMasterURLHandler; fCachePath : string; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); // IPlayList private function SelectedFile : string; procedure SelectNextFile; procedure Reset; procedure JumpToFile( index : integer ); procedure AddFile ( filename : string ); procedure AddDir ( path : string ); procedure DelFile ( index : integer ); private fPlayList : TStringList; fSelectedFile : integer; private function CollectMediaFiles( path, pattern : string ) : TStringList; // IPrivacyHandler private procedure IgnoreUser( username : string ); procedure ClearIgnoredUser( username : string ); function UserIsIgnored( username : string ) : boolean; procedure GetDefaultChannelData( out name, password : string ); procedure SetDefaultChannelData( name, password : string ); private fIgnoreList : TStringList; fDefChannel : string; fDefPassword : string; fLoaded : boolean; private procedure LoadPrivData; procedure StorePrivData; end; const tidHandlerName_Options = 'OptionsView'; tidFileName_PlayList = 'playlist.dat'; tidFileName_IgnoreList = 'ignore.dat'; tidFileName_PrivInfo = 'privacy.dat'; tidFolderName_UserData = 'userdata\'; implementation uses ServerCnxHandler, VoyagerUIEvents, Events, ServerCnxEvents, Config, SysUtils, FileCtrl; function TrimFileName( filename : string ) : string; var p : integer; begin result := ExtractFileName( filename ); p := pos( '.', result ); if p > 0 then result := copy( result, 1, p - 1 ); end; // TMetaOptionsHandler function TMetaOptionsHandler.getName : string; begin result := tidHandlerName_Options; end; function TMetaOptionsHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable, hopEnabledWhenCached]; end; function TMetaOptionsHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TMetaOptionsHandler.Instantiate : IURLHandler; begin result := TOptionsHandler.Create; end; // TOptionsHandler constructor TOptionsHandler.Create; begin inherited Create; fControl := TOptionsHandlerView.Create( nil ); end; destructor TOptionsHandler.Destroy; begin fControl.Free; inherited; end; function TOptionsHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin result := urlNotHandled; end; function TOptionsHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; procedure InitPlayList( playlistfile : string ); begin if FileExists( playlistfile ) then begin fPlayList := TStringList.Create; fPlayList.LoadFromFile( playlistfile ); end else begin ForceDirectories( ExtractFilePath( playlistfile )); fPlayList := CollectMediaFiles( fCachePath + '\Sound\', 'inmap*.mp3' ); end; end; var PlayList : IPlayList absolute info; PrivacyHandler : IPrivacyHandler absolute info; ConfigHolder : IConfigHolder; i : integer; begin result := evnHandled; case EventId of evnHandlerExposed : begin fMasterURLHandler.HandleEvent( evnAnswerConfigHolder, ConfigHolder ); fControl.AutomaticLogon.Checked := ConfigHolder.ReadBoolean( false, '', 'AutoLogon', false ); fControl.Tabs.CurrentFinger := 3; fControl.Tabs.CurrentFinger := 0; fControl.edChannelName.Text := fDefChannel; fControl.edPassword.Text := fDefPassword; fControl.IgnoreList.Items.Assign( fIgnoreList ); fControl.Playlist.Items.BeginUpdate; try fControl.Playlist.Items.Clear; for i := 0 to pred(fPlayList.count) do with fControl.Playlist.Items.Add do begin Caption := TrimFileName(fPlayList[i]); if i = fSelectedFile then StateIndex := 0 else StateIndex := -1; end; finally fControl.Playlist.Items.EndUpdate; end; if fPlayList.Count > 0 then fControl.Playlist.Items[fSelectedFile].MakeVisible( false ); end; evnHandlerUnexposed : begin end; evnGetPlaylist : begin PlayList := self; if fPlayList = nil then InitPlayList( fCachePath + tidFolderName_UserData + fClientView.getUserName + '\' + tidFileName_PlayList ); end; evnAnswerPrivacyHandler : begin PrivacyHandler := self; if not fLoaded then begin LoadPrivData; fLoaded := true; end; end; else result := evnNotHandled; end; end; function TOptionsHandler.getControl : TControl; begin result := fControl; end; procedure TOptionsHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); begin URLHandler.HandleEvent( evnAnswerClientView, fClientView ); fMasterURLHandler := URLHandler; fControl.ClientView := fClientView; fControl.MasterURLHandler := fMasterURLHandler; fControl.PlayListInt := self; fControl.PrivacyHandler := self; fControl.StartCounting; fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, fCachePath ); end; function TOptionsHandler.SelectedFile : string; begin if (fPlayList.Count > 0) and (fSelectedFile >= 0) then result := fPlayList[fSelectedFile] else result := ''; end; procedure TOptionsHandler.SelectNextFile; begin if (fControl.Playlist <> nil) and (fSelectedFile >= 0) then fControl.Playlist.Items[fSelectedFile].StateIndex := -1; if fSelectedFile < pred(fPlayList.count) then inc(fSelectedFile) else fSelectedFile := 0; if (fControl.Playlist <> nil) and (fSelectedFile >= 0) then fControl.Playlist.Items[fSelectedFile].StateIndex := 0; end; procedure TOptionsHandler.Reset; begin if fControl.Playlist <> nil then fControl.Playlist.Items[fSelectedFile].StateIndex := -1; fSelectedFile := 0; if fControl.Playlist <> nil then fControl.Playlist.Items[fSelectedFile].StateIndex := 0; end; procedure TOptionsHandler.JumpToFile( index : integer ); begin fMasterURLHandler.HandleURL( '?frame_Id=JukeBox&frame_Class=JukeBox&frame_Action=Stop' ); if (fControl.Playlist <> nil) and (fSelectedFile >= 0) then fControl.Playlist.Items[fSelectedFile].StateIndex := -1; fSelectedFile := index; if (fControl.Playlist <> nil) and (fSelectedFile >= 0) then fControl.Playlist.Items[fSelectedFile].StateIndex := 0; fMasterURLHandler.HandleURL( '?frame_Id=JukeBox&frame_Class=JukeBox&frame_Action=Play' ); end; procedure TOptionsHandler.AddFile( filename : string ); var folder : string; begin if fPlayList.IndexOf( filename ) = -1 then begin fPlayList.Add( filename ); if fControl.Playlist <> nil then with fControl.Playlist.Items.Add do begin Caption := TrimFileName(filename); MakeVisible( false ); end; folder := fCachePath + tidFolderName_UserData + fClientView.getUserName + '\'; ForceDirectories( folder ); fPlayList.SaveToFile( folder + tidFileName_PlayList ); end; end; procedure TOptionsHandler.AddDir( path : string ); var files : TStringList; i : integer; folder : string; begin files := CollectMediaFiles( path, '*.mp3' ); try for i := 0 to pred(files.Count) do if fPlayList.IndexOf( files[i] ) = -1 then begin fPlayList.Add( files[i] ); if fControl.Playlist <> nil then with fControl.Playlist.Items.Add do begin Caption := TrimFileName(files[i]); MakeVisible( false ); end; end; finally files.Free; end; folder := fCachePath + tidFolderName_UserData + fClientView.getUserName + '\'; ForceDirectories( folder ); fPlayList.SaveToFile( folder + tidFileName_PlayList ); end; procedure TOptionsHandler.DelFile( index : integer ); var folder : string; begin if index = fSelectedFile then Reset; fPlayList.Delete( index ); if fControl.Playlist <> nil then fControl.Playlist.Items.Delete( index ); folder := fCachePath + tidFolderName_UserData + fClientView.getUserName + '\'; ForceDirectories( folder ); fPlayList.SaveToFile( folder + tidFileName_PlayList ); end; function TOptionsHandler.CollectMediaFiles( path, pattern : string ) : TStringList; var CachePath : string; SearchRec : TSearchRec; found : boolean; begin if path[length(path)] <> '\' then path := path + '\'; fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, CachePath ); result := TStringList.Create; if CachePath <> '' then begin found := FindFirst( path + pattern, faArchive, SearchRec ) = 0; try while found do begin result.Add( path + SearchRec.Name ); found := FindNext( SearchRec ) = 0; end; finally FindClose( SearchRec ); end; end; end; procedure TOptionsHandler.IgnoreUser( username : string ); begin if not UserIsIgnored( username ) then begin fIgnoreList.Add( username ); fControl.IgnoreList.Items.Assign( fIgnoreList ); StorePrivData; end; end; procedure TOptionsHandler.ClearIgnoredUser( username : string ); var idx : integer; begin try idx := fIgnoreList.IndexOf( username ); fIgnoreList.Delete( idx ); fControl.IgnoreList.Items.Assign( fIgnoreList ); StorePrivData; except end; end; function TOptionsHandler.UserIsIgnored( username : string ) : boolean; begin result := fIgnoreList.IndexOf( username ) <> -1 end; procedure TOptionsHandler.GetDefaultChannelData( out name, password : string ); begin name := fDefChannel; password := fDefPassword; end; procedure TOptionsHandler.SetDefaultChannelData( name, password : string ); begin fDefChannel := name; fDefPassword := password; StorePrivData; end; procedure TOptionsHandler.LoadPrivData; var filename : string; TmpInfo : TStringList; begin fIgnoreList := TStringList.Create; try filename := fCachePath + tidFolderName_UserData + fClientView.getUserName + '\' + tidFileName_IgnoreList; if FileExists( filename ) then fIgnoreList.LoadFromFile( filename ); filename := fCachePath + tidFolderName_UserData + fClientView.getUserName + '\' + tidFileName_PrivInfo; if FileExists( filename ) then begin TmpInfo := TStringList.Create; try TmpInfo.LoadFromFile( filename ); fDefChannel := TmpInfo.Values['DefChannel']; fDefPassword := TmpInfo.Values['DefPassword']; finally TmpInfo.Free; end; end; except fIgnoreList.Clear; end; end; procedure TOptionsHandler.StorePrivData; var folder : string; TmpInfo : TStringList; begin try folder := fCachePath + tidFolderName_UserData + fClientView.getUserName + '\'; ForceDirectories( folder ); fIgnoreList.SaveToFile( folder + tidFileName_IgnoreList ); TmpInfo := TStringList.Create; try TmpInfo.Values['DefChannel'] := fDefChannel; TmpInfo.Values['DefPassword'] := fDefPassword; TmpInfo.SaveToFile( folder + tidFileName_PrivInfo ); finally TmpInfo.Free; end; except end; end; end.
unit IndustrySheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers; const AllowedChars = ['0'..'9', 'a'..'z', 'A'..'Z', '.', ' ', #8, '-', '_', ',', ';', '(', ')', '{', '}']; const tidSecurityId = 'SecurityId'; tidTrouble = 'Trouble'; tidCurrBlock = 'CurrBlock'; const facStoppedByTycoon = $04; type TResidentialSheetHandler = class; TResidentialSheetViewer = class(TVisualControl) xfer_Name: TEdit; Label1: TLabel; Label2: TLabel; xfer_Rent: TPercentEdit; xfer_Creator: TLabel; Label4: TLabel; xfer_CrimeRes: TLabel; Label3: TLabel; Label5: TLabel; xfer_PollutionRes: TLabel; xfer_GeneralQ: TLabel; Label8: TLabel; xfer_Cost: TLabel; Label9: TLabel; xfer_Cluster: TLabel; Label10: TLabel; xfer_Capacity: TLabel; Label6: TLabel; xfer_MetaFacilityName: TLabel; Label7: TLabel; Rent: TLabel; Label12: TLabel; xfer_Maintenance: TPercentEdit; Maintenance: TLabel; btnClose: TFramedButton; btnRepair: TFramedButton; btnDemolish: TFramedButton; btnSell: TFramedButton; NameLabel: TLabel; procedure xfer_NameKeyPress(Sender: TObject; var Key: Char); procedure xfer_RentChange(Sender: TObject); procedure xfer_MaintenanceChange(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure xfer_RentMoveBar(Sender: TObject); procedure btnRepairClick(Sender: TObject); procedure btnDemolishClick(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TResidentialSheetHandler; end; TResidentialSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TResidentialSheetViewer; fSecurityId : string; fCurrBlock : integer; fOwnsFacility : boolean; private procedure SetContainer(aContainer : IPropertySheetContainerHandler); override; function CreateControl(Owner : TControl) : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; private procedure SetName(str : string); end; var ResidentialSheetViewer: TResidentialSheetViewer; function ResidentialSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses SheetHandlerRegistry, FiveViewUtils, Protocol; {$R *.DFM} // TResidentialSheetHandler procedure TResidentialSheetHandler.SetContainer(aContainer : IPropertySheetContainerHandler); begin inherited; fSecurityId := fContainer.GetClientView.getSecurityId; end; function TResidentialSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TResidentialSheetViewer.Create(Owner); fControl.fHandler := self; fContainer.ChangeHeight(150 - fContainer.GetMinHeight); result := fControl; end; procedure TResidentialSheetHandler.RenderProperties(Properties : TStringList); var trouble : string; begin FiveViewUtils.SetViewProp(fControl, Properties); trouble := Properties.Values[tidTrouble]; fOwnsFacility := GrantAccess( fSecurityId, Properties.Values[tidSecurityId] ); if fOwnsFacility then begin try fCurrBlock := StrToInt(Properties.Values[tidCurrBlock]); except fCurrBlock := 0; end; fControl.NameLabel.Visible := false; fControl.xfer_Name.Visible := true; fControl.xfer_Name.SetFocus; end else begin fCurrBlock := 0; fControl.xfer_Name.Visible := false; fControl.NameLabel.Caption := fControl.xfer_Name.Text; fControl.NameLabel.Visible := true; end; try if (trouble <> '') and (StrToInt(trouble) and facStoppedByTycoon <> 0) then fControl.btnClose.Text := GetLiteral('Literal413') else fControl.btnClose.Text := GetLiteral('Literal414'); except end; fControl.xfer_Rent.Enabled := fOwnsFacility; fControl.xfer_Maintenance.Enabled := fOwnsFacility; fControl.btnClose.Enabled := fOwnsFacility; fControl.btnDemolish.Enabled := fOwnsFacility; fControl.btnRepair.Enabled := fOwnsFacility; fControl.btnSell.Enabled := fOwnsFacility; Properties.Free; end; procedure TResidentialSheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; Names := TStringList.Create; FiveViewUtils.GetViewPropNames(fControl, Names); Names.Add(tidSecurityId); Names.Add(tidTrouble); Names.Add(tidCurrBlock); RenderProperties(fContainer.GetProperties(Names)); Names.Free; end; end; procedure TResidentialSheetHandler.SetName(str : string); var MSProxy : OleVariant; CHProxy : OleVariant; SecId : string; ObjId : string; begin try try fControl.Cursor := crHourGlass; MSProxy := fContainer.GetMSProxy; CHProxy := fContainer.GetCacheObjectProxy; if not VarIsEmpty(MSProxy) and not VarIsEmpty(CHProxy) then begin SecId := CHProxy.Properties('SecurityId'); ObjId := fContainer.GetClientView.getSecurityId; if SecId = ObjId then MSProxy.Name := str else begin fControl.xfer_Name.Text := CHProxy.Properties('Name'); Beep; end; end; finally fControl.Cursor := crDefault; end; except end; end; function ResidentialSheetHandlerCreator : IPropertySheetHandler; begin result := TResidentialSheetHandler.Create; end; procedure TResidentialSheetViewer.xfer_NameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then fHandler.SetName(xfer_Name.Text); if not(Key in AllowedChars) then Key := #0; end; procedure TResidentialSheetViewer.xfer_RentMoveBar(Sender: TObject); begin Rent.Caption := IntToStr(xfer_Rent.Value) + '%'; end; procedure TResidentialSheetViewer.xfer_RentChange(Sender: TObject); var Proxy : OleVariant; begin if fHandler.fCurrBlock <> 0 then try Proxy := fHandler.fContainer.GetMSProxy; Proxy.BindTo(fHandler.fCurrBlock); Proxy.Rent := xfer_Rent.Value; except end; end; procedure TResidentialSheetViewer.xfer_MaintenanceChange(Sender: TObject); var Proxy : OleVariant; begin if fHandler.fCurrBlock <> 0 then try Proxy := fHandler.fContainer.GetMSProxy; Proxy.BindTo(fHandler.fCurrBlock); Proxy.Maintenance := xfer_Maintenance.Value; except end; end; procedure TResidentialSheetViewer.btnCloseClick(Sender: TObject); begin if btnClose.Text = GetLiteral('Literal415') then begin fHandler.fContainer.GetMSProxy.Stopped := true; btnClose.Text := GetLiteral('Literal416'); end else begin fHandler.fContainer.GetMSProxy.Stopped := false; btnClose.Text := GetLiteral('Literal417'); end end; procedure TResidentialSheetViewer.btnRepairClick(Sender: TObject); var Proxy : OleVariant; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; Proxy.BindTo(fHandler.fCurrBlock); Proxy.RdoRepair; except end; end; procedure TResidentialSheetViewer.btnDemolishClick(Sender: TObject); var Proxy : OleVariant; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo('World'); if not Proxy.RDODelFacility(fHandler.GetContainer.GetXPos, fHandler.GetContainer.GetYPos) then Beep; end; except end; end; procedure TResidentialSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; begin SheetHandlerRegistry.RegisterSheetHandler('ResGeneral', ResidentialSheetHandlerCreator); end.
unit UPedidoRepositoryIntf; interface uses UPizzaSaborEnum, UPizzaTamanhoEnum, FireDAC.Comp.Client; type IPedidoRepository = interface(IInterface) ['{76A94FF6-4634-4C52-91E4-3F969389D917}'] procedure efetuarPedido(const APizzaTamanho: TPizzaTamanhoEnum; const APizzaSabor: TPizzaSaborEnum; const AValorPedido: Currency; const ATempoPreparo: Integer; const ACodigoCliente: Integer); procedure consultarPedido(const ADocumentoCliente: String; out AFDQuery: TFDQuery ); end; implementation end.
unit RSButton; { *********************************************************************** } { } { RSPak Copyright (c) Rozhenko Sergey } { http://sites.google.com/site/sergroj/ } { sergroj@mail.ru } { } { This file is a subject to any one of these licenses at your choice: } { BSD License, MIT License, Apache License, Mozilla Public License. } { } { *********************************************************************** } {$I RSPak.inc} interface uses Windows, Messages, SysUtils, Classes, Controls, StdCtrls, RSCommon; {$I RSWinControlImport.inc} type TRSButton = class(TButton) private FOnCreateParams: TRSCreateParamsEvent; FProps: TRSWinControlProps; protected procedure CreateParams(var Params:TCreateParams); override; procedure TranslateWndProc(var Msg:TMessage); procedure WndProc(var Msg:TMessage); override; public constructor Create(AOwner:TComponent); override; published property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property BevelWidth; property OnCanResize; property OnDblClick; property OnResize; {$I RSWinControlProps.inc} end; procedure register; implementation procedure register; begin RegisterComponents('RSPak', [TRSButton]); end; { ********************************** TRSButton *********************************** } constructor TRSButton.Create(AOwner:TComponent); begin inherited Create(AOwner); WindowProc:=TranslateWndProc; end; procedure TRSButton.CreateParams(var Params:TCreateParams); begin inherited CreateParams(Params); if Assigned(FOnCreateParams) then FOnCreateParams(Params); end; procedure TRSButton.TranslateWndProc(var Msg:TMessage); var b:boolean; begin if Assigned(FProps.OnWndProc) then begin b:=false; FProps.OnWndProc(Self, Msg, b, WndProc); if b then exit; end; WndProc(Msg); end; procedure TRSButton.WndProc(var Msg:TMessage); begin RSProcessProps(self, Msg, FProps); inherited; end; end.
unit QRAnsiList; interface uses classes, sysutils; type TAnsiStringHolder = class(TObject) public stringValue : AnsiString; constructor Create; end; TAnsiStringList = class(TStringlist) private FNumElements : integer; public procedure AddString( s : AnsiString ); function GetString( index : integer ) : AnsiString; procedure Clear;override; procedure Assign( Source: TPersistent);override; { procedure Delete( index : integer);override; procedure Insert(Index: Integer; const S: string);override; function Get(Index: Integer): string; override; function GetCount: Integer; override; } end; TQRAnsiMerger = class private FOrgLines : TAnsiStringList; FStrippedLines : TAnsiStringList; FMergedLines : TAnsiStringList; FMerged : boolean; FPrepared : boolean; Expressions : TList; FDataSets : TList; protected function GetOrgLines : TAnsiStringList; function GetMergedLines : TAnsiStringList; procedure SetOrgLines(Value : TAnsiStringList); public constructor Create; destructor Destroy; override; procedure Prepare; procedure Merge; procedure UnPrepare; property Lines : TAnsiStringList read GetOrgLines write SetOrgLines; property MergedLines : TAnsiStringList read GetMergedLines; property Merged : boolean read FMerged; property Prepared : boolean read FPrepared; property DataSets : TList read FDataSets write FDataSets; end; implementation uses qrexpr; {TAnsiStringHolder} constructor TAnsiStringHolder.create; begin stringValue := ''; end; {TAnsiStringList} { function TAnsiStringList.Get(Index: Integer): string; begin end; function TAnsiStringList.GetCount: Integer; begin result := FNumElements; end; procedure TAnsiStringList.Insert(Index: Integer; const S: string); begin end; procedure TAnsiStringList.Delete( index : integer); begin end; } procedure TAnsiStringList.Assign( source : TPersistent); var k : integer; begin inherited assign( source); for k := 0 to count-1 do AddObject( '', TAnsiStringHolder(TStrings(source).Objects[k])); FNumElements := count; end; procedure TAnsiStringList.Clear; var k : integer; begin for k := 0 to count-1 do TAnsiStringHolder(self.Objects[k]).Free; inherited Clear; fNumElements := 0; end; procedure TAnsiStringList.AddString( s : AnsiString ); var sh : TAnsiStringHolder; begin sh := TAnsiStringHolder.Create; sh.stringValue := s; self.AddObject('', sh); inc(FNumElements); end; function TAnsiStringList.GetString( index : integer ) : AnsiString; begin result := TAnsiStringHolder(self.Objects[index]).stringValue; end; {TQRAnsiMerger} constructor TQRAnsiMerger.Create; begin FOrgLines := TAnsiStringList.Create; FMergedLines := nil; FMerged := false; FPrepared := false; Expressions := nil; FDataSets := TList.Create; end; destructor TQRAnsiMerger.Destroy; begin if Prepared then UnPrepare; if FOrgLines <> nil then FOrgLines.Free; if FDataSets <> nil then FDataSets.Free; inherited Destroy; end; function TQRAnsiMerger.GetOrgLines : TAnsiStringList; begin Result := FOrgLines; end; function TQRAnsiMerger.GetMergedLines : TAnsiStringList; begin if Merged then Result := FMergedLines else Result := nil; end; procedure TQRAnsiMerger.SetOrgLines(Value : TAnsiStringList); begin if FOrgLines <> nil then FOrgLines.Free; FOrgLines := Value; end; type TMemoEvaluator = class(TQREvaluator) public Line : integer; Position : integer; end; procedure TQRAnsiMerger.Prepare; var I, start, stop, Len : integer; Expr : String; aLine : string; aEvaluator : TMemoEvaluator; begin if Prepared then UnPrepare; Expressions := TList.Create; FMergedLines := TAnsiStringList.Create; if Lines.Count > 0 then begin FStrippedLines := TAnsiStringList.Create; try for I := 0 to Lines.Count - 1 do begin aLine := FOrgLines[I]; Start := AnsiPos('{', aLine); while Start > 0 do begin stop := AnsiPos('}', aLine); Len := Stop - Start - 1; if Len > 0 then begin Expr := copy(aLine, start + 1, Len); Delete(aLine, Start, Len + 2); aEvaluator := TMemoEvaluator.Create; aEvaluator.DataSets := DataSets; aEvaluator.Prepare(Expr); aEvaluator.Line := I; aEvaluator.Position := Start; Expressions.Add(aEvaluator); end; Start := AnsiPos('{', aLine); end; FStrippedLines.Add(aLine); end; finally FPrepared := true; end; end; end; procedure TQRAnsiMerger.UnPrepare; var I : integer; begin if Prepared then try for I := 0 to Expressions.Count - 1 do TMemoEvaluator(Expressions[I]).Free; FStrippedLines.Free; finally FPrepared := false; FMerged := false; end; FMergedLines.Free; Expressions.Free; end; procedure TQRAnsiMerger.Merge; var I : integer; aResult : TQREvResult; Replacement : string; aLine : string; begin if (Expressions.Count > 0) then begin if Merged then FMergedLines.Clear; FMergedLines.Assign(FStrippedLines); for I := Expressions.Count - 1 downto 0 do begin with TMemoEvaluator(Expressions[I]) do begin aResult := Value; case aResult.Kind of resInt : Replacement := IntToStr(aResult.IntResult); resDouble : Replacement := FloatToStr(aResult.dblResult); resString : Replacement := aResult.stringVal; resError : Replacement := ''; end; aLine := FMergedLines[Line]; Insert(Replacement, aLine, Position); FMergedLines[Line] := aLine; end; end end else if not Merged then FMergedLines.Assign(FOrgLines); FMerged := true; end; end.
unit ScriptCompiler; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Script compiler $jrsoftware: issrc/Projects/ScriptCompiler.pas,v 1.22 2010/11/13 06:02:48 jr Exp $ } interface uses Classes, uPSUtils; type TScriptCompilerOnLineToLineInfo = procedure(const Line: LongInt; var Filename: String; var FileLine: LongInt) of object; TScriptCompilerOnUsedLine = procedure(const Filename: String; const Line, Position: LongInt) of object; TScriptCompilerOnUsedVariable = procedure(const Filename: String; const Line, Col, Param1, Param2, Param3: LongInt; const Param4: AnsiString) of object; TScriptCompilerOnError = procedure(const Msg: String; const ErrorFilename: String; const ErrorLine: LongInt) of object; TScriptCompilerOnWarning = procedure(const Msg: String) of object; TScriptCompiler = class private FExports, FUsedLines: TList; FFunctionsFound: TStringList; FScriptText: AnsiString; FOnLineToLineInfo: TScriptCompilerOnLineToLineInfo; FOnUsedLine: TScriptCompilerOnUsedLine; FOnUsedVariable: TScriptCompilerOnUsedVariable; FOnError: TScriptCompilerOnError; FOnWarning: TScriptCompilerOnWarning; function GetExportCount: Integer; procedure PSPositionToLineCol(Position: LongInt; var Line, Col: LongInt); public constructor Create; destructor Destroy; override; procedure AddExport(const Name, Decl: String; const Required: Boolean; const RequiredFilename: String; const RequiredLine: LongInt); function CheckExports: Boolean; function Compile(const ScriptText: String; var CompiledScriptText, CompiledScriptDebugInfo: tbtString): Boolean; property ExportCount: Integer read GetExportCount; function ExportFound(const Name: String): Boolean; function FunctionFound(const Name: String): Boolean; property OnLineToLineInfo: TScriptCompilerOnLineToLineInfo write FOnLineToLineInfo; property OnUsedLine: TScriptCompilerOnUsedLine write FOnUsedLine; property OnUsedVariable: TScriptCompilerOnUsedVariable write FOnUsedVariable; property OnError: TScriptCompilerOnError write FOnError; property OnWarning: TScriptCompilerOnWarning write FOnWarning; end; implementation uses SysUtils, uPSCompiler, uPSC_dll, ScriptClasses_C, ScriptFunc_C; type TScriptExport = class Name, Decl: String; Required: Boolean; RequiredFilename: String; RequiredLine: LongInt; Exported: Boolean; end; {---} function PSPascalCompilerOnExternalProc(Sender: TPSPascalCompiler; Decl: TPSParametersDecl; const Name, FExternal: tbtstring): TPSRegProc; var S: String; P: Integer; begin S := String(FExternal) + ' '; P := Pos(' setuponly ', S); if P > 0 then begin Delete(S, P+1, Length('setuponly ')); Insert('setup:', S, Pos('@', S)+1); end else begin P := Pos(' uninstallonly ', S); if P > 0 then begin Delete(S, P+1, Length('uninstallonly ')); Insert('uninstall:', S, Pos('@', S)+1); end; end; if Pos('@uninstall:files:', S) <> 0 then begin Sender.MakeError('', ecCustomError, '"uninstallonly" cannot be used with "files:"'); Result := nil; Exit; end; Result := DllExternalProc(Sender, Decl, Name, tbtstring(TrimRight(S))); end; function PSPascalCompilerOnUses(Sender: TPSPascalCompiler; const Name: tbtstring): Boolean; begin if Name = 'SYSTEM' then begin RegisterDll_Compiletime(Sender); Sender.OnExternalProc := PSPascalCompilerOnExternalProc; ScriptClassesLibraryRegister_C(Sender); ScriptFuncLibraryRegister_C(Sender); Result := True; end else begin Sender.MakeError('', ecUnknownIdentifier, ''); Result := False; end; end; function PSPascalCompilerOnExportCheck(Sender: TPSPascalCompiler; Proc: TPSInternalProcedure; const ProcDecl: tbtstring): Boolean; var ScriptExports: TList; ScriptExport: TScriptExport; NameFound: Boolean; I: Integer; begin TScriptCompiler(Sender.ID).FFunctionsFound.Add(String(Proc.Name)); ScriptExports := TScriptCompiler(Sender.ID).FExports; { Try and see if the [Code] function matches an export name and if so, see if one of the prototypes for that name matches } NameFound := False; for I := 0 to ScriptExports.Count-1 do begin ScriptExport := ScriptExports[I]; if CompareText(ScriptExport.Name, String(Proc.Name)) = 0 then begin NameFound := True; if CompareText(ScriptExport.Decl, String(ProcDecl)) = 0 then begin ScriptExport.Exported := True; Result := True; Exit; end; end; end; if NameFound then begin with Sender.MakeError('', ecCustomError, tbtstring(Format('Invalid prototype for ''%s''', [Proc.OriginalName]))) do SetCustomPos(Proc.DeclarePos, Proc.DeclareRow, Proc.DeclareCol); Result := False; end else Result := True; end; function PSPascalCompilerOnBeforeOutput(Sender: TPSPascalCompiler): Boolean; var ScriptCompiler: TScriptCompiler; ScriptExport: TScriptExport; I: Integer; Decl: TPSParametersDecl; Msg: String; begin ScriptCompiler := Sender.ID; Result := True; { Try and see if required but non found exports match any built in function names and if so, see if the prototypes also match } for I := 0 to ScriptCompiler.FExports.Count-1 do begin ScriptExport := ScriptCompiler.FExports[I]; if ScriptExport.Required and not ScriptExport.Exported then begin Decl := Sender.UseExternalProc(tbtstring(ScriptExport.Name)); if Decl <> nil then begin if CompareText(ScriptExport.Decl, String(Sender.MakeDecl(Decl))) = 0 then ScriptExport.Exported := True else begin if Assigned(ScriptCompiler.FOnError) then begin Msg := Format('Function or procedure ''%s'' prototype is incompatible', [ScriptExport.Name]); ScriptCompiler.FOnError(Msg, ScriptExport.RequiredFilename, ScriptExport.RequiredLine); end; Result := False; end; end; end; end; end; function PSPascalCompilerOnWriteLine(Sender: TPSPascalCompiler; Position: Cardinal): Boolean; var ScriptCompiler: TScriptCompiler; Filename: String; Line, Col: LongInt; begin ScriptCompiler := Sender.ID; if Assigned(ScriptCompiler.FOnUsedLine) then begin ScriptCompiler.PSPositionToLineCol(Position, Line, Col); if ScriptCompiler.FUsedLines.IndexOf(Pointer(Line)) = -1 then begin ScriptCompiler.FUsedLines.Add(Pointer(Line)); Filename := ''; if Assigned(ScriptCompiler.FOnLineToLineInfo) then ScriptCompiler.FOnLineToLineInfo(Line, Filename, Line); ScriptCompiler.FOnUsedLine(Filename, Line, Position); Result := True; end else Result := False; end else Result := True; end; procedure PSPascalCompilerOnUseVariable(Sender: TPSPascalCompiler; VarType: TPSVariableType; VarNo: Longint; ProcNo, Position: Cardinal; const PropData: tbtstring); var ScriptCompiler: TScriptCompiler; Filename: String; Line, Col: LongInt; begin ScriptCompiler := Sender.ID; if Assigned(ScriptCompiler.FOnUsedVariable) then begin ScriptCompiler.PSPositionToLineCol(Position, Line, Col); Filename := ''; if Assigned(ScriptCompiler.FOnLineToLineInfo) then ScriptCompiler.FOnLineToLineInfo(Line, Filename, Line); ScriptCompiler.FOnUsedVariable(Filename, Line, Col, LongInt(VarType), ProcNo, VarNo, PropData); end; end; {---} constructor TScriptCompiler.Create; begin FExports := TList.Create(); FUsedLines := TList.Create(); FFunctionsFound := TStringList.Create(); end; destructor TScriptCompiler.Destroy; var I: Integer; begin FFunctionsFound.Free(); FUsedLines.Free(); for I := 0 to FExports.Count-1 do TScriptExport(FExports[I]).Free(); FExports.Free(); end; procedure TScriptCompiler.PSPositionToLineCol(Position: LongInt; var Line, Col: LongInt); function FindNewLine(const S: AnsiString; const Start: Integer): Integer; var I: Integer; begin for I := Start to Length(S) do if S[I] = #10 then begin Result := I - Start + 1; Exit; end; Result := 0; end; var LineStartPosition, LineLength: LongInt; begin Inc(Position); Line := 1; LineStartPosition := 1; LineLength := FindNewLine(FScriptText, LineStartPosition); while (LineLength <> 0) and (Position > LineLength) do begin Inc(Line); Inc(LineStartPosition, LineLength); Dec(Position, LineLength); LineLength := FindNewLine(FScriptText, LineStartPosition); end; {$IFDEF UNICODE} { Convert Position from an ANSI string index to a UTF-16 string index } Position := Length(String(Copy(FScriptText, LineStartPosition, Position - 1))) + 1; {$ENDIF} Col := Position; end; procedure TScriptCompiler.AddExport(const Name, Decl: String; const Required: Boolean; const RequiredFilename: String; const RequiredLine: LongInt); var ScriptExport: TScriptExport; I: Integer; begin for I := 0 to FExports.Count-1 do begin ScriptExport := FExports[I]; if (CompareText(ScriptExport.Name, Name) = 0) and (CompareText(ScriptExport.Decl, Decl) = 0) then begin if Required and not ScriptExport.Required then begin ScriptExport.Required := True; ScriptExport.RequiredFilename := RequiredFilename; ScriptExport.RequiredLine := RequiredLine; end; Exit; end; end; ScriptExport := TScriptExport.Create(); ScriptExport.Name := Name; ScriptExport.Decl := Decl; ScriptExport.Required := Required; if Required then begin ScriptExport.RequiredFilename := RequiredFilename; ScriptExport.RequiredLine := RequiredLine; end; FExports.Add(ScriptExport); end; function TScriptCompiler.CheckExports: Boolean; var ScriptExport, ScriptExport2: TScriptExport; I, J: Integer; Msg: String; NameFound: Boolean; begin Result := True; for I := 0 to FExports.Count-1 do begin ScriptExport := FExports[I]; if ScriptExport.Required and not ScriptExport.Exported then begin if Assigned(FOnError) then begin { Either the function wasn't present or it was present but matched another export } NameFound := False; for J := 0 to FExports.Count-1 do begin ScriptExport2 := FExports[J]; if (I <> J) and (CompareText(ScriptExport.Name, ScriptExport2.Name) = 0) then begin NameFound := True; Break; end; end; if NameFound then Msg := Format('Required function or procedure ''%s'' found but not with a compatible prototype', [ScriptExport.Name]) else Msg := Format('Required function or procedure ''%s'' not found', [ScriptExport.Name]); FOnError(Msg, ScriptExport.RequiredFilename, ScriptExport.RequiredLine); end; Result := False; Exit; end; end; end; function TScriptCompiler.Compile(const ScriptText: String; var CompiledScriptText, CompiledScriptDebugInfo: tbtString): Boolean; var PSPascalCompiler: TPSPascalCompiler; L, Line, Col: LongInt; Filename, Msg: String; begin Result := False; { Note: Cast disabled on non-Unicode to work around D2 codegen bug } FScriptText := {$IFDEF UNICODE}AnsiString{$ENDIF}(ScriptText); PSPascalCompiler := TPSPascalCompiler.Create(); try PSPascalCompiler.ID := Self; PSPascalCompiler.AllowNoBegin := True; PSPascalCompiler.AllowNoEnd := True; PSPascalCompiler.BooleanShortCircuit := True; PSPascalCompiler.OnUses := PSPascalCompilerOnUses; PSPascalCompiler.OnExportCheck := PSPascalCompilerOnExportCheck; PSPascalCompiler.OnBeforeOutput := PSPascalCompilerOnBeforeOutput; DefaultCC := ClStdCall; FUsedLines.Clear(); PSPascalCompiler.OnWriteLine := PSPascalCompilerOnWriteLine; PSPascalCompiler.OnUseVariable := PSPascalCompilerOnUseVariable; if not PSPascalCompiler.Compile(FScriptText) then begin if Assigned(FOnError) then begin for L := 0 to PSPascalCompiler.MsgCount-1 do begin if PSPascalCompiler.Msg[L] is TPSPascalCompilerError then begin PSPositionToLineCol(PSPascalCompiler.Msg[L].Pos, Line, Col); Filename := ''; if Assigned(FOnLineToLineInfo) then FOnLineToLineInfo(Line, Filename, Line); Msg := Format('Column %d:'#13#10'%s', [Col, PSPascalCompiler.Msg[L].ShortMessageToString]); FOnError(Msg, Filename, Line); Break; end; end; end; Exit; end else begin if not CheckExports() then Exit; if not PSPascalCompiler.GetOutput(CompiledScriptText) then begin if Assigned(FOnError) then begin Msg := 'GetOutput failed'; FOnError(Msg, '', 0); end; Exit; end; if not PSPascalCompiler.GetDebugOutput(CompiledScriptDebugInfo) then begin if Assigned(FOnError) then begin Msg := 'GetDebugOutput failed'; FOnError(Msg, '', 0); end; Exit; end; if Assigned(FOnWarning) then begin for L := 0 to PSPascalCompiler.MsgCount-1 do begin PSPositionToLineCol(PSPascalCompiler.Msg[L].Pos, Line, Col); Filename := ''; if Assigned(FOnLineToLineInfo) then FOnLineToLineInfo(Line, Filename, Line); Msg := ''; if Filename <> '' then Msg := Msg + Filename + ', '; Msg := Msg + Format('Line %d, Column %d: [%s] %s', [Line, Col, PSPascalCompiler.Msg[L].ErrorType, PSPascalCompiler.Msg[L].ShortMessageToString]); FOnWarning(Msg); end; end; end; Result := True; finally PSPascalCompiler.Free(); end; end; function TScriptCompiler.ExportFound(const Name: String): Boolean; var ScriptExport: TScriptExport; I: Integer; begin for I := 0 to FExports.Count-1 do begin ScriptExport := FExports[I]; if CompareText(ScriptExport.Name, Name) = 0 then begin Result := ScriptExport.Exported; Exit; end; end; Result := False; end; function TScriptCompiler.FunctionFound(const Name: String): Boolean; var I: Integer; begin Result := False; for I := 0 to FFunctionsFound.Count-1 do begin if CompareText(FFunctionsFound[I], Name) = 0 then begin Result := True; Break; end; end; end; function TScriptCompiler.GetExportCount: Integer; begin Result := FExports.Count; end; end.
// SAX for Pascal, Simple API for XML Extension Interfaces in Pascal. // Ver 1.1 July 4, 2003 // http://xml.defined.net/SAX (this will change!) // Based on http://www.saxproject.org/ // No warranty; no copyright -- use this as you will. unit SAXExt; interface uses SAX; const // There are separate interface IDs based on Widestrings/Non widestrings {$IFDEF SAX_WIDESTRINGS} IID_IDeclHandler = '{75534E2D-BB12-4379-8298-486C00141B6A}'; IID_ILexicalHandler = '{1EE9A4D2-BA2E-47C8-81CB-1C81704D9F20}'; IID_IAttributes2 = '{7E9F5766-FE9E-46FB-AC3D-7EC2BEFAF35F}'; IID_IEntityResolver2 = '{A0EFA85C-AD2C-4109-BEBA-C88B47ADA6AF}'; IID_ILocator2 = '{2CEE7326-1647-4EAA-8670-9C21717B3779}'; {$ELSE} IID_IDeclHandler = '{FC783826-A869-4CCC-A9F9-FEFB2EDB9B4C}'; IID_ILexicalHandler = '{DAE1DDCC-A591-473E-8500-75626184C69D}'; IID_IAttributes2 = '{F801E492-56B4-4E76-A201-B7E022A7A5B5}'; IID_IEntityResolver2 = '{7CCC2B11-376A-4748-BB5A-C2EBE092F1FD}'; IID_ILocator2 = '{BAED1685-030E-4CCB-88E4-FC2537516464}'; {$ENDIF} type IDeclHandler = interface; ILexicalHandler = interface; IAttributes2 = interface; IEntityResolver2 = interface; ILocator2 = interface; // SAX2 extension handler for DTD declaration events. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This is an optional extension handler for SAX2 to provide more // complete information about DTD declarations in an XML document. // XML readers are not required to recognize this handler, and it // is not part of core-only SAX2 distributions.</p> // // <p>Note that data-related DTD declarations (unparsed entities and // notations) are already reported through the <a href="../SAX/IDTDHandler.html">IDTDHandler</a> // interface.</p> // // <p>If you are using the declaration handler together with a lexical // handler, all of the events will occur between the // <a href="../SAXExt/ILexicalHandler.html#startDTD">startDTD</a> and the // <a href="../SAXExt/ILexicalHandler.html#endDTD">endDTD</a> events.</p> // // <p>To set the DeclHandler for an XML reader, use the // <a href="../SAX/IXMLReader.html#getProperty">getProperty</a> method // with the property name // <code>http://xml.org/sax/properties/declaration-handler</code> // and an object implementing this interface (or nil) as the value. // If the reader does not report declaration events, it will throw a // <a href="../SAX/ESAXNotRecognizedException.html">ESAXNotRecognizedException</a> // when you attempt to register the handler.</p> // // @since SAX 2.0 (extensions 1.0) // @see <a href="../SAX/IXMLReader.html">IXMLReader</a> // IDeclHandler = interface(IUnknown) [IID_IDeclHandler] // Report an element type declaration. // // <p>The content model will consist of the string "EMPTY", the // string "ANY", or a parenthesised group, optionally followed // by an occurrence indicator. The model will be normalized so // that all parameter entities are fully resolved and all whitespace // is removed,and will include the enclosing parentheses. Other // normalization (such as removing redundant parentheses or // simplifying occurrence indicators) is at the discretion of the // parser.</p> // // @param name The element type name. // @param model The content model as a normalized string. // @exception ESAXException The application may raise an exception. /// procedure elementDecl(const name, model : SAXString); // Report an attribute type declaration. // // <p>Only the effective (first) declaration for an attribute will // be reported. The type will be one of the strings "CDATA", // "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", // "ENTITIES", a parenthesized token group with // the separator "|" and all whitespace removed, or the word // "NOTATION" followed by a space followed by a parenthesized // token group with all whitespace removed.</p> // // <p>The value will be the value as reported to applications, // appropriately normalized and with entity and character // references expanded.</p> // // @param eName The name of the associated element. // @param aName The name of the attribute. // @param attrType A string representing the attribute type. // @@param mode A string representing the attribute defaulting mode // ("#IMPLIED", "#REQUIRED", or "#FIXED") or '' if // none of these applies. // @param value A string representing the attribute's default value, // or '' if there is none. // @exception ESAXException The application may raise an exception. procedure attributeDecl(const eName, aName, attrType, mode, value: SAXString); // Report an internal entity declaration. // // <p>Only the effective (first) declaration for each entity // will be reported. All parameter entities in the value // will be expanded, but general entities will not.</p> // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%'. // @param value The replacement text of the entity. // @exception ESAXException The application may raise an exception. // @see <a href="../SAXExt/IDeclHandler.html#externalEntityDecl">IDeclHandler.externalEntityDecl</a> // @see <a href="../SAX/IDTDHandler.html#unparsedEntityDecl">IDTDHandler.unparsedEntityDecl</a> procedure internalEntityDecl(const name, value : SAXString); // Report a parsed external entity declaration. // // <p>Only the effective (first) declaration for each entity // will be reported.</p> // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%'. // @param publicId The declared public identifier of the entity, or // an empty string if none was declared. // @param systemId The declared system identifier of the entity. // @exception ESAXException The application may raise an exception. // @see <a href="../SAXExt/IDeclHandler.html#internalEntityDecl">IDeclHandler.internalEntityDecl</a> // @see <a href="../SAX/IDTDHandler.html#unparsedEntityDecl">IDTDHandler.unparsedEntityDecl</a> procedure externalEntityDecl(const name, publicId, systemId : SAXString); end; // SAX2 extension handler for lexical events. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This is an optional extension handler for SAX2 to provide // lexical information about an XML document, such as comments // and CDATA section boundaries. // XML readers are not required to recognize this handler, and it // is not part of core-only SAX2 distributions.</p> // // <p>The events in the lexical handler apply to the entire document, // not just to the document element, and all lexical handler events // must appear between the content handler's startDocument and // endDocument events.</p> // // <p>To set the LexicalHandler for an XML reader, use the // <a href="../SAX/IXMLReader.html#getProperty">getProperty</a> method // with the property name // <code>http://xml.org/sax/properties/lexical-handler</code> // and an object implementing this interface (or nil) as the value. // If the reader does not report lexical events, it will throw a // <a href="../SAX/ESAXNotRecognizedException.html">ESAXNotRecognizedException</a> // when you attempt to register the handler.</p> // // @since SAX 2.0 (extensions 1.0) ILexicalHandler = interface(IUnknown) [IID_ILexicalHandler] // Report the start of DTD declarations, if any. // // <p>This method is intended to report the beginning of the // DOCTYPE declaration; if the document has no DOCTYPE declaration, // this method will not be invoked.</p> // // <p>All declarations reported through // <a href="../SAX/IDTDHandler.html">IDTDHandler</a> or // <a href="../SAXExt/IDeclHandler.html">IDeclHandler</a> events must appear // between the startDTD and <a href="../SAXExt/ILexicalHandler.html#endDTD">endDTD</a> events. // Declarations are assumed to belong to the internal DTD subset // unless they appear between <a href="../SAXExt/ILexicalHandler.html#startEntity">startEntity</a> // and <a href="../SAXExt/ILexicalHandler.html#endEntity">endEntity</a> events. Comments and // processing instructions from the DTD should also be reported // between the startDTD and endDTD events, in their original // order of (logical) occurrence; they are not required to // appear in their correct locations relative to DTDHandler // or DeclHandler events, however.</p> // // <p>Note that the start/endDTD events will appear within // the start/endDocument events from IContentHandler and // before the first // <a href="../SAX/IContentHandler.html#startElement">startElement</a> // event.</p> // // @param name The document type name. // @param publicId The declared public identifier for the // external DTD subset, or an empty string if none was declared. // @param systemId The declared system identifier for the // external DTD subset, or an empty string if none was declared. // (Note that this is not resolved against the document // base URI.) // @exception ESAXException The application may raise an // exception. // @see <a href="../SAXExt/ILexicalHandler.html#endDTD">ILexicalHandler.endDTD</a> // @see <a href="../SAXExt/ILexicalHandler.html#startEntity">ILexicalHandler.startEntity</a> procedure startDTD(const name, publicId, systemId : SAXString); // Report the end of DTD declarations. // // <p>This method is intended to report the end of the // DOCTYPE declaration; if the document has no DOCTYPE declaration, // this method will not be invoked.</p> // // @exception ESAXException The application may raise an exception. // @see <a href="../SAXExt/ILexicalHandler.html#startDTD">ILexicalHandler.startDTD</a> procedure endDTD(); // Report the beginning of some internal and external XML entities. // // <p>The reporting of parameter entities (including // the external DTD subset) is optional, and SAX2 drivers that // report ILexicalHandler events may not implement it; you can use the // <code // >http://xml.org/sax/features/lexical-handler/parameter-entities</code> // feature to query or control the reporting of parameter entities.</p> // // <p>General entities are reported with their regular names, // parameter entities have '%' prepended to their names, and // the external DTD subset has the pseudo-entity name "[dtd]".</p> // // <p>When a SAX2 driver is providing these events, all other // events must be properly nested within start/end entity // events. There is no additional requirement that events from // <a href="../SAXExt/IDeclHandler.html">IDeclHandler</a> or // <a href="../SAX/IDTDHandler.html">IDTDHandler</a> be properly ordered.</p> // // <p>Note that skipped entities will be reported through the // <a href="../SAX/IContentHandler.html#skippedEntity">skippedEntity</a> // event, which is part of the IContentHandler interface.</p> // // <p>Because of the streaming event model that SAX uses, some // entity boundaries cannot be reported under any // circumstances:</p> // // <ul> // <li>general entities within attribute values</li> // <li>parameter entities within declarations</li> // </ul> // // <p>These will be silently expanded, with no indication of where // the original entity boundaries were.</p> // // <p>Note also that the boundaries of character references (which // are not really entities anyway) are not reported.</p> // // <p>All start/endEntity events must be properly nested.</p> // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%', and if it is the // external DTD subset, it will be "[dtd]". // @exception SAXException The application may raise an exception. // @see <a href="../SAXExt/ILexicalHandler.html#endEntity">ILexicalHandler.endEntity</a> // @see <a href="../SAXExt/IDeclHandler.html#internalEntityDecl">IDeclHandler.internalEntityDecl</a> // @see <a href="../SAXExt/IDeclHandler.html#externalEntityDecl">IDeclHandler.externalEntityDecl</a> /// procedure startEntity(const name : SAXString); // Report the end of an entity. // // @param name The name of the entity that is ending. // @exception ESAXException The application may raise an exception. // @see <a href="../SAXExt/ILexicalHandler.html#startEntity">ILexicalHandler.startEntity</a> procedure endEntity(const name : SAXString); // Report the start of a CDATA section. // // <p>The contents of the CDATA section will be reported through // the regular <a href="../SAX/IContentHandler.html#characters">characters</a> // event; this event is intended only to report // the boundary.</p> // // @exception ESAXException The application may raise an exception. // @see <a href="../SAXExt/ILexicalHandler.html#endCDATA">ILexicalHandler.endCDATA</a> procedure startCDATA(); // Report the end of a CDATA section. // // @exception ESAXException The application may raise an exception. // @see <a href="../SAXExt/ILexicalHandler.html#startCDATA">ILexicalHandler.startCDATA</a> procedure endCDATA(); // Report an XML comment anywhere in the document. // // <p>This callback will be used for comments inside or outside the // document element, including comments in the external DTD // subset (if read). Comments in the DTD must be properly // nested inside start/endDTD and start/endEntity events (if // used).</p> // // @param ch The characters in the comment. // @exception ESAXException The application may raise an exception. procedure comment(const ch : SAXString); end; // SAX2 extension to augment the per-attribute information // provided though <a href="../SAX/IAttributes.html">IAttributes</a>. // If an implementation supports this extension, the attributes // provided in <a href="../SAX/IContentHandler.html#startElement">IContentHandler.startElement</a> // will implement this interface, // and the <em>http://xml.org/sax/features/use-attributes2</em> // feature flag will have the value <em>true</em>. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p> XMLReader implementations are not required to support this // information, and it is not part of core-only SAX2 distributions.</p> // // <p>Note that if an attribute was defaulted (<em>not isSpecified()</em>) // it will of necessity also have been declared (<em>isDeclared()</em>) // in the DTD. // Similarly if an attribute's type is anything except CDATA, then it // must have been declared. // </p> // // @since SAX 2.0 (extensions 1.1 alpha) IAttributes2 = interface(IAttributes) [IID_IAttributes2] // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // @param index The attribute index (zero-based). // @return true if the attribute was declared in the DTD, // false otherwise. // @exception Exception When the // supplied index does not identify an attribute. // function isDeclared(index : Integer) : Boolean; overload; // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // @param qName The XML 1.0 qualified name. // @return true if the attribute was declared in the DTD, // false otherwise. // @exception ESAXIllegalArgumentException When the // supplied name does not identify an attribute. function isDeclared(const qName : SAXString) : Boolean; overload; // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // <p>Remember that since DTDs do not "understand" namespaces, the // namespace URI associated with an attribute may not have come from // the DTD. The declaration will have applied to the attribute's // <em>qName</em>.</p> // // @param uri The Namespace URI, or the empty string if // the name has no Namespace URI. // @param localName The attribute's local name. // @return true if the attribute was declared in the DTD, // false otherwise. // @exception ESAXIllegalArgumentException When the // supplied names do not identify an attribute. function isDeclared(const uri, localName : SAXString) : Boolean; overload; // Returns true unless the attribute value was provided // by DTD defaulting. // // @param index The attribute index (zero-based). // @return true if the value was found in the XML text, // false if the value was provided by DTD defaulting. // @exception ESAXIllegalArgumentException When the // supplied index does not identify an attribute. function isSpecified(index : Integer) : Boolean; overload; // Returns true unless the attribute value was provided // by DTD defaulting. // // <p>Remember that since DTDs do not "understand" namespaces, the // namespace URI associated with an attribute may not have come from // the DTD. The declaration will have applied to the attribute's // <em>qName</em>.</p> // // @param uri The Namespace URI, or the empty string if // the name has no Namespace URI. // @param localName The attribute's local name. // @return true if the value was found in the XML text, // false if the value was provided by DTD defaulting. // @exception ESAXIllegalArgumentException When the // supplied names do not identify an attribute. function isSpecified(const uri, localName : SAXString) : Boolean; overload; // Returns true unless the attribute value was provided // by DTD defaulting. // // @param qName The XML 1.0 qualified name. // @return true if the value was found in the XML text, // false if the value was provided by DTD defaulting. // @exception ESAXIllegalArgumentException When the // supplied name does not identify an attribute. function isSpecified(const qName : SAXString) : Boolean; overload; end; // Extended interface for mapping external entity references to input // sources, or providing a missing external subset. The // <a href="../SAX/IXMLReader.html#setEntityResolver">IXMLReader.setEntityResolver</a> method // is used to provide implementations of this interface to parsers. // When a parser uses the methods in this interface, the // <a href="../SAXExt/IEntityResolver2.html#resolveEntity">IEntityResolver2.resolveEntity</a> // method (in this interface) is used <em>instead of</em> the older (SAX 1.0) // <a href="../SAX/IEntityResolver.html#resolveEntity">IEntityResolver.resolveEntity</a> method. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>If a SAX application requires the customized handling which this // interface defines for external entities, it must ensure that it uses // an IXMLReader with the // <em>http://xml.org/sax/features/use-entity-resolver2</em> feature flag // set to <em>true</em> (which is its default value when the feature is // recognized). If that flag is unrecognized, or its value is false, // or the resolver does not implement this interface, then only the // <a href="../SAX/IEntityResolver.html">IEntityResolver</a> method will be used. // </p> // // <p>That supports three categories of application that modify entity // resolution. <em>Old Style</em> applications won't know about this interface; // they will provide an IEntityResolver. // <em>Transitional Mode</em> provide an IEntityResolver2 and automatically // get the benefit of its methods in any systems (parsers or other tools) // supporting it, due to polymorphism. // Both <em>Old Style</em> and <em>Transitional Mode</em> applications will // work with any SAX2 parser. // <em>New style</em> applications will fail to run except on SAX2 parsers // that support this particular feature. // They will insist that feature flag have a value of "true", and the // IEntityResolver2 implementation they provide might throw an exception // if the original SAX 1.0 style entity resolution method is invoked. // </p> // // @see <a href="../SAX/IXMLReader.html#setEntityResolver">IXMLReader.setEntityResolver</a> // // @since SAX 2.0 (extensions 1.1 alpha) IEntityResolver2 = interface(IEntityResolver) [IID_IEntityResolver2] // <p>Allows applications to provide an external subset for documents // that don't explicitly define one. Documents with DOCTYPE declarations // that omit an external subset can thus augment the declarations // available for validation, entity processing, and attribute processing // (normalization, defaulting, and reporting types including ID). // This augmentation is reported // through the <a href="../SAXExt/ILexicalHandler.html#startDTD">startDTD</a> method as if // the document text had originally included the external subset; // this callback is made before any internal subset data or errors // are reported.</p> // // <p>This method can also be used with documents that have no DOCTYPE // declaration. When the root element is encountered, // but no DOCTYPE declaration has been seen, this method is // invoked. If it returns a value for the external subset, that root // element is declared to be the root element, giving the effect of // splicing a DOCTYPE declaration at the end the prolog of a document // that could not otherwise be valid. The sequence of parser callbacks // in that case logically resembles this:</p> // // <pre> // ... comments and PIs from the prolog (as usual) // startDTD('rootName', source.getPublicId(), source.getSystemId()); // startEntity ('[dtd]'); // ... declarations, comments, and PIs from the external subset // endEntity ('[dtd]'); // endDTD(); // ... then the rest of the document (as usual) // startElement (..., 'rootName', ...); // </pre> // // <p>Note that the InputSource gets no further resolution. // Implementations of this method may wish to invoke // <a href="../SAXExt/IEntityResolver2.html#resolveEntity">resolveEntity</a> to gain benefits such as use // of local caches of DTD entities. Also, this method will never be // used by a (non-validating) processor that is not including external // parameter entities. </p> // // <p>Uses for this method include facilitating data validation when // interoperating with XML processors that would always require // undesirable network accesses for external entities, or which for // other reasons adopt a "no DTDs" policy. // Non-validation motives include forcing documents to include DTDs so // that attributes are handled consistently. // For example, an XPath processor needs to know which attibutes have // type "ID" before it can process a widely used type of reference.</p> // // <p><strong>Warning:</strong> Returning an external subset modifies // the input document. By providing definitions for general entities, // it can make a malformed document appear to be well formed. // </p> // // @param name Identifies the document root element. This name comes // from a DOCTYPE declaration (where available) or from the actual // root element. // @param baseURI The document's base URI, serving as an additional // hint for selecting the external subset. This is always an absolute // URI, unless it is an empty string because the IXMLReader was given an // IInputSource without one. // // @return An InputSource object describing the new external subset // to be used by the parser, or nil to indicate that no external // subset is provided. // // @exception ESAXException Any SAX exception. function getExternalSubset(const name, baseURI : SAXString) : IInputSource; // <p>TEST !!! Allows applications to map references to external entities into input // sources, or tell the parser it should use conventional URI resolution. // This method is only called for external entities which have been // properly declared. // This method provides more flexibility than the <a href="../SAX/IEntityResolver.html">IEntityResolver</a> // interface, supporting implementations of more complex catalogue // schemes such as the one defined by the // <a href="http://www.oasis-open.org/committees/entity/spec-2001-08-06.html"> // OASIS XML Catalogs</a> specification.</p> // // <p>Parsers configured to use this resolver method will call it // to determine the input source to use for any external entity // being included because of a reference in the XML text. // That excludes the document entity, and any external entity returned // by <a href="../SAXExt/IEntityResolver2.html#getExternalSubset">getExternalSubset</a>. // When a (non-validating) processor is configured not to include // a class of entities (parameter or general) through use of feature // flags, this method is not invoked for such entities.</p> // // <p>Note that the entity naming scheme used here is the same one // used in the <a href="../SAXExt/ILexicalHandler.html">ILexicalHandler</a>, or in the // <a href="../SAX/IContentHandler.html#skippedEntity">IContentHandler.skippedEntity</a> // method. </p> // // @param name Identifies the external entity being resolved. // Either '[dtd]' for the external subset, or a name starting // with '%' to indicate a parameter entity, or else the name of // a general entity. This is never empty when invoked by a SAX2 // parser. // // @param publicId The public identifier of the external entity being // referenced (normalized as required by the XML specification), or // an empty string if none was supplied. // @param baseURI The URI with respect to which relative systemIDs // are interpreted. This is always an absolute URI, unless it is // nil because the XMLReader was given an IInputSource without one. // This URI is defined by the XML specification to be the one // associated with the '&lt;' starting the relevant declaration. // @param systemId The system identifier of the external entity // being referenced; either a relative or absolute URI. // This is never empty when invoked by a SAX2 parser; only declared // entities, and any external subset, are resolved by such parsers // // @return An IInputSource object describing the new input source to // be used by the parser. Returning nil directs the parser to // resolve the system ID against the base URI and open a connection // to resulting URI. // // @exception ESAXException Any SAX exception. function resolveEntity(const name, publicId, baseURI, systemId : SAXString) : IInputSource; end; // SAX2 extension to augment the entity information provided // though a <a href="../SAX/ILocator.html">ILocator</a>. // If an implementation supports this extension, the Locator // provided in <a href="../SAX/IContentHandler.html#setDocumentLocator">IContentHandler.setDocumentLocator</a> // will implement this interface, and the // <em>http://xml.org/sax/features/use-locator2</em> feature // flag will have the value <em>true</em>. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p> XMLReader implementations are not required to support this // information, and it is not part of core-only SAX2 distributions.</p> // // @since SAX 2.0 (extensions 1.1 alpha) ILocator2 = interface(ILocator) [IID_ILocator2] // Returns the version of XML used for the entity. This will // normally be the identifier from the current entity's // <em>&lt;?xml&#160;version='...'&#160;...?&gt;</em> declaration, // or be defaulted by the parser. // // <p> At this writing, only one version ("1.0") is defined, but it // seems likely that a new version will be defined which has slightly // different rules about which characters are legal in XML names.</p> // // @return Identifier for the XML version being used to interpret // the entity's text. function getXMLVersion() : PSAXChar; // Returns the name of the character encoding for the entity. // If the encoding was declared externally (for example, in a MIME // Content-Type header), that will be the name returned. Else if there // was an <em>&lt;?xml&#160;...encoding='...'?&gt;</em> declaration at // the start of the document, that encoding name will be returned. // Otherwise the encoding will been inferred (normally to be UTF-8, or // some UTF-16 variant), and that inferred name will be returned. // // <p>When an <a href="../SAX/IInputSource.html">IInputSource</a> is used // to provide an entity's character stream, this method returns the // encoding provided in that input stream.</p> // // <p> Note that some recent W3C specifications require that text // in some encodings be normalized, using Unicode Normalization // Form C, before processing. Such normalization must be performed // by applications, and would normally be triggered based on the // value returned by this method.</p> // // <p> Encoding names may be those used by the underlying JVM, // and comparisons should be case-insensitive.</p> // // @return Name of the character encoding being used to interpret // the entity's text, or null if this was not provided for a // character stream passed through an InputSource. function getEncoding() : PSAXChar; end; implementation end.
{$M+} unit uBackup_restore; interface uses FireDAC.Phys.FB, IBX.IBServices, FireDAC.Comp.Client, Vcl.StdCtrls, System.SysUtils, Vcl.Forms; type TBackup_restore = class(TObject) private FConexao : TFDConnection; FBackupFB: TIBBackupService; FRestoreFB: TIBRestoreService ; FMemoBackup: TMemo; procedure SetBackupFB(const Value: TIBBackupService ); procedure SetRestoreFB(const Value: TIBRestoreService); procedure SetMemoBackup(const Value: TMemo); public constructor Create(poConexao: TFDCOnnection); destructor Destroy; override; procedure Backup(psCaminhoFBK : String); procedure Restore(psCaminhoFBK : String); published property BackupFB: TIBBackupService read FBackupFB write SetBackupFB; property RestoreFB: TIBRestoreService read FRestoreFB write SetRestoreFB; property MemoBackup : TMemo read FMemoBackup write SetMemoBackup; end; implementation { TBackup_restore } procedure TBackup_restore.Backup(psCaminhoFBK : String); begin if FBackupFB <> nil then begin try MemoBackup.Clear; MemoBackup.Lines.Add('Preparando para gerar o backup...'); MemoBackup.Lines.Add(''); FConexao.Connected:=False;//desconecta da base de dados FBackupFB.DatabaseName:=FConexao.Params.Database;//caminho da base de dados FBackupFB.ServerName:='localhost';//nome do servidor FBackupFB.BackupFile.Clear; FBackupFB.BackupFile.Add(psCaminhoFBK);//adiciona o caminho do arquivo de backup escolhido pelo usuário FBackupFB.Protocol:=Local;//protocolo de conexão FBackupFB.Params.Clear; FBackupFB.Params.Add('user_name=SYSDBA');//nome de usuário FBackupFB.Params.Add('password=masterkey');//senha do usuário FBackupFB.Options:=[];//limpa a propriedade option {o bloco de if abaixo esta adicionando as opções de restauração de acordo com o que o usuário escolheu. Após esta listagem você encontra um link para um outro artigo onde você encontra mais informações sobre essas e outras opções de restauração} FBackupFB.Options:= FBackupFB.Options+[IgnoreChecksums]; FBackupFB.Options:= FBackupFB.Options+[IgnoreLimbo]; FBackupFB.Options:= FBackupFB.Options+[NoGarbageCollection]; {a propriedade verbose do TIBBackupService especifica se durante o processo de backup será retornado para a aplicação o detalhamento da execução} FBackupFB.Verbose := True; MemoBackup.Lines.Add(' Verbose: '+BoolToStr(True)); MemoBackup.Lines.Add(' Nome do servidor: '+FBackupFB.ServerName); MemoBackup.Lines.Add(''); FBackupFB.Active:=True;//ativa o serviço de backup, mais ainda não inicia. MemoBackup.Lines.Add(''); MemoBackup.Lines.Add('/***INICIO***\'); Application.ProcessMessages; MemoBackup.Lines.Add(''); try FBackupFB.ServiceStart;//inicia o processo de backup while not FBackupFB.Eof do begin {conforme o backup vai sendo executado o nos podemos pegar os detalhes da sua execução através da função GetNextLine} MemoBackup.Lines.Add(FBackupFB.GetNextLine); end; finally end; FBackupFB.Active:=False;//desativa o serviço de backup MemoBackup.Lines.Add(''); MemoBackup.Lines.Add('/****FIM****\'); MemoBackup.Lines.Add(''); MemoBackup.Lines.Add(''); MemoBackup.Lines.Add('Backup concluído.'); MemoBackup.Lines.Add('Backup gravado em: ' + psCaminhoFBK); FConexao.Connected:=True;//conecta o sistema na base de dados except on E: Exception do begin MemoBackup.Lines.Add('Ocorreu um erro inesperado. O backup não foi concluído.'); MemoBackup.Lines.Add('Informações da exceção:'); MemoBackup.Lines.Add(' '+E.Message); FConexao.Connected:=True;//conecta o sistema na base de dados end; end; end; end; constructor TBackup_restore.Create(poConexao: TFDCOnnection); begin FConexao := poConexao; end; destructor TBackup_restore.Destroy; begin inherited; end; procedure TBackup_restore.Restore(psCaminhoFBK: String); begin if FRestoreFB <> nil then begin try MemoBackup.Clear; MemoBackup.Lines.Add('Preparando para restaurar o backup...'); MemoBackup.Lines.Add(''); with FRestoreFB do begin FConexao.Connected := False;//desconecta da base DatabaseName.Clear; DatabaseName.Add(FConexao.Params.Database);//caminho da base ServerName:='';//nome do servidor BackupFile.Clear; BackupFile.Add(psCaminhoFBK);//caminho do arquivo de backup Protocol:=Local;//protocolo de conexão Params.Clear; Params.Add('user_name=SYSDBA');//nome de usuário Params.Add('password=masterkey');//senha do usuário Options:=[]; Options:=[CreateNewDB]; {o bloco de if abaixo esta adicionando as opções de restauração de acordo com o que o usuário escolheu. Após esta listagem você encontra um link para um outro artigo onde você encontra mais informações sobre essas e outras opções de restauração} // if CBDesativarIndices.Checked then // Options:=Options+[DeactivateIndexes]; // if CBSemShadow.Checked then // Options:=Options+[NoShadow]; // if CBSemValidar.Checked then // Options:=Options+[NoValidityCheck]; // if CBUmaTabela.Checked then // Options:=Options+[OneRelationAtATime]; // if CBSubstituir.Checked then // Options:=Options+[Replace]; {a propriedade verbose do TIBRestoreService especifica se durante o processo de restauração será retornado para a aplicação o detalhamento da execução} Verbose:=True; // MemoBackup.Lines.Add(' Desativar indices: '+BoolToStr(CBDesativarIndices.Checked)); // MemoBackup.Lines.Add(' Restaurar arquivo espelho: '+BoolToStr(not CBSemShadow.Checked)); // MemoBackup.Lines.Add(' Validar regras de integridade: '+BoolToStr(not CBSemValidar.Checked)); // MeMemoBackupmo1.Lines.Add(' Restaurar uma tabela por vez: '+BoolToStr(CBUmaTabela.Checked)); MemoBackup.Lines.Add(' Nome do servidor: '+ServerName); MemoBackup.Lines.Add(''); Active:=True;//ativa o servico de restauração, mais ainda nao inicia. MemoBackup.Lines.Add(''); MemoBackup.Lines.Add('/***INICIO***\'); Application.ProcessMessages; MemoBackup.Lines.Add(''); try ServiceStart;//inicia o restore while not Eof do begin {assim como no backup, conforme a restauração vai sendo executada os detalhes da execução podem ser lidos através da função GetNextLine} MemoBackup.Lines.Add(GetNextLine); end; finally end; Active:=False;//desativa o serviço de restore MemoBackup.Lines.Add(''); MemoBackup.Lines.Add('/****FIM****\'); end; MemoBackup.Lines.Add(''); MemoBackup.Lines.Add(''); MemoBackup.Lines.Add('Backup restaurado com sucesso.'); FConexao.Connected:=True;//conecta o sistema na base de dados except on E: Exception do begin MemoBackup.Lines.Add('Ocorreu um erro inesperado. O restore não foi concluído.'); MemoBackup.Lines.Add('Informações da exceção:'); MemoBackup.Lines.Add(' '+E.Message); FConexao.Connected:=True;//conecta o sistema na base de dados end; end; end; end; procedure TBackup_restore.SetBackupFB(const Value: TIBBackupService); begin FBackupFB := Value; end; procedure TBackup_restore.SetMemoBackup(const Value: TMemo); begin FMemoBackup := Value; end; procedure TBackup_restore.SetRestoreFB(const Value: TIBRestoreService); begin FRestoreFB := Value; end; end.
unit SFXBehavior; interface uses SysUtils; type TConflictBehavior = (cbAvoid, cbOverwrite, cbNewer, cbAsk); TCommentPresentation = (cpNone, cpBeforeExtracting, cpAfterExtracting); TExtractionTarget = (etExtractHere, etDesktop, etAsk); TZIPBehavior = record ConflictBehavior: TConflictBehavior; CommentPresentation: TCommentPresentation; ExtractionTarget: TExtractionTarget; end; function ReadBehavior(c: string): TZIPBehavior; function StripBehavior(c: string): string; function BehaviorStrings(bh: TZipBehavior): string; function RelocateBehaviorStringsToEnd(c: string): string; implementation const C_SIGNATURE = 'ViaThinkSoft AutoSFX Archive Configuration'; C_ASFX_CB_OVR = 'AutoSFX Conflict Behavior: Overwrite all'; C_ASFX_CB_NEW = 'AutoSFX Conflict Behavior: Overwrite older'; C_ASFX_CB_ASK = 'AutoSFX Conflict Behavior: Ask'; C_ASFX_CB_AVO = 'AutoSFX Conflict Behavior: Avoid'; C_ASFX_CP_BEF = 'AutoSFX Comment Presentation: Before extracting'; C_ASFX_CP_AFT = 'AutoSFX Comment Presentation: After extracting'; C_ASFX_CP_NON = 'AutoSFX Comment Presentation: None'; C_ASFX_ET_HER = 'AutoSFX Extraction Target: Extract here'; C_ASFX_ET_DES = 'AutoSFX Extraction Target: Extract to Desktop'; C_ASFX_ET_ASK = 'AutoSFX Extraction Target: Choose directory'; EINRUECK = '> '; // Optional to all C_ASFX const CB_DEFAULT = cbAvoid; CP_DEFAULT = cpNone; ET_DEFAULT = etExtractHere; function ReadBehavior(c: string): TZIPBehavior; function Vorkommen(s: string): boolean; begin s := AnsiLowerCase(s); result := AnsiPos(s, c) > 0; end; begin result.ConflictBehavior := CB_DEFAULT; result.CommentPresentation := CP_DEFAULT; result.ExtractionTarget := ET_DEFAULT; c := AnsiLowerCase(c); if Vorkommen(C_ASFX_CB_OVR) then begin result.ConflictBehavior := cbOverwrite; end else if Vorkommen(C_ASFX_CB_NEW) then begin result.ConflictBehavior := cbNewer; end else if Vorkommen(C_ASFX_CB_ASK) then begin result.ConflictBehavior := cbAsk; end else if Vorkommen(C_ASFX_CB_AVO) then begin result.ConflictBehavior := cbAvoid; end; if Vorkommen(C_ASFX_CP_BEF) then begin result.CommentPresentation := cpBeforeExtracting; end else if Vorkommen(C_ASFX_CP_AFT) then begin result.CommentPresentation := cpAfterExtracting; end else if Vorkommen(C_ASFX_CP_NON) then begin result.CommentPresentation := cpNone; end; if Vorkommen(C_ASFX_ET_HER) then begin result.ExtractionTarget := etExtractHere; end else if Vorkommen(C_ASFX_ET_DES) then begin result.ExtractionTarget := etDesktop; end else if Vorkommen(C_ASFX_ET_ASK) then begin result.ExtractionTarget := etAsk; end; end; function StripBehavior(c: string): string; procedure StripIt(s: string; allowEinrueck: boolean); begin if allowEinrueck then begin c := StringReplace(c, EINRUECK + s+#13#10, '', [rfReplaceAll, rfIgnoreCase]); c := StringReplace(c, EINRUECK + s+#13, '', [rfReplaceAll, rfIgnoreCase]); c := StringReplace(c, EINRUECK + s+#10, '', [rfReplaceAll, rfIgnoreCase]); c := StringReplace(c, EINRUECK + s, '', [rfReplaceAll, rfIgnoreCase]); end; c := StringReplace(c, s+#13#10, '', [rfReplaceAll, rfIgnoreCase]); c := StringReplace(c, s+#13, '', [rfReplaceAll, rfIgnoreCase]); c := StringReplace(c, s+#10, '', [rfReplaceAll, rfIgnoreCase]); c := StringReplace(c, s, '', [rfReplaceAll, rfIgnoreCase]); end; begin StripIt(C_SIGNATURE, false); StripIt(C_ASFX_CB_AVO, true); StripIt(C_ASFX_CB_OVR, true); StripIt(C_ASFX_CB_NEW, true); StripIt(C_ASFX_CB_ASK, true); StripIt(C_ASFX_CP_NON, true); StripIt(C_ASFX_CP_BEF, true); StripIt(C_ASFX_CP_AFT, true); StripIt(C_ASFX_ET_HER, true); StripIt(C_ASFX_ET_DES, true); StripIt(C_ASFX_ET_ASK, true); result := c; end; function BehaviorStrings(bh: TZipBehavior): string; begin result := C_SIGNATURE + #13#10 + EINRUECK; case bh.ConflictBehavior of cbAvoid: result := result + C_ASFX_CB_AVO; cbOverwrite: result := result + C_ASFX_CB_OVR; cbNewer: result := result + C_ASFX_CB_NEW; cbAsk: result := result + C_ASFX_CB_ASK; end; result := result + #13#10 + EINRUECK; case bh.CommentPresentation of cpNone: result := result + C_ASFX_CP_NON; cpBeforeExtracting: result := result + C_ASFX_CP_BEF; cpAfterExtracting: result := result + C_ASFX_CP_AFT; end; result := result + #13#10 + EINRUECK; case bh.ExtractionTarget of etExtractHere: result := result + C_ASFX_ET_HER; etDesktop: result := result + C_ASFX_ET_DES; etAsk: result := result + C_ASFX_ET_ASK; end; result := result + #13#10; end; function RelocateBehaviorStringsToEnd(c: string): string; var bh: TZIPBehavior; begin bh := ReadBehavior(c); c := StripBehavior(c); c := TrimRight(c); c := c + #13#10 + #13#10; c := c + BehaviorStrings(bh); result := c; end; end.
{ id:rz109291 PROG:stamps LANG:PASCAL } { 这道题的难点主要有2: 1.题目中没有说出“背包的体积”和“背包价值”,需要自己构造。一个优等的构造方法是:h:=k*max(a[i]); 2.体积循环应该在外面。因为对于每个体积,所有物品都要循环一遍以挑选出最优,和平时的背包模型不一样. 方程:f[v]:=min(f[v],f[v-cost[i]]+1); 我一开始沙茶般的让价值为COST[I],体积为K,占用为1.然后处理起来非常麻烦。 看来,背包模型的难点不只是发现背包,还有背包的构造。 } { USER: r z [rz109291] TASK: stamps LANG: PASCAL Compiling... Compile: OK Executing... Test 1: TEST OK [0.000 secs, 8132 KB] Test 2: TEST OK [0.000 secs, 8132 KB] Test 3: TEST OK [0.000 secs, 8132 KB] Test 4: TEST OK [0.000 secs, 8132 KB] Test 5: TEST OK [0.000 secs, 8132 KB] Test 6: TEST OK [0.000 secs, 8132 KB] Test 7: TEST OK [0.000 secs, 8132 KB] Test 8: TEST OK [0.000 secs, 8132 KB] Test 9: TEST OK [0.000 secs, 8132 KB] Test 10: TEST OK [0.081 secs, 8132 KB] Test 11: TEST OK [0.756 secs, 8132 KB] Test 12: TEST OK [0.243 secs, 8132 KB] Test 13: TEST OK [0.000 secs, 8132 KB] All tests OK. YOUR PROGRAM ('stamps') WORKED FIRST TIME! That's fantastic -- and a rare thing. Please accept these special automated congratulations. } var f:array[0..2010000]of longint; a:array[0..2000]of longint; i,j,n,k,max,v:longint; begin assign(input,'stamps.in');reset(input);assign(output,'stamps.out');rewrite(output); readln(k,n); for i:=1 to n do begin read(a[i]); if a[i]>max then max:=a[i]; end; v:=max*k+1; for i:=1 to v do f[i]:=$3f3f3f3f; f[0]:=0; for j:=1 to v do begin for i:=1 to n do if (j>=a[i])then if(f[j]>f[j-a[i]]+1) then f[j]:=f[j-a[i]]+1; if f[j]>k then begin writeln(j-1); close(input);close(output);halt; end; end; end.
unit D_DocumentProperties; { Автор: Люлин А.В. © } { Модуль: D_DocumentProperties - } { Начат: 21.02.2001 12:02 } { $Id: D_DocumentProperties.pas,v 1.13 2008/04/15 17:36:14 lulin Exp $ } // $Log: D_DocumentProperties.pas,v $ // Revision 1.13 2008/04/15 17:36:14 lulin // - автоматизируем переключение между версиями редактора. // // Revision 1.12 2007/12/05 13:51:28 lulin // - bug fix: не собирался Эверест. // // Revision 1.9.2.3 2007/03/27 07:59:35 dinishev // Bug fix: не собирался Everest в ветке // // Revision 1.9.2.2 2006/12/21 16:23:04 dinishev // Bug fix: Everest в ветке не компилировался // // Revision 1.9.2.1 2006/02/07 15:15:59 lulin // - попытка доточить под ветку (пока неудачно). // // Revision 1.9 2005/05/27 14:44:27 lulin // - базовый контрол переехал в быблиотеку L3. // // Revision 1.8 2004/04/23 16:11:30 law // - new unit: evEdit. // // Revision 1.7 2003/10/13 15:06:41 law // - rename unit: evEdWnd -> evEditorWindow. // // Revision 1.6 2001/05/24 14:29:51 law // - new behavior: подстраиваемся под изменения Вована, относительно PopupWindow. // // Revision 1.5 2001/05/07 08:54:36 law // - new behavior: Tl3Tree ->Il3RootNode. // - cleanup: убраны ненужные ссылки на RXSpin. // // Revision 1.4 2001/02/21 12:34:39 law // - nothing special. // // Revision 1.3 2001/02/21 12:32:20 law // - поправлена кодировка. // // Revision 1.2 2001/02/21 12:31:35 law // - вставлен заголовок модуля. // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, D_Base, l3Types, evInternalInterfaces, evEditorWindow, evEditor, evMemo, evEdit, evMultiSelectEditorWindow, evEditorWithOperations, evCustomEditor, nevTools, OvcBase, vtSpin, afwControl; type TDocumentPropertiesDlg = class(TBaseDlg) lbShortName: TLabel; edShortName: TevEdit; lbName: TLabel; memName: TevMemo; lbComment: TLabel; memComment: TevMemo; lbNumber: TLabel; edExternalNumber: TvtSpinEdit; procedure FormDestroy(Sender: TObject); procedure OKBtnClick(Sender: TObject); private { Private declarations } f_Document : IevDocument; public { Public declarations } function Execute(const aDocument: IevDocument): Long; {-} end;//TDocumentPropertiesDlg implementation {$R *.DFM} function TDocumentPropertiesDlg.Execute(const aDocument: IevDocument): Long; {-} begin if (aDocument = nil) then Result := mrCancel else begin f_Document := aDocument; with f_Document do begin edShortName.Buffer := ShortName; memName.Buffer := Name; memComment.Buffer := Comment; edExternalNumber.Value := ExternalHandle; end;//with f_Document Result := ShowModal; end;//aDocument = nil end; procedure TDocumentPropertiesDlg.FormDestroy(Sender: TObject); begin inherited; f_Document := nil; end; procedure TDocumentPropertiesDlg.OKBtnClick(Sender: TObject); begin inherited; with f_Document do begin if edShortName.Modified then ShortName := Tl3PCharLen(edShortName.Buffer); if memName.Modified then Name := Tl3PCharLen(memName.Buffer); if memComment.Modified then Comment := Tl3PCharLen(memComment.Buffer); if edExternalNumber.Modified then ExternalHandle := edExternalNumber.AsInteger; end;//with f_Document end; end.
unit K540414514; {* [Requestlink:540414514] } // Модуль: "w:\common\components\rtl\Garant\Daily\K540414514.pas" // Стереотип: "TestCase" // Элемент модели: "K540414514" MUID: (53903EFB0324) // Имя типа: "TK540414514" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK540414514 = class(TRTFtoEVDWriterTest) {* [Requestlink:540414514] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK540414514 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *53903EFB0324impl_uses* //#UC END# *53903EFB0324impl_uses* ; function TK540414514.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.10'; end;//TK540414514.GetFolder function TK540414514.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '53903EFB0324'; end;//TK540414514.GetModelElementGUID initialization TestFramework.RegisterTest(TK540414514.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit ZusiTools; interface Uses Windows, SysUtils, Registry, Classes; function GetZusiDir: String; function IsZusiLoaded: Boolean; function SendKeyToZusi(Key: Integer; Pressed, Release: Boolean): Boolean; function ShutdownComputer(Force: Boolean): Boolean; procedure FindFiles (aPath, aFindMask: String; aWithSub: Boolean; aResult: tStrings); function FarbeRGBToInt(R, G, B: Byte): Integer; implementation procedure FindFiles (aPath, aFindMask: String; aWithSub: Boolean; aResult: tStrings); var FindRec: tSearchRec; begin // Wenn die Stringliste nil ist oder aPath oder aFind nicht angegeben ist // dann raus If (aPath = '') or (aFindMask = '') or Not Assigned (aResult) Then Exit; // Wenn am Ende der Pfadangabe noch kein \ steht, dieses hinzufügen If aPath[Length (aPath)] <> '\' Then aPath := aPath + '\'; // Im aktuellen Verzeichnis nach der Datei suchen If FindFirst (aPath + aFindMask, faAnyFile, FindRec) = 0 Then Repeat If (FindRec.Name <> '.') and (FindRec.Name <> '..') Then // ...Ergebnis in die Stringlist einfügen aResult.Add (aPath + FindRec.Name); Until FindNext (FindRec) <> 0; FindClose (FindRec); // Wenn nicht in Unterverzeichnissen gesucht werden soll dann raus If Not aWithSub Then Exit; // In Unterverzeichnissen weiter suchen If FindFirst (aPath + '*.*', faAnyFile, FindRec) = 0 Then Repeat If (FindRec.Name <> '.') and (FindRec.Name <> '..') Then // Feststellen, ob es sich um ein Verzeichnis handelt If Boolean (FindRec.Attr and faDirectory) Then // Funktion erneut aufrufen, um Verzeichnis zu durchsuchen (Rekursion) FindFiles (aPath + FindRec.Name, aFindMask, aWithSub, aResult); Until FindNext (FindRec) <> 0; FindClose (FindRec); end; function GetZusiDir: String; var Reg: TRegistry; S: String; begin Reg := TRegistry.Create; Reg.RootKey := HKEY_CURRENT_USER; Reg.OpenKeyReadOnly('Software\Zusi'); S := Reg.ReadString('ZusiDir'); If S[Length(S)] <> '\' then S := S + '\'; If S = '\' then S := '' else Result := S; Reg.CloseKey; Reg.Free; end; function IsZusiLoaded: Boolean; var Wnd: HWND; begin Wnd := FindWindow('TFormZusiD3DApplication',nil); Result := not (Wnd = 0); end; function SendKeyToZusi(Key: Integer; Pressed, Release: Boolean): Boolean; var Wnd: HWND; begin Wnd := FindWindow('TFormZusiD3DApplication',nil); SetForegroundWindow(Wnd); If Pressed then keybd_event(Key,0,0,(Key shl 8) + 1) else keybd_event(Key,0,KEYEVENTF_KEYUP,(Key shl 8) + 1); If (Pressed and Release) then begin Sleep(10); keybd_event(Key,0,KEYEVENTF_KEYUP,(Key shl 8) + 1); end; Result := not (Wnd = 0); end; function ShutdownComputer(Force: Boolean): Boolean; var TTokenHd: THandle; TTokenPvg: TTokenPrivileges; cbtpPrevious: DWORD; rTTokenPvg: TTokenPrivileges; pcbtpPreviousRequired: DWORD; tpResult: Boolean; RebootParam: LongWord; const SE_SHUTDOWN_NAME = 'SeShutdownPrivilege'; begin if Win32Platform = VER_PLATFORM_WIN32_NT then begin tpResult := OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TTokenHd); if tpResult then begin tpResult := LookupPrivilegeValue(nil, SE_SHUTDOWN_NAME, TTokenPvg.Privileges[0].Luid); TTokenPvg.PrivilegeCount := 1; TTokenPvg.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; cbtpPrevious := SizeOf(rTTokenPvg); pcbtpPreviousRequired := 0; if tpResult then Windows.AdjustTokenPrivileges(TTokenHd, False, TTokenPvg, cbtpPrevious, rTTokenPvg, pcbtpPreviousRequired); end; end; If Force then RebootParam := EWX_POWEROFF or EWX_FORCE else RebootParam := EWX_POWEROFF; Result := ExitWindowsEx(RebootParam, 0); end; function FarbeRGBToInt(R, G, B: Byte): Integer; var FarbeHex: String; begin FarbeHex := IntToHex(B, 2) + IntToHex(G, 2) + IntToHex(R, 2); Result := StrToInt('$' + FarbeHex); end; end.
unit pgDataProviderFactory; // Модуль: "w:\common\components\rtl\Garant\PG\pgDataProviderFactory.pas" // Стереотип: "SimpleClass" // Элемент модели: "TpgDataProviderFactory" MUID: (55D6E2FB025D) {$Include w:\common\components\rtl\Garant\PG\pgDefine.inc} interface {$If Defined(UsePostgres)} uses l3IntfUses , daDataProviderFactory , daDataProviderParams , daInterfaces , ddAppConfig ; type TpgDataProviderFactory = class(TdaDataProviderFactory) public class function Key: AnsiString; override; function MakeFromConfig: TdaDataProviderParams; override; procedure SaveToConfig(aParams: TdaDataProviderParams); override; function ParamType: TdaDataProviderParamsClass; override; procedure FillOutConfig(aConfig: TddAppConfiguration; aEtalon: TdaDataProviderParams; out aParams: TdaDataProviderParams); override; procedure FillInConfig(aConfig: TddAppConfiguration; aParams: TdaDataProviderParams; ForInfoOnly: Boolean = False); override; procedure BuildConfig(aConfig: TddAppConfiguration; const aProviderKey: AnsiString = ''; ForInfoOnly: Boolean = False); override; procedure LoadDBVersion(aParams: TdaDataProviderParams); override; function DoMakeProvider(aParams: TdaDataProviderParams; ForCheckLogin: Boolean; AllowClearLocks: Boolean; SetGlobalProvider: Boolean = True): IdaDataProvider; override; procedure LoginCheckSucceed(aParams: TdaDataProviderParams); override; procedure CorrectByClient(aParams: TdaDataProviderParams; CorrectTempPath: Boolean); override; function IsParamsValid(aParams: TdaDataProviderParams; Quiet: Boolean = False): Boolean; override; end;//TpgDataProviderFactory {$IfEnd} // Defined(UsePostgres) implementation {$If Defined(UsePostgres)} uses l3ImplUses , pgDataProviderParams , pgDataProvider , pgInterfaces , ddAppConfigTypes , l3Base , SysUtils , l3IniFile , l3FileUtils //#UC START# *55D6E2FB025Dimpl_uses* //#UC END# *55D6E2FB025Dimpl_uses* ; class function TpgDataProviderFactory.Key: AnsiString; //#UC START# *54F8635B023E_55D6E2FB025D_var* //#UC END# *54F8635B023E_55D6E2FB025D_var* begin //#UC START# *54F8635B023E_55D6E2FB025D_impl* Result := 'Postgress'; //#UC END# *54F8635B023E_55D6E2FB025D_impl* end;//TpgDataProviderFactory.Key function TpgDataProviderFactory.MakeFromConfig: TdaDataProviderParams; //#UC START# *54FEB57302B0_55D6E2FB025D_var* var l_Storage: IpgParamsStorage; //#UC END# *54FEB57302B0_55D6E2FB025D_var* begin //#UC START# *54FEB57302B0_55D6E2FB025D_impl* Result := TpgDataProviderParams.Create; LoadCommonParams(Result); l_Storage := ParamsStorage as IpgParamsStorage; try TpgDataProviderParams(Result).DataServerHostName := l_Storage.DataServerHostName; // Invalid TpgDataProviderParams(Result).DataServerPort := l_Storage.DataServerPort; // Инвалид finally l_Storage := nil; end; //#UC END# *54FEB57302B0_55D6E2FB025D_impl* end;//TpgDataProviderFactory.MakeFromConfig procedure TpgDataProviderFactory.SaveToConfig(aParams: TdaDataProviderParams); //#UC START# *550AAD0101F9_55D6E2FB025D_var* var l_Storage: IpgParamsStorage; //#UC END# *550AAD0101F9_55D6E2FB025D_var* begin //#UC START# *550AAD0101F9_55D6E2FB025D_impl* Assert(aParams is TpgDataProviderParams); SaveCommonParams(aParams); l_Storage := ParamsStorage as IpgParamsStorage; try l_Storage.DataServerHostName := TpgDataProviderParams(aParams).DataServerHostName; l_Storage.DataServerPort := TpgDataProviderParams(aParams).DataServerPort; finally l_Storage := nil; end; //#UC END# *550AAD0101F9_55D6E2FB025D_impl* end;//TpgDataProviderFactory.SaveToConfig function TpgDataProviderFactory.ParamType: TdaDataProviderParamsClass; //#UC START# *550FD49301BF_55D6E2FB025D_var* //#UC END# *550FD49301BF_55D6E2FB025D_var* begin //#UC START# *550FD49301BF_55D6E2FB025D_impl* Result := TpgDataProviderParams; //#UC END# *550FD49301BF_55D6E2FB025D_impl* end;//TpgDataProviderFactory.ParamType procedure TpgDataProviderFactory.FillOutConfig(aConfig: TddAppConfiguration; aEtalon: TdaDataProviderParams; out aParams: TdaDataProviderParams); //#UC START# *5512BAB20128_55D6E2FB025D_var* //#UC END# *5512BAB20128_55D6E2FB025D_var* begin //#UC START# *5512BAB20128_55D6E2FB025D_impl* if ParamsStorage.OuterConfigEdit then aParams := MakeFromConfig else begin aParams := TpgDataProviderParams.Create; aParams.AssignParams(aEtalon); with aConfig do begin aParams.Login := AsString['Login']; aParams.Password := AsString['Password']; TpgDataProviderParams(aParams).DataServerHostName := AsString['DataServerHostName']; TpgDataProviderParams(aParams).DataServerPort := AsInteger['DataServerPort']; end; end; //#UC END# *5512BAB20128_55D6E2FB025D_impl* end;//TpgDataProviderFactory.FillOutConfig procedure TpgDataProviderFactory.FillInConfig(aConfig: TddAppConfiguration; aParams: TdaDataProviderParams; ForInfoOnly: Boolean = False); //#UC START# *5512BB030346_55D6E2FB025D_var* var l_Params: TpgDataProviderParams; //#UC END# *5512BB030346_55D6E2FB025D_var* begin //#UC START# *5512BB030346_55D6E2FB025D_impl* if ParamsStorage.OuterConfigEdit then Exit; Assert(aParams is TpgDataProviderParams); l_Params := aParams as TpgDataProviderParams; with aConfig do begin if ForInfoOnly then begin AsString['DataConnectParams'] := Format('%s:%d', [l_Params.DataServerHostName, l_Params.DataServerPort]); end else begin AsString['DataServerHostName'] := l_Params.DataServerHostName; AsInteger['DataServerPort'] := l_Params.DataServerPort; end; end; //#UC END# *5512BB030346_55D6E2FB025D_impl* end;//TpgDataProviderFactory.FillInConfig procedure TpgDataProviderFactory.BuildConfig(aConfig: TddAppConfiguration; const aProviderKey: AnsiString = ''; ForInfoOnly: Boolean = False); //#UC START# *5512BB1F023F_55D6E2FB025D_var* var l_Item: TddBaseConfigItem; //#UC END# *5512BB1F023F_55D6E2FB025D_var* begin //#UC START# *5512BB1F023F_55D6E2FB025D_impl* if ParamsStorage.OuterConfigEdit then ParamsStorage.BuildConfig(aConfig, Key) else begin if ForInfoOnly then begin l_Item := aConfig.AddStringItem('DataConnectParams', 'Подключено'); aConfig.Hint:= 'Параметры подключения к Серверу БД'; l_Item.ReadOnly := True; end else begin aConfig.AddStringItem('DataServerHostName', 'Адрес сервера БД', ''); aConfig.AddIntegerItem(l3CStr('DataServerPort'), l3CStr('Порт сервера БД'), c_DefaultPostgresPort); end; end; //#UC END# *5512BB1F023F_55D6E2FB025D_impl* end;//TpgDataProviderFactory.BuildConfig procedure TpgDataProviderFactory.LoadDBVersion(aParams: TdaDataProviderParams); //#UC START# *551904FC039A_55D6E2FB025D_var* var l_BaseIni: TCfgList; //#UC END# *551904FC039A_55D6E2FB025D_var* begin //#UC START# *551904FC039A_55D6E2FB025D_impl* l_BaseIni := aParams.MakeBaseIni; try l_BaseIni.Section:= 'Tables'; aParams.DocBaseVersion := l_BaseIni.ReadParamIntDef('Version', c_BadVersion); aParams.AdminBaseVersion := aParams.DocBaseVersion; finally FreeAndNil(l_BaseIni); end; //#UC END# *551904FC039A_55D6E2FB025D_impl* end;//TpgDataProviderFactory.LoadDBVersion function TpgDataProviderFactory.DoMakeProvider(aParams: TdaDataProviderParams; ForCheckLogin: Boolean; AllowClearLocks: Boolean; SetGlobalProvider: Boolean = True): IdaDataProvider; //#UC START# *551D06D402AF_55D6E2FB025D_var* //#UC END# *551D06D402AF_55D6E2FB025D_var* begin //#UC START# *551D06D402AF_55D6E2FB025D_impl* Assert(aParams is TpgDataProviderParams); Result := TpgDataProvider.Make(TpgDataProviderParams(aParams), ForCheckLogin, AllowClearLocks, SetGlobalProvider); //#UC END# *551D06D402AF_55D6E2FB025D_impl* end;//TpgDataProviderFactory.DoMakeProvider procedure TpgDataProviderFactory.LoginCheckSucceed(aParams: TdaDataProviderParams); //#UC START# *55D706D201C3_55D6E2FB025D_var* //#UC END# *55D706D201C3_55D6E2FB025D_var* begin //#UC START# *55D706D201C3_55D6E2FB025D_impl* // Do nothing //#UC END# *55D706D201C3_55D6E2FB025D_impl* end;//TpgDataProviderFactory.LoginCheckSucceed procedure TpgDataProviderFactory.CorrectByClient(aParams: TdaDataProviderParams; CorrectTempPath: Boolean); //#UC START# *55110FBB00E5_55D6E2FB025D_var* var l_Storage: IpgParamsStorage; //#UC END# *55110FBB00E5_55D6E2FB025D_var* begin //#UC START# *55110FBB00E5_55D6E2FB025D_impl* Exit; l_Storage := ParamsStorage as IpgParamsStorage; try TpgDataProviderParams(aParams).DataServerHostName := l_Storage.DataServerHostName; TpgDataProviderParams(aParams).DataServerPort := l_Storage.DataServerPort; finally l_Storage := nil; end; //#UC END# *55110FBB00E5_55D6E2FB025D_impl* end;//TpgDataProviderFactory.CorrectByClient function TpgDataProviderFactory.IsParamsValid(aParams: TdaDataProviderParams; Quiet: Boolean = False): Boolean; //#UC START# *551166B40046_55D6E2FB025D_var* var l_Result: Boolean; l_Storage: IpgParamsStorage; //#UC END# *551166B40046_55D6E2FB025D_var* begin //#UC START# *551166B40046_55D6E2FB025D_impl* l_Result := inherited IsParamsValid(aParams); Result := False; if TpgDataProviderParams(aParams).DataServerHostName = '' then begin if not Quiet then l3System.Msg2Log('Не задан сервер БД!'); Exit; end; Result := l_Result; //#UC END# *551166B40046_55D6E2FB025D_impl* end;//TpgDataProviderFactory.IsParamsValid {$IfEnd} // Defined(UsePostgres) end.
unit Base.Color; interface Const BRANCO = $00F9F9F9; // branco AZUL = $00A00000; // azul AZULC = $00FFAC59; // Azul Claro AZULE = $00400000; // azul escuro VERMELHO = $002020FF; // vermelho VERMELHOC = $008080FF; // vermelho claro VERDE = $00408000; // verde VERDEC = $0080FF00; // verde claro PRETO = $00171717; // preto CINZA = $00C5C5C5; // cinza LARANJA = $000080FF; // laranja AMARELOC = $00BFFFFF; //Amarelo Type COR = Record BRANCO: word; // branco AZUL: word; // azul AZULC: word; // Azul Claro AZULE: word; // azul escuro VERMELHO: word; // vermelho VERMELHOC: word; // vermelho claro VERDE: word; // verde VERDEC: word; // verde claro PRETO: word; // preto CINZA: word; // cinza LARANJA: word; // laranja End; implementation end.
unit mrdo_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,sn_76496,gfx_engine,rom_engine, pal_engine,sound_engine; function iniciar_mrdo:boolean; implementation const mrdo_rom:array[0..3] of tipo_roms=( (n:'a4-01.bin';l:$2000;p:0;crc:$03dcfba2),(n:'c4-02.bin';l:$2000;p:$2000;crc:$0ecdd39c), (n:'e4-03.bin';l:$2000;p:$4000;crc:$358f5dc2),(n:'f4-04.bin';l:$2000;p:$6000;crc:$f4190cfc)); mrdo_pal:array[0..2] of tipo_roms=( (n:'u02--2.bin';l:$20;p:0;crc:$238a65d7),(n:'t02--3.bin';l:$20;p:$20;crc:$ae263dc0), (n:'f10--1.bin';l:$20;p:$40;crc:$16ee4ca2)); mrdo_char1:array[0..1] of tipo_roms=( (n:'s8-09.bin';l:$1000;p:0;crc:$aa80c5b6),(n:'u8-10.bin';l:$1000;p:$1000;crc:$d20ec85b)); mrdo_char2:array[0..1] of tipo_roms=( (n:'r8-08.bin';l:$1000;p:0;crc:$dbdc9ffa),(n:'n8-07.bin';l:$1000;p:$1000;crc:$4b9973db)); mrdo_sprites:array[0..1] of tipo_roms=( (n:'h5-05.bin';l:$1000;p:0;crc:$e1218cc5),(n:'k5-06.bin';l:$1000;p:$1000;crc:$b1f68b04)); //Dip mrdo_dip_a:array [0..6] of def_dip=( (mask:$3;name:'Difficulty';number:4;dip:((dip_val:$3;dip_name:'Easy'),(dip_val:$2;dip_name:'Medium'),(dip_val:$1;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Rack Test (Cheat)';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Special';number:2;dip:((dip_val:$8;dip_name:'Easy'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Extra';number:2;dip:((dip_val:$10;dip_name:'Easy'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$20;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'2'),(dip_val:$c0;dip_name:'3'),(dip_val:$80;dip_name:'4'),(dip_val:$40;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); mrdo_dip_b:array [0..2] of def_dip=( (mask:$f0;name:'Coin A';number:11;dip:((dip_val:$60;dip_name:'4C 1C'),(dip_val:$80;dip_name:'3C 1C'),(dip_val:$a0;dip_name:'2C 1C'),(dip_val:$70;dip_name:'3C 2C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$90;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),())), (mask:$0f;name:'Coin B';number:11;dip:((dip_val:$06;dip_name:'4C 1C'),(dip_val:$08;dip_name:'3C 1C'),(dip_val:$0a;dip_name:'2C 1C'),(dip_val:$07;dip_name:'3C 2C'),(dip_val:$0f;dip_name:'1C 1C'),(dip_val:$09;dip_name:'2C 3C'),(dip_val:$0e;dip_name:'1C 2C'),(dip_val:$0d;dip_name:'1C 3C'),(dip_val:$0c;dip_name:'1C 4C'),(dip_val:$0b;dip_name:'1C 5C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),())),()); var scroll_x,scroll_y,prot:byte; procedure update_video_mrdo; var f,color,nchar:word; x,y,atrib:byte; begin for f:=$0 to $3ff do begin x:=f div 32; y:=31-(f mod 32); if gfx[1].buffer[f] then begin atrib:=memoria[$8000+f]; nchar:=memoria[$8400+f]+(atrib and $80) shl 1; color:=(atrib and $3f) shl 2; if (atrib and $40)<>0 then begin put_gfx(x*8,y*8,nchar,color,1,1); put_gfx_block_trans(x*8,y*8,4,8,8); end else begin put_gfx_block(x*8,y*8,1,8,8,0); put_gfx_trans(x*8,y*8,nchar,color,4,1); end; gfx[1].buffer[f]:=false; end; atrib:=memoria[$8800+f]; if ((gfx[0].buffer[f]) or ((atrib and $40)<>0)) then begin nchar:=memoria[$8c00+f]+(atrib and $80) shl 1; color:=(atrib and $3f) shl 2; if (atrib and $40)<>0 then begin put_gfx(x*8,y*8,nchar,color,2,0); put_gfx_block_trans(x*8,y*8,5,8,8); end else begin put_gfx_block_trans(x*8,y*8,2,8,8); put_gfx_trans(x*8,y*8,nchar,color,5,0); end; gfx[0].buffer[f]:=false; end; end; //Es MUY IMPORTANTE este orden para poder pintar correctamente la pantalla!!! scroll_x_y(1,3,scroll_x,scroll_y); actualiza_trozo(0,0,256,256,2,0,0,256,256,3); scroll_x_y(4,3,scroll_x,scroll_y); actualiza_trozo(0,0,256,256,5,0,0,256,256,3); for f:=$3f downto 0 do begin x:=memoria[(f*4)+$9001]; if (x<>0) then begin nchar:=memoria[(f*4)+$9000] and $7f; atrib:=memoria[(f*4)+$9002]; color:=(atrib and $0f) shl 2; y:=240-memoria[(f*4)+$9003]; put_gfx_sprite(nchar,color,(atrib and $20)<>0,(atrib and $10)<>0,2); actualiza_gfx_sprite(256-x,y,3,2); end; end; actualiza_trozo_final(32,8,192,240,3); end; procedure eventos_mrdo; begin if event.arcade then begin //p1 if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); //p2 if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.coin[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.coin[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); end; end; procedure mrdo_principal; var frame_m:single; f:word; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 261 do begin z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; if f=223 then begin z80_0.change_irq(HOLD_LINE); update_video_mrdo; end; end; eventos_mrdo; video_sync; end; end; function mrdo_getbyte(direccion:word):byte; var z80_0_reg:npreg_z80; begin case direccion of 0..$8fff,$e000..$efff:mrdo_getbyte:=memoria[direccion]; $9803:begin z80_0_reg:=z80_0.get_internal_r; mrdo_getbyte:=memoria[z80_0_reg.hl.w]; end; $a000:mrdo_getbyte:=marcade.in0; $a001:mrdo_getbyte:=marcade.in1; $a002:mrdo_getbyte:=marcade.dswa; $a003:mrdo_getbyte:=marcade.dswb; end; end; procedure mrdo_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$87ff:if memoria[direccion]<>valor then begin gfx[1].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $8800..$8fff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $9000..$90ff,$e000..$efff:memoria[direccion]:=valor; $9800:main_screen.flip_main_screen:=(valor and 1)<>0; $9801:sn_76496_0.Write(valor); $9802:sn_76496_1.Write(valor); $f000..$f7ff:scroll_y:=valor; $f800..$ffff:scroll_x:=valor; end; end; procedure mrdo_update_sound; begin sn_76496_0.Update; sn_76496_1.Update; end; //Main procedure reset_mrdo; begin z80_0.reset; sn_76496_0.reset; sn_76496_1.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; scroll_x:=0; scroll_y:=0; prot:=$ff; end; function iniciar_mrdo:boolean; var memoria_temp:array[0..$1fff] of byte; const pc_x:array[0..7] of dword=(7, 6, 5, 4, 3, 2, 1, 0); pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); ps_x:array[0..15] of dword=(3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0, 16+3, 16+2, 16+1, 16+0, 24+3, 24+2, 24+1, 24+0); ps_y:array[0..15] of dword=(0*16, 2*16, 4*16, 6*16, 8*16, 10*16, 12*16, 14*16, 16*16, 18*16, 20*16, 22*16, 24*16, 26*16, 28*16, 30*16); procedure calc_paleta; var weight,pot:array[0..15] of single; par:single; f,a1,a2,bits0,bits1:byte; colores:tpaleta; const R1=150; R2=120; R3=100; R4=75; PULL=220; POTADJUST=0.7; // diode voltage drop begin for f:=$f downto 0 do begin par:=0; if (f and 1)<>0 then par:=par+(1.0/R1); if (f and 2)<>0 then par:=par+(1.0/R2); if (f and 4)<>0 then par:=par+(1.0/R3); if (f and 8)<>0 then par:=par+(1.0/R4); if (par<>0) then begin par:=1/par; pot[f]:=PULL/(PULL+par)-POTADJUST; end else pot[f]:=0; weight[f]:=$ff*pot[f]/pot[$f]; if weight[f]<0 then weight[f]:=0; end; for f:=0 to $ff do begin a1:=((f shr 3) and $1c)+(f and $03)+$20; a2:=((f shr 0) and $1c)+(f and $03); bits0:=(memoria_temp[a1] shr 0) and $03; bits1:=(memoria_temp[a2] shr 0) and $03; colores[f].r:=trunc(weight[bits0+(bits1 shl 2)]); bits0:=(memoria_temp[a1] shr 2) and $03; bits1:=(memoria_temp[a2] shr 2) and $03; colores[f].g:=trunc(weight[bits0 + (bits1 shl 2)]); bits0:=(memoria_temp[a1] shr 4) and $03; bits1:=(memoria_temp[a2] shr 4) and $03; colores[f].b:=trunc(weight[bits0+(bits1 shl 2)]); end; set_pal(colores,$100); //CLUT sprites for f:=0 to $3f do begin bits0:=memoria_temp[($40+(f and $1f))]; if (f and $20)<>0 then bits0:=bits0 shr 4 // high 4 bits are for sprite color n + 8 else bits0:=bits0 and $0f; // low 4 bits are for sprite color n gfx[2].colores[f]:=bits0+((bits0 and $0c) shl 3); end; end; begin llamadas_maquina.bucle_general:=mrdo_principal; llamadas_maquina.reset:=reset_mrdo; llamadas_maquina.fps_max:=59.94323742; iniciar_mrdo:=false; iniciar_audio(false); screen_init(1,256,256,true); screen_mod_scroll(1,256,256,255,256,256,255); screen_init(2,256,256,true); screen_init(3,256,256,false,true); screen_init(4,256,256,true); screen_mod_scroll(4,256,256,255,256,256,255); screen_init(5,256,256,true); iniciar_video(192,240); //Main CPU z80_0:=cpu_z80.create(4100000,262); z80_0.change_ram_calls(mrdo_getbyte,mrdo_putbyte); z80_0.init_sound(mrdo_update_sound); //Sound Chips sn_76496_0:=sn76496_chip.Create(4100000); sn_76496_1:=sn76496_chip.Create(4100000); //cargar roms if not(roms_load(@memoria,mrdo_rom)) then exit; //convertir chars fg if not(roms_load(@memoria_temp,mrdo_char1)) then exit; init_gfx(0,8,8,512); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,8*8,0,512*8*8); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,true); //convertir chars bg if not(roms_load(@memoria_temp,mrdo_char2)) then exit; init_gfx(1,8,8,512); gfx[1].trans[0]:=true; gfx_set_desc_data(2,0,8*8,0,512*8*8); convert_gfx(1,0,@memoria_temp,@pc_x,@pc_y,false,true); //convertir sprites if not(roms_load(@memoria_temp,mrdo_sprites)) then exit; init_gfx(2,16,16,128); gfx[2].trans[0]:=true; gfx_set_desc_data(2,0,64*8,4,0); convert_gfx(2,0,@memoria_temp,@ps_x,@ps_y,false,true); //poner la paleta if not(roms_load(@memoria_temp,mrdo_pal)) then exit; calc_paleta; //dip marcade.dswa:=$df; marcade.dswb:=$ff; marcade.dswa_val:=@mrdo_dip_a; marcade.dswb_val:=@mrdo_dip_b; //final reset_mrdo; iniciar_mrdo:=true; end; end.
unit TestTrackingSamplesUnit; interface uses TestFramework, Classes, SysUtils, BaseTestOnlineExamplesUnit; type TRec = record RouteId: String; MemberId: string; end; TRecs = array of TRec; TTestTrackingSamples = class(TTestOnlineExamples) private { procedure InitParameters(index: Integer; out RouteId: String; out MemberId: String); procedure SaveParameters(); procedure LoadParameters();} published procedure SetGPS; procedure TrackDeviceLastLocationHistory; procedure GetLocationHistory; procedure GetLocationHistoryFromTimeRange; procedure GetAssetTrackingData; end; implementation uses DateUtils, NullableBasicTypesUnit, GPSParametersUnit, EnumsUnit, DataObjectUnit, TrackingHistoryResponseUnit, TrackingDataUnit; {var FRecs: TRecs;} procedure TTestTrackingSamples.GetAssetTrackingData; var ErrorString: String; TrackingData: TTrackingData; TrackingNumber: String; begin TrackingNumber := 'Q7G9P1L9'; TrackingData := FRoute4MeManager.Tracking.GetAssetTrackingData( TrackingNumber, ErrorString); try CheckNotNull(TrackingData); CheckEquals(EmptyStr, ErrorString); finally FreeAndNil(TrackingData); end; TrackingNumber := 'qwe123'; TrackingData := FRoute4MeManager.Tracking.GetAssetTrackingData( TrackingNumber, ErrorString); try CheckNull(TrackingData); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(TrackingData); end; end; procedure TTestTrackingSamples.GetLocationHistory; const LastPositionOnly = False; var ErrorString: String; Response: TTrackingHistoryResponse; RouteId: String; Period: TPeriod; begin RouteId := '814FB49CEA8188D134E9D4D4B8B0DAF7'; Period := pAllTime; Response := FRoute4MeManager.Tracking.GetLocationHistory( RouteId, Period, LastPositionOnly, ErrorString); try CheckNotNull(Response); CheckTrue(Length(Response.TrackingHistories) > 0); CheckEquals(EmptyStr, ErrorString); finally FreeAndNil(Response); end; RouteId := 'qwe'; Response := FRoute4MeManager.Tracking.GetLocationHistory( RouteId, Period, LastPositionOnly, ErrorString); try CheckNull(Response); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(Response); end; end; procedure TTestTrackingSamples.GetLocationHistoryFromTimeRange; const LastPositionOnly = False; var ErrorString: String; Response: TTrackingHistoryResponse; RouteId: String; StartDate, EndDate: TDateTime; begin RouteId := '814FB49CEA8188D134E9D4D4B8B0DAF7'; StartDate := EncodeDateTime(2016, 10, 20, 0, 0, 0, 0); EndDate := EncodeDateTime(2016, 10, 26, 23, 59, 59, 0); Response := FRoute4MeManager.Tracking.GetLocationHistory( RouteId, StartDate, EndDate, LastPositionOnly, ErrorString); try CheckNotNull(Response); CheckTrue(Length(Response.TrackingHistories) > 0); CheckEquals(EmptyStr, ErrorString); finally FreeAndNil(Response); end; RouteId := 'qwe'; Response := FRoute4MeManager.Tracking.GetLocationHistory( RouteId, StartDate, EndDate, LastPositionOnly, ErrorString); try CheckNull(Response); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(Response); end; StartDate := IncYear(Now); EndDate := IncDay(StartDate); Response := FRoute4MeManager.Tracking.GetLocationHistory( RouteId, StartDate, EndDate, LastPositionOnly, ErrorString); try CheckNull(Response); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(Response); end; end; {procedure TTestTrackingSamples.InitParameters(index: Integer; out RouteId: String; out MemberId: String); begin RouteId := FRecs[index].RouteId; MemberId := FRecs[index].MemberId; end; procedure TTestTrackingSamples.LoadParameters; var st: TStringList; strings: TStringList; i: Integer; begin if not FileExists('RouteIds.txt') then Exit; st := TStringList.Create; try st.LoadFromFile('RouteIds.txt'); SetLength(FRecs, st.Count); for i := 0 to st.Count - 1 do begin strings := TStringList.Create; try ExtractStrings([';'], [' '], PWideChar(st[i]), strings); FRecs[i].RouteId := strings[0]; FRecs[i].MemberId := strings[1]; finally FreeAndNil(strings); end; end; finally FreeAndNil(st); end; end; procedure TTestTrackingSamples.SaveParameters; const MaxPageCount = 5; var ErrorString: String; Routes: TDataObjectRouteList; st: TStringList; offset: Integer; i: Integer; begin st := TStringList.Create; begin Routes := FRoute4MeManager.Route.GetList(5000, 0, ErrorString); try CheckNotNull(Routes); CheckEquals(EmptyStr, ErrorString); CheckTrue(Routes.Count > 0); for i := 0 to Routes.Count - 1 do st.Add(Routes[i].RouteId + ';' + Routes[i].MemberId); finally FreeAndNil(Routes); end; end; st.SaveToFile('RouteIds.txt'); end; } procedure TTestTrackingSamples.SetGPS; var ErrorString: String; Parameters: TGPSParameters; RouteId: String; begin RouteId := '15D9B7219B4691E0CAB8937FAFF11E58'; Parameters := TGPSParameters.Create; try Parameters.Format := TFormatDescription[TFormatEnum.Xml]; Parameters.RouteId := RouteId; Parameters.Latitude := 55.6884868; Parameters.Longitude := 12.5366426; Parameters.Course := 70; Parameters.Speed := 60; Parameters.DeviceType := TDeviceTypeDescription[TDeviceType.AndroidPhone]; Parameters.MemberId := 1; Parameters.DeviceGuid := 'HK5454H0K454564WWER445'; FRoute4MeManager.Tracking.SetGPS(Parameters, ErrorString); CheckEquals(EmptyStr, ErrorString); Parameters.MemberId := -1; FRoute4MeManager.Tracking.SetGPS(Parameters, ErrorString); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(Parameters); end; end; procedure TTestTrackingSamples.TrackDeviceLastLocationHistory; var ErrorString: String; Route: TDataObjectRoute; RouteId: String; begin RouteId := '15D9B7219B4691E0CAB8937FAFF11E58'; Route := FRoute4MeManager.Tracking.GetLastLocation(RouteId, ErrorString); try CheckNotNull(Route); CheckEquals(EmptyStr, ErrorString); finally FreeAndNil(Route); end; RouteId := 'qwe'; Route := FRoute4MeManager.Tracking.GetLastLocation(RouteId, ErrorString); try CheckNull(Route); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(Route); end; end; initialization RegisterTest('Examples\Online\Tracking\', TTestTrackingSamples.Suite); // SetLength(FRecs, 0); end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Math, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, DPF.iOS.BaseControl, DPF.iOS.Common, Macapi.ObjectiveC, iOSapi.CoreGraphics, iOSApi.UIKit, iOSApi.QuartzCore, iOSapi.Foundation, iOSapi.CoreText, iOSapi.CocoaTypes, Macapi.CoreFoundation, DPF.iOS.UIView; type TFDrawingNative = class( TForm ) DPFUIView1: TDPFUIView; procedure DPFUIView1DrawRect( Sender: TObject; Rect: DPFNSRect ); private { Private declarations } procedure DrawGradient; protected procedure PaintRects( const UpdateRects: array of TRectF ); override; public { Public declarations } end; var FDrawingNative: TFDrawingNative; implementation {$R *.fmx} procedure TFDrawingNative.DrawGradient; var imageBounds: CGRect; alignStroke: CGFloat; resolution : CGFloat; path : CGMutablePathRef; drawRect : CGRect; gradient : CGGradientRef; colors : NSMutableArray; color : UIColor; space : CGColorSpaceRef; context : CGContextRef; point, point2: CGPoint; locations : array [0 .. 4] of CGFloat; begin imageBounds := CGRectMake( 0.0, 0.0, DPFUIView1.width, DPFUIView1.height ); space := CGColorSpaceCreateDeviceRGB( ); context := UIGraphicsGetCurrentContext( ); resolution := 0.5 * ( DPFUIView1.width / imageBounds.size.width + DPFUIView1.height / imageBounds.size.height ); alignStroke := 0.0; path := CGPathCreateMutable( ); drawRect := CGRectMake( 0.0, 0.0, DPFUIView1.width, DPFUIView1.height ); drawRect.origin.x := ( round( resolution * drawRect.origin.x + alignStroke ) - alignStroke ) / resolution; drawRect.origin.y := ( round( resolution * drawRect.origin.y + alignStroke ) - alignStroke ) / resolution; drawRect.size.width := round( resolution * drawRect.size.width ) / resolution; drawRect.size.height := round( resolution * drawRect.size.height ) / resolution; CGPathAddRect( path, nil, drawRect ); colors := TNSMutableArray.Wrap( TNSMutableArray.OCClass.arrayWithCapacity( 5 ) ); color := TUIColor.Wrap( TUIColor.OCClass.colorWithRed( 0.351, 0.444, 0.573, 1.0 ) ); colors.addObject( color.CGColor ); locations[0] := 0.0; color := TUIColor.Wrap( TUIColor.OCClass.colorWithRed( 0.62, 0.676, 0.754, 1.0 ) ); colors.addObject( color.CGColor ); locations[1] := 1.0; color := TUIColor.Wrap( TUIColor.OCClass.colorWithRed( 0.563, 0.627, 0.713, 1.0 ) ); colors.addObject( color.CGColor ); locations[2] := 0.743; color := TUIColor.Wrap( TUIColor.OCClass.colorWithRed( 0.479, 0.553, 0.66, 1.0 ) ); colors.addObject( color.CGColor ); locations[3] := 0.498; color := TUIColor.Wrap( TUIColor.OCClass.colorWithRed( 0.43, 0.51, 0.63, 1.0 ) ); colors.addObject( color.CGColor ); locations[4] := 0.465; gradient := CGGradientCreateWithColors( space, ( colors as ILocalObject ).GetObjectID, @locations[0] ); CGContextAddPath( context, path ); CGContextSaveGState( context ); CGContextEOClip( context ); point := CGPointMake( 100.0, DPFUIView1.height ); point2 := CGPointMake( 100.0, 0.0 ); CGContextDrawLinearGradient( context, gradient, point, point2, ( kCGGradientDrawsBeforeStartLocation or kCGGradientDrawsAfterEndLocation ) ); CGContextRestoreGState( context ); CGGradientRelease( gradient ); CGPathRelease( path ); CGColorSpaceRelease( space ); end; procedure TFDrawingNative.DPFUIView1DrawRect( Sender: TObject; Rect: DPFNSRect ); const components: array [0 .. 3] of CGFloat = ( 0.0, 0.0, 1.0, 1.0 ); locs: array [0 .. 2] of CGFloat = ( 0.0, 0.5, 1.0 ); colors: array [0 .. 11] of CGFloat = ( 0.3, 0.3, 0.3, 0.8, // starting color, transparent gray 0.0, 0.0, 0.0, 1.0, // intermediate color, black 0.3, 0.3, 0.3, 0.8// ending color, transparent gray ); var currentContext, context: CGContextRef; colorspace : CGColorSpaceRef; color : CGColorRef; rectangle : CGRect; colStep : CGFloat; startColor : UIColor; startColorComponents : ^CGFloat; con : CGContextRef; sp : CGColorSpaceRef; grad: CGGradientRef; begin DrawGradient; context := UIGraphicsGetCurrentContext( ); // -------------------------------------------------------------- // Draw Line CGContextSetLineWidth( context, 5.0 ); colorspace := CGColorSpaceCreateDeviceRGB( ); color := CGColorCreate( colorspace, @components[0] ); CGContextSetStrokeColorWithColor( context, color ); CGContextMoveToPoint( context, width / 2, 0 ); CGContextAddLineToPoint( context, width / 2, Height ); CGContextStrokePath( context ); // -------------------------------------------------------------- // Draw Arc CGContextSetLineWidth( context, 3.0 ); CGContextSetStrokeColorWithColor( context, TUIColor.Wrap( TUIColor.OCClass.magentaColor ).CGColor ); rectangle := CGRectMake( 60, 170, 200, 80 ); CGContextAddEllipseInRect( context, rectangle ); CGContextStrokePath( context ); // -------------------------------------------------------------- // Drawing a Cubic Bezier Curve CGContextSetLineWidth( context, 2.0 ); CGContextSetStrokeColorWithColor( context, TUIColor.Wrap( TUIColor.OCClass.redColor ).CGColor ); CGContextMoveToPoint( context, 10, 10 ); CGContextAddCurveToPoint( context, 0, 50, 300, 250, 300, 400 ); CGContextStrokePath( context ); // -------------------------------------------------------------- // Drawing a Quadratic Bezier Curve CGContextSetLineWidth( context, 2.0 ); CGContextSetStrokeColorWithColor( context, TUIColor.Wrap( TUIColor.OCClass.blueColor ).CGColor ); CGContextMoveToPoint( context, 10, 200 ); CGContextAddQuadCurveToPoint( context, 150, 10, 300, 200 ); CGContextStrokePath( context ); // -------------------------------------------------------------- // Drawing Gradiant con := UIGraphicsGetCurrentContext( ); CGContextSaveGState( con ); // punch triangular hole in context clipping region CGContextMoveToPoint( con, 90, 100 ); CGContextAddLineToPoint( con, 100, 90 ); CGContextAddLineToPoint( con, 110, 100 ); CGContextClosePath( con ); CGContextAddRect( con, CGContextGetClipBoundingBox( con ) ); CGContextEOClip( con ); // draw the vertical line, add its shape to the clipping region CGContextMoveToPoint( con, 100, 100 ); CGContextAddLineToPoint( con, 100, 19 ); CGContextSetLineWidth( con, 20 ); CGContextReplacePathWithStrokedPath( con ); CGContextClip( con ); // draw the gradient sp := CGColorSpaceCreateDeviceGray( ); grad := CGGradientCreateWithColorComponents( sp, @colors[0], @locs[0], 3 ); CGContextDrawLinearGradient( con, grad, CGPointMake( 89, 0 ), CGPointMake( 111, 0 ), 0 ); CGColorSpaceRelease( sp ); CGGradientRelease( grad ); CGContextRestoreGState( con ); // done clipping // draw the red triangle, the point of the arrow CGContextSetFillColorWithColor( con, TUIColor.Wrap( TUIColor.OCClass.redColor ).CGColor ); CGContextMoveToPoint( con, 80, 25 ); CGContextAddLineToPoint( con, 100, 0 ); CGContextAddLineToPoint( con, 120, 25 ); CGContextFillPath( con ); // -------------------------------------------------------------- // Draw & Release CGContextStrokePath( context ); CGColorSpaceRelease( colorspace ); CGColorRelease( color ); end; procedure TFDrawingNative.PaintRects( const UpdateRects: array of TRectF ); begin { } end; end.
unit F1Like_InternalOperations_Controls; // Модуль: "w:\common\components\gui\Garant\VCM\View\F1Like_InternalOperations_Controls.pas" // Стереотип: "VCMControls" // Элемент модели: "InternalOperations" MUID: (4F71AD0E01FE) {$Include w:\common\components\gui\f1LikeAppDefine.inc} interface uses l3IntfUses {$If NOT Defined(NoVCM)} , vcmInterfaces {$IfEnd} // NOT Defined(NoVCM) {$If NOT Defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} // NOT Defined(NoVCM) ; type ISwitcher_BecomeActive_Params = interface {* Параметры для операции Switcher.BecomeActive } function Get_Form: IvcmEntityForm; property Form: IvcmEntityForm read Get_Form; end;//ISwitcher_BecomeActive_Params Op_Switcher_BecomeActive = {final} class {* Класс для вызова операции Switcher.BecomeActive } public class function Call(const aTarget: IvcmEntity; const aForm: IvcmEntityForm): Boolean; overload; {* Вызов операции Switcher.BecomeActive у сущности } class function Call(const aTarget: IvcmAggregate; const aForm: IvcmEntityForm): Boolean; overload; {* Вызов операции Switcher.BecomeActive у агрегации } class function Call(const aTarget: IvcmEntityForm; const aForm: IvcmEntityForm): Boolean; overload; {* Вызов операции Switcher.BecomeActive у формы } class function Call(const aTarget: IvcmContainer; const aForm: IvcmEntityForm): Boolean; overload; {* Вызов операции Switcher.BecomeActive у контейнера } end;//Op_Switcher_BecomeActive Op_Switcher_SetFirstPageActive = {final} class {* Класс для вызова операции Switcher.SetFirstPageActive } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции Switcher.SetFirstPageActive у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции Switcher.SetFirstPageActive у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции Switcher.SetFirstPageActive у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции Switcher.SetFirstPageActive у контейнера } end;//Op_Switcher_SetFirstPageActive ICommon_ShowSplitter_Params = interface {* Параметры для операции Common.ShowSplitter } function Get_Visible: Boolean; property Visible: Boolean read Get_Visible; end;//ICommon_ShowSplitter_Params Op_Common_ShowSplitter = {final} class {* Класс для вызова операции Common.ShowSplitter } public class function Call(const aTarget: IvcmEntity; aVisible: Boolean): Boolean; overload; {* Вызов операции Common.ShowSplitter у сущности } class function Call(const aTarget: IvcmAggregate; aVisible: Boolean): Boolean; overload; {* Вызов операции Common.ShowSplitter у агрегации } class function Call(const aTarget: IvcmEntityForm; aVisible: Boolean): Boolean; overload; {* Вызов операции Common.ShowSplitter у формы } class function Call(const aTarget: IvcmContainer; aVisible: Boolean): Boolean; overload; {* Вызов операции Common.ShowSplitter у контейнера } end;//Op_Common_ShowSplitter ICommon_CheckChildZone_Params = interface {* Параметры для операции Common.CheckChildZone } function Get_Toggle: Boolean; property Toggle: Boolean read Get_Toggle; end;//ICommon_CheckChildZone_Params Op_Common_CheckChildZone = {final} class {* Класс для вызова операции Common.CheckChildZone } public class function Call(const aTarget: IvcmEntity; aToggle: Boolean): Boolean; overload; {* Вызов операции Common.CheckChildZone у сущности } class function Call(const aTarget: IvcmAggregate; aToggle: Boolean): Boolean; overload; {* Вызов операции Common.CheckChildZone у агрегации } class function Call(const aTarget: IvcmEntityForm; aToggle: Boolean): Boolean; overload; {* Вызов операции Common.CheckChildZone у формы } class function Call(const aTarget: IvcmContainer; aToggle: Boolean): Boolean; overload; {* Вызов операции Common.CheckChildZone у контейнера } end;//Op_Common_CheckChildZone const en_Switcher = 'Switcher'; en_capSwitcher = 'Сущность для управления закладками формы-контейнера'; op_BecomeActive = 'BecomeActive'; op_capBecomeActive = ''; op_SetFirstPageActive = 'SetFirstPageActive'; op_capSetFirstPageActive = ''; en_Common = 'Common'; en_capCommon = ''; op_ShowSplitter = 'ShowSplitter'; op_capShowSplitter = ''; op_CheckChildZone = 'CheckChildZone'; op_capCheckChildZone = ''; var opcode_Switcher_BecomeActive: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Switcher_SetFirstPageActive: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Common_ShowSplitter: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Common_CheckChildZone: TvcmOPID = (rEnID : -1; rOpID : -1); implementation uses l3ImplUses , l3CProtoObject {$If NOT Defined(NoVCM)} , vcmOperationsForRegister {$IfEnd} // NOT Defined(NoVCM) {$If NOT Defined(NoVCM)} , vcmOperationStatesForRegister {$IfEnd} // NOT Defined(NoVCM) , l3Base {$If NOT Defined(NoVCM)} , vcmBase {$IfEnd} // NOT Defined(NoVCM) ; type TSwitcher_BecomeActive_Params = {final} class(Tl3CProtoObject, ISwitcher_BecomeActive_Params) {* Реализация ISwitcher_BecomeActive_Params } private f_Form: IvcmEntityForm; protected function Get_Form: IvcmEntityForm; procedure ClearFields; override; public constructor Create(const aForm: IvcmEntityForm); reintroduce; class function Make(const aForm: IvcmEntityForm): ISwitcher_BecomeActive_Params; reintroduce; end;//TSwitcher_BecomeActive_Params TCommon_ShowSplitter_Params = {final} class(Tl3CProtoObject, ICommon_ShowSplitter_Params) {* Реализация ICommon_ShowSplitter_Params } private f_Visible: Boolean; protected function Get_Visible: Boolean; public constructor Create(aVisible: Boolean); reintroduce; class function Make(aVisible: Boolean): ICommon_ShowSplitter_Params; reintroduce; end;//TCommon_ShowSplitter_Params TCommon_CheckChildZone_Params = {final} class(Tl3CProtoObject, ICommon_CheckChildZone_Params) {* Реализация ICommon_CheckChildZone_Params } private f_Toggle: Boolean; protected function Get_Toggle: Boolean; public constructor Create(aToggle: Boolean); reintroduce; class function Make(aToggle: Boolean): ICommon_CheckChildZone_Params; reintroduce; end;//TCommon_CheckChildZone_Params constructor TSwitcher_BecomeActive_Params.Create(const aForm: IvcmEntityForm); begin inherited Create; f_Form := aForm; end;//TSwitcher_BecomeActive_Params.Create class function TSwitcher_BecomeActive_Params.Make(const aForm: IvcmEntityForm): ISwitcher_BecomeActive_Params; var l_Inst : TSwitcher_BecomeActive_Params; begin l_Inst := Create(aForm); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TSwitcher_BecomeActive_Params.Make function TSwitcher_BecomeActive_Params.Get_Form: IvcmEntityForm; begin Result := f_Form; end;//TSwitcher_BecomeActive_Params.Get_Form procedure TSwitcher_BecomeActive_Params.ClearFields; begin f_Form := nil; inherited; end;//TSwitcher_BecomeActive_Params.ClearFields class function Op_Switcher_BecomeActive.Call(const aTarget: IvcmEntity; const aForm: IvcmEntityForm): Boolean; {* Вызов операции Switcher.BecomeActive у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TSwitcher_BecomeActive_Params.Make(aForm)); aTarget.Operation(opcode_Switcher_BecomeActive, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Switcher_BecomeActive.Call class function Op_Switcher_BecomeActive.Call(const aTarget: IvcmAggregate; const aForm: IvcmEntityForm): Boolean; {* Вызов операции Switcher.BecomeActive у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TSwitcher_BecomeActive_Params.Make(aForm)); aTarget.Operation(opcode_Switcher_BecomeActive, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Switcher_BecomeActive.Call class function Op_Switcher_BecomeActive.Call(const aTarget: IvcmEntityForm; const aForm: IvcmEntityForm): Boolean; {* Вызов операции Switcher.BecomeActive у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aForm); end;//Op_Switcher_BecomeActive.Call class function Op_Switcher_BecomeActive.Call(const aTarget: IvcmContainer; const aForm: IvcmEntityForm): Boolean; {* Вызов операции Switcher.BecomeActive у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aForm); end;//Op_Switcher_BecomeActive.Call class function Op_Switcher_SetFirstPageActive.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции Switcher.SetFirstPageActive у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_Switcher_SetFirstPageActive, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Switcher_SetFirstPageActive.Call class function Op_Switcher_SetFirstPageActive.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции Switcher.SetFirstPageActive у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_Switcher_SetFirstPageActive, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Switcher_SetFirstPageActive.Call class function Op_Switcher_SetFirstPageActive.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции Switcher.SetFirstPageActive у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_Switcher_SetFirstPageActive.Call class function Op_Switcher_SetFirstPageActive.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции Switcher.SetFirstPageActive у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_Switcher_SetFirstPageActive.Call constructor TCommon_ShowSplitter_Params.Create(aVisible: Boolean); begin inherited Create; f_Visible := aVisible; end;//TCommon_ShowSplitter_Params.Create class function TCommon_ShowSplitter_Params.Make(aVisible: Boolean): ICommon_ShowSplitter_Params; var l_Inst : TCommon_ShowSplitter_Params; begin l_Inst := Create(aVisible); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TCommon_ShowSplitter_Params.Make function TCommon_ShowSplitter_Params.Get_Visible: Boolean; begin Result := f_Visible; end;//TCommon_ShowSplitter_Params.Get_Visible class function Op_Common_ShowSplitter.Call(const aTarget: IvcmEntity; aVisible: Boolean): Boolean; {* Вызов операции Common.ShowSplitter у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TCommon_ShowSplitter_Params.Make(aVisible)); aTarget.Operation(opcode_Common_ShowSplitter, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Common_ShowSplitter.Call class function Op_Common_ShowSplitter.Call(const aTarget: IvcmAggregate; aVisible: Boolean): Boolean; {* Вызов операции Common.ShowSplitter у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TCommon_ShowSplitter_Params.Make(aVisible)); aTarget.Operation(opcode_Common_ShowSplitter, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Common_ShowSplitter.Call class function Op_Common_ShowSplitter.Call(const aTarget: IvcmEntityForm; aVisible: Boolean): Boolean; {* Вызов операции Common.ShowSplitter у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aVisible); end;//Op_Common_ShowSplitter.Call class function Op_Common_ShowSplitter.Call(const aTarget: IvcmContainer; aVisible: Boolean): Boolean; {* Вызов операции Common.ShowSplitter у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aVisible); end;//Op_Common_ShowSplitter.Call constructor TCommon_CheckChildZone_Params.Create(aToggle: Boolean); begin inherited Create; f_Toggle := aToggle; end;//TCommon_CheckChildZone_Params.Create class function TCommon_CheckChildZone_Params.Make(aToggle: Boolean): ICommon_CheckChildZone_Params; var l_Inst : TCommon_CheckChildZone_Params; begin l_Inst := Create(aToggle); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TCommon_CheckChildZone_Params.Make function TCommon_CheckChildZone_Params.Get_Toggle: Boolean; begin Result := f_Toggle; end;//TCommon_CheckChildZone_Params.Get_Toggle class function Op_Common_CheckChildZone.Call(const aTarget: IvcmEntity; aToggle: Boolean): Boolean; {* Вызов операции Common.CheckChildZone у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TCommon_CheckChildZone_Params.Make(aToggle)); aTarget.Operation(opcode_Common_CheckChildZone, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Common_CheckChildZone.Call class function Op_Common_CheckChildZone.Call(const aTarget: IvcmAggregate; aToggle: Boolean): Boolean; {* Вызов операции Common.CheckChildZone у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TCommon_CheckChildZone_Params.Make(aToggle)); aTarget.Operation(opcode_Common_CheckChildZone, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Common_CheckChildZone.Call class function Op_Common_CheckChildZone.Call(const aTarget: IvcmEntityForm; aToggle: Boolean): Boolean; {* Вызов операции Common.CheckChildZone у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aToggle); end;//Op_Common_CheckChildZone.Call class function Op_Common_CheckChildZone.Call(const aTarget: IvcmContainer; aToggle: Boolean): Boolean; {* Вызов операции Common.CheckChildZone у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aToggle); end;//Op_Common_CheckChildZone.Call initialization with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Switcher, op_BecomeActive, en_capSwitcher, op_capBecomeActive, True, False, opcode_Switcher_BecomeActive)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Switcher, op_SetFirstPageActive, en_capSwitcher, op_capSetFirstPageActive, True, False, opcode_Switcher_SetFirstPageActive)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Common, op_ShowSplitter, en_capCommon, op_capShowSplitter, True, False, opcode_Common_ShowSplitter)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Common, op_CheckChildZone, en_capCommon, op_capCheckChildZone, True, False, opcode_Common_CheckChildZone)) do begin end; end.
unit PictureExt; interface uses Classes , Graphics; type TExtPicture =class(TPicture) public procedure LoadFromStream(const AStream : TStream); procedure SaveToStream(const AStream : TStream); end; implementation { TExtPicture } procedure TExtPicture.LoadFromStream(const AStream: TStream); begin inherited LoadFromStream(AStream); end; procedure TExtPicture.SaveToStream(const AStream: TStream); begin inherited SaveToStream(AStream); end; end.
unit Control.Acessos; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Control.Sistema, Model.Acessos, Vcl.ActnList; type TAcessosControl = class private FAcessos: TAcessos; public constructor Create(); destructor Destroy(); override; property Acessos: TAcessos read FAcessos write FAcessos; function ValidaCampos(): Boolean; function Localizar(aParam: array of variant): TFDQuery; function VerificaLogin(iMenu: Integer; iUsuario: Integer): Boolean; function VerificaModulo(iModulo: Integer; iUsuario: Integer): Boolean; function VerificaSistema(iSistema: Integer; iUsuario: Integer): Boolean; function Gravar(): Boolean; end; implementation { TAcessosControl } constructor TAcessosControl.Create; begin FAcessos := TAcessos.Create; end; destructor TAcessosControl.Destroy; begin FAcessos.Free; inherited; end; function TAcessosControl.Gravar: Boolean; begin Result := False; Result := FAcessos.Gravar(); end; function TAcessosControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FAcessos.Localizar(aParam); end; function TAcessosControl.ValidaCampos: Boolean; var aParam: Array of variant; begin try Result := False; if FAcessos.Usuario = 0 then begin Application.MessageBox('Informe um usuário para este acesso!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if FAcessos.Sistema = 0 then begin Application.MessageBox('Informe um código de sistema!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if FAcessos.Modulo = 0 then begin Application.MessageBox('Informe um código de módulo!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if FAcessos.Menu = 0 then begin Application.MessageBox('Informe um código de menu!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; SetLength(aParam,5); aParam[0] := 'ACESSO'; aParam[1] := FAcessos.Sistema; aParam[2] := FAcessos.Modulo; aParam[3] := FAcessos.Menu; aParam[4] := FAcessos.Usuario; if FAcessos.AcessoExiste(aParam) then begin if FAcessos.Acao = tacExcluir then begin Application.MessageBox('Acesso não cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; end; Result := True; finally Finalize(aParam); end; end; function TAcessosControl.VerificaLogin(iMenu, iUsuario: Integer): Boolean; begin Result := Facessos.VerificaLogin(iMenu, iUsuario); end; function TAcessosControl.VerificaModulo(iModulo, iUsuario: Integer): Boolean; begin Result := Facessos.VerificaModulo(iModulo, iUsuario); end; function TAcessosControl.VerificaSistema(iSistema, iUsuario: Integer): Boolean; begin Result := Facessos.VerificaSistema(iSistema, iUsuario); end; end.
// stores the bookmarks while the source file is being reformatted // Original Author: Thomas Mueller (http://www.dummzeuch.de) unit GX_CodeFormatterBookmarks; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, ToolsApi, GX_BookmarkList; type TBookmarkHandler = class private FBookmarks: TBookmarkList; protected function GetEditView(var _SourceEditor: IOTASourceEditor; var _EditView: IOTAEditView): Boolean; public constructor Create; destructor Destroy; override; procedure RestoreItems; procedure SaveItems; end; implementation uses GX_OtaUtils; { TBookmarkHandler } constructor TBookmarkHandler.Create; begin inherited Create; FBookmarks := TBookmarkList.Create; end; destructor TBookmarkHandler.Destroy; begin FBookmarks.Free; inherited; end; function TBookmarkHandler.GetEditView(var _SourceEditor: IOTASourceEditor; var _EditView: IOTAEditView): Boolean; begin Result := False; if not GxOtaTryGetCurrentSourceEditor(_SourceEditor) then Exit; _EditView := _SourceEditor.GetEditView(0); Result := Assigned(_EditView); end; procedure TBookmarkHandler.SaveItems; var SourceEditor: IOTASourceEditor; EditView: IOTAEditView; i: Integer; BmPos: TOTACharPos; begin FBookmarks.Clear; if not GetEditView(SourceEditor, EditView) then Exit; for i := 0 to 19 do begin BmPos := EditView.BookmarkPos[i]; if BmPos.Line <> 0 then FBookmarks.Add(i, BmPos.Line, BmPos.CharIndex); end; end; procedure TBookmarkHandler.RestoreItems; var SourceEditor: IOTASourceEditor; EditView: IOTAEditView; SaveCursorPos: TOTAEditPos; BmEditPos: TOTAEditPos; i: Integer; begin if not GetEditView(SourceEditor, EditView) then Exit; SaveCursorPos := EditView.GetCursorPos; try for i := 0 to FBookmarks.Count - 1 do begin BmEditPos.Line := FBookmarks[i].Line; BmEditPos.Col := FBookmarks[i].CharIdx; EditView.SetCursorPos(BmEditPos); EditView.BookmarkToggle(FBookmarks[i].Number); end; finally EditView.SetCursorPos(SaveCursorPos); end; EditView.Paint; SourceEditor.Show; FBookmarks.Clear; 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.4 10/26/2004 10:59:30 PM JPMugaas { Updated ref. } { Rev 1.3 5/29/2004 10:02:20 AM DSiders Corrected case in Create parameter. } { { Rev 1.2 2004.02.03 5:44:54 PM czhower { Name changes } { { Rev 1.1 2004.01.21 1:04:52 PM czhower { InitComponenet } { { Rev 1.0 11/14/2002 02:13:40 PM JPMugaas } unit IdAuthenticationManager; interface Uses IdAuthentication, IdBaseComponent, IdSys, IdObjs, IdURI; Type TIdAuthenticationItem = class(TIdCollectionItem) protected FURI: TIdURI; FParams: TIdStringList; procedure SetParams(const Value: TIdStringList); procedure SetURI(const Value: TIdURI); public constructor Create(ACollection: TIdCollection); override; destructor Destroy; override; property URL: TIdURI read FURI write SetURI; property Params: TIdStringList read FParams write SetParams; end; TIdAuthenticationCollection = class(TIdOwnedCollection) protected function GetAuthItem(AIndex: Integer): TIdAuthenticationItem; procedure SetAuthItem(AIndex: Integer; const Value: TIdAuthenticationItem); public function Add: TIdAuthenticationItem; constructor Create(AOwner: TIdPersistent); // property Items[AIndex: Integer]: TIdAuthenticationItem read GetAuthItem write SetAuthItem; end; TIdAuthenticationManager = class(TIdBaseComponent) protected FAuthentications: TIdAuthenticationCollection; // procedure InitComponent; override; public destructor Destroy; override; procedure AddAuthentication(AAuthtetication: TIdAuthentication; AURL: TIdURI); property Authentications: TIdAuthenticationCollection read FAuthentications; end; implementation uses IdGlobal; { TIdAuthenticationManager } function TIdAuthenticationCollection.Add: TIdAuthenticationItem; begin result := TIdAuthenticationItem.Create(self); end; constructor TIdAuthenticationCollection.Create(AOwner: TIdPersistent); begin inherited Create(AOwner, TIdAuthenticationItem); end; function TIdAuthenticationCollection.GetAuthItem( AIndex: Integer): TIdAuthenticationItem; begin result := TIdAuthenticationItem(inherited Items[AIndex]); end; procedure TIdAuthenticationCollection.SetAuthItem(AIndex: Integer; const Value: TIdAuthenticationItem); begin if Items[AIndex] <> nil then begin Items[AIndex].Assign(Value); end; end; { TIdAuthenticationManager } procedure TIdAuthenticationManager.AddAuthentication( AAuthtetication: TIdAuthentication; AURL: TIdURI); begin with Authentications.Add do begin URL.URI := AURL.URI; Params.Assign(AAuthtetication.Params); end; end; destructor TIdAuthenticationManager.Destroy; begin Sys.FreeAndNil(FAuthentications); inherited Destroy; end; procedure TIdAuthenticationManager.InitComponent; begin inherited InitComponent; FAuthentications := TIdAuthenticationCollection.Create(Self); end; { TIdAuthenticationItem } constructor TIdAuthenticationItem.Create(ACollection: TIdCollection); begin inherited Create(ACollection); FURI := TIdURI.Create; FParams := TIdStringList.Create; end; destructor TIdAuthenticationItem.Destroy; begin Sys.FreeAndNil(FURI); Sys.FreeAndNil(FParams); inherited Destroy; end; procedure TIdAuthenticationItem.SetParams(const Value: TIdStringList); begin FParams.Assign(Value); end; procedure TIdAuthenticationItem.SetURI(const Value: TIdURI); begin FURI.URI := Value.URI; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIAsn1Choice; {$I ..\Include\CryptoLib.inc} interface type /// ** // * Marker interface for CHOICE objects - if you implement this in a roll-your-own // * object, any attempt to tag the object implicitly will convert the tag to an // * explicit one as the encoding rules require. // * <p> // * If you use this interface your class should also implement the GetInstance // * pattern which takes a tag object and the tagging mode used. // * </p> // */ IAsn1Choice = interface(IInterface) // marker interface ['{9C12BE01-9579-48F2-A5B0-4FA5DD807B32}'] end; implementation end.
unit uTelaPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, uDMSolicitacao, uSolicitacaoVO, uSolicitacaoViewModel, uDM; Const C_PARAR: string = 'Parar'; C_INICIAR: string = 'Iniciar'; type TfrmTelaPrincipal = class(TForm) lblCliente: TLabel; lblIdSolicitacao: TLabel; Label2: TLabel; Label3: TLabel; lblTitulo: TLabel; Label5: TLabel; lblNivel: TLabel; Label7: TLabel; Panel1: TPanel; btnControle: TBitBtn; lblStatus: TLabel; Label4: TLabel; btnDetalhe: TSpeedButton; Label1: TLabel; lblTempoPrevisto: TLabel; Label6: TLabel; lblTempoDecorrido: TLabel; procedure FormShow(Sender: TObject); procedure btnControleClick(Sender: TObject); procedure btnDetalheClick(Sender: TObject); private { Private declarations } FIdUsuarioLogado: Integer; FIdSolicitacao: Integer; FIdUsuarioAtendeAtual: Integer; procedure MostrarDados; procedure Iniciar(); procedure Parar(); procedure CorTela(); procedure Detalhes(); procedure Detalhar(); procedure Resumir(); procedure TamanhoTela(); public { Public declarations } end; var frmTelaPrincipal: TfrmTelaPrincipal; implementation {$R *.dfm} procedure TfrmTelaPrincipal.btnControleClick(Sender: TObject); begin if btnControle.Caption = C_PARAR then Parar() else Iniciar(); end; procedure TfrmTelaPrincipal.btnDetalheClick(Sender: TObject); begin Detalhes(); end; procedure TfrmTelaPrincipal.CorTela; begin if btnControle.Caption = C_INICIAR then Self.Color := clGreen else Self.Color := clRed; end; procedure TfrmTelaPrincipal.Detalhar; begin Self.Height := 200; Self.Width := 520; // self.Left := 3; // self.Top := 3; // Self.Left := 1400; // Self.Top := 841; btnDetalhe.Caption := '>>'; MostrarDados(); TamanhoTela(); end; procedure TfrmTelaPrincipal.Detalhes; begin if btnDetalhe.Caption = '>>' then Resumir() else Detalhar(); end; procedure TfrmTelaPrincipal.FormShow(Sender: TObject); var id: Integer; idUsuario: Integer; begin FIdSolicitacao := StrToIntDef(ParamStr(1), 0); FIdUsuarioLogado := StrToIntDef(ParamStr(2), 0); lblIdSolicitacao.Caption := ''; lblCliente.Caption := ''; lblTitulo.Caption := ''; lblNivel.Caption := ''; lblStatus.Caption := ''; lblTempoPrevisto.Caption := ''; lblTempoDecorrido.Caption := ''; // FIdSolicitacao := 1115; // FIdUsuarioLogado := 21; if FIdSolicitacao = 0 then begin ShowMessage('Informe a Solicitação.'); Application.Terminate; Exit; end; MostrarDados(); Resumir(); TamanhoTela(); end; procedure TfrmTelaPrincipal.Parar; var SolicitacaoViewModel: TSolicitacaoViewModel; begin SolicitacaoViewModel := TSolicitacaoViewModel.Create; try try SolicitacaoViewModel.Id := FIdSolicitacao; SolicitacaoViewModel.IdUsuarioAtendeAtual := FIdUsuarioAtendeAtual; dmSolicitacao.FinalizarTempo(FIdUsuarioLogado, SolicitacaoViewModel); btnControle.Caption := C_INICIAR; CorTela(); except On E: Exception do begin raise Exception.Create(E.Message); end; end; finally FreeAndNil(SolicitacaoViewModel); end; end; procedure TfrmTelaPrincipal.Resumir; begin Self.Height := 70; Self.Width := 375; btnDetalhe.Caption := '<<'; TamanhoTela(); end; procedure TfrmTelaPrincipal.TamanhoTela; begin Self.Top := Screen.Height - Self.Height - 35; Self.Left := Screen.Width - Self.Width; end; procedure TfrmTelaPrincipal.MostrarDados; var model: TSolicitacaoViewModel; begin model := dmSolicitacao.ObterPorId(FIdSolicitacao); lblIdSolicitacao.Caption := model.Id.ToString(); lblCliente.Caption := model.NomeCliente; lblTitulo.Caption := model.Titulo; lblNivel.Caption := model.Nivel; lblStatus.Caption := model.NomeStatus; lblTempoPrevisto.Caption := FormatFloat(',##0.00', model.TempoPrevisto); lblTempoDecorrido.Caption := model.TempoDecorrido; FIdUsuarioAtendeAtual := model.IdUsuarioAtendeAtual; if model.TempoAberto then btnControle.Caption := C_PARAR else btnControle.Caption := C_INICIAR; CorTela(); FreeAndNil(model); end; procedure TfrmTelaPrincipal.Iniciar; var SolicitacaoViewModel: TSolicitacaoViewModel; begin SolicitacaoViewModel := TSolicitacaoViewModel.Create; try try SolicitacaoViewModel.Id := FIdSolicitacao; SolicitacaoViewModel.IdUsuarioAtendeAtual := FIdUsuarioAtendeAtual; SolicitacaoViewModel.NomeStatus := lblStatus.Caption; dmSolicitacao.IniciarTempo(FIdUsuarioLogado, SolicitacaoViewModel); btnControle.Caption := C_PARAR; CorTela(); except on E: Exception do begin raise Exception.Create(E.Message); end; end; finally FreeAndNil(SolicitacaoViewModel); end; end; end.
unit untCarregaBases; interface uses Classes, Forms, SysUtils, Messages, Dialogs; procedure CarregaBases; implementation uses udmPadrao, udmVariaveis, udmPrincipal, udmDadosCTe, udmFiliais, udmCliente, udmConhecimentos, udmMinutaContainer, udmDocsFaturar, udmEntregas, udmNotaEmbarcada, udmCotacoesFrete, udmOrdemServico, udmInformacaoEmbarque, udmParametros, udmDescontos, udmConfiguracoes, udmRotasGerais, udmRotasEspecificas, udmBairrosDistribuicao, udmTabsPromocionais, udmTabsGerais, udmTabsEspecificas, udmTabsProdutos, udmTabsVeiculos, udmTaxas, udmAliquotaICMS, udmTpVeiculo, udmEmpresasEDI, udmCidades, udmRomsDistribuicao, udmVendedores, udmLctoPendencias, udmVeiculo, udmMotorista, udmCntrCarreteiros, udmServicos, udmManifestos, udmCtasReceber, udmDadosAduaneiros, udmColetas, udmImpostoRenda, udmProduto, udmAutsPagamento; procedure CarregaBases; begin try if not Assigned(dmPadrao) then dmPadrao := TdmPadrao.Create(Application); if not Assigned(dmVariaveis) then dmVariaveis := TdmVariaveis.Create(Application); if not Assigned(dmPrincipal) then dmPrincipal := TdmPrincipal.Create(Application); if not Assigned(dmDadosCTe) then dmDadosCTe := TdmDadosCTe.Create(Application); if not Assigned(dmFiliais) then dmFiliais := TdmFiliais.Create(Application); if not Assigned(dmCliente) then dmCliente := TdmCliente.Create(Application); if not Assigned(dmConhecimentos) then dmConhecimentos := TdmConhecimentos.Create(Application); if not Assigned(dmMinutaContainer) then dmMinutaContainer := TdmMinutaContainer.Create(Application); if not Assigned(dmDocsFaturar) then dmDocsFaturar := TdmDocsFaturar.Create(Application); if not Assigned(dmEntregas) then dmEntregas := TdmEntregas.Create(Application); if not Assigned(dmNotaEmbarcada) then dmNotaEmbarcada := TdmNotaEmbarcada.Create(Application); if not Assigned(dmCotacoesFrete) then dmCotacoesFrete := TdmCotacoesFrete.Create(Application); if not Assigned(dmOrdemServico) then dmOrdemServico := TdmOrdemServico.Create(Application); if not Assigned(dmInformacaoEmbarque) then dmInformacaoEmbarque := TdmInformacaoEmbarque.Create(Application); //usados na libcalculo if not Assigned(dmParametros) then dmParametros := TdmParametros.Create(Application); if not Assigned(dmDescontos) then dmDescontos := TdmDescontos.Create(Application); if not Assigned(dmRotasGerais) then dmRotasGerais := TdmRotasGerais.Create(Application); if not Assigned(dmRotasEspecificas) then dmRotasEspecificas := TdmRotasEspecificas.Create(Application); if not Assigned(dmBairrosDistribuicao) then dmBairrosDistribuicao := TdmBairrosDistribuicao.Create(Application); if not Assigned(dmTabsPromocionais) then dmTabsPromocionais := TdmTabsPromocionais.Create(Application); if not Assigned(dmTabsGerais) then dmTabsGerais := TdmTabsGerais.Create(Application); if not Assigned(dmTabsEspecificas) then dmTabsEspecificas := TdmTabsEspecificas.Create(Application); if not Assigned(dmTabsProdutos) then dmTabsProdutos := TdmTabsProdutos.Create(Application); if not Assigned(dmTabsVeiculos) then dmTabsVeiculos := TdmTabsVeiculos.Create(Application); if not Assigned(dmTaxas) then dmTaxas := TdmTaxas.Create(Application); if not Assigned(dmAliquotaICMS) then dmAliquotaICMS := TdmAliquotaICMS.Create(Application); if not Assigned(dmTpVeiculo) then dmTpVeiculo := TdmTpVeiculo.Create(Application); if not Assigned(dmEmpresasEDI) then dmEmpresasEDI := TdmEmpresasEDI.Create(Application); if not Assigned(dmCidades) then dmCidades := TdmCidades.Create(Application); if not Assigned(dmRomsDistribuicao) then dmRomsDistribuicao := TdmRomsDistribuicao.Create(Application); if not Assigned(dmVendedores) then dmVendedores := TdmVendedores.Create(Application); if not Assigned(dmLctoPendencias) then dmLctoPendencias := TdmLctoPendencias.Create(Application); if not Assigned(dmVeiculo) then dmVeiculo := TdmVeiculo.Create(Application); if not Assigned(dmCntrCarreteiros) then dmCntrCarreteiros := TdmCntrCarreteiros.Create(Application); if not Assigned(dmMotorista) then dmMotorista := TdmMotorista.Create(Application); if not Assigned(dmServicos) then dmServicos := TdmServicos.Create(Application); if not Assigned(dmManifestos) then dmManifestos := TdmManifestos.Create(Application); if not Assigned(dmDadosAduaneiros) then dmDadosAduaneiros := TdmDadosAduaneiros.Create(Application); if not Assigned(dmCtasReceber) then dmCtasReceber := TdmCtasReceber.Create(Application); if not Assigned(dmColetas) then dmColetas := TdmColetas.Create(Application); if not Assigned(dmImpostoRenda) then dmImpostoRenda := TdmImpostoRenda.Create(Application); if not Assigned(dmProduto) then dmProduto := TdmProduto.Create(Application); if not Assigned(dmVariaveis) then dmVariaveis := TdmVariaveis.Create(Application); if not Assigned(dmAutsPagamento) then dmAutsPagamento := TdmAutsPagamento.Create(Application); except on e: exception do showmessage(e.message); end; end; end.
unit xpr.interpreter; { Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) Interpreter, for the execution of code } {$I express.inc} interface uses Classes, SysUtils, xpr.express, xpr.bytecode, {$I objects.inc}; const STACK_MIN_SIZE = 16; STACK_MULTIPLIER = 2; type TFrame = record Stack: TObjectArray; StackPos: Int32; procedure Init; procedure Push(value: TEpObject); inline; function Pop: TEpObject; inline; procedure Popn(n:Int32; var dest:TObjectArray); inline; function Top: TEpObject; inline; procedure SetTop(value: TEpObject); inline; function StackToString: String; end; TCallerData = record vars: TObjectArray; varStart, pc: UInt32; end; TCallStack = record Stack: array of TCallerData; StackPos: Int32; procedure Init; procedure Push(constref vars:TObjectArray; constref pc, varStart: UInt32); procedure Reset(var pc: UInt32; var bcVars:TObjectArray); inline; end; TInterpreter = class(TObject) public Frame: TFrame; CallStack: TCallStack; Bytecode: TBytecode; Pc: UInt32; public constructor Create(bc:TBytecode); destructor Destroy; override; procedure CollectGarbage(); inline; procedure ExecuteSafe; procedure Execute; inline; procedure CallFunction(func:TFuncObject; counter:Int32); inline; procedure BuildList(var dest:TEpObject); inline; procedure PrintStatement(n:Int32); inline; end; procedure PrintFunc(exprs:TObjectArray); implementation uses xpr.utils, xpr.errors, xpr.opcodes, xpr.mmgr; procedure PrintFunc(exprs:TObjectArray); var str:epString; i:Int32; begin for i:=0 to High(exprs) do begin str += exprs[i].AsString; if i < High(exprs) then str += ' '; end; WriteLn(str); end; procedure TFrame.Init; begin SetLength(Stack, STACK_MIN_SIZE); StackPos := -1; end; procedure TFrame.Push(value: TEpObject); begin Assert(value <> nil); if StackPos = High(Stack) then SetLength(Stack, Length(stack) * STACK_MULTIPLIER); Assert(StackPos+1<Length(stack), 'Stack overflow'); Inc(StackPos); Stack[StackPos] := value; end; function TFrame.Pop: TEpObject; begin Assert(StackPos>-1, 'Stack underflow'); Result := Stack[StackPos]; Dec(StackPos); Assert(Result <> nil); end; procedure TFrame.Popn(n:Int32; var dest:TObjectArray); begin if n > 0 then begin Move(Stack[StackPos-n+1], dest[0], n*SizeOf(Pointer)); Dec(StackPos, n); end; end; function TFrame.Top: TEpObject; begin Assert((StackPos>-1) and (StackPos<Length(Stack)), 'Corrupted stack'); Result := Stack[StackPos]; Assert(Result <> nil); end; procedure TFrame.SetTop(value: TEpObject); begin Assert(value <> nil); Assert((StackPos>-1) and (StackPos<Length(Stack)), 'Corrupted stack'); Stack[StackPos] := value; end; function TFrame.StackToString: String; var i,size:Int32; begin Result := '['; if StackPos > 10 then size := 10 else size := StackPos; for i:=0 to size do begin Result += stack[i].AsString; if i <> StackPos then Result += ', '; end; if StackPos > 10 then Result += '...'; Result += ']'; end; (* Call stack *) procedure TCallStack.Init; begin SetLength(Stack, STACK_MIN_SIZE); StackPos := -1; end; procedure TCallStack.Push(constref vars:TObjectArray; constref pc, varStart: UInt32); begin if StackPos = High(Stack) then SetLength(Stack, Length(stack) * STACK_MULTIPLIER); Inc(StackPos); Stack[StackPos].pc := pc; Stack[StackPos].vars := vars; Stack[StackPos].varStart := varStart; end; procedure TCallStack.Reset(var PC: UInt32; var bcVars:TObjectArray); var GC:TGarbageCollector; top:TCallerData; i:Int32; begin top := Stack[StackPos]; PC := top.pc; GC := TGarbageCollector(bcVars[0].GC); for i:=0 to High(top.vars) do begin GC.Release(bcVars[top.varStart+i]); bcVars[top.varStart+i] := top.vars[i]; end; Dec(StackPos); end; (* Interpreter *) constructor TInterpreter.Create(bc:TBytecode); begin Bytecode := bc; Pc := 0; Frame.Init; CallStack.Init; end; destructor TInterpreter.Destroy; begin Bytecode.Free; inherited; end; procedure TInterpreter.CollectGarbage(); var g,i:Int32; begin if not Bytecode.GC.ShouldEnter then Exit; //WriteLn('+GC'); for g:=0 to High(Bytecode.GC.CountDown) do if Bytecode.GC.CountDown[g] <= 0 then begin Bytecode.GC.PrepareCollection(g); // mark the following variables so they don't go away for i:=0 to CallStack.StackPos do Bytecode.GC.Mark(g, CallStack.Stack[i].vars, High(CallStack.Stack[i].vars)); Bytecode.GC.Mark(g, Frame.Stack, Frame.StackPos); Bytecode.GC.Mark(g, Bytecode.Variables, High(Bytecode.Variables)); Bytecode.GC.Mark(g, Bytecode.Constants, High(Bytecode.Constants)); //remove everything that wasn't marked, promote the remainders to another generation (when possible) Bytecode.GC.Sweep(g); end; //WriteLn('-GC'); end; procedure TInterpreter.ExecuteSafe; begin try Execute; except on e:RuntimeError do raise RuntimeError.Create(e.Message +' at '+ Bytecode.DocPos[pc-1].ToString); end; end; procedure TInterpreter.Execute; var op: TOperation; index,tmp,right: TEpObject; begin pc := 0; while True do begin CollectGarbage(); op := Bytecode.Code[pc]; Inc(pc); case op.code of LOAD: frame.Push(bytecode.Variables[op.arg]); LOAD_CONST: frame.Push(bytecode.Constants[op.arg]); STORE_FAST: bytecode.Variables[op.arg] := frame.Pop; DISCARD_TOP: frame.Pop(); COPY_FAST: Frame.SetTop(frame.Top.Copy()); (* jumps *) JMP_IF_FALSE: if (not frame.pop().AsBool) then pc := op.arg; JMP_IF_TRUE: if (frame.pop().AsBool) then pc := op.arg; JUMP, JMP_BACK, JMP_FORWARD: pc := op.arg; (* ... *) ASGN: begin right := frame.Pop(); frame.Pop.ASGN(right, bytecode.Variables[op.arg]); end; RASGN: begin frame.Pop().ASGN(frame.Pop(), bytecode.Variables[op.arg]); end; BUILD_LIST: BuildList(bytecode.Variables[op.arg]); (* Inc/Dec operators *) UNARY_PREINC: begin frame.Pop.PREINC(bytecode.Variables[op.arg]); frame.Push(bytecode.Variables[op.arg]); end; UNARY_PREDEC: begin frame.Pop.PREDEC(bytecode.Variables[op.arg]); frame.Push(bytecode.Variables[op.arg]); end; UNARY_POSTINC: begin frame.Pop.POSTINC(bytecode.Variables[op.arg]); frame.Push(bytecode.Variables[op.arg]); end; UNARY_POSTDEC: begin frame.Pop.POSTDEC(bytecode.Variables[op.arg]); frame.Push(bytecode.Variables[op.arg]); end; (* inplace assignment operators *) INPLACE_ADD: begin right := frame.Pop(); frame.Pop.INPLACE_ADD(right); end; INPLACE_SUB: begin right := frame.Pop(); frame.Pop().INPLACE_SUB(right); end; INPLACE_MUL: begin right := frame.Pop(); frame.Pop().INPLACE_MUL(right); end; INPLACE_DIV: begin right := frame.Pop(); frame.Pop().INPLACE_DIV(right); end; (* unary operations *) UNARY_SUB: begin Frame.Top.UNARY_SUB(bytecode.Variables[op.arg]); Frame.SetTop(bytecode.Variables[op.arg]); end; UNARY_NOT: begin Frame.Top.LOGIC_NOT(bytecode.Variables[op.arg]); Frame.SetTop(bytecode.Variables[op.arg]); end; UNARY_BINV: begin Frame.Top.UNARY_INV(bytecode.Variables[op.arg]); Frame.SetTop(bytecode.Variables[op.arg]); end; (* arithmetic operations *) BIN_ADD: begin right := frame.Pop(); frame.Top.add(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_SUB: begin right := frame.Pop(); frame.Top.sub(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_MUL: begin right := frame.Pop(); frame.Top.MUL(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_DIV: begin right := frame.Pop(); frame.Top.IDIV(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_FDIV: begin right := frame.Pop(); frame.Top.FDIV(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_MOD: begin right := frame.Pop(); frame.Top.MODULO(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; (* equality operations *) BIN_EQ: begin right := frame.Pop(); frame.Top.EQ(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_NE: begin right := frame.Pop(); frame.Top.NE(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_LT: begin right := frame.Pop(); frame.Top.LT(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_GT: begin right := frame.Pop(); frame.Top.GT(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_LE: begin right := frame.Pop(); frame.Top.LE(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_GE: begin right := frame.Pop(); frame.Top.GE(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; (* logical operators *) BIN_AND: begin right := frame.Pop(); frame.Top.LOGIC_AND(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_OR: begin right := frame.Pop(); frame.Top.LOGIC_OR(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; (* bitwise *) BIN_BAND: begin right := frame.Pop(); frame.Top.BAND(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_BOR: begin right := frame.Pop(); frame.Top.BOR(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; BIN_BXOR: begin right := frame.Pop(); frame.Top.BXOR(right, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; (* indexable *) GET_ITEM: begin frame.Pop.GET_ITEM(frame.Top, bytecode.Variables[op.arg]); frame.SetTop(bytecode.Variables[op.arg]); end; SET_ITEM: begin index := frame.Pop(); frame.Pop.SET_ITEM(index, frame.Pop()); end; (* other *) CALL: begin tmp := Frame.Pop(); (*if tmp is TNativeFuncObject then begin args := *pop arguments* (count = TNativeFuncObject(tmp).Parms) tmp := TNativeFuncObject(tmp).value(args); if tmp = nil then Frame.Push(bytecode.Constants[0]) else Frame.Push(tmp); end else *) begin CallFunction(tmp as TFuncObject, PC); pc := TFuncObject(tmp).codePos; end; end; PRINT: PrintStatement(op.arg); TIMENOW: begin tmp := Bytecode.GC.AllocFloat(MarkTime()); Frame.Push(tmp); end; RETURN: begin if CallStack.StackPos >= 0 then begin Frame.SetTop(frame.Top.Copy()); CallStack.Reset(pc, bytecode.Variables) end else Exit; end; else raise Exception.Create('Operation not implemented'); end; end; end; (* The code runs.. but a tad slow.. *) procedure TInterpreter.CallFunction(func:TFuncObject; counter:Int32); var i:Int32; locals:TObjectArray; begin SetLength(locals, func.VarRange.High - func.VarRange.Low + 1); for i:=func.VarRange.Low to func.VarRange.High do begin locals[i-func.VarRange.Low] := Bytecode.Variables[i]; Bytecode.Variables[i] := Bytecode.Constants[0]; end; CallStack.Push(locals, counter, func.VarRange.Low); end; procedure TInterpreter.BuildList(var dest:TEpObject); var arr :TObjectArray; argCount:TIntObject; i:Int32; begin argCount := Frame.Pop() as TIntObject; SetLength(arr, argCount.value); for i:=1 to argCount.value do arr[argCount.value-i] := Frame.Pop.Copy(); Bytecode.GC.Release(dest); dest := Bytecode.GC.AllocList(arr); Frame.Push(dest); end; procedure TInterpreter.PrintStatement(n:Int32); var arr: TObjectArray; i:Int32; begin SetLength(arr, n); for i:=1 to n do arr[n-i] := Frame.Pop; PrintFunc(arr); end; (* function Interpret(source:String): TFrame; begin bc := CompileAST(Parse(source)); Result := Frame(bc); //for tests and later introspection Execute(Result, bc); end;*) end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmDatabaseLinkProperties; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GenelDM, OraDBLink, VirtualTable, frmBaseform, dxBar, cxMemo, cxRichEdit, cxLabel, cxContainer, cxEdit, cxTextEdit, jpeg, cxPC, cxControls, StdCtrls, ExtCtrls; type TDatabaseLinkPropertiesFrm = class(TBaseform) Panel1: TPanel; imgToolBar: TImage; lblDescription: TLabel; pcSequenceProperties: TcxPageControl; tsSequenceDetails: TcxTabSheet; dxBarDockControl1: TdxBarDockControl; edtOwner: TcxTextEdit; cxLabel1: TcxLabel; cxLabel2: TcxLabel; edtUserName: TcxTextEdit; cxLabel3: TcxLabel; edtHost: TcxTextEdit; cxLabel8: TcxLabel; edtDBLink: TcxTextEdit; cxLabel5: TcxLabel; edtCreated: TcxTextEdit; tsSequenceScripts: TcxTabSheet; redtDDL: TcxRichEdit; dxBarManager1: TdxBarManager; bbtnCreateDBLink: TdxBarButton; bbtnDropDBLink: TdxBarButton; bbtnRefreshDBLink: TdxBarButton; bbtnAlterDBLink: TdxBarButton; procedure bbtnCreateDBLinkClick(Sender: TObject); procedure bbtnAlterDBLinkClick(Sender: TObject); procedure bbtnRefreshDBLinkClick(Sender: TObject); procedure bbtnDropDBLinkClick(Sender: TObject); private { Private declarations } FDBLinkName, FOwner: string; DBLink: TDBLink; procedure GetDBLink; procedure GetDBLinkDetail; public { Public declarations } procedure Init(ObjName, OwnerName: string); override; end; var DatabaseLinkPropertiesFrm: TDatabaseLinkPropertiesFrm; implementation {$R *.dfm} uses frmSchemaBrowser, Util, OraStorage, frmSchemaPublicEvent, frmDatabaseLinkDetail, VisualOptions; procedure TDatabaseLinkPropertiesFrm.Init(ObjName, OwnerName: string); begin inherited Show; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); top := 0; left := 0; FDBlinkName := ObjName; FOwner := OwnerName; GetDBLink; end; procedure TDatabaseLinkPropertiesFrm.GetDBLink; begin if DBLink <> nil then FreeAndNil(DBLink); DBLink := TDBLink.Create; DBLink.OraSession := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession; DBLink.DB_LINK := FDBlinkName; DBLink.OWNER := FOwner; DBLink.SetDDL; lblDescription.Caption := DBLink.Status; GetDBLinkDetail; redtDDL.Text := DBLink.GetDDL; CodeColors(self, 'Default', redtDDL, false); end; procedure TDatabaseLinkPropertiesFrm.GetDBLinkDetail; begin edtOwner.Text := DBLink.OWNER; edtDBLink.Text := DBLink.DB_LINK; edtUserName.Text := DBLink.USER_NAME; edtHost.Text := DBLink.HOST; edtCreated.Text := DBLink.CREATED; end; procedure TDatabaseLinkPropertiesFrm.bbtnCreateDBLinkClick( Sender: TObject); var FDBLink : TDBLink; begin FDBLink := TDBLink.Create; FDBLink.OraSession := DBLink.OraSession; FDBLink.Mode := InsertMode; if DatabaseLinkDetailFrm.Init(FDBLink) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbDatabaseLinks); end; procedure TDatabaseLinkPropertiesFrm.bbtnAlterDBLinkClick(Sender: TObject); begin if DBLink = nil then exit; if DBLink.DB_LINK = '' then exit; DBLink.Mode := UpdateMode; if DatabaseLinkDetailFrm.Init(DBLink) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbDatabaseLinks); end; procedure TDatabaseLinkPropertiesFrm.bbtnRefreshDBLinkClick( Sender: TObject); begin GetDBLink; end; procedure TDatabaseLinkPropertiesFrm.bbtnDropDBLinkClick(Sender: TObject); begin if DBLink = nil then exit; if DBLink.DB_LINK = '' then exit; if SchemaPublicEventFrm.Init(DBLink, oeDrop) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbDatabaseLinks); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerSequence; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpCryptoLibTypes, ClpDerOutputStream, ClpIProxiedInterface, ClpAsn1Tags, ClpIAsn1EncodableVector, ClpAsn1Sequence, ClpIDerSequence; type TDerSequence = class(TAsn1Sequence, IDerSequence) strict private class var FEmpty: IDerSequence; class constructor DerSequence(); class function GetEmpty: IDerSequence; static; inline; public class function FromVector(const v: IAsn1EncodableVector) : IDerSequence; static; /// <summary> /// create an empty sequence /// </summary> constructor Create(); overload; /// <summary> /// create a sequence containing one object /// </summary> constructor Create(const obj: IAsn1Encodable); overload; constructor Create(const v: array of IAsn1Encodable); overload; /// <summary> /// create a sequence containing a vector of objects. /// </summary> constructor Create(const v: IAsn1EncodableVector); overload; destructor Destroy(); override; /// <summary> /// A note on the implementation: <br />As Der requires the constructed, /// definite-length model to <br />be used for structured types, this /// varies slightly from the <br />ASN.1 descriptions given. Rather than /// just outputing Sequence, <br />we also have to specify Constructed, /// and the objects length. <br /> /// </summary> procedure Encode(const derOut: TStream); override; class property Empty: IDerSequence read GetEmpty; end; implementation { TDerSequence } class function TDerSequence.GetEmpty: IDerSequence; begin result := FEmpty; end; constructor TDerSequence.Create(const obj: IAsn1Encodable); begin Inherited Create(1); AddObject(obj); end; constructor TDerSequence.Create; begin Inherited Create(0); end; constructor TDerSequence.Create(const v: IAsn1EncodableVector); var ae: IAsn1Encodable; LListAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>; begin Inherited Create(v.Count); LListAsn1Encodable := v.GetEnumerable; for ae in LListAsn1Encodable do begin AddObject(ae); end; end; constructor TDerSequence.Create(const v: array of IAsn1Encodable); var ae: IAsn1Encodable; begin Inherited Create(System.Length(v)); for ae in v do begin AddObject(ae); end; end; class constructor TDerSequence.DerSequence; begin FEmpty := TDerSequence.Create(); end; destructor TDerSequence.Destroy; begin inherited Destroy; end; procedure TDerSequence.Encode(const derOut: TStream); var bOut: TMemoryStream; dOut: TDerOutputStream; obj: IAsn1Encodable; bytes: TCryptoLibByteArray; LListAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>; begin // TODO Intermediate buffer could be avoided if we could calculate expected length bOut := TMemoryStream.Create(); dOut := TDerOutputStream.Create(bOut); try LListAsn1Encodable := Self.GetEnumerable; for obj in LListAsn1Encodable do begin dOut.WriteObject(obj); end; System.SetLength(bytes, bOut.Size); bOut.Position := 0; bOut.Read(bytes[0], bOut.Size); finally bOut.Free; dOut.Free; end; (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.Sequence or TAsn1Tags.Constructed, bytes); end; class function TDerSequence.FromVector(const v: IAsn1EncodableVector) : IDerSequence; begin if v.Count < 1 then begin result := Empty; end else begin result := TDerSequence.Create(v); end; end; end.
unit ThreadReportBase; interface uses Classes, dbisamtb, ReportGen, FFSProcessTable, TicklerTypes; type TRptStatus = (rsNone, rsDone, rsProblem, rsScan, rsReport, rsNMSR, rsDelCat); TThdReportBase = class(TThread) private tblProcess : TFFSProcessTable; ModNum : int64; // used to determine update frequency ScanCount, TotalCount, FoundCount: int64; CurrentStatus : TRptStatus; { Private declarations } protected pSession : TdbisamSession; pSessionTag : TdbisamSession; dbase : TdbIsamDatabase; dbaseTag : TdbIsamDatabase; rg : TReportGen; ReportID : integer; FAbortProcess : boolean; rptOptions : TReportOptions; OptionList : TStringList; rptRec : TFFSProcessRecord; StartTimeStamp : string; procedure Execute; override; procedure UpdateStatus(AStatus:TRptStatus;More:string = ''); procedure ResetCounter(TotalRecords:int64); function GetFoundCount:int64; procedure FoundOne; procedure ScanOne(More:string=''); procedure SetPercent(pct:integer); procedure GetProcessRecord; public constructor create(ARptID:integer;DoOnTerminate:TNotifyEvent); virtual; destructor destroy; override; end; implementation uses sysutils, FFSUtils, programsettings; { TThdReportBase } procedure TThdReportBase.GetProcessRecord; begin if not tblProcess.FindKey([ReportID]) then raise exception.create('Report ID Not Found'); rptRec := tblProcess.GetDataBuffer; OptionList.Text := tblProcess.FieldByName('Options').AsString; ReportRecordToReportOpions(rptRec, OptionList.Text, RptOptions); end; constructor TThdReportBase.create(ARptID:integer;DoOnTerminate:TNotifyEvent); begin inherited create(true); // save the start time StartTimeStamp := DateTimeStamp; // Local inits ModNum := 10; FoundCount := 0; ScanCount := 0; TotalCount := 0; CurrentStatus := rsNone; // priority := tpLowest; FreeOnTerminate := true; OnTerminate := DoOnTerminate; ReportID := ARptID; // Create The report generator rg := TReportGen.create(nil); rg.MarginTop := 0.5; rg.MarginBottom := 0.5; rg.PageLength := 11; rg.Paging := true; // private session 1 pSession := TDBISAMSession.Create(nil); pSession.AutoSessionName := true; pSession.StrictChangeDetection := false; pSession.Open; // private session 2 - because it is using transactions pSessionTag := TDBISAMSession.Create(nil); pSessionTag.AutoSessionName := true; pSessionTag.Open; // Database 1 dbase := TDBISAMDatabase.Create(pSession); dbase.SessionName := pSession.SessionName; dbase.DatabaseName := 'dbase' + pSession.SessionName; dbase.Directory := dir(drData); dbase.Connected := true; // Database 2 dbaseTag := TDBISAMDatabase.Create(pSessionTag); dbaseTag.SessionName := pSessionTag.SessionName; dbaseTag.DatabaseName := 'dbaseTag' + pSessionTag.SessionName; dbaseTag.Directory := dir(drReports); dbaseTag.Connected := true; // Report Run Table OptionList := TStringList.create; tblProcess := TFFSProcessTable.create(pSession, dbase, 'PROCESS'); tblProcess.open; GetProcessRecord; end; destructor TThdReportBase.destroy; begin OptionList.free; // free session // the sessions were created with a nil parent so they need to be destroyed explicitly // the databases and tables do not need to be explicitly destroyed because they will be destroyed when // the parents(sessions) are freed. pSession.free; pSessionTag.free; // free others rg.free; inherited; end; procedure TThdReportBase.UpdateStatus(AStatus:TRptStatus;More:string); var pct : string; ok : boolean; begin tblProcess.refresh; if tblProcess.PStopStatus = 'ABORTED' then FAbortProcess := true; if TotalCount > 0 then pct := inttostr((ScanCount * 100) div TotalCount) else pct := '0'; ok := false; repeat tblProcess.Refresh; try tblProcess.edit; ok := true; except // keep trying end; until ok; // got the lock CurrentStatus := AStatus; case AStatus of rsDelCat : begin tblProcess.PControlStatus := 'T' + pct; tblProcess.PControlScanMsg := More + ' ' + inttostr(ScanCount) + '/' + inttostr(TotalCount); tblProcess.PControlMsg := More; end; rsNMSR : begin tblProcess.PControlStatus := 'T' + pct; tblProcess.PControlScanMsg := More + ' ' + inttostr(ScanCount) + '/' + inttostr(TotalCount); tblProcess.PControlMsg := More; end; rsScan : begin tblProcess.PControlStatus := 'T' + pct; tblProcess.PControlScanMsg := 'Scan ' + inttostr(ScanCount) + '/' + inttostr(TotalCount) + ' Found ' + inttostr(FoundCount); tblProcess.PControlMsg := More; end; rsReport : begin tblProcess.Pcontrolstatus := 'R' + pct; tblProcess.PControlScanMsg := 'Preparing ' + inttostr(ScanCount) + '/' + inttostr(TotalCount); tblProcess.PControlMsg := More; end; rsDone : begin tblProcess.PControlStatus := 'DONE'; tblProcess.PControlScanMsg := 'Processed ' + inttostr(TotalCount) + ' Records'; tblProcess.PControlMsg := More; tblProcess.PStop := DateTimeStamp; if not FAbortProcess then tblProcess.PStopStatus := 'DONE'; end; rsProblem: begin tblProcess.PControlStatus := 'PROBLEM'; tblProcess.PControlScanMsg := 'Stopped Processing at ' + inttostr(ScanCount) + ' of ' + inttostr(TotalCount); tblProcess.PControlMsg := More; tblProcess.PStop := DateTimeStamp; if not FAbortProcess then tblProcess.PStopStatus := 'PROBLEM'; end; end; tblProcess.post; end; procedure TThdReportBase.Execute; begin { Place thread code here } end; procedure TThdReportBase.FoundOne; begin inc(FoundCount); end; procedure TThdReportBase.ScanOne(More:string=''); begin inc(ScanCount); if (ScanCount mod ModNum) = 0 then UpdateStatus(CurrentStatus,More); end; procedure TThdReportBase.ResetCounter(TotalRecords: int64); begin TotalCount := TotalRecords; ModNum := TotalCount div 100; if ModNum > 100 then ModNum := 100; if ModNum = 0 then ModNum := 5; FoundCount := 0; ScanCount := 0; end; procedure TThdReportBase.SetPercent(pct: integer); begin ScanCount := pct; end; function TThdReportBase.GetFoundCount: int64; begin result := FoundCount; end; end.
unit GX_DesignerMenu; {$I GX_CondDefine.inc} interface uses Classes, DesignIntf, DesignMenus; type TGxDesignerMenu = class(TBaseSelectionEditor, ISelectionEditor) Indexes: array of Integer; procedure ExecuteVerb(Index: Integer; const List: IDesignerSelections); function GetVerb(Index: Integer): string; function GetVerbCount: Integer; procedure PrepareItem(Index: Integer; const AItem: IMenuItem); procedure RequiresUnits(Proc: TGetStrProc); end; implementation uses GX_GExperts, GX_Experts; { TGxSelectionEditor } procedure TGxDesignerMenu.ExecuteVerb(Index: Integer; const List: IDesignerSelections); begin GExpertsInst.ExpertList[Indexes[Index]].Execute(Self); end; function TGxDesignerMenu.GetVerb(Index: Integer): string; begin Result := GExpertsInst.ExpertList[Indexes[Index]].GetActionCaption; end; function TGxDesignerMenu.GetVerbCount: Integer; var i: Integer; Expert: TGX_Expert; begin Result := 0; SetLength(Indexes, GExpertsInst.ExpertCount); for i := 0 to GExpertsInst.ExpertCount - 1 do begin Expert := GExpertsInst.ExpertList[i]; if Expert.Active and Expert.HasDesignerMenuItem then begin Indexes[Result] := i; Inc(Result); end; end; end; procedure TGxDesignerMenu.PrepareItem(Index: Integer; const AItem: IMenuItem); begin GExpertsInst.ExpertList[Indexes[Index]].DoUpdateAction; AItem.Visible := GExpertsInst.ExpertList[Indexes[Index]].GetActionEnabled; end; procedure TGxDesignerMenu.RequiresUnits(Proc: TGetStrProc); begin // FI:W519 // Nothing end; initialization RegisterSelectionEditor(TComponent, TGxDesignerMenu); end.
{$apptype console} {$product KTX Console Manager 2.0} {$company Kotov Projects} {$copyright Alexandr Kotov} ///Модуль для удобной работы с консолью unit KTX; const ///Название модуля Name = 'KTX Console Manager'; ///Версия модуля Version: record Major, Minor: integer; end = (Major: 2; Minor: 0); function StrVersion := $'{version.Major}.{version.Minor}'; function StrFull := $'{Name} {StrVersion}'; type ///Тип цвета консоли Color = System.ConsoleColor; const ///Чёрный Black = Color.Black; ///Тёмно-синий DarkBlue = Color.DarkBlue; ///Тёмно-зелёный DarkGreen = Color.DarkGreen; ///Тёмно-бирюзовый DarkCyan = Color.DarkCyan; ///Тёмно-красный DarkRed = Color.DarkRed; ///Тёмно-пурпурный DarkMagenta = Color.DarkMagenta; ///Тёмно-жёлтый DarkYellow = Color.DarkYellow; ///Серый Gray = Color.Gray; ///Тёмно-серый DarkGray = Color.DarkGray; ///Синий Blue = Color.Blue; ///Зелёный Green = Color.Green; ///Бирюзовый Cyan = Color.Cyan; ///Красный Red = Color.Red; ///Пурпурный Magenta = Color.Magenta; ///Жёлтый Yellow = Color.Yellow; ///Белый White = Color.White; type Console = static class private const Err1: string = 'Window size too small'; public static procedure SetTitle(s: string); begin System.Console.Title:=s; end; public static property Title: string read System.Console.Title write SetTitle; internal static procedure Pre; begin System.Console.CursorVisible:=true; end; internal static procedure After; begin System.Console.CursorVisible:=false; end; private static IsInit: boolean; private static _MinimalWidth: integer = 100; private static _MinimalHeight: integer = 30; ///Минимально-допустимое значение ширины экрана public static property MinimalWidth: integer read _MinimalWidth; ///Минимально-допустимое значение высоты экрана public static property MinimalHeight: integer read _MinimalHeight; ///Задаёт минимально-допустимые значения ширины и высоты экрана public static procedure SetMinimal(x, y: integer); begin _MinimalWidth:=x; _MinimalHeight:=y; end; private static _width: integer = 100; private static _height: integer = 30; private static _cfore: Color = Black; private static _cback: Color = White; private static _cdisable: Color = Gray; private static _cerr: Color = Red; private static _ctrue: Color = DarkGreen; private static _cfalse: Color = Red; ///Действительное значение цвета бэкграунда консоли public static property RealBack: Color read System.Console.BackgroundColor; ///Действительное значение цвета текста консоли public static property RealFore: Color read System.Console.ForegroundColor; ///Стандартное значение цвета текста консоли public static property ColorFore: Color read _cfore; ///Стандартное значение цвета бэкграунда консоли public static property ColorBack: Color read _cback; ///Стандартное значение цвета недоступного текста консоли public static property ColorDisable: Color read _cdisable; ///Стандартное значение цвета текста ошибок консоли public static property ColorError: Color read _cerr; ///Стандартное значение цвета текста истинных значений консоли public static property ColorTrue: Color read _ctrue; ///Стандартное значение цвета текста ложных значений консоли public static property ColorFalse: Color read _cfalse; ///Действительная высота окна консоли public static property RealHeight: integer read System.Console.WindowHeight; ///Действительная ширина окна консоли public static property RealWidth: integer read System.Console.WindowWidth; ///Высота окна консоли public static property Height: integer read _height; ///Ширина окна консоли public static property Width: integer read _width; ///Максимально-возможная высота окна консоли public static property MaxHeight: integer read System.Console.LargestWindowHeight; ///Максимально-возможная ширина окна консоли public static property MaxWidth: integer read System.Console.LargestWindowWidth; ///Устанавливает положение курсора public static procedure SetCursorPosition(x,y: integer) := System.Console.SetCursorPosition(x,y); public static procedure SetPos(x, y: integer) := System.Console.SetCursorPosition(x, y); ///Очищает окно консоли, заливая его текущем цветом бэкграунда public static procedure Clear() := System.Console.Clear(); ///Задаёт размеры окна консоли текущими значениями ширины и высоты окна public static procedure SetWindowSize() := System.Console.SetWindowSize(_width, _height); ///Задаёт размеры окна консоли public static procedure SetWindowSize(x, y: integer); begin _width:=x; _height:=y; System.Console.SetWindowSize(x, y); end; ///Задаёт размер буфера консоли public static procedure SetBufferSize(x, y: integer) := System.Console.SetBufferSize(x, y); ///Задаёт размер буфера консоли public static procedure SetBufferSize(y: integer) := System.Console.SetBufferSize(_width,y); ///Изменяет цвет текста на цвет текста ошибок public static procedure SetFontError(); begin System.Console.ForegroundColor:=_cerr; end; ///Изменяет цвет текста на цвет недоступного текста public static procedure SetFontOff(); begin System.Console.ForegroundColor:=_cdisable; end; ///Изменяет цвет текста на стандартный public static procedure SetFontStandard(); begin System.Console.ForegroundColor:=_cfore; end; ///Изменяет цвет текста на цвет ложного текста public static procedure SetFontFalse(); begin System.Console.ForegroundColor:=_cfalse; end; ///Изменяет цвет текста на цвет истинного текста public static procedure SetFontTrue(); begin System.Console.ForegroundColor:=_ctrue; end; ///Изменяет цвет текста на цвет текста по a public static procedure SetFontBool(a: boolean); begin if a then SetFontTrue() else SetFontFalse(); end; ///Обновляет размеры консоли ///Рекомендуется использовать на каждой итерации цикла public static procedure Resize(); begin while (Console.MaxWidth<Console.MinimalWidth) or (Console.MaxHeight<Console.MinimalHeight) do begin Clear(); SetFontError(); write(Err1); sleep(100); SetFontStandard(); end; if not ((Console.Width<=Console.MaxWidth) and (Console.Height<=Console.MaxHeight)) then begin _width:=Console.MaxWidth; _height:=Console.MaxHeight; SetWindowSize(); end; Clear(); if (Console.RealHeight>console.Height) or (Console.RealWidth>console.Width) then System.Console.SetWindowSize(1,1); Console.SetBufferSize(Width,Height); Console.SetWindowSize(Width,Height); end; ///Изменяет размер буфера исходя из start и size public static procedure Resize(start, size: integer); begin if size>=(_Height-start) then Console.SetBufferSize(size+start); end; ///Инициализирует стандартные значения public static procedure Init; begin System.Console.BackgroundColor:=_cback; System.Console.ForegroundColor:=_cfore; System.Console.SetWindowSize(1,1); System.Console.SetBufferSize(_width, _height); System.Console.SetWindowSize(_width, _height); IsInit:=true; end; public static procedure Draw(params o: array of object); begin for var i:=0 to o.Length-1 do begin match o[i] with Color(var c): System.Console.ForegroundColor:=c; else write(o[i].ToString); end; end; end; public static procedure DrawOn(x, y: integer; params o: array of object); begin Console.SetCursorPosition(x,y); write(o); end; public static procedure DrawLnOn(x, y: integer; params o: array of object); begin Console.SetCursorPosition(x,y); writeln(o); end; end; Block = class ///-- private const Zero: integer = integer.MinValue; ///-- private const Null: string = ''; ///-- private _input: string; ///-- private _output: integer; ///-- private _status: boolean; ///Изменяет вывод public procedure SetOut(a: integer); begin _output:=a; end; ///Ввод public property Input: string read _input; ///Вывод public property Output: integer read _output write SetOut; ///Состояние public property Status: boolean read _status; ///-- public static function operator implicit(a: Block): boolean := a._status; ///Переводит Status в false public procedure Close(); begin _status:=false; end; ///Создаёт новый экземпляр класса KTX.Block public constructor Create(); begin if not Console.IsInit then Console.Init; _input:=Null; _output:=Zero; _status:=true; end; ///Обнуляет ввод и вывод public procedure Reload(); begin Console.Resize; _input:=Null; _output:=Zero; end; ///Ввод public procedure Read(); begin Console.Pre; var s: string = ''; while (s='') and ((Console.RealHeight=Console.Height) and (Console.RealWidth=Console.Width)) do begin Console.SetCursorPosition(1,Console.Height-2);write(': '); readln(s); end; _input:=s; Console.After; end; ///Ввод при изменении размера public procedure ReadWithResize(start, size: integer); begin Console.Pre; var s: string = ''; while (s='') and ((Console.RealHeight=Console.Height) and (Console.RealWidth=Console.Width)) do begin if size>=(Console.Height-start) then begin Console.SetCursorPosition(1,size+start-1); Console.SetCursorPosition(1,size+start-2); end else Console.SetCursorPosition(1,Console.Height-2); write(': '); readln(s); end; _input:=s; Console.After; end; public function ToString: string; override := _input; end; ConvertColor = static class public static function ColorToInt(a: Color): byte := Ord(a); public static function IntToColor(a: byte): Color := Color(integer(a)); public static function ColorToHex(a: Color): string := ColorToInt(a).ToString('X'); public static function HexToColor(s: string): Color := IntToColor(System.Convert.ToInt32(s,16)); end; DrawBox = class public PosX, PosY: integer; public Back, Fore: Color; public Symbol: char; public constructor (x,y: integer; c: char; B, F: Color); begin PosX:=x; PosY:=y; Back:=B; Fore:=F; Symbol:=c; end; //public static function Parse(s: string): DrawBox := new DrawBox(s); public function ToString: string; override := $'{Symbol}{ConvertColor.ColorToHex(Back)}{ConvertColor.ColorToHex(Fore)}'; end; DrawBoxFile = record x, y: integer; c: char; b, f: byte; public constructor; begin end; public constructor (a: DrawBox); begin x:=a.PosX; y:=a.PosY; c:=a.Symbol; b:=ConvertColor.ColorToInt(a.Back); f:=ConvertColor.ColorToInt(a.Fore); end; public function ToDrawBox: DrawBox; begin Result:=new DrawBox(x,y,c,ConvertColor.IntToColor(b),ConvertColor.IntToColor(f)); end; end; DrawBoxBlock = class public SizeX, SizeY: integer; public Background: Color; public Draws: array of DrawBox; public constructor (x, y: integer; b: Color; arr: array of DrawBox); begin SizeX:=x; SizeY:=y; Background:=b; Draws:=arr; end; public constructor (name: string); begin var f: file; reset(f,name); Read(f,SizeX); Read(f,SizeY); var a1: byte; var a2: integer; Read(f,a1); Read(f,a2); Background:=ConvertColor.IntToColor(a1); Draws:=new DrawBox[a2]; for var i:=0 to Draws.Length-1 do begin var a3: DrawBoxFile; Read(f,a3); Draws[i]:=a3.ToDrawBox; end; f.Close; end; public procedure WriteKTXFile(name: string); begin var f: file; rewrite(f,name); f.Write(SizeX); f.Write(SizeY); f.Write(ConvertColor.ColorToInt(Background)); f.Write(Draws.Length); for var i:=0 to Draws.Length-1 do begin f.Write(new DrawBoxFile(Draws[i])); end; f.Close; end; end; Drawing = static class public static function GetStartPos(a: DrawBoxBlock): (integer, integer); begin var x:=abs(a.SizeX-Console.Width) div 2; var y:=abs(a.SizeY-Console.Height) div 2; Result:=(x,y); end; ///Полный вывод всей картинки public static procedure DrawAll(a: DrawBoxBlock); begin var t:=GetStartPos(a); var (x, y):=t; System.Console.BackgroundColor:=a.Background; Console.Clear; for var i:=0 to a.Draws.Length-1 do begin Console.SetCursorPosition(a.Draws[i].PosX+x,a.Draws[i].PosY+y); System.Console.BackgroundColor:=a.Draws[i].Back; System.Console.ForegroundColor:=a.Draws[i].Fore; write(a.Draws[i].Symbol); end; end; ///Быстрый вывод по цветам заднего фона консоли public static procedure HexDraw(a: DrawBoxBlock); begin var t:=GetStartPos(a); var (x, y):=t; System.Console.BackgroundColor:=a.Background; Console.Clear; var aa: array[1..16] of array of DrawBox; for var i:=1 to 16 do begin aa[i]:=a.Draws.Where(x -> ConvertColor.ColorToInt(x.Back)=i-1).ToArray; end; for var i:=1 to 16 do begin System.Console.BackgroundColor:=ConvertColor.IntToColor(i-1); if aa[i]<>nil then begin for var j:=0 to aa[i].Length-1 do begin Console.SetCursorPosition(aa[i][j].PosX+x,aa[i][j].PosY+y); System.Console.ForegroundColor:=aa[i][j].Fore; write(aa[i][j].Symbol); end; end; end; end; ///Медленнее обычного HexDraw, но окажется гораздо быстрее, если в DrawBox'ах используется один и тот же цвет текста public static procedure HexDrawWithSearch(a: DrawBoxBlock); begin var t:=GetStartPos(a); var (x, y):=t; System.Console.BackgroundColor:=a.Background; Console.Clear; var aa: array[1..16] of array of DrawBox; for var i:=1 to 16 do begin aa[i]:=a.Draws.Where(x -> ConvertColor.ColorToInt(x.Back)=i-1).ToArray; end; for var i:=1 to 16 do begin System.Console.BackgroundColor:=ConvertColor.IntToColor(i-1); if aa[i]<>nil then begin for var j:=0 to aa[i].Length-1 do begin Console.SetCursorPosition(aa[i][j].PosX+x,aa[i][j].PosY+y); if Console.RealFore<>aa[i][j].Fore then System.Console.ForegroundColor:=aa[i][j].Fore; write(aa[i][j].Symbol); end; end; end; end; end; begin end.
unit uDepartamentoAcessoVO; interface uses System.SysUtils, uKeyField, uTableName; type [TableName('Departamento_Acesso')] TDepartamentoAcessoVO = class private FExcluir: Boolean; FIdDepartamento: Integer; FIncluir: Boolean; FId: Integer; FPrograma: Integer; FRelatorio: Boolean; FAcesso: Boolean; FEditar: Boolean; procedure SetAcesso(const Value: Boolean); procedure SetEditar(const Value: Boolean); procedure SetExcluir(const Value: Boolean); procedure SetId(const Value: Integer); procedure SetIdDepartamento(const Value: Integer); procedure SetIncluir(const Value: Boolean); procedure SetPrograma(const Value: Integer); procedure SetRelatorio(const Value: Boolean); public [KeyField('DepAc_Id')] property Id: Integer read FId write SetId; [FieldName('DepAc_Departamento')] property IdDepartamento: Integer read FIdDepartamento write SetIdDepartamento; [FieldName('DepAc_Programa')] property Programa: Integer read FPrograma write SetPrograma; [FieldName('DepAc_Acesso')] property Acesso: Boolean read FAcesso write SetAcesso; [FieldName('DepAc_Incluir')] property Incluir: Boolean read FIncluir write SetIncluir; [FieldName('DepAc_Editar')] property Editar: Boolean read FEditar write SetEditar; [FieldName('DepAc_Excluir')] property Excluir: Boolean read FExcluir write SetExcluir; [FieldName('DepAc_Relatorio')] property Relatorio: Boolean read FRelatorio write SetRelatorio; end; implementation { TDepartamentoAcessoVO } procedure TDepartamentoAcessoVO.SetAcesso(const Value: Boolean); begin FAcesso := Value; end; procedure TDepartamentoAcessoVO.SetEditar(const Value: Boolean); begin FEditar := Value; end; procedure TDepartamentoAcessoVO.SetExcluir(const Value: Boolean); begin FExcluir := Value; end; procedure TDepartamentoAcessoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TDepartamentoAcessoVO.SetIdDepartamento(const Value: Integer); begin FIdDepartamento := Value; end; procedure TDepartamentoAcessoVO.SetIncluir(const Value: Boolean); begin FIncluir := Value; end; procedure TDepartamentoAcessoVO.SetPrograma(const Value: Integer); begin FPrograma := Value; end; procedure TDepartamentoAcessoVO.SetRelatorio(const Value: Boolean); begin FRelatorio := Value; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.IO, RemObjects.Elements.EUnit; type PathTest = public class (Test) private property FolderPath: String read Folder.UserLocal.Path; public method ChangeExtension; method Combine; method GetParentDirectory; method GetExtension; method GetFileName; method GetFileNameWithoutExtension; method RemoveExtension; end; implementation method PathTest.ChangeExtension; begin Assert.AreEqual(Path.ChangeExtension("1.txt", "jpg"), "1.jpg"); Assert.AreEqual(Path.ChangeExtension("1.txt.jpg", "zip"), "1.txt.zip"); Assert.AreEqual(Path.ChangeExtension("1", "txt"), "1.txt"); Assert.AreEqual(Path.ChangeExtension("1", ".txt"), "1.txt"); Assert.AreEqual(Path.ChangeExtension("1.", "txt"), "1.txt"); Assert.AreEqual(Path.ChangeExtension("1.", ".txt"), "1.txt"); Assert.AreEqual(Path.ChangeExtension("", "txt"), ".txt"); Assert.AreEqual(Path.ChangeExtension("1", ""), "1"); Assert.AreEqual(Path.ChangeExtension("1.", ""), "1."); Assert.AreEqual(Path.ChangeExtension("1.txt", nil), "1"); Assert.AreEqual(Path.ChangeExtension(Path.Combine(FolderPath, "1.txt"), "jpg"), Path.Combine(FolderPath, "1.jpg")); Assert.Throws(->Path.ChangeExtension(nil, "")); end; method PathTest.Combine; begin Assert.AreEqual(Path.Combine("", "1.txt"), "1.txt"); Assert.AreEqual(Path.Combine(nil, "1.txt"), "1.txt"); Assert.AreEqual(Path.Combine(FolderPath, "1.txt"), FolderPath + Folder.Separator + "1.txt"); Assert.AreEqual(Path.Combine(FolderPath + Folder.Separator, "1.txt"), FolderPath + Folder.Separator + "1.txt"); Assert.AreEqual(Path.Combine(FolderPath, "Folder"), FolderPath + Folder.Separator + "Folder"); Assert.AreEqual(Path.Combine(FolderPath, ""), FolderPath); Assert.AreEqual(Path.Combine(FolderPath, nil), FolderPath); Assert.Throws(->Path.Combine(nil, nil)); Assert.Throws(->Path.Combine(nil, "")); Assert.Throws(->Path.Combine("", "")); Assert.Throws(->Path.Combine("", nil)); Assert.AreEqual(Path.Combine(FolderPath, "NewFolder", "1.txt"), FolderPath + Folder.Separator + "NewFolder" + Folder.Separator + "1.txt"); end; method PathTest.GetParentDirectory; begin Assert.AreEqual(Path.GetParentDirectory(Path.Combine("root", "1.txt")), "root"); Assert.AreEqual(Path.GetParentDirectory(Path.Combine("root", "folder1", "folder2")), Path.Combine("root", "folder1")); Assert.AreEqual(Path.GetParentDirectory(Path.Combine("root", "folder1")), "root"); Assert.IsNil(Path.GetParentDirectory("root")); Assert.IsNil(Path.GetParentDirectory("root" + Folder.Separator)); Assert.IsNil(Path.GetParentDirectory("1.txt")); Assert.IsNil(Path.GetParentDirectory("")); Assert.Throws(->Path.GetParentDirectory(nil)); end; method PathTest.GetExtension; begin Assert.AreEqual(Path.GetExtension("1.txt"), ".txt"); Assert.AreEqual(Path.GetExtension("1.txt.jpg"), ".jpg"); Assert.AreEqual(Path.GetExtension("1"), ""); Assert.AreEqual(Path.GetExtension("1."), ""); Assert.AreEqual(Path.GetExtension(Path.Combine(FolderPath, "1.txt")), ".txt"); Assert.Throws(->Path.GetExtension(nil)); end; method PathTest.GetFileName; begin Assert.AreEqual(Path.GetFileName("1.txt"), "1.txt"); Assert.AreEqual(Path.GetFileName(Folder.Separator + "1.txt"), "1.txt"); Assert.AreEqual(Path.GetFileName("1.txt.jpg"), "1.txt.jpg"); Assert.AreEqual(Path.GetFileName(""), ""); Assert.AreEqual(Path.GetFileName(Folder.Separator), ""); Assert.AreEqual(Path.GetFileName(Path.Combine("root", "folder1", "folder2")), "folder2"); Assert.AreEqual(Path.GetFileName(Path.Combine("root", "folder1")), "folder1"); Assert.AreEqual(Path.GetFileName("root"), "root"); Assert.AreEqual(Path.GetFileName("root" + Folder.Separator), "root"); Assert.AreEqual(Path.GetFileName(Path.Combine(FolderPath, "1.txt")), "1.txt"); Assert.Throws(->Path.GetFileName(nil)); end; method PathTest.GetFileNameWithoutExtension; begin Assert.AreEqual(Path.GetFileNameWithoutExtension("1.txt"), "1"); Assert.AreEqual(Path.GetFileNameWithoutExtension(Folder.Separator + "1.txt"), "1"); Assert.AreEqual(Path.GetFileNameWithoutExtension("1.txt.jpg"), "1.txt"); Assert.AreEqual(Path.GetFileNameWithoutExtension(""), ""); Assert.AreEqual(Path.GetFileNameWithoutExtension(Folder.Separator), ""); Assert.AreEqual(Path.GetFileNameWithoutExtension(Path.Combine(FolderPath, "1.txt")), "1"); Assert.Throws(->Path.GetFileNameWithoutExtension(nil)); end; method PathTest.RemoveExtension; begin Assert.AreEqual(Path.RemoveExtension("1.txt"), "1"); Assert.AreEqual(Path.RemoveExtension("1.txt.jpg"), "1.txt"); Assert.AreEqual(Path.RemoveExtension("1.1.txt"), "1.1"); Assert.AreEqual(Path.RemoveExtension("1."), "1"); Assert.AreEqual(Path.RemoveExtension("1"), "1"); Assert.AreEqual(Path.RemoveExtension(""), ""); Assert.Throws(->Path.RemoveExtension(nil)); 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.20 10/26/2004 11:08:10 PM JPMugaas Updated refs. Rev 1.19 27.08.2004 22:03:22 Andreas Hausladen Optimized encoders speed optimization ("const" for string parameters) Rev 1.18 24/08/2004 10:33:44 CCostelloe Was too slow (~45 mins for 2MB down to ~1sec) Rev 1.17 2004.05.20 1:39:22 PM czhower Last of the IdStream updates Rev 1.16 2004.05.20 11:37:10 AM czhower IdStreamVCL Rev 1.15 2004.05.20 11:13:14 AM czhower More IdStream conversions Rev 1.14 2004.05.19 3:06:54 PM czhower IdStream / .NET fix Rev 1.13 2/19/2004 11:52:02 PM JPMugaas Removed IFDEF's. Moved some functions into IdGlobalProtocols for reuse elsewhere. Rev 1.12 2004.02.03 5:45:00 PM czhower Name changes Rev 1.11 2004.02.03 2:12:06 PM czhower $I path change Rev 1.10 1/22/2004 3:59:14 PM SPerry fixed set problems Rev 1.9 11/10/2003 7:41:30 PM BGooijen Did all todo's ( TStream to TIdStream mainly ) Rev 1.8 2003.10.17 6:14:44 PM czhower Fix to match new IdStream Rev 1.7 2003.10.12 3:38:26 PM czhower Added path to .inc Rev 1.6 10/12/2003 1:33:42 PM BGooijen Compiles on D7 now too Rev 1.5 10/12/2003 12:02:50 PM BGooijen DotNet Rev 1.4 6/13/2003 12:07:44 PM JPMugaas QP was broken again. Rev 1.3 6/13/2003 07:58:50 AM JPMugaas Should now compile with new decoder design. Rev 1.2 6/13/2003 06:17:06 AM JPMugaas Should now compil,e. Rev 1.1 12.6.2003 ã. 12:00:28 DBondzhev Fix for . at the begining of new line Rev 1.0 11/14/2002 02:15:00 PM JPMugaas 2002-08-13/14 - Johannes Berg completely rewrote the Encoder. May do the Decoder later. The encoder will add an EOL to the end of the file if it had no EOL at start. I can't avoid this due to the design of IdStream.ReadLn, but its also no problem, because in transmission this would happen anyway. 9-17-2001 - J. Peter Mugaas made the interpretation of =20 + EOL to mean a hard line break soft line breaks are now ignored. It does not make much sense in plain text. Soft breaks do not indicate the end of paragraphs unlike hard line breaks that do end paragraphs. 3-24-2001 - J. Peter Mugaas Rewrote the Decoder according to a new design. 3-25-2001 - J. Peter Mugaas Rewrote the Encoder according to the new design } unit IdCoderQuotedPrintable; interface {$i IdCompilerDefines.inc} uses Classes, IdCoder, IdStream, SysUtils; type TIdDecoderQuotedPrintable = class(TIdDecoder) public procedure Decode(ASrcStream: TStream; const ABytes: Integer = -1); override; end; TIdEncoderQuotedPrintable = class(TIdEncoder) public procedure Encode(ASrcStream, ADestStream: TStream; const ABytes: Integer = -1); override; end; implementation uses IdException, IdGlobal, IdGlobalProtocols; { TIdDecoderQuotedPrintable } procedure TIdDecoderQuotedPrintable.Decode(ASrcStream: TStream; const ABytes: Integer = -1); var LBuffer: TIdBytes; i : Integer; B, DecodedByte : Byte; LBufferLen: Integer; LBufferIndex: Integer; LPos: integer; procedure StripEOLChars; var j: Integer; begin for j := 1 to 2 do begin if (LBufferIndex >= LBufferLen) or (not ByteIsInEOL(LBuffer, LBufferIndex)) then begin Break; end; Inc(LBufferIndex); end; end; function TrimRightWhiteSpace(const ABuf: TIdBytes): TIdBytes; var LSaveBytes: TIdBytes; li, LLen: Integer; begin SetLength(LSaveBytes, 0); LLen := Length(ABuf); for li := Length(ABuf)-1 downto 0 do begin case ABuf[li] of 9, 32: ; 10, 13: begin //BGO: TODO: Change this InsertByte(LSaveBytes, ABuf[li], 0); end; else begin Break; end; end; Dec(LLen); end; SetLength(Result, LLen + Length(LSaveBytes)); if LLen > 0 then begin CopyTIdBytes(ABuf, 0, Result, 0, LLen); end; if Length(LSaveBytes) > 0 then begin CopyTIdBytes(LSaveBytes, 0, Result, LLen, Length(LSaveBytes)); end; end; procedure WriteByte(AValue: Byte; AWriteEOL: Boolean); var LTemp: TIdBytes; begin SetLength(LTemp, iif(AWriteEOL, 3, 1)); LTemp[0] := AValue; if AWriteEOL then begin LTemp[1] := Ord(CR); LTemp[2] := Ord(LF); end; TIdStreamHelper.Write(FStream, LTemp); end; begin LBufferLen := IndyLength(ASrcStream, ABytes); if LBufferLen <= 0 then begin Exit; end; SetLength(LBuffer, LBufferLen); TIdStreamHelper.ReadBytes(ASrcStream, LBuffer, LBufferLen); { when decoding a Quoted-Printable body, any trailing white space on a line must be deleted, - RFC 1521} LBuffer := TrimRightWhiteSpace(LBuffer); LBufferLen := Length(LBuffer); LBufferIndex := 0; while LBufferIndex < LBufferLen do begin LPos := ByteIndex(Ord('='), LBuffer, LBufferIndex); if LPos = -1 then begin if Assigned(FStream) then begin TIdStreamHelper.Write(FStream, LBuffer, -1, LBufferIndex); end; Break; end; if Assigned(FStream) then begin TIdStreamHelper.Write(FStream, LBuffer, LPos-LBufferIndex, LBufferIndex); end; LBufferIndex := LPos+1; // process any following hexidecimal representation if LBufferIndex < LBufferLen then begin i := 0; DecodedByte := 0; while LBufferIndex < LBufferLen do begin B := LBuffer[LBufferIndex]; case B of 48..57: //0-9 {Do not Localize} DecodedByte := (DecodedByte shl 4) or (B - 48); {Do not Localize} 65..70: //A-F {Do not Localize} DecodedByte := (DecodedByte shl 4) or (B - 65 + 10); {Do not Localize} 97..102://a-f {Do not Localize} DecodedByte := (DecodedByte shl 4) or (B - 97 + 10); {Do not Localize} else Break; end; Inc(i); Inc(LBufferIndex); if i > 1 then begin Break; end; end; if i > 0 then begin //if =20 + EOL, this is a hard line break after a space if (DecodedByte = 32) and (LBufferIndex < LBufferLen) and ByteIsInEOL(LBuffer, LBufferIndex) then begin if Assigned(FStream) then begin WriteByte(DecodedByte, True); end; StripEOLChars; end else begin if Assigned(FStream) then begin WriteByte(DecodedByte, False); end; end; end else begin //ignore soft line breaks - StripEOLChars; end; end; end; end; { TIdEncoderQuotedPrintable } function CharToHex(const AChar: Char): String; begin Result := '=' + ByteToHex(Ord(AChar)); {do not localize} end; procedure TIdEncoderQuotedPrintable.Encode(ASrcStream, ADestStream: TStream; const ABytes: Integer = -1); const SafeChars = '!"#$%&''()*+,-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmonpqrstuvwxyz{|}~'; HalfSafeChars = #9' '; // Rule #2, #3 var I, CurrentLen: Integer; LSourceSize: TIdStreamSize; S, SourceLine: String; begin //ie while not eof LSourceSize := ASrcStream.Size; while ASrcStream.Position < LSourceSize do begin SourceLine := ReadLnFromStream(ASrcStream, -1, False, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); CurrentLen := 0; for I := 1 to Length(SourceLine) do begin if not CharIsInSet(SourceLine, I, SafeChars) then begin if CharIsInSet(SourceLine, I, HalfSafeChars) and (I < Length(SourceLine)) then begin S := SourceLine[I]; end else begin S := CharToHex(SourceLine[I]); end; end else if ((CurrentLen = 0) or (CurrentLen >= 70)) and (SourceLine[I] = '.') then begin {do not localize} S := CharToHex(SourceLine[I]); end else begin S := SourceLine[I]; end; WriteStringToStream(ADestStream, S); Inc(CurrentLen, Length(S)); if CurrentLen >= 70 then begin WriteStringToStream(ADestStream, '='+EOL); {Do not Localize} CurrentLen := 0; end; end; WriteStringToStream(ADestStream, EOL); end; end; end.
unit K619559603; {* [Requestlink:619559603] } // Модуль: "w:\common\components\rtl\Garant\Daily\K619559603.pas" // Стереотип: "TestCase" // Элемент модели: "K619559603" MUID: (56E01A9F0388) // Имя типа: "TK619559603" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK619559603 = class(TRTFtoEVDWriterTest) {* [Requestlink:619559603] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK619559603 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *56E01A9F0388impl_uses* //#UC END# *56E01A9F0388impl_uses* ; function TK619559603.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.12'; end;//TK619559603.GetFolder function TK619559603.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '56E01A9F0388'; end;//TK619559603.GetModelElementGUID initialization TestFramework.RegisterTest(TK619559603.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit UMemOperationBlock; interface uses UAccountKey, UDynRawBytes, U32Bytes; {$include MemoryReductionSettings.inc} {$IFDEF uselowmem} type TMemOperationBlock = Record // TOperationBlock with less memory usage // block number is discarded (-4 bytes) {$IFDEF useAccountKeyStorage} account_keyKS: PAccountKey; {$ELSE} account_key: TDynRawBytes; {$ENDIF} reward: UInt64; fee: UInt64; protocol_version: Word; protocol_available: Word; timestamp: Cardinal; compact_target: Cardinal; nonce: Cardinal; block_payload : TDynRawBytes; initial_safe_box_hash: T32Bytes; // 32 direct bytes instead of use an AnsiString (-8 bytes) operations_hash: T32Bytes; // 32 direct bytes instead of use an AnsiString (-8 bytes) proof_of_work: T32Bytes; // 32 direct bytes instead of use an AnsiString (-8 bytes) end; {$ENDIF} implementation end.
unit UFrmExample; interface uses Vcl.Forms, System.ImageList, Vcl.ImgList, Vcl.Controls, Vcl.StdCtrls, System.Classes, System.Types, Vcl.Graphics, DzListHeader; type TForm1 = class(TForm) LH: TDzListHeader; IL: TImageList; L: TListBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure LHDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure LHColumnDraw(Sender: TObject; Col: TDzListHeaderCol; Canvas: TCanvas; Rect: TRect; Hover: Boolean); end; var Form1: TForm1; implementation {$R *.dfm} uses System.SysUtils, System.IniFiles; type TPerson = class ID: Integer; Name, Gender, Sector: String; Amount: Double; Age: Byte; Birthday: String; class function New(aID: Integer; const aName, aGender, aSector: String; aAge: Byte; const aBirthday: String; aAmount: Double): TPerson; end; class function TPerson.New(aID: Integer; const aName, aGender, aSector: String; aAge: Byte; const aBirthday: String; aAmount: Double): TPerson; begin Result := TPerson.Create; Result.ID := aID; Result.Name := aName; Result.Gender := aGender; Result.Sector := aSector; Result.Age := aAge; Result.Birthday := aBirthday; Result.Amount := aAmount; end; // function GetIniFile: String; begin Result := ExtractFilePath(Application.ExeName)+'Custom.ini'; end; procedure TForm1.FormCreate(Sender: TObject); var Ini: TIniFile; begin //Load customization from ini file Ini := TIniFile.Create(GetIniFile); try LH.LoadCustom( Ini.ReadString('ListHeader', 'Columns', '') ); finally Ini.Free; end; //Create sample items objects L.Items.AddObject('', TPerson.New(1, 'JOHN', 'MALE', 'Finance', 40, '02/03/1979', 800000) ); L.Items.AddObject('', TPerson.New(2, 'ALFRED', 'MALE', 'Administration', 55, '01/05/1964', 900000) ); L.Items.AddObject('', TPerson.New(3, 'SARAH', 'FEMALE', 'Technical', 31, '22/07/1988', 120000) ); L.Items.AddObject('', TPerson.New(4, 'BRED', 'MALE', 'Technical', 30, '24/12/1989', 100000) ); L.Items.AddObject('', TPerson.New(5, 'ROBSON', 'MALE', 'Technical', 33, '17/04/1986', 80000) ); L.Items.AddObject('', TPerson.New(6, 'ARTHUR', 'MALE', 'Technical', 39, '26/04/1980', 70000) ); L.Items.AddObject('', TPerson.New(7, 'RAY', 'MALE', 'Technical', 25, '14/11/1994', 150000) ); end; procedure TForm1.FormDestroy(Sender: TObject); var I: Integer; Ini: TIniFile; begin for I := 0 to L.Count-1 do L.Items.Objects[I].Free; //Save customization to ini file Ini := TIniFile.Create(GetIniFile); try Ini.WriteString('ListHeader', 'Columns', LH.SaveCustom); finally Ini.Free; end; end; procedure TForm1.LHColumnDraw(Sender: TObject; Col: TDzListHeaderCol; Canvas: TCanvas; Rect: TRect; Hover: Boolean); begin if Col.ID=3 then //birthday column IL.Draw(Canvas, Rect.Right-20, Rect.Top+2, 2); end; procedure TForm1.LHDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var P: TPerson; ImgIdx: Integer; ColGender: TDzListHeaderCol; begin P := TPerson(L.Items.Objects[Index]); ColGender := LH.ColByID(4); //get "Gender" column object if ColGender.Visible then begin if P.Gender = 'MALE' then ImgIdx := 0 else if P.Gender = 'FEMALE' then ImgIdx := 1 else ImgIdx := -1; if ImgIdx<>-1 then IL.Draw(L.Canvas, ColGender.GetLeft, Rect.Top+1, ImgIdx); end; LH.DwCol(0, Rect, P.ID); LH.DwCol(1, Rect, P.Name); LH.DwCol(2, Rect, P.Age); LH.DwCol(3, Rect, P.Birthday); LH.DwCol(4, Rect, P.Gender, 20); LH.DwCol(5, Rect, P.Sector); if P.Amount>100000 then L.Canvas.Font.Color := clGreen else L.Canvas.Font.Color := clPurple; LH.DwCol(6, Rect, FormatFloat('#,##0.000', P.Amount)); 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.30 15.09.2004 22:38:22 Andreas Hausladen Added "Delphi 7.1 compiler warning bug" fix code Rev 1.29 27.08.2004 22:03:22 Andreas Hausladen Optimized encoders speed optimization ("const" for string parameters) Rev 1.28 7/8/04 5:09:04 PM RLebeau Updated Encode() to remove use of local TIdBytes variable Rev 1.27 2004.05.20 1:39:20 PM czhower Last of the IdStream updates Rev 1.26 2004.05.20 11:37:08 AM czhower IdStreamVCL Rev 1.25 2004.05.20 11:13:12 AM czhower More IdStream conversions Rev 1.24 2004.05.19 3:06:54 PM czhower IdStream / .NET fix Rev 1.23 2004.03.12 7:54:18 PM czhower Removed old commented out code. Rev 1.22 11/03/2004 22:36:14 CCostelloe Bug fix (1 to 3 spurious extra characters at the end of UUE encoded messages, see comment starting CC3. Rev 1.21 2004.02.03 5:44:56 PM czhower Name changes Rev 1.20 28/1/2004 6:22:16 PM SGrobety Removed base 64 encoding stream length check is stream size was provided Rev 1.19 16/01/2004 17:47:48 CCostelloe Restructured slightly to allow IdCoderBinHex4 reuse some of its code Rev 1.18 02/01/2004 20:59:28 CCostelloe Fixed bugs to get ported code to work in Delphi 7 (changes marked CC2) Rev 1.17 11/10/2003 7:54:14 PM BGooijen Did all todo's ( TStream to TIdStream mainly ) Rev 1.16 2003.10.24 10:43:02 AM czhower TIdSTream to dos Rev 1.15 22/10/2003 12:25:36 HHariri Stephanes changes Rev 1.14 10/16/2003 11:10:18 PM DSiders Added localization comments, whitespace. Rev 1.13 2003.10.11 10:00:12 PM czhower Compiles again Rev 1.12 10/5/2003 4:31:02 PM GGrieve use ToBytes for Cardinal to Bytes conversion Rev 1.11 10/4/2003 9:12:18 PM GGrieve DotNet Rev 1.10 2003.06.24 12:02:10 AM czhower Coders now decode properly again. Rev 1.9 2003.06.23 10:53:16 PM czhower Removed unused overriden methods. Rev 1.8 2003.06.13 6:57:10 PM czhower Speed improvement Rev 1.7 2003.06.13 3:41:18 PM czhower Optimizaitions. Rev 1.6 2003.06.13 2:24:08 PM czhower Speed improvement Rev 1.5 10/6/2003 5:37:02 PM SGrobety Bug fix in decoders. Rev 1.4 6/6/2003 4:50:30 PM SGrobety Reworked the 3to4decoder for performance and stability. Note that encoders haven't been touched. Will come later. Another problem: input is ALWAYS a string. Should be a TStream. 1/ Fix: added filtering for #13,#10 and #32 to the decoding mechanism. 2/ Optimization: Speed the decoding by a factor 7-10 AND added filtering ;) Could still do better by using a pointer and a stiding window by a factor 2-3. 3/ Improvement: instead of writing everything to the output stream, there is an internal buffer of 4k. It should speed things up when working on large data (no large chunk of memory pre-allocated while keeping a decent perf by not requiring every byte to be written separately). Rev 1.3 28/05/2003 10:06:56 CCostelloe StripCRLFs changes stripped out at the request of Chad Rev 1.2 20/05/2003 02:01:00 CCostelloe Rev 1.1 20/05/2003 01:44:12 CCostelloe Bug fix: decoder code altered to ensure that any CRLFs inserted by an MTA are removed Rev 1.0 11/14/2002 02:14:36 PM JPMugaas } unit IdCoder3to4; interface {$i IdCompilerDefines.inc} uses Classes, IdCoder, IdGlobal, SysUtils; type TIdDecodeTable = array[1..127] of Byte; TIdEncoder3to4 = class(TIdEncoder) protected FCodingTable: AnsiString; FFillChar: AnsiChar; function InternalEncode(const ABuffer: TIdBytes): TIdBytes; public procedure Encode(ASrcStream: TStream; ADestStream: TStream; const ABytes: Integer = -1); override; published property CodingTable: AnsiString read FCodingTable; property FillChar: AnsiChar read FFillChar write FFillChar; end; TIdEncoder3to4Class = class of TIdEncoder3to4; TIdDecoder4to3 = class(TIdDecoder) protected FCodingTable: AnsiString; FDecodeTable: TIdDecodeTable; FFillChar: AnsiChar; function InternalDecode(const ABuffer: TIdBytes; const AIgnoreFiller: Boolean = False): TIdBytes; public class procedure ConstructDecodeTable(const ACodingTable: AnsiString; var ADecodeArray: TIdDecodeTable); procedure Decode(ASrcStream: TStream; const ABytes: Integer = -1); override; published property FillChar: AnsiChar read FFillChar write FFillChar; end; implementation uses IdException, IdResourceStrings, IdStream; { TIdDecoder4to3 } class procedure TIdDecoder4to3.ConstructDecodeTable(const ACodingTable: AnsiString; var ADecodeArray: TIdDecodeTable); var i: integer; begin //TODO: See if we can find an efficient way, or maybe an option to see if the requested //decode char is valid, that is it returns a 255 from the DecodeTable, or at maybe //check its presence in the encode table. for i := Low(ADecodeArray) to High(ADecodeArray) do begin ADecodeArray[i] := 255; end; for i := 1 to Length(ACodingTable) do begin ADecodeArray[Ord(ACodingTable[i])] := i - 1; end; end; procedure TIdDecoder4to3.Decode(ASrcStream: TStream; const ABytes: Integer = -1); var LBuffer: TIdBytes; LBufSize: Integer; begin // No no - this will read the whole thing into memory and what if its MBs? // need to load it in smaller buffered chunks MaxInt is WAY too big.... LBufSize := IndyLength(ASrcStream, ABytes); if LBufSize > 0 then begin SetLength(LBuffer, LBufSize); TIdStreamHelper.ReadBytes(ASrcStream, LBuffer, LBufSize); LBuffer := InternalDecode(LBuffer); if Assigned(FStream) then begin TIdStreamHelper.Write(FStream, LBuffer); end; end; end; function TIdDecoder4to3.InternalDecode(const ABuffer: TIdBytes; const AIgnoreFiller: Boolean): TIdBytes; var LInBufSize: Integer; LEmptyBytes: Integer; LInBytes: array[0..3] of Byte; LOutPos: Integer; LOutSize: Integer; LInLimit: Integer; LInPos: Integer; LFillChar: Byte; // local copy of FFillChar begin LInPos := 0; LInBufSize := Length(ABuffer); if (LInBufSize mod 4) <> 0 then begin LInLimit := (LInBufSize div 4) * 4; end else begin LInLimit := LInBufSize; end; // Presize output buffer //CC2, bugfix: was LOutPos := 1; LOutPos := 0; LOutSize := (LInLimit div 4) * 3; SetLength(Result, LOutSize); while LInPos < LInLimit do begin // Read 4 bytes in for processing //CC2 bugfix: was CopyTIdBytes(LIn, LInPos, LInBytes, 0, LInBytesLen); //CopyTIdBytes(LIn, LInPos-1, LInBytes, 0, LInBytesLen); // Faster than CopyTIdBytes LInBytes[0] := ABuffer[LInPos]; LInBytes[1] := ABuffer[LInPos + 1]; LInBytes[2] := ABuffer[LInPos + 2]; LInBytes[3] := ABuffer[LInPos + 3]; // Inc pointer Inc(LInPos, 4); // Reduce to 3 bytes Result[LOutPos] := ((FDecodeTable[LInBytes[0]] and 63) shl 2) or ((FDecodeTable[LInBytes[1]] shr 4) and 3); Result[LOutPos + 1] := ((FDecodeTable[LInBytes[1]] and 15) shl 4) or ((FDecodeTable[LInBytes[2]] shr 2) and 15); Result[LOutPos + 2] := ((FDecodeTable[LInBytes[2]] and 3) shl 6) or (FDecodeTable[LInBytes[3]] and 63); Inc(LOutPos, 3); // If we dont know how many bytes we need to watch for fill chars. MIME // is this way. // // In best case, the end is not before the end of the input, but the input // may be right padded with spaces, or even contain the EOL chars. // // Because of this we watch for early ends beyond what we originally // estimated. end; // RLebeau: normally, the FillChar does not appear inside the encoded bytes, // however UUE/XXE does allow it, where encoded lines are prefixed with the // unencoded data lengths instead... if (not AIgnoreFiller) and (LInPos > 0) then begin LFillChar := Byte(FillChar); if ABuffer[LInPos-1] = LFillChar then begin if ABuffer[LInPos-2] = LFillChar then begin LEmptyBytes := 2; end else begin LEmptyBytes := 1; end; SetLength(Result, LOutSize - LEmptyBytes); end; end; end; { TIdEncoder3to4 } procedure TIdEncoder3to4.Encode(ASrcStream, ADestStream: TStream; const ABytes: Integer = -1); var LBuffer: TIdBytes; LBufSize: Integer; begin // No no - this will read the whole thing into memory and what if its MBs? // need to load it in smaller buffered chunks MaxInt is WAY too big.... LBufSize := IndyLength(ASrcStream, ABytes); if LBufSize > 0 then begin SetLength(LBuffer, LBufSize); TIdStreamHelper.ReadBytes(ASrcStream, LBuffer, LBufSize); LBuffer := InternalEncode(LBuffer); TIdStreamHelper.Write(ADestStream, LBuffer); end; end; //TODO: Make this more efficient. Profile it to test, but maybe make single // calls to ReadBuffer then pull from memory function TIdEncoder3to4.InternalEncode(const ABuffer: TIdBytes): TIdBytes; var LInBufSize : Integer; LOutSize: Integer; LLen : integer; LPos : Integer; LBufDataLen: Integer; LIn1, LIn2, LIn3: Byte; LSize : Integer; begin LInBufSize := Length(ABuffer); LOutSize := ((LInBufSize + 2) div 3) * 4; SetLength(Result, LOutSize); // we know that the string will grow by 4/3 adjusted to 3 boundary LLen := 0; LPos := 0; // S.G. 21/10/2003: Copy the relevant bytes into the temporary buffer. // S.G. 21/10/2003: Record the data length and force exit loop when necessary while LPos < LInBufSize do begin Assert((LLen + 4) <= LOutSize, 'TIdEncoder3to4.Encode: Calculated length exceeded (expected '+ {do not localize} IntToStr(LOutSize) + ', about to go '+ {do not localize} IntToStr(LLen + 4) + ' at offset ' + {do not localize} IntToStr(LPos) + ' of '+ {do not localize} IntToStr(LInBufSize)); LBufDataLen := LInBufSize - LPos; if LBufDataLen > 2 then begin LIn1 := ABuffer[LPos]; LIn2 := ABuffer[LPos+1]; LIn3 := ABuffer[LPos+2]; LSize := 3; end else if LBufDataLen > 1 then begin LIn1 := ABuffer[LPos]; LIn2 := ABuffer[LPos+1]; LIn3 := 0; LSize := 2; end else begin LIn1 := ABuffer[LPos]; LIn2 := 0; LIn3 := 0; LSize := 1; end; Inc(LPos, LSize); //possible to do a better assert than this? Assert(Length(FCodingTable)>0); Result[LLen] := Byte(FCodingTable[((LIn1 shr 2) and 63) + 1]); Result[LLen + 1] := Byte(FCodingTable[((((LIn1 and 3) shl 4) or ((LIn2 shr 4) and 15)) and 63) + 1]); Result[LLen + 2] := Byte(FCodingTable[((((LIn2 and 15) shl 2) or ((LIn3 shr 6) and 3)) and 63) + 1]); Result[LLen + 3] := Byte(FCodingTable[(LIn3 and 63) + 1]); Inc(LLen, 4); if LSize < 3 then begin Result[LLen-1] := Byte(FillChar); if LSize = 1 then begin Result[LLen-2] := Byte(FillChar); end; end; end; SetLength(Result, LLen); Assert(LLen = LOutSize, 'TIdEncoder3to4.Encode: Calculated length not met (expected ' + {do not localize} IntToStr(LOutSize) + ', finished at ' + {do not localize} IntToStr(LLen) + ', BufSize = ' + {do not localize} IntToStr(LInBufSize)); end; end.
unit ZMZipFile19; (* ZMZipFile19.pas - Represents the 'Directory' of a Zip file 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 modified 2010-06-20 ---------------------------------------------------------------------------*) interface uses Classes, Windows, ZipMstr19, ZMCore19, ZMIRec19, ZMHash19, ZMWorkFile19, ZMCompat19, ZMEOC19; type TZCChanges = (zccNone, zccBegin, zccCount, zccAdd, zccEdit, zccDelete, zccEnd, zccCheckNo); TZCChangeEvent = procedure(Sender: TObject; idx: Integer; change: TZCChanges) of object; type TVariableData = array of Byte; type TZMCXFields = (zcxUncomp, zcxComp, zcxOffs, zcxStart); type TZMZipFile = class(TZMEOC) private FAddOptions: TZMAddOpts; fCheckNo: Cardinal; FEncodeAs: TZMEncodingOpts; fEncoding: TZMEncodingOpts; fEncoding_CP: Cardinal; fEntries: TList; fEOCFileTime: TFileTime; FFirst: Integer; FIgnoreDirOnly: boolean; fOnChange: TZCChangeEvent; fOpenRet: Integer; FSelCount: integer; fSFXOfs: Cardinal; fShowAll: Boolean; fStub: TMemoryStream; fUseSFX: Boolean; FWriteOptions: TZMWriteOpts; function GetCount: Integer; function GetItems(Idx: Integer): TZMIRec; function SelectEntry(t: TZMIRec; How: TZipSelects): Boolean; procedure SetCount(const Value: Integer); procedure SetEncoding(const Value: TZMEncodingOpts); procedure SetEncoding_CP(const Value: Cardinal); procedure SetItems(Idx: Integer; const Value: TZMIRec); procedure SetShowAll(const Value: Boolean); procedure SetStub(const Value: TMemoryStream); protected fHashList: TZMDirHashList; function BeforeCommit: Integer; virtual; function CalcSizes(var NoEntries: Integer; var ToProcess: Int64; var CenSize: Cardinal): Integer; procedure ClearCachedNames; procedure ClearEntries; function EOCSize(Is64: Boolean): Cardinal; procedure InferNumbering; function Load: Integer; procedure MarkDirty; function Open1(EOConly: Boolean): Integer; function WriteCentral: Integer; property Entries: TList Read fEntries; public constructor Create(Wrkr: TZMCore); override; function Add(rec: TZMIRec): Integer; procedure AssignFrom(Src: TZMWorkFile); override; procedure AssignStub(from: TZMZipFile); procedure BeforeDestruction; override; procedure ClearSelection; function Commit(MarkLatest: Boolean): Integer; function CommitAppend(Last: Integer; MarkLatest: Boolean): Integer; procedure Replicate(Src: TZMZipFile; LastEntry: Integer); function Entry(Chk: Cardinal; Idx: Integer): TZMIRec; function FindName(const pattern: TZMString; var idx: Integer): TZMIRec; overload; function FindName(const pattern: TZMString; var idx: Integer; const myself: TZMIRec): TZMIRec; overload; function FindNameEx(const pattern: TZMString; var idx: Integer; IsWild: boolean): TZMIRec; function HasDupName(const rec: TZMIRec): Integer; //1 Returns the number of duplicates function HashContents(var HList: TZMDirHashList; what: integer): Integer; //1 Mark as Contents Invalid procedure Invalidate; function Next(Current: Integer): integer; function NextSelected(Current: Integer): integer; function Open(EOConly, NoLoad: Boolean): Integer; function PrepareWrite(typ: TZipWrites): Boolean; function Reopen(Mode: Cardinal): integer; function Select(const Pattern: TZMString; How: TZipSelects): Integer; function Select1(const Pattern, reject: TZMString; How: TZipSelects): Integer; function SelectFiles(const want, reject: TStrings; skipped: TStrings): Integer; function VerifyOpen: Integer; property AddOptions: TZMAddOpts read FAddOptions write FAddOptions; property CheckNo: Cardinal Read fCheckNo; property Count: Integer Read GetCount Write SetCount; // how new/modified entries will be encoded property EncodeAs: TZMEncodingOpts read FEncodeAs write FEncodeAs; // how to interpret entry strings property Encoding: TZMEncodingOpts read fEncoding write SetEncoding; property Encoding_CP: Cardinal Read fEncoding_CP Write SetEncoding_CP; property EOCFileTime: TFileTime Read fEOCFileTime; property First: Integer read FFirst; property IgnoreDirOnly: boolean read FIgnoreDirOnly write FIgnoreDirOnly; property Items[Idx: Integer]: TZMIRec Read GetItems Write SetItems; default; property OpenRet: Integer Read fOpenRet Write fOpenRet; property SelCount: integer read FSelCount; property SFXOfs: Cardinal Read fSFXOfs Write fSFXOfs; property ShowAll: Boolean Read fShowAll Write SetShowAll; property Stub: TMemoryStream Read fStub Write SetStub; property UseSFX: Boolean Read fUseSFX Write fUseSFX; property WriteOptions: TZMWriteOpts read FWriteOptions write FWriteOptions; property OnChange: TZCChangeEvent Read fOnChange Write fOnChange; end; type TZMCopyRec = class(TZMIRec) private fLink: TZMIRec; procedure SetLink(const Value: TZMIRec); public constructor Create(theOwner: TZMWorkFile); procedure AfterConstruction; override; function Process: Int64; override; function ProcessSize: Int64; override; property Link: TZMIRec Read fLink Write SetLink; end; type TZMZipCopy = class(TZMZipFile) protected function AffixZippedFile(rec: TZMIRec): Integer; public constructor Create(Wrkr: TZMCore); override; function AffixZippedFiles(Src: TZMZipFile; All: Boolean): Integer; function WriteFile(InZip: TZMZipFile; All: Boolean): Int64; end; const BadIndex = -HIGH(Integer); const zfi_Loaded: cardinal = $1000; // central loaded zfi_DidLoad: cardinal = $2000; // central loaded zfi_Invalid: Cardinal = $8000; // needs reload implementation uses SysUtils, ZMMsg19, ZMXcpt19, ZMMsgStr19, ZMStructs19, ZMDelZip19, ZMUtils19, ZMMatch19, ZMUTF819; {$INCLUDE '.\ZipVers19.inc'} const AllSpec: String = '*.*'; AnySpec: String = '*'; constructor TZMZipFile.Create(Wrkr: TZMCore); begin inherited; fEntries := TList.Create; fHashList := TZMDirHashList.Create; {$IFNDEF UNICODE} fHashList.Worker := Worker; {$ENDIF} fEncoding := Wrkr.Encoding; fAddOptions := wrkr.AddOptions; fEncodeAs := wrkr.EncodeAs; fEncoding_CP := wrkr.Encoding_CP; fIgnoreDirOnly := Wrkr.IgnoreDirOnly; FWriteOptions := Wrkr.WriteOptions; end; function TZMZipFile.Add(rec: TZMIRec): Integer; begin Result := fEntries.Add(rec); if fHashList.Empty then fHashList.Add(rec); end; procedure TZMZipFile.AssignFrom(Src: TZMWorkFile); begin inherited; if (Src is TZMZipFile) and (Src <> Self) then begin Replicate(TZMZipFile(Src), -1); // copy all entries end; end; procedure TZMZipFile.AssignStub(from: TZMZipFile); begin FreeAndNil(fStub); fStub := from.Stub; from.fStub := nil; end; function TZMZipFile.BeforeCommit: Integer; begin Result := 0; end; procedure TZMZipFile.BeforeDestruction; begin ClearEntries; FreeAndNil(fEntries); FreeAndNil(fStub); FreeAndNil(fHashList); inherited; end; function TZMZipFile.CalcSizes(var NoEntries: Integer; var ToProcess: Int64; var CenSize: Cardinal): Integer; var i: Integer; rec: TZMIRec; begin Result := 0; for i := 0 to Count - 1 do begin rec := Items[i]; ToProcess := ToProcess + rec.ProcessSize; CenSize := CenSize + rec.CentralSize; Inc(NoEntries); end; end; procedure TZMZipFile.ClearCachedNames; var i: Integer; tmp: TObject; begin for i := 0 to Count - 1 do begin tmp := fEntries[i]; if tmp is TZMIRec then TZMIRec(tmp).ClearCachedName; end; fHashList.Clear; end; procedure TZMZipFile.ClearEntries; var i: Integer; tmp: TObject; begin for i := 0 to pred(fEntries.Count) do begin tmp := fEntries.Items[i]; if tmp <> nil then begin fEntries.Items[i] := nil; tmp.Free; end; end; fEntries.Clear; fHashList.Clear; FFirst := -1; fSelCount := 0; end; procedure TZMZipFile.ClearSelection; var i: Integer; t: TZMIRec; begin FSelCount := 0; for i := 0 to fEntries.Count - 1 do begin t := fEntries[i]; t.Selected := False; end; end; function TZMZipFile.Commit(MarkLatest: Boolean): Integer; var i: Integer; latest: Cardinal; NoEntries: Integer; ToDo: Int64; r: Integer; rec: TZMIRec; s: Cardinal; ToProcess: Int64; TotalProcess: Int64; w64: Int64; wrote: Int64; begin Diag('Commit file'); latest := 0; wrote := 0; Result := BeforeCommit; if Result < 0 then exit; // calculate sizes NoEntries := 0; ToProcess := 0; for i := 0 to Count - 1 do begin Boss.CheckCancel; rec := TZMIRec(Items[i]); Assert(assigned(rec), ' no rec'); ToProcess := ToProcess + rec.ProcessSize; Inc(NoEntries); if MarkLatest and (rec.ModifDateTime > Latest) then Latest := rec.ModifDateTime; end; // mostly right ToProcess = total compressed sizes TotalProcess := ToProcess; if UseSFX and assigned(Stub) and (Stub.size > 0) then TotalProcess := TotalProcess + Stub.Size; ProgReport(zacCount, PR_Writing, '', NoEntries + 1); ProgReport(zacSize, PR_Writing, '', TotalProcess); Diag(' to process ' + IntToStr(NoEntries) + ' entries'); Diag(' size = ' + IntToStr(TotalProcess)); Result := 0; if MarkLatest then begin // Diag(' latest date = ' + DateTimeToStr(FileDateToLocalDateTime(latest))); StampDate := latest; end; try // if out is going to split should write proper signal if IsMultiPart then begin s := ExtLocalSig; Result := Write(s, -4); if (Result <> 4) and (Result > 0) then Result := -DS_NoWrite; Sig := zfsMulti; end else // write stub if required if UseSFX and assigned(Stub) and (Stub.size > 0) then begin // write the sfx stub ProgReport(zacItem, PR_SFX, '', Stub.Size); Stub.Position := 0; Result := WriteFrom(Stub, Stub.Size); if Result > 0 then begin wrote := Stub.Size; ProgReport(zacProgress, PR_SFX, '', Stub.Size); if ShowProgress = zspFull then Boss.ProgDetail.Written(wrote); Sig := zfsDOS; // assume correct end; end else Sig := zfsLocal; if (Result >= 0) and (ToProcess > 0) then begin for i := 0 to Count - 1 do begin Boss.CheckCancel; rec := TZMIRec(Items[i]); ToDo := rec.ProcessSize; if ToDo > 0 then begin w64 := rec.Process; if w64 < 0 then begin Result := w64; Break; end; wrote := wrote + w64; if ShowProgress = zspFull then Boss.TotalWritten := wrote; end; end; end; // finished locals and data if Result >= 0 then begin // write central Boss.ReportMsg(GE_Copying, [Boss.ZipLoadStr(DS_CopyCentral)]); r := WriteCentral; // uses XProgress if r >= 0 then wrote := wrote + r; Diag(' wrote = ' + IntToStr(wrote)); if r > 0 then begin Result := FinishWrite; if r >= 0 then begin Result := 0; File_Size := wrote; Diag(' finished ok'); end; end; end; finally ProgReport(zacEndOfBatch, 7, '', 0); end; end; function TZMZipFile.CommitAppend(Last: Integer; MarkLatest: Boolean): Integer; var i: Integer; latest: Cardinal; NoEntries: Integer; ToDo: Int64; r: Integer; rec: TZMIRec; ToProcess: Int64; TotalProcess: Int64; w64: Int64; wrote: Int64; begin Diag('CommitAppend file'); latest := 0; wrote := 0; // calculate sizes NoEntries := 0; ToProcess := 0; for i := 0 to Count - 1 do begin Boss.CheckCancel; rec := TZMIRec(Items[i]); Assert(assigned(rec), ' no rec'); if i >= Last then begin ToProcess := ToProcess + rec.ProcessSize; Inc(NoEntries); end; if MarkLatest and (rec.ModifDateTime > latest) then latest := rec.ModifDateTime; end; // mostly right ToProcess = total compressed sizes TotalProcess := ToProcess; if UseSFX and assigned(Stub) and (Stub.size > 0) and (First < 0) then TotalProcess := TotalProcess + Stub.size; ProgReport(zacCount, PR_Writing, '', NoEntries + 1); ProgReport(zacSize, PR_Writing, '', TotalProcess); Diag(' to process ' + IntToStr(NoEntries) + ' entries'); Diag(' size = ' + IntToStr(TotalProcess)); Result := 0; if MarkLatest then begin // Diag(' latest date = ' + DateTimeToStr(FileDateToLocalDateTime(latest))); StampDate := latest; end; try // write stub if required if UseSFX and assigned(Stub) and (Stub.size > 0) and (First < 0) then begin // write the sfx stub ProgReport(zacItem, PR_SFX, '', Stub.size); Stub.Position := 0; Result := WriteFrom(Stub, Stub.size); if Result > 0 then begin wrote := Stub.size; ProgReport(zacProgress, PR_SFX, '', Stub.size); if ShowProgress = zspFull then Boss.ProgDetail.Written(wrote); Sig := zfsDOS; // assume correct end; end else Sig := zfsLocal; if (Result >= 0) and (ToProcess > 0) then begin for i := Last to Count - 1 do begin Boss.CheckCancel; rec := TZMIRec(Items[i]); ToDo := rec.ProcessSize; if ToDo > 0 then begin w64 := rec.Process; if w64 < 0 then begin Result := w64; Break; end; wrote := wrote + w64; if ShowProgress = zspFull then Boss.TotalWritten := wrote; end; end; end; // finished locals and data if Result >= 0 then begin // write central Boss.ReportMsg(GE_Copying, [Boss.ZipLoadStr(DS_CopyCentral)]); r := WriteCentral; // uses XProgress if r >= 0 then wrote := wrote + r; Diag(' wrote = ' + IntToStr(wrote)); if r > 0 then begin Result := 0; File_Size := wrote; Diag(' finished ok'); end; end; finally ProgReport(zacEndOfBatch, 7, '', 0); end; end; function TZMZipFile.Entry(Chk: Cardinal; Idx: Integer): TZMIRec; begin Result := nil; if (Chk = CheckNo) and (Idx >= 0) and (Idx < Count) then Result := Items[Idx]; end; // Zip64 size aproximate only function TZMZipFile.EOCSize(Is64: Boolean): Cardinal; begin Result := Cardinal(sizeof(TZipEndOfCentral) + Length(ZipComment)); if Is64 then Result := Result + sizeof(TZip64EOCLocator) + sizeof(TZipEOC64) + (3 * sizeof(Int64)); end; function TZMZipFile.FindName(const pattern: TZMString; var idx: Integer): TZMIRec; begin Result := FindNameEx(pattern, idx, CanHash(pattern)); end; function TZMZipFile.FindName(const pattern: TZMString; var idx: Integer; const myself: TZMIRec): TZMIRec; begin if myself = nil then Result := FindNameEx(pattern, idx, CanHash(pattern)) else begin myself.SetStatusBit(zsbIgnore); // prevent 'finding' myself Result := FindNameEx(pattern, idx, CanHash(pattern)); myself.ClearStatusBit(zsbIgnore); end; end; function TZMZipFile.FindNameEx(const pattern: TZMString; var idx: Integer; IsWild: boolean): TZMIRec; var found: Boolean; hash: Cardinal; begin found := False; Result := nil; // keep compiler happy hash := 0; // keep compiler happy if (pattern <> '') then begin // if it wild or multiple we must try to match - else only if same hash if (not IsWild) and (idx < 0) and (fHashList.Size > 0) then Result := fHashList.Find(pattern) // do it quick else Begin if not IsWild then hash := HashFunc(pattern); repeat idx := Next(idx); if idx < 0 then break; Result := Entries[idx]; if IsWild or (Result.Hash = hash) then begin found := Worker.FNMatch(pattern, Result.Filename); if Result.StatusBit[zsbIgnore] <> 0 then found := false; end; until (found); if not found then Result := nil; End; end; if Result = nil then idx := BadIndex; end; function TZMZipFile.GetCount: Integer; begin Result := fEntries.Count; end; function TZMZipFile.GetItems(Idx: Integer): TZMIRec; begin if Idx >= Count then Result := nil else Result := Entries[Idx]; end; // searches for record with same name function TZMZipFile.HasDupName(const rec: TZMIRec): Integer; var nrec: TZMIRec; begin Result := -1; if fHashList.Size = 0 then HashContents(fHashList, 0); nrec := fHashList.Add(rec); if nrec <> nil then// exists begin Diag('Duplicate FileName: ' + rec.FileName); for Result := 0 to Count - 1 do begin if nrec = TZMIRec(Items[Result]) then break; end; end; end; // zsbDirty = $1; // zsbSelected = $2; // zsbSkipped = $4; // zsbIgnore = $8; // zsbDirOnly = $10; // zsbInvalid = $20; // what = -1 _ all // else ignore rubbish // what = 0 _ any non rubbish function TZMZipFile.HashContents(var HList: TZMDirHashList; what: integer): Integer; const Skip = zsbInvalid or zsbIgnore or zsbSkipped; var I: Integer; rec: TZMIRec; use: boolean; begin Result := 0; HList.AutoSize(Count); // make required size for I := 0 to Count - 1 do begin rec := Entries[i]; if rec = nil then continue; use := what = -1; if (not use) then begin if (rec.StatusBit[Skip] <> 0) then continue; use := (what = 0) or (rec.StatusBit[what] <> 0); end; if use then begin if HList.Add(Entries[I]) <> nil then Inc(Result); // count duplicates end; end; end; // Use after EOC found and FileName is last part // if removable has proper numbered volume name we assume it is numbered volume procedure TZMZipFile.InferNumbering; var fname: string; num: Integer; numStr: string; begin // only if unknown if (Numbering = znsNone) and (TotalDisks > 1) then begin if WorkDrive.DriveIsFloppy and AnsiSameText(WorkDrive.DiskName, VolName(DiskNr)) then Numbering := znsVolume else begin numStr := ''; fname := ExtractNameOfFile(FileName); Numbering := znsExt; if Length(fname) > 3 then begin numStr := Copy(fname, length(fname) - 2, 3); num := StrToIntDef(numStr, -1); if num = (DiskNr + 1) then begin // ambiguous conflict if WorkDrive.DriveIsFixed then begin if HasSpanSig(ChangeNumberedName(FileName, 1, True)) then Numbering := znsName; // unless there is an orphan end; end; end; end; end; end; procedure TZMZipFile.Invalidate; begin info := info or zfi_Invalid; end; function TZMZipFile.Load: Integer; var i: Integer; LiE: Integer; OffsetDiff: Int64; r: Integer; rec: TZMIRec; sgn: Cardinal; SOCOfs: Int64; begin if not IsOpen then begin Result := DS_FileOpen; exit; end; Result := -LI_ErrorUnknown; if (info and zfi_EOC) = 0 then exit; // should not get here if eoc has not been read LiE := 1; OffsetDiff := 0; ClearEntries; fCheckNo := TZMCore(Worker).NextCheckNo; if Assigned(OnChange) then OnChange(Self, CheckNo, zccBegin); SOCOfs := CentralOffset; try OffsetDiff := CentralOffset; // Do we have to request for a previous disk first? if DiskNr <> CentralDiskNo then begin SeekDisk(CentralDiskNo); File_Size := Seek(0, 2); end else if not Z64 then begin // Due to the fact that v1.3 and v1.4x programs do not change the archives // EOC and CEH records in case of a SFX conversion (and back) we have to // make this extra check. OffsetDiff := File_Size - (Integer(CentralSize) + SizeOf(TZipEndOfCentral) + ZipCommentLen); end; SOCOfs := OffsetDiff; // save the location of the Start Of Central dir SFXOfs := Cardinal(OffsetDiff); if SFXOfs <> SOCOfs then SFXOfs := 0; // initialize this - we will reduce it later if File_Size = 22 then SFXOfs := 0; if CentralOffset <> OffsetDiff then begin // We need this in the ConvertXxx functions. Boss.ShowZipMessage(LI_WrongZipStruct, ''); CheckSeek(CentralOffset, 0, LI_ReadZipError); CheckRead(sgn, 4, DS_CEHBadRead); if sgn = CentralFileHeaderSig then begin SOCOfs := CentralOffset; // TODO warn - central size error end; end; // Now we can go to the start of the Central directory. CheckSeek(SOCOfs, 0, LI_ReadZipError); ProgReport(zacItem, PR_Loading, '', TotalEntries); // Read every entry: The central header and save the information. {$IFDEF DEBUG} if Boss.Verbosity >= zvTrace then Diag(Format('List - expecting %d files', [TotalEntries])); {$ENDIF} fEntries.Capacity := TotalEntries; rec := nil; if Assigned(OnChange) then OnChange(Self, TotalEntries, zccCount); fHashList.AutoSize(TotalEntries); for i := 0 to (TotalEntries - 1) do begin FreeAndNil(rec); rec := TZMIRec.Create(Self); r := rec.Read(Self); if r < 0 then begin FreeAndNil(rec); raise EZipMaster.CreateResDisp(r, True); end; if r > 0 then Z64 := True; {$IFDEF DEBUG} if Boss.Verbosity >= zvTrace then //Trace then Diag(Format('List - [%d] "%s"', [i, rec.FileName])); {$ENDIF} fEntries.Add(rec); fHashList.Add(rec); // Notify user, when needed, of the NextSelected entry in the ZipDir. if Assigned(OnChange) then OnChange(Self, i, zccAdd); // change event to give TZipDirEntry // Calculate the earliest Local Header start if SFXOfs > rec.RelOffLocal then SFXOfs := rec.RelOffLocal; rec := nil; // used ProgReport(zacProgress, PR_Loading, '', 1); Boss.CheckCancel; end; // for LiE := 0; // finished ok Result := 0; info := (info and not (zfi_MakeMask)) or zfi_Loaded; finally ProgReport(zacEndOfBatch, PR_Loading, '', 0); if LiE = 1 then begin FileName := ''; SFXOfs := 0; File_Close; end else begin CentralOffset := SOCOfs; // corrected // Correct the offset for v1.3 and 1.4x SFXOfs := SFXOfs + Cardinal(OffsetDiff - CentralOffset); end; // Let the user's program know we just refreshed the zip dir contents. if Assigned(OnChange) then OnChange(Self, Count, zccEnd); end; end; procedure TZMZipFile.MarkDirty; begin info := info or zfi_Dirty; end; // allow current = -1 to get first // get next index, if IgnoreDirOnly = True skip DirOnly entries function TZMZipFile.Next(Current: Integer): Integer; var cnt: Integer; begin Result := BadIndex; if Current >= -1 then begin cnt := Entries.Count; if IgnoreDirOnly then begin repeat Inc(Current); until (Current >= cnt) or ((TZMIRec(Entries[Current]).StatusBits and zsbDirOnly) = 0); end else Inc(Current); if Current < cnt then Result := Current; end; end; // return BadIndex when no more function TZMZipFile.NextSelected(Current: Integer): integer; var k: Cardinal; mask: cardinal; rec: TZMIRec; begin Result := BadIndex; mask := zsbSkipped or zsbSelected; if IgnoreDirOnly then mask := mask or zsbDirOnly; if Current >= -1 then begin while Current < Entries.Count -1 do begin inc(Current); rec := TZMIRec(Entries[Current]); if rec <> nil then begin k := rec.StatusBit[mask]; if k = zsbSelected then begin Result := Current; break; end; end; end; end; end; function TZMZipFile.Open(EOConly, NoLoad: Boolean): Integer; var r: Integer; begin // verify disk loaded ClearFileInformation; info := (info and zfi_MakeMask) or zfi_Loading; if WorkDrive.DriveIsFixed or WorkDrive.HasMedia(False) then begin Result := Open1(EOConly); if (Result >= 0) then begin LastWriteTime(fEOCFileTime); InferNumbering; if not (EOConly or NoLoad) then begin info := info or zfi_EOC; if (Result and EOCBadComment) <> 0 then Boss.ShowZipMessage(DS_CECommentLen, ''); if (Result and EOCBadStruct) <> 0 then Boss.ShowZipMessage(LI_WrongZipStruct, ''); r := Load; if r <> 0 then Result := r else begin info := info or zfi_Loaded or zfi_DidLoad; SaveFileInformation; // get details end; end; end; end else Result := -DS_NoInFile; OpenRet := Result; if Boss.Verbosity >= zvTrace then begin if Result < 0 then Diag('Open = ' + Boss.ZipLoadStr(-Result)) else Diag('Open = ' + IntToStr(Result)); end; end; function TZMZipFile.Open1(EOConly: Boolean): Integer; var fn: string; SfxType: Integer; size: Integer; begin SfxType := 0; // keep compiler happy ReqFileName := FileName; fn := FileName; Result := OpenEOC(EOConly); if (Result >= 0) and (Sig = zfsDOS) then begin stub := nil; SfxType := CheckSFXType(handle, fn, size); if SfxType >= cstSFX17 then begin if Seek(0, 0) <> 0 then exit; stub := TMemoryStream.Create; try if ReadTo(stub, size) <> size then begin stub := nil; end; except stub := nil; end; end; end; if not (spExactName in SpanOptions) then begin if (Result >= 0) and (SfxType >= cstDetached) then begin // it is last part of detached sfx File_Close; // Get proper path and name FileName := IncludeTrailingBackslash(ExtractFilePath(ReqFileName)) + fn; // find last part Result := -DS_NoInFile; end; if Result < 0 then Result := OpenLast(EOConly, Result); end; end; function TZMZipFile.PrepareWrite(typ: TZipWrites): Boolean; begin case typ of zwSingle: Result := false; zwMultiple: Result := True; else Result := zwoDiskSpan in WriteOptions; end; IsMultiPart := Result; if Result then begin DiskNr := 0; File_Close; end else begin DiskNr := -1; end; end; function TZMZipFile.Reopen(Mode: Cardinal): integer; begin Result := 0; if (not IsOpen) or (OpenMode <> Mode) then begin File_Close; if Boss.Verbosity >= zvTrace then Diag('Trace: Reopening ' + RealFileName); if not File_Open(Mode) then begin Diag('Could not reopen: ' + RealFileName); Result := -DS_FileOpen; end; end; if (Result = 0) and ((info and zfi_Loaded) <> 0) and not VerifyFileInformation then begin Worker.Diag('File has changed! ' + RealFileName); // close it? Result := GE_FileChanged; // just complain at moment end; end; procedure TZMZipFile.Replicate(Src: TZMZipFile; LastEntry: Integer); var I: Integer; rec: TZMIRec; begin if (Src <> nil) and (Src <> Self) then begin inherited AssignFrom(Src); fCheckNo := Worker.NextCheckNo; // FAddOptions := Src.FAddOptions; // FEncodeAs := Src.FEncodeAs; // fEncoding := Src.fEncoding; // fEncoding_CP := Src.fEncoding_CP; // FIgnoreDirOnly := Src.FIgnoreDirOnly; fEOCFileTime := Src.fEOCFileTime; FFirst := Src.FFirst; fOnChange := Src.fOnChange; fOpenRet := Src.fOpenRet; FSelCount := Src.FSelCount; fSFXOfs := Src.fSFXOfs; fShowAll := Src.fShowAll; fStub := nil; fUseSFX := False; if Src.UseSFX and Assigned(Src.fStub) then begin fStub := TMemoryStream.Create; Src.fStub.Position := 0; if fStub.CopyFrom(Src.fStub, Src.fStub.Size) = Src.fStub.Size then fUseSFX := True else FreeAndNil(fStub); end; // add records from Src if (LastEntry < 0) or (LastEntry > Src.Count) then LastEntry := Src.Count - 1; for I := 0 to LastEntry do begin rec := TZMIRec.Create(self); rec.AssignFrom(Src[I]); Add(rec); end; end; end; // select entries matching external pattern - return number of selected entries function TZMZipFile.Select(const Pattern: TZMString; How: TZipSelects): Integer; var i: Integer; srch: Integer; t: TZMIRec; wild: Boolean; begin Result := 0; // if it wild or multiple we must try to match - else only if same hash wild := not CanHash(pattern); if (Pattern = '') or (wild and ((Pattern = AllSpec) or (Pattern = AnySpec))) then begin // do all for i := 0 to fEntries.Count - 1 do begin t := fEntries[i]; if SelectEntry(t, How) then Inc(Result); end; end else begin // select specific pattern i := -1; srch := 1; while srch <> 0 do begin t := FindNameEx(Pattern, i, wild); if t = nil then break; if SelectEntry(t, How) then Inc(Result); if srch > 0 then begin if wild then srch := -1 // search all else srch := 0; // done end; end; end; end; // Select1 entries matching external pattern function TZMZipFile.Select1(const Pattern, reject: TZMString; How: TZipSelects): Integer; var args: string; i: Integer; exc: string; ptn: string; aRec: TZMIRec; wild: Boolean; begin Result := 0; args := ''; // default args - empty exc := reject; // default excludes ptn := Pattern; // need to remove switches // split Pattern into pattern and switches // if it wild or multiple we must try to match - else only if same hash wild := not CanHash(ptn); if (ptn = '') or (wild and ((ptn = AllSpec) or (ptn = AnySpec))) then begin // do all for i := 0 to fEntries.Count - 1 do begin aRec := fEntries[i]; if (exc <> '') and (Worker.FNMatch(exc, aRec.Filename)) then Continue; if SelectEntry(aRec, How) then begin // set SelectArgs aRec.SelectArgs := args; end; Inc(Result); end; end else begin // Select1 specific pattern i := -1; while True do begin aRec := FindNameEx(ptn, i, wild); if aRec = nil then break; // no matches if (exc = '') or not (Worker.FNMatch(exc, aRec.Filename)) then begin if SelectEntry(aRec, How) then begin // set SelectArgs aRec.SelectArgs := args; end; Inc(Result); end; if not wild then Break; // old find first end; end; end; function TZMZipFile.SelectEntry(t: TZMIRec; How: TZipSelects): Boolean; begin Result := t.Select(How); if Result then inc(FSelCount) else dec(FSelCount); end; function TZMZipFile.SelectFiles(const want, reject: TStrings; skipped: TStrings): Integer; var a: Integer; SelectsCount: Integer; exc: string; I: Integer; NoSelected: Integer; spec: String; begin Result := 0; ClearSelection; // clear all SelectsCount := want.Count; if (SelectsCount < 1) or (Count < 1) then exit; exc := ''; // combine rejects into a string if (reject <> nil) and (reject.Count > 0) then begin exc := reject[0]; for I := 1 to reject.Count - 1 do exc := exc + ZSwitchFollows + reject[I]; end; // attempt to select each wanted spec for a := 0 to SelectsCount - 1 do begin spec := want[a]; NoSelected := Select1(spec, exc, zzsSet); if NoSelected < 1 then begin // none found if Boss.Verbosity >= zvVerbose then Diag('Skipped filespec ' + spec); if assigned(skipped) then skipped.Add(spec); end; if NoSelected > 0 then Result := Result + NoSelected; if NoSelected >= Count then break; // all have been done end; end; procedure TZMZipFile.SetCount(const Value: Integer); begin // not allowed end; procedure TZMZipFile.SetEncoding(const Value: TZMEncodingOpts); begin if fEncoding <> Value then begin ClearCachedNames; fEncoding := Value; end; end; procedure TZMZipFile.SetEncoding_CP(const Value: Cardinal); begin if fEncoding_CP <> Value then begin ClearCachedNames; fEncoding_CP := Value; end; end; procedure TZMZipFile.SetItems(Idx: Integer; const Value: TZMIRec); var tmp: TObject; begin tmp := fEntries[Idx]; if tmp <> Value then begin fEntries[Idx] := Value; tmp.Free; end; end; procedure TZMZipFile.SetShowAll(const Value: Boolean); begin fShowAll := Value; end; procedure TZMZipFile.SetStub(const Value: TMemoryStream); begin if fStub <> Value then begin if assigned(fStub) then fStub.Free; fStub := Value; end; end; function TZMZipFile.VerifyOpen: Integer; var ft: TFileTime; begin Result := DS_FileOpen; if not IsOpen and not File_Open(fmOpenRead or fmShareDenyWrite) then exit; if LastWriteTime(ft) then begin Result := 0; LastWriteTime(fEOCFileTime); if CompareFileTime(EOCFileTime, ft) <> 0 then Result := -DS_FileChanged; end; end; // returns bytes written or <0 _ error function TZMZipFile.WriteCentral: Integer; var i: Integer; rec: TZMIRec; wrote: Integer; begin Result := 0; wrote := 0; CentralOffset := Position; CentralDiskNo := DiskNr; TotalEntries := 0; CentralEntries := 0; CentralSize := 0; ProgReport(zacXItem, PR_CentrlDir, '', Count); for i := 0 to Count - 1 do begin rec := TZMIRec(Items[i]); if rec.StatusBit[zsbError] = 0 then begin // no processing error if Boss.Verbosity >= zvTrace then Diag('Writing central [' + IntToStr(i) + '] ' + rec.FileName); // check for deleted? Result := rec.Write; if Result < 0 then break; // error if Position <= Result then // started new part CentralEntries := 0; wrote := wrote + Result; CentralSize := CentralSize + Cardinal(Result); TotalEntries := TotalEntries + 1; CentralEntries := CentralEntries + 1; ProgReport(zacXProgress, PR_CentrlDir, '', 1); end else Diag('skipped Writing central ['+ IntToStr(i) + '] ' + rec.FileName); end; // finished Central if Result >= 0 then begin Result := WriteEOC; if Result >= 0 then begin ProgReport(zacXProgress, PR_CentrlDir, '', 1); Result := wrote + Result; if Result > 0 then begin Diag(' finished ok'); end; end; end; end; constructor TZMCopyRec.Create(theOwner: TZMWorkFile); begin inherited Create(theOwner); end; procedure TZMCopyRec.AfterConstruction; begin inherited; fLink := nil; end; // process record, return bytes written; <0 = -error function TZMCopyRec.Process: Int64; var did: Int64; InRec: TZMIRec; InWorkFile: TZMWorkFile; stNr: Integer; stt: Int64; ToWrite: Int64; wrt: Int64; begin // ASSERT(assigned(Owner), 'no owner'); if Owner.Boss.Verbosity >= zvVerbose then Owner.Boss.ReportMsg(GE_Copying, [FileName]); InRec := Link; InWorkFile := InRec.Owner; if Owner.Boss.Verbosity >= zvVerbose then Diag('Copying local'); Result := InRec.SeekLocalData; if Result < 0 then exit; // error stNr := Owner.DiskNr; stt := Owner.Position; Result := WriteAsLocal1(ModifDateTime, CRC32); if Result < 0 then exit; // error wrt := Result; Owner.ProgReport(zacProgress, PR_Copying, '', wrt); // Diag(' finished copy local'); // ok so update positions RelOffLocal := stt; DiskStart := stNr; ToWrite := CompressedSize; // Diag('copying zipped data'); Owner.ProgReport(zacItem, zprCompressed, FileName, ToWrite); did := Owner.CopyFrom(InWorkFile, ToWrite); if did <> ToWrite then begin if did < 0 then Result := did // write error else Result := -DS_DataCopy; exit; end; wrt := wrt + did; if (Flag and 8) <> 0 then begin did := WriteDataDesc(Owner); if did < 0 then begin Result := did; // error exit; end; wrt := wrt + did; Owner.ProgReport(zacProgress, PR_Copying, '', did); end; Result := wrt; end; // return bytes to be processed function TZMCopyRec.ProcessSize: Int64; begin Result := CompressedSize + LocalSize; if (Flag and 8) <> 0 then Result := Result + sizeof(TZipDataDescriptor); end; procedure TZMCopyRec.SetLink(const Value: TZMIRec); begin if fLink <> Value then begin fLink := Value; end; end; constructor TZMZipCopy.Create(Wrkr: TZMCore); begin inherited Create(Wrkr); end; // Add a copy of source record if name is unique function TZMZipCopy.AffixZippedFile(rec: TZMIRec): Integer; var nrec: TZMCopyRec; begin Result := -1; if HasDupName(rec) < 0 then begin // accept it nrec := TZMCopyRec.Create(self); // make a copy nrec.AssignFrom(rec); // clear unknowns ? nrec.Link := rec; // link to original Result := Add(nrec); end; end; // return >=0 number added <0 error function TZMZipCopy.AffixZippedFiles(Src: TZMZipFile; All: Boolean): Integer; var i: Integer; r: Integer; rec: TZMIRec; begin Result := 0; for i := 0 to Src.Count - 1 do begin rec := Src[i]; if not assigned(rec) then continue; if All or rec.TestStatusBit(zsbSelected) then begin Diag('including: ' + rec.FileName); r := AffixZippedFile(rec); if (r >= 0) then Inc(Result) // added else begin // error if r < 0 then Result := r; end; end else Diag('ignoring: ' + rec.FileName); end; end; // copies selected files from InZip function TZMZipCopy.WriteFile(InZip: TZMZipFile; All: Boolean): Int64; begin ASSERT(assigned(InZip), 'no input'); Diag('Write file'); Result := InZip.VerifyOpen; // verify unchanged and open if Result < 0 then exit; ZipComment := InZip.ZipComment; Result := AffixZippedFiles(InZip, All); if Result >= 0 then Result := Commit(zwoZipTime in {Worker.}WriteOptions); end; end.
unit caParam; // Модуль: "w:\common\components\rtl\Garant\ComboAccess\caParam.pas" // Стереотип: "SimpleClass" // Элемент модели: "TcaParam" MUID: (56E14CE0012E) {$Include w:\common\components\rtl\Garant\ComboAccess\caDefine.inc} interface {$If Defined(UsePostgres) AND Defined(TestComboAccess)} uses l3IntfUses , l3ProtoObject , daInterfaces , daTypes , l3Date ; type TcaParam = class(Tl3ProtoObject, IdaParam) private f_HTParam: IdaParam; f_PGParam: IdaParam; protected function Get_Name: AnsiString; function IsSameType(const aDesc: IdaParamDescription): Boolean; function Get_AsInteger: LongInt; procedure Set_AsInteger(aValue: LongInt); function Get_DataBuffer: Pointer; function Get_AsLargeInt: LargeInt; procedure Set_AsLargeInt(aValue: LargeInt); function Get_AsString: AnsiString; procedure Set_AsString(const aValue: AnsiString); function Get_AsStDate: TStDate; procedure Set_AsStDate(const aValue: TStDate); function Get_AsStTime: TStTime; procedure Set_AsStTime(const aValue: TStTime); function Get_ParamType: TdaParamType; function Get_AsByte: Byte; procedure Set_AsByte(aValue: Byte); procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aHTParam: IdaParam; const aPGParam: IdaParam); reintroduce; class function Make(const aHTParam: IdaParam; const aPGParam: IdaParam): IdaParam; reintroduce; end;//TcaParam {$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess) implementation {$If Defined(UsePostgres) AND Defined(TestComboAccess)} uses l3ImplUses //#UC START# *56E14CE0012Eimpl_uses* //#UC END# *56E14CE0012Eimpl_uses* ; constructor TcaParam.Create(const aHTParam: IdaParam; const aPGParam: IdaParam); //#UC START# *56E14D92025C_56E14CE0012E_var* //#UC END# *56E14D92025C_56E14CE0012E_var* begin //#UC START# *56E14D92025C_56E14CE0012E_impl* inherited Create; f_HTParam := aHTParam; f_PGParam := aPGParam; //#UC END# *56E14D92025C_56E14CE0012E_impl* end;//TcaParam.Create class function TcaParam.Make(const aHTParam: IdaParam; const aPGParam: IdaParam): IdaParam; var l_Inst : TcaParam; begin l_Inst := Create(aHTParam, aPGParam); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TcaParam.Make function TcaParam.Get_Name: AnsiString; //#UC START# *5555CC750283_56E14CE0012Eget_var* //#UC END# *5555CC750283_56E14CE0012Eget_var* begin //#UC START# *5555CC750283_56E14CE0012Eget_impl* Result := f_HTParam.Name; Assert(Result = f_PGParam.Name); //#UC END# *5555CC750283_56E14CE0012Eget_impl* end;//TcaParam.Get_Name function TcaParam.IsSameType(const aDesc: IdaParamDescription): Boolean; //#UC START# *5555D4F5030D_56E14CE0012E_var* //#UC END# *5555D4F5030D_56E14CE0012E_var* begin //#UC START# *5555D4F5030D_56E14CE0012E_impl* Result := f_HTParam.IsSameType(aDesc); Assert(Result = f_PGParam.IsSameType(aDesc)); //#UC END# *5555D4F5030D_56E14CE0012E_impl* end;//TcaParam.IsSameType function TcaParam.Get_AsInteger: LongInt; //#UC START# *5555E85C00B8_56E14CE0012Eget_var* //#UC END# *5555E85C00B8_56E14CE0012Eget_var* begin //#UC START# *5555E85C00B8_56E14CE0012Eget_impl* Result := f_HTParam.AsInteger; Assert(Result = f_PGParam.AsInteger); //#UC END# *5555E85C00B8_56E14CE0012Eget_impl* end;//TcaParam.Get_AsInteger procedure TcaParam.Set_AsInteger(aValue: LongInt); //#UC START# *5555E85C00B8_56E14CE0012Eset_var* //#UC END# *5555E85C00B8_56E14CE0012Eset_var* begin //#UC START# *5555E85C00B8_56E14CE0012Eset_impl* f_HTParam.AsInteger := aValue; f_PGParam.AsInteger := aValue; Assert(f_HTParam.AsInteger = f_PGParam.AsInteger); //#UC END# *5555E85C00B8_56E14CE0012Eset_impl* end;//TcaParam.Set_AsInteger function TcaParam.Get_DataBuffer: Pointer; //#UC START# *555D928D00E0_56E14CE0012Eget_var* //#UC END# *555D928D00E0_56E14CE0012Eget_var* begin //#UC START# *555D928D00E0_56E14CE0012Eget_impl* Result := nil; Assert(False, 'Unimplemented'); //#UC END# *555D928D00E0_56E14CE0012Eget_impl* end;//TcaParam.Get_DataBuffer function TcaParam.Get_AsLargeInt: LargeInt; //#UC START# *55FA75FD01D3_56E14CE0012Eget_var* //#UC END# *55FA75FD01D3_56E14CE0012Eget_var* begin //#UC START# *55FA75FD01D3_56E14CE0012Eget_impl* Result := f_HTParam.AsLargeInt; Assert(Result = f_PGParam.AsLargeInt); //#UC END# *55FA75FD01D3_56E14CE0012Eget_impl* end;//TcaParam.Get_AsLargeInt procedure TcaParam.Set_AsLargeInt(aValue: LargeInt); //#UC START# *55FA75FD01D3_56E14CE0012Eset_var* //#UC END# *55FA75FD01D3_56E14CE0012Eset_var* begin //#UC START# *55FA75FD01D3_56E14CE0012Eset_impl* f_HTParam.AsLargeInt := aValue; f_PGParam.AsLargeInt := aValue; Assert(f_HTParam.AsLargeInt = f_PGParam.AsLargeInt); //#UC END# *55FA75FD01D3_56E14CE0012Eset_impl* end;//TcaParam.Set_AsLargeInt function TcaParam.Get_AsString: AnsiString; //#UC START# *560CEA210293_56E14CE0012Eget_var* //#UC END# *560CEA210293_56E14CE0012Eget_var* begin //#UC START# *560CEA210293_56E14CE0012Eget_impl* Result := f_HTParam.AsString; Assert(Result = f_PGParam.AsString); //#UC END# *560CEA210293_56E14CE0012Eget_impl* end;//TcaParam.Get_AsString procedure TcaParam.Set_AsString(const aValue: AnsiString); //#UC START# *560CEA210293_56E14CE0012Eset_var* //#UC END# *560CEA210293_56E14CE0012Eset_var* begin //#UC START# *560CEA210293_56E14CE0012Eset_impl* f_HTParam.AsString := aValue; f_PGParam.AsString := aValue; Assert(f_HTParam.AsString = f_PGParam.AsString); //#UC END# *560CEA210293_56E14CE0012Eset_impl* end;//TcaParam.Set_AsString function TcaParam.Get_AsStDate: TStDate; //#UC START# *563C8B50016A_56E14CE0012Eget_var* //#UC END# *563C8B50016A_56E14CE0012Eget_var* begin //#UC START# *563C8B50016A_56E14CE0012Eget_impl* Result := f_HTParam.AsStDate; Assert(Result = f_PGParam.AsStDate); //#UC END# *563C8B50016A_56E14CE0012Eget_impl* end;//TcaParam.Get_AsStDate procedure TcaParam.Set_AsStDate(const aValue: TStDate); //#UC START# *563C8B50016A_56E14CE0012Eset_var* //#UC END# *563C8B50016A_56E14CE0012Eset_var* begin //#UC START# *563C8B50016A_56E14CE0012Eset_impl* f_HTParam.AsStDate := aValue; f_PGParam.AsStDate := aValue; Assert(f_HTParam.AsStDate = f_PGParam.AsStDate); //#UC END# *563C8B50016A_56E14CE0012Eset_impl* end;//TcaParam.Set_AsStDate function TcaParam.Get_AsStTime: TStTime; //#UC START# *564C37CF00C4_56E14CE0012Eget_var* //#UC END# *564C37CF00C4_56E14CE0012Eget_var* begin //#UC START# *564C37CF00C4_56E14CE0012Eget_impl* Result := f_HTParam.AsStTime; Assert(Result = f_PGParam.AsStTime); //#UC END# *564C37CF00C4_56E14CE0012Eget_impl* end;//TcaParam.Get_AsStTime procedure TcaParam.Set_AsStTime(const aValue: TStTime); //#UC START# *564C37CF00C4_56E14CE0012Eset_var* //#UC END# *564C37CF00C4_56E14CE0012Eset_var* begin //#UC START# *564C37CF00C4_56E14CE0012Eset_impl* f_HTParam.AsStTime := aValue; f_PGParam.AsStTime := aValue; Assert(f_HTParam.AsStTime = f_PGParam.AsStTime); //#UC END# *564C37CF00C4_56E14CE0012Eset_impl* end;//TcaParam.Set_AsStTime function TcaParam.Get_ParamType: TdaParamType; //#UC START# *5666822101CA_56E14CE0012Eget_var* //#UC END# *5666822101CA_56E14CE0012Eget_var* begin //#UC START# *5666822101CA_56E14CE0012Eget_impl* Result := f_HTParam.ParamType; Assert(Result = f_PGParam.ParamType); //#UC END# *5666822101CA_56E14CE0012Eget_impl* end;//TcaParam.Get_ParamType function TcaParam.Get_AsByte: Byte; //#UC START# *578625FB03A1_56E14CE0012Eget_var* //#UC END# *578625FB03A1_56E14CE0012Eget_var* begin //#UC START# *578625FB03A1_56E14CE0012Eget_impl* Result := f_HTParam.AsByte; Assert(Result = f_PGParam.AsByte); //#UC END# *578625FB03A1_56E14CE0012Eget_impl* end;//TcaParam.Get_AsByte procedure TcaParam.Set_AsByte(aValue: Byte); //#UC START# *578625FB03A1_56E14CE0012Eset_var* //#UC END# *578625FB03A1_56E14CE0012Eset_var* begin //#UC START# *578625FB03A1_56E14CE0012Eset_impl* f_HTParam.AsByte := aValue; f_PGParam.AsByte := aValue; Assert(f_HTParam.AsByte = f_PGParam.AsByte); //#UC END# *578625FB03A1_56E14CE0012Eset_impl* end;//TcaParam.Set_AsByte procedure TcaParam.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_56E14CE0012E_var* //#UC END# *479731C50290_56E14CE0012E_var* begin //#UC START# *479731C50290_56E14CE0012E_impl* f_HTParam := nil; f_PGParam := nil; inherited; //#UC END# *479731C50290_56E14CE0012E_impl* end;//TcaParam.Cleanup {$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess) end.
unit OiMenuUtil; interface uses SysUtils, Classes, Contnrs; //PARAM type TRequestParam = class token : PChar; customUrl : PChar; end; //SIMPLE RESULT type TSimpleResult = class success : Boolean; message : PChar; responseCode : Integer; data : PChar; count : Integer; end; //ORDER type TOrderProduct = class code : PChar; name : PChar; quantity : Integer; price : Double; end; type TOrderItemOption = class id : PChar; optionId : PChar; code : PChar; name : PChar; quantity : Integer; price : Double; notes : TStringList; extraFields : PChar; constructor Create; Destructor Destroy; end; type TListOrderItemOption = Class( TObjectList ) private function GetItems(Index: Integer): TOrderItemOption; procedure SetItems(Index: Integer; const Value: TOrderItemOption); public function Add(AObject: TOrderItemOption): Integer; property Items[Index: Integer]: TOrderItemOption read GetItems write SetItems; default; End; type TOrderItem = class id : PChar; code : PChar; name : PChar; quantity : Integer; price : Double; options : TListOrderItemOption; notes : TStringList; extraFields : PChar; constructor Create; Destructor Destroy; end; type TListOrderItem = Class( TObjectList ) private function GetItems(Index: Integer): TOrderItem; procedure SetItems(Index: Integer; const Value: TOrderItem); public function Add(AObject: TOrderItem): Integer; property Items[Index: Integer]: TOrderItem read GetItems write SetItems; default; End; type TOrder = class id : PChar; date : PChar; table : Integer; card : Integer; waiter : PChar; items : TListOrderItem; constructor Create; Destructor Destroy; end; type TListOrder = Class( TObjectList ) private function GetItems(Index: Integer): TOrder; procedure SetItems(Index: Integer; const Value: TOrder); public function Add(AObject: TOrder): Integer; property Items[Index: Integer]: TOrder read GetItems write SetItems; default; End; type TOrderResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListOrder; count : Integer; constructor Create; Destructor Destroy; end; //BILL type TBillItem = class total : Double; items : TListOrderItem; constructor Create; Destructor Destroy; end; type TBillResult = class success : Boolean; message : PChar; responseCode : Integer; data : TBillItem; count : Integer; constructor Create; Destructor Destroy; end; //EVENT type TEventTheCheck = class table : PChar; card : PChar; waiter : PChar; document : PChar; splitWith : PChar; end; type TEventCallWaiter = class table : PChar; waiter : PChar; options : TStringList; constructor Create; Destructor Destroy; end; type TEvent = class id : PChar; date : PChar; eventType : PChar; data : TObject; end; type TListEvent = Class( TObjectList ) private function GetItems(Index: Integer): TEvent; procedure SetItems(Index: Integer; const Value: TEvent); public function Add(AObject: TEvent): Integer; property Items[Index: Integer]: TEvent read GetItems write SetItems; default; End; type TEventResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListEvent; count : Integer; constructor Create; Destructor Destroy; end; //PRODUCT type TProduct = class code : PChar; name : PChar; price : Double; extraFields : PChar; end; type TListProduct = Class( TObjectList ) private function GetItems(Index: Integer): TProduct; procedure SetItems(Index: Integer; const Value: TProduct); public function Add(AObject: TProduct): Integer; property Items[Index: Integer]: TProduct read GetItems write SetItems; default; End; type TProductResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListProduct; count : Integer; constructor Create; Destructor Destroy; end; //TABLE type TTable = class code : Integer; name : PChar; servicePercentage : Double; end; type TListTable = Class( TObjectList ) private function GetItems(Index: Integer): TTable; procedure SetItems(Index: Integer; const Value: TTable); public function Add(AObject: TTable): Integer; property Items[Index: Integer]: TTable read GetItems write SetItems; default; End; type TTableResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListTable; count : Integer; constructor Create; Destructor Destroy; end; //CARD type TCard = class code : Integer; qrCode : PChar; servicePercentage : Double; end; type TListCard = Class( TObjectList ) private function GetItems(Index: Integer): TCard; procedure SetItems(Index: Integer; const Value: TCard); public function Add(AObject: TCard): Integer; property Items[Index: Integer]: TCard read GetItems write SetItems; default; End; type TCardResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListCard; count : Integer; constructor Create; Destructor Destroy; end; //USER type TUser = class code : Integer; name : PChar; active : Boolean; end; type TListUser = Class( TObjectList ) private function GetItems(Index: Integer): TUser; procedure SetItems(Index: Integer; const Value: TUser); public function Add(AObject: TUser): Integer; property Items[Index: Integer]: TUser read GetItems write SetItems; default; End; type TUserResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListUser; count : Integer; constructor Create; Destructor Destroy; end; //ITEM type TITemResult = class success : Boolean; message : PChar; responseCode : Integer; data : TOrderItem; count : Integer; end; function createProduct(param: TRequestParam; product: TProduct): TProductResult; stdcall; external 'oimenuapi.dll'; function batchProducts(param: TRequestParam; products: TListProduct): TSimpleResult; stdcall; external 'oimenuapi.dll'; function updateProduct(param: TRequestParam; product: TProduct): TProductResult; stdcall; external 'oimenuapi.dll'; function deleteProduct(param: TRequestParam; id: PChar): TSimpleResult; stdcall; external 'oimenuapi.dll'; function getAllOrders(param: TRequestParam): TOrderResult; stdcall; external 'oimenuapi.dll'; function setOrderAsReceived(param: TRequestParam; id: String): TSimpleResult; stdcall; external 'oimenuapi.dll'; function getAllEvents(param: TRequestParam): TEventResult; stdcall; external 'oimenuapi.dll'; function setEventAsReceived(param: TRequestParam; id: String): TSimpleResult; stdcall; external 'oimenuapi.dll'; function closeTable(param: TRequestParam; code: Integer ): TSimpleResult; stdcall; external 'oimenuapi.dll'; function transferTable(param: TRequestParam; code: Integer; codeNew: Integer ): TSimpleResult;stdcall; external 'oimenuapi.dll'; function cancelTable(param: TRequestParam; code: Integer ): TSimpleResult; stdcall; external 'oimenuapi.dll'; function reopenTable(param: TRequestParam; code: Integer ): TSimpleResult; stdcall; external 'oimenuapi.dll'; function createTableItem(param: TRequestParam; codeTable: Integer; product: TOrderProduct): TItemResult;stdcall; external 'oimenuapi.dll'; function updateTableItem(param: TRequestParam; codeTable: Integer; idItem: String; quantity: Integer; price: Double ): TItemResult;stdcall external 'oimenuapi.dll'; function transferTableItem(param: TRequestParam; codeTable: Integer; codeTableNew: Integer; idItem: String): TItemResult;stdcall; external 'oimenuapi.dll'; function transferTableItemQtd(param: TRequestParam; codeTable: Integer; codeTableNew: Integer; idItem: String; quantity: Integer): TItemResult;stdcall; external 'oimenuapi.dll'; function cancelTableItem(param: TRequestParam; code: Integer; idItem: String ): TItemResult; stdcall; external 'oimenuapi.dll'; function cancelTableItemQtd(param: TRequestParam; code: Integer; idItem: String; quantity: Integer ): TItemResult; stdcall; external 'oimenuapi.dll'; function getTableBill(param: TRequestParam; code: Integer): TBillResult; stdcall; external 'oimenuapi.dll'; function closeCard(param: TRequestParam; code: Integer ): TSimpleResult; stdcall; external 'oimenuapi.dll'; function transferCard(param: TRequestParam; code: Integer; codeNew: Integer ): TSimpleResult;stdcall; external 'oimenuapi.dll'; function cancelCard(param: TRequestParam; code: Integer ): TSimpleResult; stdcall; external 'oimenuapi.dll'; function reopenCard(param: TRequestParam; code: Integer ): TSimpleResult; stdcall; external 'oimenuapi.dll'; function createCardItem(param: TRequestParam; codeCard: Integer; product: TOrderProduct): TItemResult;stdcall; external 'oimenuapi.dll'; function updateCardItem(param: TRequestParam; codeCard: Integer; idItem: String; quantity: Integer; price: Double ): TItemResult;stdcall; external 'oimenuapi.dll'; function transferCardItem(param: TRequestParam; codeCard: Integer; codeCardNew: Integer; idItem: String): TItemResult;stdcall; external 'oimenuapi.dll'; function transferCardItemQtd(param: TRequestParam; codeCard: Integer; codeCardNew: Integer; idItem: String; quantity: Integer): TItemResult;stdcall; external 'oimenuapi.dll'; function cancelCardItem(param: TRequestParam; code: Integer; idItem: String ): TItemResult; stdcall; external 'oimenuapi.dll'; function cancelCardItemQtd(param: TRequestParam; code: Integer; idItem: String; quantity: Integer ): TItemResult; stdcall; external 'oimenuapi.dll'; function getCardBill(param: TRequestParam; code: Integer): TBillResult; stdcall; external 'oimenuapi.dll'; function getAllTables(param: TRequestParam): TTableResult; stdcall; external 'oimenuapi.dll'; function createTable(param: TRequestParam; table: TTable): TTableResult; stdcall; external 'oimenuapi.dll'; function batchTables(param: TRequestParam; tables: TListTable): TSimpleResult; stdcall; external 'oimenuapi.dll'; function updateTable(param: TRequestParam; table: TTable): TTableResult; stdcall; external 'oimenuapi.dll'; function deleteTable(param: TRequestParam; id: Integer): TSimpleResult; stdcall; external 'oimenuapi.dll'; function getAllCards(param: TRequestParam): TCardResult; stdcall; external 'oimenuapi.dll'; function createCard(param: TRequestParam; card: TCard): TCardResult; stdcall; external 'oimenuapi.dll'; function batchCards(param: TRequestParam; cards: TListCard): TSimpleResult; stdcall; external 'oimenuapi.dll'; function updateCard(param: TRequestParam; card: TCard): TCardResult; stdcall; external 'oimenuapi.dll'; function deleteCard(param: TRequestParam; id: Integer): TSimpleResult; stdcall; external 'oimenuapi.dll'; function getAllUsers(param: TRequestParam): TUserResult; stdcall; external 'oimenuapi.dll'; function createUser(param: TRequestParam; user: TUser): TUserResult; stdcall; external 'oimenuapi.dll'; function batchUsers(param: TRequestParam; users: TListUser): TSimpleResult; stdcall; external 'oimenuapi.dll'; function updateUser(param: TRequestParam; user: TUser): TUserResult; stdcall; external 'oimenuapi.dll'; function deleteUser(param: TRequestParam; id: Integer): TSimpleResult; stdcall; external 'oimenuapi.dll'; implementation Constructor TOrderItemOption.Create; begin notes := TStringList.Create; end; Destructor TOrderItemOption.Destroy; begin FreeAndNil(notes); end; Constructor TOrderItem.Create; begin options := TListOrderItemOption.Create; notes := TStringList.Create; end; Destructor TOrderItem.Destroy; begin FreeAndNil(options); FreeAndNil(notes); end; Constructor TOrder.Create; begin items := TListOrderItem.Create; end; Destructor TOrder.Destroy; begin FreeAndNil(items); end; Constructor TOrderResult.Create; begin data := TListOrder.Create; end; Destructor TOrderResult.Destroy; begin FreeAndNil(data); end; function TListOrderItemOption.GetItems(Index: Integer): TOrderItemOption; begin Result := TOrderItemOption(inherited Items[Index]); end; procedure TListOrderItemOption.SetItems(Index: Integer; const Value: TOrderItemOption); begin inherited Items[Index] := Value; end; function TListOrderItemOption.Add(AObject: TOrderItemOption): Integer; begin Result := inherited Add(AObject); end; function TListOrderItem.GetItems(Index: Integer): TOrderItem; begin Result := TOrderItem(inherited Items[Index]); end; procedure TListOrderItem.SetItems(Index: Integer; const Value: TOrderItem); begin inherited Items[Index] := Value; end; function TListOrderItem.Add(AObject: TOrderItem): Integer; begin Result := inherited Add(AObject); end; function TListOrder.GetItems(Index: Integer): TOrder; begin Result := TOrder(inherited Items[Index]); end; procedure TListOrder.SetItems(Index: Integer; const Value: TOrder); begin inherited Items[Index] := Value; end; function TListOrder.Add(AObject: TOrder): Integer; begin Result := inherited Add(AObject); end; //BILL Constructor TBillResult.Create; begin data := TBillItem.Create; end; Destructor TBillResult.Destroy; begin FreeAndNil(data); end; Constructor TBillItem.Create; begin items := TListOrderItem.Create; end; Destructor TBillItem.Destroy; begin FreeAndNil(items); end; //EVENT Constructor TEventResult.Create; begin data := TListEvent.Create; end; Destructor TEventResult.Destroy; begin FreeAndNil(data); end; function TListEvent.GetItems(Index: Integer): TEvent; begin Result := TEvent(inherited Items[Index]); end; procedure TListEvent.SetItems(Index: Integer; const Value: TEvent); begin inherited Items[Index] := Value; end; function TListEvent.Add(AObject: TEvent): Integer; begin Result := inherited Add(AObject); end; Constructor TEventCallWaiter.Create; begin options := TStringList.Create; end; Destructor TEventCallWaiter.Destroy; begin FreeAndNil(options); end; //PRODUCT Constructor TProductResult.Create; begin data := TListProduct.Create; end; Destructor TProductResult.Destroy; begin FreeAndNil(data); end; function TListProduct.GetItems(Index: Integer): TProduct; begin Result := TProduct(inherited Items[Index]); end; procedure TListProduct.SetItems(Index: Integer; const Value: TProduct); begin inherited Items[Index] := Value; end; function TListProduct.Add(AObject: TProduct): Integer; begin Result := inherited Add(AObject); end; //TABLE Constructor TTableResult.Create; begin data := TListTable.Create; end; Destructor TTableResult.Destroy; begin FreeAndNil(data); end; function TListTable.GetItems(Index: Integer): TTable; begin Result := TTable(inherited Items[Index]); end; procedure TListTable.SetItems(Index: Integer; const Value: TTable); begin inherited Items[Index] := Value; end; function TListTable.Add(AObject: TTable): Integer; begin Result := inherited Add(AObject); end; //CARD Constructor TCardResult.Create; begin data := TListCard.Create; end; Destructor TCardResult.Destroy; begin FreeAndNil(data); end; function TListCard.GetItems(Index: Integer): TCard; begin Result := TCard(inherited Items[Index]); end; procedure TListCard.SetItems(Index: Integer; const Value: TCard); begin inherited Items[Index] := Value; end; function TListCard.Add(AObject: TCard): Integer; begin Result := inherited Add(AObject); end; //USER Constructor TUserResult.Create; begin data := TListUser.Create; end; Destructor TUserResult.Destroy; begin FreeAndNil(data); end; function TListUser.GetItems(Index: Integer): TUser; begin Result := TUser(inherited Items[Index]); end; procedure TListUser.SetItems(Index: Integer; const Value: TUser); begin inherited Items[Index] := Value; end; function TListUser.Add(AObject: TUser): Integer; begin Result := inherited Add(AObject); end; end.
namespace Sugar.Collections; interface uses Sugar; type Queue<T> = public class mapped to {$IF COOPER}java.util.LinkedList<T>{$ELSEIF ECHOES}System.Collections.Generic.Queue<T>{$ELSEIF TOFFEE}Foundation.NSMutableArray{$ENDIF} public constructor; mapped to constructor(); method Contains(Item: T): Boolean; method Clear; method Peek: T; method Enqueue(Item: T); method Dequeue: T; method ToArray: array of T; property Count: Integer read {$IF COOPER}mapped.size{$ELSEIF ECHOES OR TOFFEE}mapped.Count{$ENDIF}; end; implementation method Queue<T>.Contains(Item: T): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Contains(Item); {$ELSEIF TOFFEE} exit mapped.containsObject(NullHelper.ValueOf(Item)); {$ENDIF} end; method Queue<T>.Clear; begin {$IF COOPER OR ECHOES} mapped.Clear; {$ELSEIF TOFFEE} mapped.removeAllObjects; {$ENDIF} end; method Queue<T>.Dequeue: T; begin {$IF COOPER} if self.Count = 0 then raise new SugarInvalidOperationException(ErrorMessage.COLLECTION_EMPTY); exit mapped.poll; {$ELSEIF ECHOES} exit mapped.Dequeue; {$ELSEIF TOFFEE} if self.Count = 0 then raise new SugarInvalidOperationException(ErrorMessage.COLLECTION_EMPTY); result := NullHelper.ValueOf(mapped.objectAtIndex(0)); mapped.removeObjectAtIndex(0); {$ENDIF} end; method Queue<T>.Enqueue(Item: T); begin {$IF COOPER} mapped.add(Item); {$ELSEIF ECHOES} mapped.Enqueue(Item); {$ELSEIF TOFFEE} mapped.addObject(NullHelper.ValueOf(Item)); {$ENDIF} end; method Queue<T>.Peek: T; begin {$IF COOPER OR ECHOES} {$IFDEF COOPER} if self.Count = 0 then raise new SugarInvalidOperationException(ErrorMessage.COLLECTION_EMPTY); {$ENDIF} exit mapped.Peek; {$ELSEIF TOFFEE} if self.Count = 0 then raise new SugarInvalidOperationException(ErrorMessage.COLLECTION_EMPTY); exit NullHelper.ValueOf(mapped.objectAtIndex(0)); {$ENDIF} end; method Queue<T>.ToArray: array of T; begin {$IF COOPER} exit mapped.toArray(new T[0]); {$ELSEIF ECHOES} exit mapped.ToArray; {$ELSEIF TOFFEE} exit ListHelpers.ToArray<T>(self); {$ENDIF} end; end.
unit WallpaperSetterProvider; {$mode objfpc}{$H+} interface uses Classes, SysUtils, WpcExceptions, WallpaperSetter, OSUtils; type { TWpcWallpaperSetterProvider } TWpcWallpaperSetterProvider = class(TObject) public function GetWallpaperSetter(SetterType : TWpcWallpaperSetterType) : IWallpaperSetter; private function DetectCurrentEnvironmentWallaperSetter() : TWpcWallpaperSetterType; end; implementation { TWpcWallpaperSetterProvider } function TWpcWallpaperSetterProvider.GetWallpaperSetter(SetterType: TWpcWallpaperSetterType): IWallpaperSetter; begin case SetterType of WPST_AUTODETECT: Result := Self.GetWallpaperSetter(DetectCurrentEnvironmentWallaperSetter()); WPST_DEBUG: Result := TWpcDebugWallpaperSetter.Create('Debug.txt') else raise TWpcUseErrorException.Create('Unsupported wallaper setter.'); end; end; function TWpcWallpaperSetterProvider.DetectCurrentEnvironmentWallaperSetter() : TWpcWallpaperSetterType; begin // TODO Result := WPST_DEBUG; end; end.
unit MenuWordsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\MenuWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "MenuWordsPack" MUID: (4FC7292F02EA) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , Menus , tfwClassLike , tfwScriptingInterfaces , TypInfo , tfwPropertyLike , tfwTypeInfo , tfwAxiomaticsResNameGetter , Controls , Forms , l3ScreenService , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4FC7292F02EAimpl_uses* //#UC END# *4FC7292F02EAimpl_uses* ; type TMenuItemFriend = {abstract} class(TMenuItem) {* Друг к классу TMenuItem } end;//TMenuItemFriend TkwMenuItemClick = {final} class(TtfwClassLike) {* Слово скрипта menuitem:Click } private procedure Click(const aCtx: TtfwContext; aMenuItem: TMenuItem); {* Реализация слова скрипта menuitem:Click } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwMenuItemClick TkwMenuItemGetItem = {final} class(TtfwClassLike) {* Слово скрипта menuitem:GetItem } private function GetItem(const aCtx: TtfwContext; aMenuItem: TMenuItem; anIndex: Integer): TMenuItem; {* Реализация слова скрипта menuitem:GetItem } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwMenuItemGetItem TkwMenuItemGetMenuHeight = {final} class(TtfwClassLike) {* Слово скрипта menuitem:GetMenuHeight } private function GetMenuHeight(const aCtx: TtfwContext; aMenuItem: TMenuItem): Integer; {* Реализация слова скрипта menuitem:GetMenuHeight } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwMenuItemGetMenuHeight TkwMenuItemCaption = {final} class(TtfwPropertyLike) {* Слово скрипта menuitem:GetCaption } private function Caption(const aCtx: TtfwContext; aMenuItem: TMenuItem): AnsiString; {* Реализация слова скрипта menuitem:GetCaption } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwMenuItemCaption TkwMenuItemCount = {final} class(TtfwPropertyLike) {* Слово скрипта menuitem:GetCount } private function Count(const aCtx: TtfwContext; aMenuItem: TMenuItem): Integer; {* Реализация слова скрипта menuitem:GetCount } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwMenuItemCount TkwMenuItemEnabled = {final} class(TtfwPropertyLike) {* Слово скрипта menuitem:IsEnabled } private function Enabled(const aCtx: TtfwContext; aMenuItem: TMenuItem): Boolean; {* Реализация слова скрипта menuitem:IsEnabled } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwMenuItemEnabled TkwMenuItemVisible = {final} class(TtfwPropertyLike) {* Слово скрипта menuitem:IsVisible } private function Visible(const aCtx: TtfwContext; aMenuItem: TMenuItem): Boolean; {* Реализация слова скрипта menuitem:IsVisible } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwMenuItemVisible TMenuWordsPackResNameGetter = {final} class(TtfwAxiomaticsResNameGetter) {* Регистрация скриптованой аксиоматики } public class function ResName: AnsiString; override; end;//TMenuWordsPackResNameGetter procedure TkwMenuItemClick.Click(const aCtx: TtfwContext; aMenuItem: TMenuItem); {* Реализация слова скрипта menuitem:Click } begin aMenuItem.Click; end;//TkwMenuItemClick.Click class function TkwMenuItemClick.GetWordNameForRegister: AnsiString; begin Result := 'menuitem:Click'; end;//TkwMenuItemClick.GetWordNameForRegister function TkwMenuItemClick.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwMenuItemClick.GetResultTypeInfo function TkwMenuItemClick.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwMenuItemClick.GetAllParamsCount function TkwMenuItemClick.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TMenuItem)]); end;//TkwMenuItemClick.ParamsTypes procedure TkwMenuItemClick.DoDoIt(const aCtx: TtfwContext); var l_aMenuItem: TMenuItem; begin try l_aMenuItem := TMenuItem(aCtx.rEngine.PopObjAs(TMenuItem)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aMenuItem: TMenuItem : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except Click(aCtx, l_aMenuItem); end;//TkwMenuItemClick.DoDoIt function TkwMenuItemGetItem.GetItem(const aCtx: TtfwContext; aMenuItem: TMenuItem; anIndex: Integer): TMenuItem; {* Реализация слова скрипта menuitem:GetItem } //#UC START# *552E570E0302_552E570E0302_47E7ABCB0296_Word_var* //#UC END# *552E570E0302_552E570E0302_47E7ABCB0296_Word_var* begin //#UC START# *552E570E0302_552E570E0302_47E7ABCB0296_Word_impl* Result := aMenuItem.Items[anIndex]; Result.InitiateAction; //#UC END# *552E570E0302_552E570E0302_47E7ABCB0296_Word_impl* end;//TkwMenuItemGetItem.GetItem class function TkwMenuItemGetItem.GetWordNameForRegister: AnsiString; begin Result := 'menuitem:GetItem'; end;//TkwMenuItemGetItem.GetWordNameForRegister function TkwMenuItemGetItem.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TMenuItem); end;//TkwMenuItemGetItem.GetResultTypeInfo function TkwMenuItemGetItem.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwMenuItemGetItem.GetAllParamsCount function TkwMenuItemGetItem.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TMenuItem), TypeInfo(Integer)]); end;//TkwMenuItemGetItem.ParamsTypes procedure TkwMenuItemGetItem.DoDoIt(const aCtx: TtfwContext); var l_aMenuItem: TMenuItem; var l_anIndex: Integer; begin try l_aMenuItem := TMenuItem(aCtx.rEngine.PopObjAs(TMenuItem)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aMenuItem: TMenuItem : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetItem(aCtx, l_aMenuItem, l_anIndex)); end;//TkwMenuItemGetItem.DoDoIt function TkwMenuItemGetMenuHeight.GetMenuHeight(const aCtx: TtfwContext; aMenuItem: TMenuItem): Integer; {* Реализация слова скрипта menuitem:GetMenuHeight } //#UC START# *552E57E00346_552E57E00346_47E7ABCB0296_Word_var* var I: Integer; l_Width, l_Height, l_TotalHeight: Integer; l_Canvas: TControlCanvas; //#UC END# *552E57E00346_552E57E00346_47E7ABCB0296_Word_var* begin //#UC START# *552E57E00346_552E57E00346_47E7ABCB0296_Word_impl* l_TotalHeight := 0; l_Canvas := TControlCanvas.Create; try l_Canvas.Handle := Tl3ScreenService.Instance.IC.DC; l_Canvas.Font := Screen.MenuFont; for I := 0 to aMenuItem.Count - 1 do begin l_Height := 0; TMenuItemFriend(aMenuItem.Items[I]).MeasureItem(l_Canvas, l_Width, l_Height); l_TotalHeight := l_TotalHeight + l_Height; end;//for I finally FreeAndNil(l_Canvas); end;//try..finally Result := l_TotalHeight; //#UC END# *552E57E00346_552E57E00346_47E7ABCB0296_Word_impl* end;//TkwMenuItemGetMenuHeight.GetMenuHeight class function TkwMenuItemGetMenuHeight.GetWordNameForRegister: AnsiString; begin Result := 'menuitem:GetMenuHeight'; end;//TkwMenuItemGetMenuHeight.GetWordNameForRegister function TkwMenuItemGetMenuHeight.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwMenuItemGetMenuHeight.GetResultTypeInfo function TkwMenuItemGetMenuHeight.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwMenuItemGetMenuHeight.GetAllParamsCount function TkwMenuItemGetMenuHeight.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TMenuItem)]); end;//TkwMenuItemGetMenuHeight.ParamsTypes procedure TkwMenuItemGetMenuHeight.DoDoIt(const aCtx: TtfwContext); var l_aMenuItem: TMenuItem; begin try l_aMenuItem := TMenuItem(aCtx.rEngine.PopObjAs(TMenuItem)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aMenuItem: TMenuItem : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(GetMenuHeight(aCtx, l_aMenuItem)); end;//TkwMenuItemGetMenuHeight.DoDoIt function TkwMenuItemCaption.Caption(const aCtx: TtfwContext; aMenuItem: TMenuItem): AnsiString; {* Реализация слова скрипта menuitem:GetCaption } begin Result := aMenuItem.Caption; end;//TkwMenuItemCaption.Caption class function TkwMenuItemCaption.GetWordNameForRegister: AnsiString; begin Result := 'menuitem:GetCaption'; end;//TkwMenuItemCaption.GetWordNameForRegister function TkwMenuItemCaption.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwMenuItemCaption.GetResultTypeInfo function TkwMenuItemCaption.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwMenuItemCaption.GetAllParamsCount function TkwMenuItemCaption.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TMenuItem)]); end;//TkwMenuItemCaption.ParamsTypes procedure TkwMenuItemCaption.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Caption', aCtx); end;//TkwMenuItemCaption.SetValuePrim procedure TkwMenuItemCaption.DoDoIt(const aCtx: TtfwContext); var l_aMenuItem: TMenuItem; begin try l_aMenuItem := TMenuItem(aCtx.rEngine.PopObjAs(TMenuItem)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aMenuItem: TMenuItem : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(Caption(aCtx, l_aMenuItem)); end;//TkwMenuItemCaption.DoDoIt function TkwMenuItemCount.Count(const aCtx: TtfwContext; aMenuItem: TMenuItem): Integer; {* Реализация слова скрипта menuitem:GetCount } begin Result := aMenuItem.Count; end;//TkwMenuItemCount.Count class function TkwMenuItemCount.GetWordNameForRegister: AnsiString; begin Result := 'menuitem:GetCount'; end;//TkwMenuItemCount.GetWordNameForRegister function TkwMenuItemCount.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwMenuItemCount.GetResultTypeInfo function TkwMenuItemCount.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwMenuItemCount.GetAllParamsCount function TkwMenuItemCount.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TMenuItem)]); end;//TkwMenuItemCount.ParamsTypes procedure TkwMenuItemCount.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Count', aCtx); end;//TkwMenuItemCount.SetValuePrim procedure TkwMenuItemCount.DoDoIt(const aCtx: TtfwContext); var l_aMenuItem: TMenuItem; begin try l_aMenuItem := TMenuItem(aCtx.rEngine.PopObjAs(TMenuItem)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aMenuItem: TMenuItem : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(Count(aCtx, l_aMenuItem)); end;//TkwMenuItemCount.DoDoIt function TkwMenuItemEnabled.Enabled(const aCtx: TtfwContext; aMenuItem: TMenuItem): Boolean; {* Реализация слова скрипта menuitem:IsEnabled } begin Result := aMenuItem.Enabled; end;//TkwMenuItemEnabled.Enabled class function TkwMenuItemEnabled.GetWordNameForRegister: AnsiString; begin Result := 'menuitem:IsEnabled'; end;//TkwMenuItemEnabled.GetWordNameForRegister function TkwMenuItemEnabled.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwMenuItemEnabled.GetResultTypeInfo function TkwMenuItemEnabled.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwMenuItemEnabled.GetAllParamsCount function TkwMenuItemEnabled.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TMenuItem)]); end;//TkwMenuItemEnabled.ParamsTypes procedure TkwMenuItemEnabled.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Enabled', aCtx); end;//TkwMenuItemEnabled.SetValuePrim procedure TkwMenuItemEnabled.DoDoIt(const aCtx: TtfwContext); var l_aMenuItem: TMenuItem; begin try l_aMenuItem := TMenuItem(aCtx.rEngine.PopObjAs(TMenuItem)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aMenuItem: TMenuItem : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(Enabled(aCtx, l_aMenuItem)); end;//TkwMenuItemEnabled.DoDoIt function TkwMenuItemVisible.Visible(const aCtx: TtfwContext; aMenuItem: TMenuItem): Boolean; {* Реализация слова скрипта menuitem:IsVisible } begin Result := aMenuItem.Visible; end;//TkwMenuItemVisible.Visible class function TkwMenuItemVisible.GetWordNameForRegister: AnsiString; begin Result := 'menuitem:IsVisible'; end;//TkwMenuItemVisible.GetWordNameForRegister function TkwMenuItemVisible.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwMenuItemVisible.GetResultTypeInfo function TkwMenuItemVisible.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwMenuItemVisible.GetAllParamsCount function TkwMenuItemVisible.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TMenuItem)]); end;//TkwMenuItemVisible.ParamsTypes procedure TkwMenuItemVisible.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Visible', aCtx); end;//TkwMenuItemVisible.SetValuePrim procedure TkwMenuItemVisible.DoDoIt(const aCtx: TtfwContext); var l_aMenuItem: TMenuItem; begin try l_aMenuItem := TMenuItem(aCtx.rEngine.PopObjAs(TMenuItem)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aMenuItem: TMenuItem : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(Visible(aCtx, l_aMenuItem)); end;//TkwMenuItemVisible.DoDoIt class function TMenuWordsPackResNameGetter.ResName: AnsiString; begin Result := 'MenuWordsPack'; end;//TMenuWordsPackResNameGetter.ResName {$R MenuWordsPack.res} initialization TkwMenuItemClick.RegisterInEngine; {* Регистрация MenuItem_Click } TkwMenuItemGetItem.RegisterInEngine; {* Регистрация MenuItem_GetItem } TkwMenuItemGetMenuHeight.RegisterInEngine; {* Регистрация MenuItem_GetMenuHeight } TkwMenuItemCaption.RegisterInEngine; {* Регистрация MenuItem_Caption } TkwMenuItemCount.RegisterInEngine; {* Регистрация MenuItem_Count } TkwMenuItemEnabled.RegisterInEngine; {* Регистрация MenuItem_Enabled } TkwMenuItemVisible.RegisterInEngine; {* Регистрация MenuItem_Visible } TMenuWordsPackResNameGetter.Register; {* Регистрация скриптованой аксиоматики } TtfwTypeRegistrator.RegisterType(TypeInfo(TMenuItem)); {* Регистрация типа TMenuItem } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Sequences, Works, StdCtrls, ArchManThd, IniFiles; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; Memo2: TMemo; stTime: TStaticText; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } S1,S2:TSequence; Thd1,Thd2:TFinder; AM:TArchManThread; Stop,InProcess:Boolean; Time,StopTime:TDateTime; Calc1Time,Calc2Time:TDateTime; Ini:TIniFile; MaxDT,BlockLen:Integer; WriteTracks:Boolean; ShowMinDT,ShowMaxDT:Integer; ShowWToAvgRatio:Double; end; const Section='Config'; dtOneSecond=1/(24*60*60); var Form1: TForm1; implementation uses Misc, DataTypes, SensorTypes; {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); var Alpha1,Alpha2,Damping,Smoothing:Double; begin InitFormattingVariables; Ini:=TIniFile.Create(GetModuleFullName+'.ini'); MaxDT:=Ini.ReadInteger(Section,'MaxDT',100); BlockLen:=Ini.ReadInteger(Section,'BlockLen',15); Alpha1:=Ini.ReadFloat(Section,'Alpha1',0.7); Alpha2:=Ini.ReadFloat(Section,'Alpha2',0.98); Damping:=Ini.ReadFloat(Section,'Damping',0.15); Smoothing:=Ini.ReadFloat(Section,'Smoothing',0.95); // S1:=TDiffSequence.Create(MaxDT+BlockLen,Alpha1,Alpha2); // S2:=TDiffSequence.Create(MaxDT+BlockLen,Alpha1,Alpha2); S1:=TDispSequence.Create(MaxDT+BlockLen,15); S2:=TDispSequence.Create(MaxDT+BlockLen,15); AM:=TArchManThread.Create; // 1 Thd1:=TFinder.Create; Thd1.S1:=S1; Thd1.S2:=S2; Thd1.BlockLen:=BlockLen; Thd1.Damping:=Damping; Thd1.Smoothing:=Smoothing; // 2 Thd2:=TFinder.Create; Thd2.S1:=S2; Thd2.S2:=S1; Thd2.BlockLen:=BlockLen; Thd2.Damping:=Damping; Thd2.Smoothing:=Smoothing; // Time:=Ini.ReadDateTime(Section,'StartTime',0); StopTime:=Ini.ReadDateTime(Section,'StopTime',0); Calc1Time:=Ini.ReadDateTime(Section,'Calc1Time',0)+(MaxDT+BlockLen)*dtOneSecond; Calc2Time:=Ini.ReadDateTime(Section,'Calc2Time',0)+(MaxDT+BlockLen)*dtOneSecond; WriteTracks:=Ini.ReadBool(Section,'WriteTracks',False); ShowMinDT:=Ini.ReadInteger(Section,'ShowMinDT',0); ShowMaxDT:=Ini.ReadInteger(Section,'ShowMaxDT',MaxDT); ShowWToAvgRatio:=Ini.ReadFloat(Section,'ShowWToAvgRatio',0.5); end; procedure TForm1.FormDestroy(Sender: TObject); begin Thd2.Free; Thd1.Free; AM.Free; S2.Free; S1.Free; end; procedure TForm1.Button1Click(Sender: TObject); type TWorkState=record Old_iMax:Integer; OldMaxWeight:Double; end; var i,SecCnt:Integer; InID1,InID2:Integer; OutID1,OutID2:Integer; InData1,InData2:WideString; OutData1,OutData2:WideString; AD:TAnalogData; Value1,Value2:Single; WS1,WS2:TWorkState; StartTime:TDateTime; procedure ShowWorkState(Memo:TMemo; var WS:TWorkState; Thd:TFinder); var StartT:TDateTime; begin if (ShowMinDT<=Thd.iFound) and (Thd.iFound<=ShowMaxDT) and (Thd.wFound<Thd.wAvg*ShowWToAvgRatio) { and ( (Abs(WS.Old_iMax-Thd.iFound)>1) or (Thd.wFound<WS.OldMaxWeight) )//} then begin WS.Old_iMax:=Thd.iFound; WS.OldMaxWeight:=Thd.wFound; StartT:=Frac(Time)-Thd.S1.ItemsLength*dtOneSecond; Memo.SelText:= 'T='+TimeToStr(StartT)+ '; T2='+TimeToStr(StartT+Thd.iFound*dtOneSecond)+ '; DT='+IntToStr(Thd.iFound)+ '; w/wA='+Format('%g',[Thd.wFound/Thd.wAvg])+#13#10; end; end; begin if (Time>=StopTime) or InProcess then begin Stop:=True; exit; end; Button1.Caption:='Stop'; Stop:=False; InProcess:=True; AM.Resume; AM.StrToTrackID(Ini.ReadString(Section, 'InTrk1','ZZZ'), InID1); AM.setTrackInfo( InID1,3,24*60*60); AM.StrToTrackID(Ini.ReadString(Section, 'InTrk2','ZZZ'), InID2); AM.setTrackInfo( InID2,3,24*60*60); AM.StrToTrackID(Ini.ReadString(Section,'OutTrk1','ZZZ'),OutID1); AM.setTrackInfo(OutID1,3,24*60*60); AM.StrToTrackID(Ini.ReadString(Section,'OutTrk2','ZZZ'),OutID2); AM.setTrackInfo(OutID2,3,24*60*60); Value1:=0; Value2:=0; StartTime:=Time; SecCnt:=Round((StopTime-StartTime)/dtOneSecond); AM.readRecords(InID1,StartTime,SecCnt,InData1); SetLength(OutData1,Length(InData1)); AM.readRecords(InID2,StartTime,SecCnt,InData2); SetLength(OutData2,Length(InData2)); AM.Suspend; i:=0; FillChar(WS1,SizeOf(WS1),0); FillChar(WS2,SizeOf(WS2),0); while (i<SecCnt) and not Stop do begin // 1 TMySensor.GetAD(InData1,i,AD); if ValidAD(AD) then Value1:=AD.Value; S1.Add(Value1); AD.Value:=S1.LastValue; if AD.Flags=0 then AD.Value:=SignedZero; TMySensor.SetAD(OutData1,i,AD); // 2 TMySensor.GetAD(InData2,i,AD); if ValidAD(AD) then Value2:=AD.Value; S2.Add(Value2); AD.Value:=S2.LastValue; if AD.Flags=0 then AD.Value:=SignedZero; TMySensor.SetAD(OutData2,i,AD); if (Time<=Calc1Time) and (Calc1Time<=Time+dtOneSecond) then Thd1.CalcParams(Ini.ReadInteger(Section,'Calc1DT',MaxDT)); if (Time<=Calc2Time) and (Calc2Time<=Time+dtOneSecond) then Thd2.CalcParams(Ini.ReadInteger(Section,'Calc2DT',MaxDT)); // find if Thd1.Work2(MaxDT) then ShowWorkState(Memo1,WS1,Thd1); if Thd2.Work2(MaxDT) then ShowWorkState(Memo2,WS2,Thd2); // next Inc(i); if (i and $7F=$7F) or (i=SecCnt) then begin Application.ProcessMessages; if (i and $FF=$FF) or (i=SecCnt) then stTime.Caption:=TimeToStr(Frac(Time)); end; Time:=Time+dtOneSecond; end; if WriteTracks then begin i:=Round((Time-StartTime)/dtOneSecond); AM.Resume; AM.writeRecords(OutID1,StartTime,i,OutData1); AM.writeRecords(OutID2,StartTime,i,OutData2); AM.Suspend; end; InProcess:=False; if Time>=StopTime then Button1.Visible:=False else Button1.Caption:='Start'; end; end.
(* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 Thrift.Utils; interface uses Classes, Windows, SysUtils, SyncObjs; type IOverlappedHelper = interface ['{A1832EFA-2E02-4884-8F09-F0A0277157FA}'] function Overlapped : TOverlapped; function OverlappedPtr : POverlapped; function WaitHandle : THandle; function WaitFor(dwTimeout: DWORD) : DWORD; end; TOverlappedHelperImpl = class( TInterfacedObject, IOverlappedHelper) strict protected FOverlapped : TOverlapped; FEvent : TEvent; // IOverlappedHelper function Overlapped : TOverlapped; function OverlappedPtr : POverlapped; function WaitHandle : THandle; function WaitFor(dwTimeout: DWORD) : DWORD; public constructor Create; destructor Destroy; override; end; function IfValue(B: Boolean; const TrueValue, FalseValue: WideString): string; implementation function IfValue(B: Boolean; const TrueValue, FalseValue: WideString): string; begin if B then Result := TrueValue else Result := FalseValue; end; { TOverlappedHelperImpl } constructor TOverlappedHelperImpl.Create; begin inherited Create; FillChar( FOverlapped, SizeOf(FOverlapped), 0); FEvent := TEvent.Create( nil, TRUE, FALSE, ''); // always ManualReset, see MSDN FOverlapped.hEvent := FEvent.Handle; end; destructor TOverlappedHelperImpl.Destroy; begin try FOverlapped.hEvent := 0; FreeAndNil( FEvent); finally inherited Destroy; end; end; function TOverlappedHelperImpl.Overlapped : TOverlapped; begin result := FOverlapped; end; function TOverlappedHelperImpl.OverlappedPtr : POverlapped; begin result := @FOverlapped; end; function TOverlappedHelperImpl.WaitHandle : THandle; begin result := FOverlapped.hEvent; end; function TOverlappedHelperImpl.WaitFor( dwTimeout : DWORD) : DWORD; begin result := WaitForSingleObject( FOverlapped.hEvent, dwTimeout); end; end.
unit nsDownloader; interface uses Classes, Windows, ActiveX, UrlMon, l3ProtoObject, nsDownloaderInterfaces, nsDownloaderThread, nsDownloaderThreadList, nscSystemProgressDialog; type TnsDownloadParams = class(Tl3ProtoObject, InsDownloadParams) private FFileAction: TnsDownloadFileAction; FURL: string; FFileName: string; FFileTypeString: string; FFileIcon: HICON; procedure MakeFileName; procedure GetFileProperties; constructor Create(const AURL: String; AFileAction: TnsDownloadFileAction); overload; constructor Create(const AURL: String; AFileAction: TnsDownloadFileAction; const AFileName: String); overload; protected function GetFileAction: TnsDownloadFileAction; procedure SetFileAction(AFileAction: TnsDownloadFileAction); function GetURL: string; procedure SetURL(const AURL: String); function GetFileName: string; procedure SetFileName(const AFileName: String); function GetFileTypeString: string; procedure SetFileTypeString(const AFileTypeString: String); function GetFileIcon: HICON; public class function Make(const AURL: String; AFileAction: TnsDownloadFileAction): InsDownloadParams; overload; class function Make(const AURL: String; AFileAction: TnsDownloadFileAction; const AFileName: String): InsDownloadParams; overload; end; TnsDownloader = class(Tl3ProtoObject, IBindStatusCallback, InsDownloader) private FLockCS: TRTLCriticalSection; FBinding: IBinding; FParams: InsDownloadParams; FEventSink: Pointer; FDownloaderState: TnsDownloaderState; FCurrentProgress: Integer; FTotalProgress: Integer; FFinished: Boolean; FStartCalled: Boolean; constructor Create(const AParams: InsDownloadParams; ASink: InsDownloaderEventSink); procedure StartDownload; procedure Lock; procedure Unlock; protected procedure Cleanup; override; // IBindStatusCallBack function OnStartBinding(dwReserved: DWORD; pib: IBinding): HResult; stdcall; function GetPriority(out nPriority): HResult; stdcall; function OnLowResource(reserved: DWORD): HResult; stdcall; function OnProgress(ulProgress, ulProgressMax, ulStatusCode: ULONG; szStatusText: LPCWSTR): HResult; stdcall; function OnStopBinding(hresult: HResult; szError: LPCWSTR): HResult; stdcall; function GetBindInfo(out grfBINDF: DWORD; var bindinfo: TBindInfo): HResult; stdcall; function OnDataAvailable(grfBSCF: DWORD; dwSize: DWORD; formatetc: PFormatEtc; stgmed: PStgMedium): HResult; stdcall; function OnObjectAvailable(const iid: TGUID; punk: IUnknown): HResult; stdcall; // InsDownloader function GetParams: InsDownloadParams; procedure CancelDownload; function MakeState: TnsDownloaderState; function GetFinished: Boolean; procedure Start; procedure Cancel; public class function Make(const AParams: InsDownloadParams; ASink: InsDownloaderEventSink): InsDownloader; end; TnsDownloadService = class(Tl3ProtoObject) private FThreads: TnsDownloaderThreadList; FActiveThreadNumber: Integer; procedure RegisterThread(AThread: TnsDownloaderThread); procedure UnregisterThread(AThread: TnsDownloaderThread); procedure TerminateThreads; procedure WaitForThreads; function MakeThread(const AParams: InsDownloadParams): TnsDownloaderThread; constructor Create; protected procedure DoOnThreadStarted(AThread: TnsDownloaderThread); procedure DoOnBeforeThreadDestroy(AThread: TnsDownloaderThread); procedure Cleanup; override; public class function Instance: TnsDownloadService; procedure DownloadFile(const AURL: String); end; implementation uses SysUtils, Forms, ShellAPI, l3Base, l3Interlocked, l3String, nsDownloaderRes, nsDownloaderGUIService; function HexToInt(const AHexStr: String): Int64; var l_Len: Integer; l_Str: String; i: Byte; begin l_Len := Length(AHexStr); l_Str := UpperCase(AHexStr); if l_Str[l_Len] = 'H' then Delete(l_Str, l_Len, 1); Result := 0; for i := 1 to l_Len do begin Result := Result shl 4; if l_Str[i] in ['0'..'9'] then Result := Result + (byte(l_Str[i]) - 48) else if l_Str[i] in ['A'..'F'] then Result := Result + (byte(l_Str[i]) - 55) else begin Result := 0; break; end; end; end; function UrlDecode(const AEncodedStr: String): String; var i: Integer; l_Len: Integer; begin Result := ''; l_Len := Length(AEncodedStr); if l_Len > 0 then begin i := 1; while i <= l_Len do begin if AEncodedStr[i] = '%' then begin Result := Result + Chr(HexToInt(AEncodedStr[i + 1] + AEncodedStr[i + 2])); Inc(i, 2); end else if AEncodedStr[i] = '+' then Result := Result + ' ' else Result := Result + AEncodedStr[i]; Inc(i); end; end; end; function GetURLFilename(const AFilePath: String; const ADelimiter: String = '/'): string; var l_DelimPos: Integer; begin l_DelimPos := LastDelimiter(ADelimiter, AFilePath); Result := Copy(AFilePath, l_DelimPos + 1, MaxInt); Result := UrlDecode(Result); end; { TnsDownloadParams } procedure TnsDownloadParams.MakeFileName; var l_FileName: String; l_Path: String; l_PathLen: Integer; begin l_FileName := GetURLFilename(FURL); case FFileAction of dfaOpen: begin l_PathLen := MAX_PATH; SetLength(l_Path, l_PathLen); GetTempPath(l_PathLen, PChar(l_Path)); FFileName := PChar(IncludeTrailingPathDelimiter(l_Path)) + l_FileName; end; dfaSave: FFileName := IncludeTrailingPathDelimiter(GetCurrentDir) + l_FileName; dfaSaveAs: FFileName := ''; end; end; procedure TnsDownloadParams.GetFileProperties; var l_SFI: TShFileInfo; begin l3FillChar(l_SFI, SizeOf(l_SFI), 0); if (SHGetFileInfo(PChar(ExtractFileName(FFileName)), FILE_ATTRIBUTE_NORMAL, l_SFI, SizeOf(l_SFI), SHGFI_USEFILEATTRIBUTES or SHGFI_TYPENAME or SHGFI_DISPLAYNAME or SHGFI_ICON or SHGFI_LARGEICON) <> 0) then FFileTypeString := l_SFI.szTypeName else FFileTypeString := l3Str(str_UnknownFile.AsCStr); FFileIcon := l_SFI.hIcon; end; constructor TnsDownloadParams.Create(const AURL: String; AFileAction: TnsDownloadFileAction); begin inherited Create; FURL := AURL; FFileAction := AFileAction; MakeFileName; GetFileProperties; end; constructor TnsDownloadParams.Create(const AURL: String; AFileAction: TnsDownloadFileAction; const AFileName: String); begin Create(AURL, AFileAction); FFileName := AFileName; end; function TnsDownloadParams.GetFileAction: TnsDownloadFileAction; begin Result := FFileAction; end; procedure TnsDownloadParams.SetFileAction(AFileAction: TnsDownloadFileAction); begin if (AFileAction <> FFileAction) then begin FFileAction := AFileAction; MakeFileName; end; end; function TnsDownloadParams.GetURL: string; begin Result := FURL; end; procedure TnsDownloadParams.SetURL(const AURL: String); begin if (AURL <> FURL) then FURL := AURL; end; function TnsDownloadParams.GetFileName: String; begin Result := FFileName; end; procedure TnsDownloadParams.SetFileName(const AFileName: String); begin if (AFileName <> FFileName) then FFileName := AFileName; end; function TnsDownloadParams.GetFileTypeString: String; begin Result := FFileTypeString end; procedure TnsDownloadParams.SetFileTypeString(const AFileTypeString: String); begin if (AFileTypeString <> FFileTypeString) then FFileTypeString := AFileTypeString; end; function TnsDownloadParams.GetFileIcon: HICON; begin Result := FFileIcon; end; class function TnsDownloadParams.Make(const AURL: String; AFileAction: TnsDownloadFileAction): InsDownloadParams; var l_Inst: TnsDownloadParams; begin l_Inst := Create(AURL, AFileAction); Result := l_Inst; FreeAndNil(l_Inst); end; class function TnsDownloadParams.Make(const AURL: String; AFileAction: TnsDownloadFileAction; const AFileName: String): InsDownloadParams; var l_Inst: TnsDownloadParams; begin l_Inst := Create(AURL, AFileAction, AFileName); Result := l_Inst; FreeAndNil(l_Inst); end; { TnsDownloader } constructor TnsDownloader.Create(const AParams: InsDownloadParams; ASink: InsDownloaderEventSink); begin inherited Create; InitializeCriticalSection(FLockCS); FParams := AParams; FEventSink := Pointer(ASink); end; procedure TnsDownloader.StartDownload; begin URLDownloadToFile(nil, PChar(FParams.URL), PChar(FParams.FileName), 0, Self); end; procedure TnsDownloader.Lock; begin EnterCriticalSection(FLockCS); end; procedure TnsDownloader.Unlock; begin LeaveCriticalSection(FLockCS); end; procedure TnsDownloader.Cleanup; begin DeleteCriticalSection(FLockCS); FBinding := nil; FParams := nil; FEventSink := nil; inherited; end; function TnsDownloader.OnStartBinding(dwReserved: DWORD; pib: IBinding): HResult; begin Result := E_NOTIMPL; FBinding := pib; end; function TnsDownloader.GetPriority(out nPriority): HResult; begin Result := E_NOTIMPL; end; function TnsDownloader.OnLowResource(reserved: DWORD): HResult; begin Result := E_NOTIMPL; end; function TnsDownloader.OnProgress(ulProgress, ulProgressMax, ulStatusCode: ULONG; szStatusText: LPCWSTR): HResult; var l_State: TnsDownloaderState; begin Lock; try FCurrentProgress := ulProgress; FTotalProgress := ulProgressMax; l_State := MakeState; if not FStartCalled then begin if (FEventSink <> nil) then InsDownloaderEventSink(FEventSink).OnStartDownload(FParams, l_State); FStartCalled := True; end; case ulStatusCode of BINDSTATUS_ENDDOWNLOADDATA: begin if (FEventSink <> nil) then InsDownloaderEventSink(FEventSink).OnDownloadFinished(FParams, l_State); FFinished := True; end; BINDSTATUS_DOWNLOADINGDATA: if (FEventSink <> nil) then InsDownloaderEventSink(FEventSink).OnProgress(FParams, l_State); end; Result := S_OK; finally Unlock; end; end; function TnsDownloader.OnStopBinding(hresult: HResult; szError: LPCWSTR): HResult; begin FBinding := nil; Result := E_NOTIMPL; end; function TnsDownloader.GetBindInfo(out grfBINDF: DWORD; var bindinfo: TBindInfo): HResult; begin Result := E_NOTIMPL; end; function TnsDownloader.OnDataAvailable(grfBSCF: DWORD; dwSize: DWORD; formatetc: PFormatEtc; stgmed: PStgMedium): HResult; begin Result := E_NOTIMPL; end; function TnsDownloader.OnObjectAvailable(const iid: TGUID; punk: IUnknown): HResult; begin Result := E_NOTIMPL; end; function TnsDownloader.GetParams: InsDownloadParams; begin Result := FParams; end; procedure TnsDownloader.CancelDownload; begin FBinding.Abort; end; function TnsDownloader.MakeState: TnsDownloaderState; begin Finalize(Result); Result := TnsDownloaderState_C(FTotalProgress, FCurrentProgress, FParams); end; function TnsDownloader.GetFinished: Boolean; begin Lock; Result := FFinished; Unlock; end; procedure TnsDownloader.Start; begin StartDownload; end; procedure TnsDownloader.Cancel; begin if (FBinding <> nil) then FBinding.Abort; // А если FBinding = nil - значит, уже и так никакой загрузки не происходит, // нечего и отменять. end; class function TnsDownloader.Make(const AParams: InsDownloadParams; ASink: InsDownloaderEventSink): InsDownloader; var l_Inst: TnsDownloader; begin l_Inst := TnsDownloader.Create(AParams, ASink); Result := l_Inst; FreeAndNil(l_Inst); end; { TnsDownloadService } procedure TnsDownloadService.RegisterThread(AThread: TnsDownloaderThread); begin FThreads.Add(AThread); end; procedure TnsDownloadService.UnregisterThread(AThread: TnsDownloaderThread); begin FThreads.Remove(AThread); end; procedure TnsDownloadService.TerminateThreads; var l_Index: Integer; begin for l_Index := 0 to Pred(FThreads.Count) do FThreads[l_Index].Terminate; end; procedure TnsDownloadService.WaitForThreads; var l_Handles: TWOHandleArray; l_Index: Integer; begin l3FillChar(l_Handles, SizeOf(l_Handles), 0); for l_Index := 0 to Pred(FThreads.Count) do l_Handles[l_Index] := FThreads[l_Index].Handle; WaitForMultipleObjects(FThreads.Count, @l_Handles, True, INFINITE); end; function TnsDownloadService.MakeThread(const AParams: InsDownloadParams): TnsDownloaderThread; begin Result := TnsDownloaderThread.Create(AParams); Result.OnStarted := DoOnThreadStarted; Result.OnBeforeDestroy := DoOnBeforeThreadDestroy; end; constructor TnsDownloadService.Create; begin inherited; FThreads := TnsDownloaderThreadList.Create; end; procedure TnsDownloadService.DoOnThreadStarted(AThread: TnsDownloaderThread); begin RegisterThread(AThread); end; procedure TnsDownloadService.DoOnBeforeThreadDestroy(AThread: TnsDownloaderThread); begin UnregisterThread(AThread); end; procedure TnsDownloadService.Cleanup; begin TerminateThreads; WaitForThreads; FreeAndNil(FThreads); inherited; end; var g_TnsDownloadService: TnsDownloadService = nil; procedure TnsDownloadService_Free; begin FreeAndNil(g_TnsDownloadService); end; class function TnsDownloadService.Instance: TnsDownloadService; begin if (g_TnsDownloadService = nil) then begin g_TnsDownloadService := TnsDownloadService.Create; l3System.AddExitProc(TnsDownloadService_Free); end; Result := g_TnsDownloadService; end; procedure TnsDownloadService.DownloadFile(const AURL: String); var l_Params: InsDownloadParams; l_Thread: TnsDownloaderThread; begin l_Params := TnsDownloadParams.Make(AURL, dfaSave); if (not TnsDownloaderGUIService.Instance.EditParams(l_Params)) then Exit; l_Thread := MakeThread(l_Params); l_Thread.Resume; end; end.
unit ultiboGLES2C; {$mode delphi} {Default to Delphi compatible syntax} {$H+} {Default to AnsiString} {$inline on} {Allow use of Inline procedures} interface {The VideoCore IV GPU supports both OpenGL ES 1.1 and 2.0 so we have enabled the Free Pascal units for both versions in Ultibo. When using OpenGL ES 2.0 the GLES20 unit includes the EGL functions needed to setup and initialize OpenGL ES so the only additional requirement is DispmanX} uses GlobalConst,GlobalTypes,GlobalConfig,Platform,HeapManager,Console,SysUtils,GLES20,Threads,DispmanX,VC4,Math,Syscalls,Mouse,DWCOTG; {$linklib libultiboCgeneric} procedure ultibo_C_main; cdecl; external 'libultiboCgeneric' name 'ultibo_C_main'; procedure glSwapBuffer;export; cdecl; procedure getMouseXY(var cx: integer; var cy: integer; var btc: integer; var mwh: integer);export; cdecl; procedure getScreenSize(var scrWidth: LongWord ; var scrHeight: LongWord);export; cdecl; procedure getKey(var value : integer); export; cdecl; type {A structure to keep track of the overall state including the DispmanX and EGL handles} {GLES2 State} PGLES2State = ^TGLES2State; TGLES2State = record {Screen dimensions} ScreenWidth:LongWord; ScreenHeight:LongWord; {DispmanX window} DispmanDisplay:DISPMANX_DISPLAY_HANDLE_T; DispmanElement:DISPMANX_ELEMENT_HANDLE_T; {EGL data} Display:EGLDisplay; Surface:EGLSurface; Context:EGLContext; {EGL config} Alpha:VC_DISPMANX_ALPHA_T; NativeWindow:EGL_DISPMANX_WINDOW_T; ConfigAttributes:array[0..18] of EGLint; ContextAttributes:array[0..2] of EGLint; end; var State:TGLES2State; Thread1Handle:TThreadHandle; mouseCX: integer = 0; mouseCY: integer = 0; mouseBt: integer = 0; mouseWh: integer = 0; {The main functions of our GLES2 example} procedure StartGLES2; procedure CleanupGLES2(var State:TGLES2State); procedure NonBlockingMouse; {Functions dealing with initializing, updating and rendering our OpenGL ES scene} function GLES2Init(var State:TGLES2State):Boolean; implementation procedure getKey(var value : integer); var Key: Char; begin // Check if a key is available (without waiting) if ConsolePeekKey(Key, nil) then begin // Remove the key from the buffer ConsoleGetKey(Key, nil); // Return the ordinal value of the character value := Ord(Key); end else value := -1; end; procedure getMouseXY(var cx: integer; var cy: integer; var btc: integer; var mwh: integer); begin cx := mouseCX; cy := mouseCY; btc := mouseBt; mwh := mouseWh; end; procedure getScreenSize(var scrWidth: LongWord ; var scrHeight: LongWord); begin scrWidth := State.ScreenWidth; scrHeight := State.ScreenHeight; end; procedure NonBlockingMouse; var Mousedata : TMouseData; count : LongWord; ScalingX:Double; ScalingY:Double; ScalingW:Double; ScreenWidth:LongWord; ScreenHeight:LongWord; begin ScreenWidth := State.ScreenWidth; ScreenHeight := State.ScreenHeight; while True do begin {if (MousePeek() = ERROR_SUCCESS) then} if MouseRead(@MouseData,SizeOf(TMouseData),Count) = ERROR_SUCCESS then begin {We received a mouse message so let's process it to see what it contains. The TMouseData structure will give us an X an Y Offset as well as any buttons that are currently pressed.} {Check the buttons} if MouseData.Buttons = 0 then begin mouseBt:=0; end else begin if (MouseData.Buttons and (MOUSE_LEFT_BUTTON or MOUSE_RIGHT_BUTTON)) = (MOUSE_LEFT_BUTTON or MOUSE_RIGHT_BUTTON) then begin mouseBt:=3; end else if (MouseData.Buttons and MOUSE_LEFT_BUTTON) = MOUSE_LEFT_BUTTON then begin mouseBt:=1; end else if (MouseData.Buttons and MOUSE_RIGHT_BUTTON) = MOUSE_RIGHT_BUTTON then begin mouseBt:=2; end else begin mouseBt:=4; end; end; end; {Now update our mouse tracking for cursor X and Y} {Check if the X value is absolute instead of relative} if (MouseData.Buttons and MOUSE_ABSOLUTE_X) = MOUSE_ABSOLUTE_X then begin {For absolute values the maximum X field allows us to scale the cursor X value relative to the size of our screen} ScalingX:=MouseData.MaximumX / ScreenWidth; if ScalingX <= 0 then ScalingX:=1.0; mouseCX:=Trunc(MouseData.OffsetX / ScalingX); end else begin mouseCX:=mouseCX + MouseData.OffsetX; end; if mouseCX < 0 then mouseCX:=0; if mouseCX > (ScreenWidth - 1) then mouseCX:=ScreenWidth - 1; {Check if the Y value is absolute} if (MouseData.Buttons and MOUSE_ABSOLUTE_Y) = MOUSE_ABSOLUTE_Y then begin {Use maximum Y to scale the Y value to the screen} ScalingY:=MouseData.MaximumY / ScreenHeight; if ScalingY <= 0 then ScalingY:=1.0; mouseCY:=Trunc(MouseData.OffsetY / ScalingY); end else begin mouseCY:=mouseCY + MouseData.OffsetY; end; if mouseCY < 0 then mouseCY:=0; if mouseCY > (ScreenHeight - 1) then mouseCY:=ScreenHeight - 1; {start wheel} if (MouseData.Buttons and MOUSE_ABSOLUTE_WHEEL) = MOUSE_ABSOLUTE_WHEEL then begin {Use maximum Wheel to scale the wheel value to the screen} ScalingW:=MouseData.MaximumWheel / ScreenHeight; if ScalingW <= 0 then ScalingW:=1.0; mouseWh:= Trunc(MouseData.OffsetWheel / ScalingW); end else begin mouseWh:= mouseWh + MouseData.OffsetWheel; end; {if mouseWh < 0 then mouseWh:=0;} {if mouseWh > (ScreenHeight - 1) then mouseWh:=ScreenHeight - 1;} {end wheel} end; end; procedure glSwapBuffer; begin eglSwapBuffers(State.Display,State.Surface); end; procedure StartGLES2; {var} {State:TGLES2State;} {Scene:TGLES2Scene;} begin {} {This is the stating point for our OpenGL ES example, this routine sets up all of the required elements and then continually redraws our scene onto the screen until a key is pressed} {All applications using the VideoCore IV must call BCMHostInit before doing any other operations. This will initialize all of the supporting libraries and start the VCHIQ communication service. Applications should also call BCMHostDeinit when they no longer require any VC4 services} BCMHostInit; {Clear our state and scene} FillChar(State,SizeOf(TGLES2State),0); {Initialize the OpenGL ES 2.0 state} GLES2Init(State); {Initialize the OpenGL ES 2.0 scene} {Empty the keyboard buffer before starting our loop} while ConsoleKeypressed do begin ConsoleReadKey; end; Thread1Handle:=BeginThread(@NonBlockingMouse,nil,Thread1Handle,THREAD_STACK_DEFAULT_SIZE); if Thread1Handle = INVALID_HANDLE_VALUE then begin {If the thread handle is not valid then BeginThread failed} {ConsoleWindowWriteLn(WindowHandle,'Failed to create Thread1');} end else begin ultibo_C_main; end; while True do begin {Render the scene and display again} {GLES2RenderScene(State,Scene); original} {Check for a keypress and break if found} if ConsoleKeyPressed then Break; end; {Cleanup the OpenGL ES 2.0 state and scene} CleanupGLES2(State); {Deinitialize the VC4} BCMHostDeinit; end; procedure CleanupGLES2(var State:TGLES2State); var Success:Integer; DispmanUpdate:DISPMANX_UPDATE_HANDLE_T; begin {} {Clear the screen} glClear(GL_COLOR_BUFFER_BIT); eglSwapBuffers(State.Display,State.Surface); {Destroy the EGL surface} eglDestroySurface(State.Display,State.Surface); {Begin a DispmanX update} DispmanUpdate:=vc_dispmanx_update_start(0); {Remove the DispmanX element} Success:=vc_dispmanx_element_remove(DispmanUpdate,State.DispmanElement); if Success <> 0 then Exit; {And submit the change to DispmanX} vc_dispmanx_update_submit_sync(DispmanUpdate); {Close the DispmanX display we opened earlier} Success:=vc_dispmanx_display_close(State.DispmanDisplay); if Success <> 0 then Exit; {Release OpenGL resources and terminate EGL} eglMakeCurrent(State.Display,EGL_NO_SURFACE,EGL_NO_SURFACE,EGL_NO_CONTEXT); eglDestroyContext(State.Display,State.Context); eglTerminate(State.Display); end; function GLES2Init(var State:TGLES2State):Boolean; var Config:EGLConfig; ConfigCount:EGLint; EGLResult:EGLBoolean; DestRect:VC_RECT_T; SourceRect:VC_RECT_T; DispmanUpdate:DISPMANX_UPDATE_HANDLE_T; begin {} {This function provides a good general outline of how to initialize OpenGL ES 2.0 on the VideoCore IV and obtain the necessary handles and contexts. You will need something similar to this in all OpenGL ES applications before you can perform any OpenGL ES operations. For an OpenGL ES 1.1 version of this function please see the HelloGLES example} Result:=False; {Setup some DispmanX and EGL defaults} State.DispmanDisplay:=DISPMANX_NO_HANDLE; State.DispmanElement:=DISPMANX_NO_HANDLE; DispmanUpdate:=DISPMANX_NO_HANDLE; State.Display:=EGL_NO_DISPLAY; State.Surface:=EGL_NO_SURFACE; State.Context:=EGL_NO_CONTEXT; {Setup the alpha channel state} State.Alpha.flags:= DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS; State.Alpha.opacity:=255; State.Alpha.mask:=0; {Setup the EGL configuration attributes} State.ConfigAttributes[0]:=EGL_RENDERABLE_TYPE; State.ConfigAttributes[1]:=EGL_OPENGL_ES2_BIT; State.ConfigAttributes[2]:=EGL_SURFACE_TYPE; State.ConfigAttributes[3]:=EGL_WINDOW_BIT; State.ConfigAttributes[4]:=EGL_BLUE_SIZE; State.ConfigAttributes[5]:=8; State.ConfigAttributes[6]:=EGL_GREEN_SIZE; State.ConfigAttributes[7]:=8; State.ConfigAttributes[8]:=EGL_RED_SIZE; State.ConfigAttributes[9]:=8; State.ConfigAttributes[10]:=EGL_STENCIL_SIZE; State.ConfigAttributes[11]:=8; {State.ConfigAttributes[12]:=EGL_ALPHA_SIZE;} {State.ConfigAttributes[13]:=8;} State.ConfigAttributes[12]:=EGL_DEPTH_SIZE; State.ConfigAttributes[13]:=24; State.ConfigAttributes[14]:=EGL_SAMPLE_BUFFERS; State.ConfigAttributes[15]:=1; State.ConfigAttributes[16]:=EGL_SAMPLES; State.ConfigAttributes[17]:=4; State.ConfigAttributes[18]:=EGL_NONE; {Setup the EGL context attributes} State.ContextAttributes[0]:=EGL_CONTEXT_CLIENT_VERSION; State.ContextAttributes[1]:=2; State.ContextAttributes[2]:=EGL_NONE; try {Get an EGL display connection} State.Display:=eglGetDisplay(EGL_DEFAULT_DISPLAY); if State.Display = EGL_NO_DISPLAY then Exit; {Initialize the EGL display connection} EGLResult:=eglInitialize(State.Display,nil,nil); if EGLResult = EGL_FALSE then Exit; {Get an appropriate EGL framebuffer configuration} EGLResult:=eglChooseConfig(State.Display,@State.ConfigAttributes,@Config,1,@ConfigCount); if EGLResult = EGL_FALSE then Exit; {Bind to the OpenGL ES API} EGLResult:=eglBindAPI(EGL_OPENGL_ES_API); {EGL_OPENVG_API EGL_OPENGL_ES_API} if EGLResult = EGL_FALSE then Exit; {Create an EGL rendering context} State.Context:=eglCreateContext(State.Display,Config,EGL_NO_CONTEXT,@State.ContextAttributes); if State.Context = EGL_NO_CONTEXT then Exit; {Create an EGL window surface} if BCMHostGraphicsGetDisplaySize(DISPMANX_ID_MAIN_LCD,State.ScreenWidth,State.ScreenHeight) < 0 then Exit; {Setup the DispmanX source and destination rectangles} vc_dispmanx_rect_set(@DestRect,0,0,State.ScreenWidth,State.ScreenHeight); vc_dispmanx_rect_set(@SourceRect,0 shl 16,0 shl 16,State.ScreenWidth shl 16,State.ScreenHeight shl 16); {Open the DispmanX display} State.DispmanDisplay:=vc_dispmanx_display_open(DISPMANX_ID_MAIN_LCD); if State.DispmanDisplay = DISPMANX_NO_HANDLE then Exit; {Start a DispmanX update} DispmanUpdate:=vc_dispmanx_update_start(0); if DispmanUpdate = DISPMANX_NO_HANDLE then Exit; {Add a DispmanX element for our display} State.DispmanElement:=vc_dispmanx_element_add(DispmanUpdate,State.DispmanDisplay,0 {Layer},@DestRect,0 {Source},@SourceRect,DISPMANX_PROTECTION_NONE,@State.Alpha,nil {Clamp},DISPMANX_NO_ROTATE {Transform}); if State.DispmanElement = DISPMANX_NO_HANDLE then Exit; {Define an EGL DispmanX native window structure} State.NativeWindow.Element:=State.DispmanElement; State.NativeWindow.Width:=State.ScreenWidth; State.NativeWindow.Height:=State.ScreenHeight; {Submit the DispmanX update} vc_dispmanx_update_submit_sync(DispmanUpdate); {Create an EGL window surface} State.Surface:=eglCreateWindowSurface(State.Display,Config,@State.NativeWindow,nil); if State.Surface = EGL_NO_SURFACE then Exit; {Preserve the buffers on swap} EGLResult:=eglSurfaceAttrib(State.Display,State.Surface,EGL_SWAP_BEHAVIOR,EGL_BUFFER_DESTROYED ); {EGL_BUFFER_PRESERVED} if EGLResult = EGL_FALSE then Exit; {Connect the EGL context to the EGL surface} EGLResult:=eglMakeCurrent(State.Display,State.Surface,State.Surface,State.Context); if EGLResult = EGL_FALSE then Exit; Result:=True; finally {Check if the initialization was successful, if not cleanup} if not Result then begin {Close the DispmanX display if opened} if State.DispmanDisplay <> DISPMANX_NO_HANDLE then vc_dispmanx_display_close(State.DispmanDisplay); {Check for an EGL display connection} if State.Display <> EGL_NO_DISPLAY then begin {Terminate EGL} eglMakeCurrent(State.Display,EGL_NO_SURFACE,EGL_NO_SURFACE,EGL_NO_CONTEXT); {Destroy the EGL surface} if State.Surface <> EGL_NO_SURFACE then eglDestroySurface(State.Display,State.Surface); {Destroy the EGL context} if State.Context <> EGL_NO_CONTEXT then eglDestroyContext(State.Display,State.Context); {Terminate the EGL display} eglTerminate(State.Display); end; end; end; end; end.
unit settings; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TfSettings = class(TForm) bOK: TButton; bCancel: TButton; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Label1: TLabel; lPanelCount: TLabel; tbPanelCount: TTrackBar; cbW2K: TCheckBox; cbAutoDirSize: TCheckBox; GroupBox1: TGroupBox; Label2: TLabel; Label3: TLabel; Label4: TLabel; cbCopyMethod: TComboBox; cbMoveMethod: TComboBox; cbDeleteMethod: TComboBox; procedure bOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tbPanelCountChange(Sender: TObject); public procedure readSettings; procedure saveSettings; end; var fSettings: TfSettings; implementation uses procs; {$R *.dfm} { TfSettings } procedure TfSettings.readSettings; begin cbW2K.Checked := getCfgBool('W2KExtensions',true); cbAutoDirSize.Checked := getCfgBool('AutoDirSize',true); tbPanelCount.Position := getCfgInt('PanelCount',2); lPanelCount.Caption := IntToStr(tbPanelCount.Position); cbCopyMethod.ItemIndex := getCfgInt('CopyMethod',0); cbMoveMethod.ItemIndex := getCfgInt('MoveMethod',0); cbDeleteMethod.ItemIndex := getCfgInt('DeleteMethod',0); end; procedure TfSettings.saveSettings; begin putCfgBool('W2KExtensions',cbW2K.Checked); putCfgBool('AutoDirSize',cbAutoDirSize.Checked); putCfgInt('PanelCount',tbPanelCount.Position); end; procedure TfSettings.bOKClick(Sender: TObject); begin saveSettings; ModalResult := mrOK; end; procedure TfSettings.FormCreate(Sender: TObject); begin readSettings; end; procedure TfSettings.tbPanelCountChange(Sender: TObject); begin lPanelCount.Caption := IntToStr(tbPanelCount.Position); end; end.
unit Sample.Targa; {$INCLUDE 'Sample.inc'} interface uses Neslib.Ooogles; type TPixel = array [0..3] of Byte; type TTgaImage = record public Width: Integer; Height: Integer; Data: TArray<TPixel>; public function Load(const APath: String): Boolean; function ToTexture: TGLTexture; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.SysUtils, Sample.Assets; type TTgaHeader = packed record Size: UInt8; MapType: UInt8; ImageType: UInt8; PaletteStart: UInt16; PaletteSize: UInt16; PaletteEntryDepth: UInt8; X: UInt16; Y: UInt16; Width: UInt16; Height: UInt16; ColorDepth: UInt8; Descriptor: UInt8; end; const INVERTED_BIT = 1 shl 5; { TTgaImage } function TTgaImage.Load(const APath: String): Boolean; var Bytes: TBytes; Header: TTgaHeader; X, Y, PixelComponentCount, RowIdx, PixelIdx, TargetIdx: Integer; Pixel: TPixel; begin Bytes := TAssets.Load(APath); if (Length(Bytes) < SizeOf(Header)) then Exit(False); Move(Bytes[0], Header, SizeOf(Header)); Width := Header.Width; Height := Header.Height; PixelComponentCount := Header.ColorDepth div 8; if (Width = 0) or (Height = 0) or (PixelComponentCount = 0) then Exit(False); SetLength(Data, Width * Height); TargetIdx := 0; for Y := 0 to Height - 1 do begin if ((Header.Descriptor and INVERTED_BIT) <> 0) then RowIdx := Height - 1 - Y else RowIdx := Y; RowIdx := SizeOf(Header) + (RowIdx * Width * PixelComponentCount); for X := 0 to Width - 1 do begin PixelIdx := RowIdx + (X * PixelComponentCount); Cardinal(Pixel) := $FF000000; if (PixelComponentCount > 2) then Pixel[0] := Bytes[PixelIdx + 2]; if (PixelComponentCount > 1) then Pixel[1] := Bytes[PixelIdx + 1]; if (PixelComponentCount > 0) then Pixel[2] := Bytes[PixelIdx + 0]; if (PixelComponentCount > 3) then Pixel[3] := Bytes[PixelIdx + 3]; Data[TargetIdx] := Pixel; Inc(TargetIdx); end; end; Result := True; end; function TTgaImage.ToTexture: TGLTexture; begin Result.New; Result.Bind; Result.MinFilter(TGLMinFilter.LinearMipmapLinear); Result.MagFilter(TGLMagFilter.Linear); gl.PixelStore(TGLPixelStoreMode.UnpackAlignment, TGLPixelStoreValue.One); Result.Upload(TGLPixelFormat.RGBA, Width, Height, @Data[0]); Result.GenerateMipmap; end; end.
{ Subroutine SST_W_C_TERMS_IMPLICIT (TERM1,N_TERMS,DTYPE,SYM_P) * * Create an implicit var, if neccessary, from the expression formed by the * list of terms starting at TERM1. N_TERMS is the number of terms that are * to be considered in the expression. SYM_P is returned pointing to the * symbol descriptor of the implicit variable if one is created. It will be * returned NIL when no implicit variable is created. DTYPE is the descriptor * for the data type to make the implicit variable if one is created. } module sst_w_c_TERMS_IMPLICIT; define sst_w_c_terms_implicit; %include 'sst_w_c.ins.pas'; procedure sst_w_c_terms_implicit ( {make implicit var from terms list if needed} in term1: sst_exp_term_t; {descriptor for first term in chain} in n_terms: sys_int_machine_t; {number of terms in chain to consider} in dtype: sst_dtype_t; {descriptor for data type of implicit var} out sym_p: sst_symbol_p_t); {will pnt to implicit var, or NIL for unused} var term_p: sst_exp_term_p_t; {points to current term in terms chain} i: sys_int_machine_t; {scratch integer and loop counter} v: sst_var_t; {descriptor for implicit variable reference} begin if {don't need implicit variable ?} (n_terms = 1) and then {only one term, not a compound expression ?} sst_term_simple(term1) {the one and only term is "simple" ?} then begin sym_p := nil; return; end; { * An implicit variable needs to be created. } sst_w_c_implicit_var (dtype, v); {create and declare implicit variable} sym_p := v.mod1.top_sym_p; {extract and pass back pointer to variable} sst_w_c_pos_push (sment_type_exec_k); {position for write before curr statement} sst_w_c_sment_start; {start assignment statement} sst_w.append_sym_name^ (sym_p^); {write name of implicit variable} sst_w.delimit^; sst_w.appendn^ ('=', 1); {assignment operator} sst_w.delimit^; if n_terms <= 1 then begin {expression is only one term} sst_w_c_term (term1, 0, enclose_no_k); {write value of term} end else begin {expression is list of terms with operators} term_p := term1.next_p; {init curr term to second in chain} for i := 3 to n_terms do begin {loop until TERM_P points to last term} term_p := term_p^.next_p; {advance current term to next in chain} end; sst_w_c_exp2( {write the compound expression} term1, {first term in expression before operator} n_terms - 1, {number of terms in exp before operator} term_p^, {first term in expression after operator} 1, {number of terms in exp after operator} term_p^.op2, {operator between expressions} enclose_no_k); {no need to enclose expression in parentheses} end ; {done writing expression value} sst_w_c_sment_end; sst_w_c_pos_pop; {restore original writing position} end;