text
stringlengths
14
6.51M
unit cEnemy; interface uses Contnrs; type TEnemy = class private _X : SmallInt; _Y : SmallInt; _ScreenID : Byte; _ID : Byte; _EnemyCheckPointStatus : Byte; procedure SetX(pX :SmallInt); procedure SetY(pY : SmallInt); procedure SetScreenX(pX : Integer); function GetScreenX : Integer; public property X : SmallInt read _X write SetX; property Y : SmallInt read _Y write SetY; property ScreenX : Integer read GetScreenX write SetScreenX; property ScreenID : Byte read _ScreenID write _ScreenID; property ID : Byte read _ID write _ID; property CheckPointStatus : Byte read _EnemyCheckPointStatus write _EnemyCheckPointStatus; end; TEnemyList = class(TObjectList) protected function GetEnemy(Index: Integer) : TEnemy; procedure SetEnemy(Index: Integer; const Value: TEnemy); public function Add(AObject: TEnemy) : Integer; property Items[Index: Integer] : TEnemy read GetEnemy write SetEnemy;default; function Last : TEnemy; end; implementation { TEnemyList } function TEnemyList.Add(AObject: TEnemy): Integer; begin Result := inherited Add(AObject); end; function TEnemyList.GetEnemy(Index: Integer): TEnemy; begin Result := TEnemy(inherited Items[Index]); end; procedure TEnemyList.SetEnemy(Index: Integer; const Value: TEnemy); begin inherited Items[Index] := Value; end; function TEnemyList.Last : TEnemy; begin result := TEnemy(inherited Last); end; {TEnemy} procedure TEnemy.SetX(pX :SmallInt); begin if pX > 247 then self._X := 247 else self._X := pX; end; procedure TEnemy.SetY(pY : SmallInt); begin if pY > 247 then self._Y := 247 else self._Y := pY; end; procedure TEnemy.SetScreenX(pX : Integer); begin _ScreenID := (pX div 256); _X := pX mod 256; end; // This function retrieves an X co-ordinate which is // the number of screens times 256, plus the X co-ordinate. function TEnemy.GetScreenX : Integer; begin result := (self._ScreenID * 256) + _X; end; end.
unit nsMainMenuNew; // Библиотека : Проект Немезис; // Название : nsMainMenuNew; // Автор : Морозов М. А; // Назначение : Содержит классы используемые для работы с "основным меню"; // Версия : $Id: nsMainMenuNew.pas,v 1.14 2013/07/05 18:33:13 lulin Exp $ (*---------------------------------------------------------------------------- $Log: nsMainMenuNew.pas,v $ Revision 1.14 2013/07/05 18:33:13 lulin - вычищаем устаревшее. Revision 1.13 2013/07/04 08:36:45 morozov {RequestLink:434744658} Revision 1.12 2012/10/01 07:40:39 kostitsin [$397291566] Revision 1.11 2011/02/14 11:11:15 lulin - вычищаем мусор. Revision 1.10 2010/04/06 08:59:19 oman - new: {RequestLink:200902034} Revision 1.9 2010/01/28 08:37:36 oman - new: обрабатываем пустые списки {RequestLink:182452345} Revision 1.8 2009/11/24 14:19:40 oman - new: LE_OPEN_DOCUMENT_FROM_HISTORY {RequestLink:121157219} Revision 1.7 2009/10/21 16:26:09 lulin - переносим на модель ноды оболочки. Revision 1.6 2009/10/19 14:02:20 lulin {RequestLink:167348987}. Revision 1.5 2009/10/07 14:33:38 lulin - выкидываем неиспользуемое. Revision 1.4 2009/10/07 13:06:30 lulin - вычистил неиспользуемое. Revision 1.3 2009/10/07 10:40:33 lulin {RequestLink:162596818}. Подгоняем по макет. Revision 1.2 2009/10/06 13:13:57 lulin {RequestLink:162596818}. Добился правильной вёрстки. Revision 1.1 2009/10/05 11:15:24 lulin {RequestLink:162596818}. Подготавливаем инфраструктуру. Revision 1.123 2009/09/14 12:28:01 lulin - модуль Документ кладём в правильное место. Revision 1.122 2009/09/09 18:55:16 lulin - переносим на модель код проектов. Revision 1.121 2009/09/04 17:08:23 lulin {RequestLink:128288497}. Revision 1.120 2009/09/03 13:25:53 lulin - делаем прецеденты более изолированными друг от друга. Revision 1.119 2009/08/19 08:50:58 oman - new: Журнальные закладки - {RequestLink:159355458} Revision 1.118 2009/08/12 11:59:53 oman - new: Пользуем фабрику диспетчера - {RequestLink:152408792} Revision 1.117 2009/08/12 10:48:06 oman - new: Первое приближение - {RequestLink:159355458} Revision 1.116 2009/07/31 17:29:55 lulin - убираем мусор. Revision 1.115 2009/03/23 16:57:29 lulin [$122669214]. Revision 1.114 2009/03/11 13:03:31 oman - fix: Сломалась расцветка (К-139430030) Revision 1.113 2009/02/20 10:12:56 lulin - чистка комментариев. Revision 1.112 2009/02/10 19:03:55 lulin - <K>: 133891247. Вычищаем морально устаревший модуль. Revision 1.111 2009/02/09 15:51:06 lulin - <K>: 133891247. Выделяем интерфейсы основного меню. Revision 1.110 2008/12/25 12:20:11 lulin - <K>: 121153186. Revision 1.109 2008/11/01 13:46:17 lulin - <K>: 121167578. Revision 1.108 2008/11/01 13:15:04 lulin - <K>: 121167580. Revision 1.107 2008/11/01 12:31:18 lulin - <K>: 121167580. Revision 1.106 2008/11/01 12:11:24 lulin - <K>: 121167580. Revision 1.105 2008/11/01 11:48:22 lulin - <K>: 121167580. Revision 1.104 2008/11/01 11:33:12 lulin - <K>: 121167580. Revision 1.103 2008/11/01 11:19:55 lulin - <K>: 121167580. Revision 1.102 2008/11/01 10:58:30 lulin - <K>: 121167580. Revision 1.101 2008/11/01 10:37:56 lulin - <K>: 121167580. Revision 1.100 2008/11/01 10:08:57 lulin - <K>: 121167580. Revision 1.99 2008/10/31 14:21:32 lulin - <K>: 121167580. Revision 1.98 2008/10/31 13:55:22 lulin - <K>: 121167580. Revision 1.97 2008/10/31 12:54:21 lulin - <K>: 121167580. Revision 1.96 2008/10/31 11:55:11 lulin - <K>: 121167580. Revision 1.95 2008/10/31 10:45:07 lulin - <K>: 121167580. Revision 1.94 2008/10/29 18:48:25 lulin - <K>: 121164067. Revision 1.93 2008/10/29 16:12:49 lulin - <K>: 121166916. Revision 1.92 2008/10/02 12:24:41 oman - fix: Заменили топик (К-119473714) Revision 1.91 2008/07/23 11:49:06 mmorozov - change: интерфейс открытия документа по номеру (K<100958789>); Revision 1.90 2008/06/18 10:32:56 mmorozov - new: последние открытые препараты (CQ: OIT5-29385); Revision 1.89 2008/06/04 13:05:30 mmorozov - new: показываем основные разделы справочника в основном меню Инфарм; Revision 1.88 2008/06/04 10:54:44 mmorozov - new: документы Инфарм в основном меню. Revision 1.87 2008/05/27 12:04:10 mmorozov - new: регистрация операций открытия препарата и фирмы производителя. Revision 1.86 2008/05/22 10:34:44 mmorozov - основное меню Инфарм. Revision 1.85 2008/05/22 10:14:43 mmorozov - new: основное меню Инфарм. Revision 1.84 2008/05/22 07:06:03 mmorozov - new: основное меню Инфарм. Revision 1.83 2008/04/21 10:53:49 mmorozov - new: при фильтрации элементов моих документов используется параметр для чего вызвали мои документы: документы | препараты. Revision 1.82 2008/03/26 14:28:59 lulin - <K>: 88080898. Revision 1.81 2008/03/26 11:37:10 lulin - зачистка в рамках <K>: 88080898. Revision 1.80 2008/03/26 11:12:46 lulin - зачистка в рамках <K>: 88080898. Revision 1.79 2008/03/20 11:27:05 oman - fix: Не падаем в случае отсутствия значений Revision 1.78 2008/01/10 07:23:30 oman Переход на новый адаптер Revision 1.77 2007/12/21 07:12:20 mmorozov - new: подписка на уведомление об обновлении данных (CQ: OIT5-27823); Revision 1.75.2.5 2007/12/06 10:47:27 oman Не ловили исключение Revision 1.75.2.4 2007/11/27 07:21:50 oman Перепиливаем на новый адаптер - логгирование Revision 1.75.2.3 2007/11/26 09:04:03 oman Перепиливаем на новый адаптер Revision 1.75.2.2 2007/11/21 15:07:48 oman Перепиливаем на новый адаптер Revision 1.76 2007/11/13 13:37:52 mmorozov - new: прокрутка колесом мыши в простом основном меню (CQ: OIT5-27201); Revision 1.75 2007/10/24 11:48:11 mmorozov - new: поддержка межстрочного интервала (voShowInterRowSpace) для элементов дерева с фиксированной высотой (CQ: OIT5-25021); Revision 1.74 2007/08/14 19:31:50 lulin - оптимизируем очистку памяти. Revision 1.73 2007/07/18 13:27:21 mmorozov - new: регистрирация события открытие докумнета из последних открытых (в рамках CQ: OIT5-25852); Revision 1.72 2007/05/08 09:02:09 oman - fix: Общая функциональность вынесена в общее место Revision 1.71 2007/05/03 09:44:19 mmorozov - change: отрезаем заголовок "продвинутого основного меню" (CQ: OIT5-25061); Revision 1.70 2007/04/17 09:30:03 mmorozov - new: определены параметры поиска элементов дерева навигатора; Revision 1.69 2007/04/12 10:37:07 mmorozov - change: назначаем правильную высоту однострочным элементам основного меню; Revision 1.68 2007/04/11 15:15:17 mmorozov - new: в простом основном меню показываем полные названия в списке последних открытых (CQ: OIT5-24958); Revision 1.67 2007/04/10 09:21:56 mmorozov - new: строим основное меню используя новые идентификаторы элементов навигатора (CQ: OIT5-24602); Revision 1.66 2007/03/28 11:04:54 mmorozov - "таблица перехода фокуса" перенесена в библиотеку визуальных компонентов проекта Немезис; Revision 1.65 2007/03/22 12:29:32 mmorozov - change: ячейка сетки контролов в виде скрываемого поля с деревом перенесена в общее место; Revision 1.64 2007/03/21 14:14:50 lulin - cleanup. Revision 1.63 2007/02/16 16:31:32 lulin - избавляемся от стандартного строкового типа. Revision 1.62 2007/02/07 17:48:45 lulin - избавляемся от копирования строк при чтении из настроек. Revision 1.61 2007/02/07 14:30:45 lulin - переводим на строки с кодировкой. Revision 1.60 2007/02/05 11:11:50 mmorozov - new: поддержка деревьями основных меню (простое, продвинутое) сброса после обновления; Revision 1.59 2007/02/02 14:55:10 mmorozov - new: используем новые типы узлов рубрикатора; Revision 1.58 2007/01/31 19:00:11 lulin - переходим к строкам с кодировкой. Revision 1.57 2007/01/29 10:09:35 mmorozov - new: в рамках работы над CQ: OIT5-24234; - bugfix: не обновляли деревья после переключения базы; Revision 1.56 2007/01/28 12:12:18 mmorozov - bugfix: AV при обновлении (CQ: OIT5-24208); Revision 1.55 2007/01/22 12:22:59 lulin - переходим на более правильные строки. Revision 1.54 2007/01/20 18:36:31 lulin - вычищаем ненужное создание параметров. Revision 1.53 2007/01/19 09:24:45 mmorozov - bugfix: в таблицу контролов основного меню затесалась пустая строка; Revision 1.52 2007/01/18 12:57:18 mmorozov - new: Простое основное меню (CQ: OIT5-23939); Revision 1.51 2007/01/15 06:33:56 mmorozov - высносим общую функциональность из основного меню (выделен в отдельный модуль компонент управления фокусом с клавиатуры; использование компонента "сетка контролов", для управления размещением элементов основного меню), в рамках работы над "CQ: OIT5-23939"; Revision 1.50 2006/12/22 15:06:34 lulin - текст ноды - теперь структура с длиной и кодовой страницей. Revision 1.49 2006/12/20 13:34:15 lulin - удален ненужный модуль. Revision 1.48 2006/07/21 09:33:22 mmorozov - rename variables; Revision 1.47 2006/04/28 13:04:19 demon - optimize: переименовл несколько методов, вынес общую функциональность. Revision 1.46 2006/04/17 14:42:36 oman - new beh: перекладываем StdStr в _StdRes Revision 1.45 2006/03/16 11:36:07 oman - new beh: Перекладываем все текстовые константы в три места (StdStr, DebugStr и SystemStr) Revision 1.44 2005/11/21 17:21:08 lulin - cleanup. Revision 1.43 2005/07/07 09:31:45 mmorozov - warning fix; Revision 1.42 2005/06/09 07:43:25 mmorozov change: param name; Revision 1.41 2005/06/08 12:54:07 mmorozov bugfix: новые варианты не работоспособности переключения фокуса; Revision 1.40 2005/06/08 12:33:09 mmorozov bugfix: перемещение курсора (новые варианты не работоспособности); Revision 1.39 2005/06/08 11:25:26 mmorozov - bugfix: в таблице перемещения курсора не учитывалось, что некоторые элементы могут быть не видимыми; Revision 1.38 2005/03/28 11:39:10 demon - cleanup (remove hints) Revision 1.37 2005/03/14 13:15:33 mmorozov new: global function nsTaskbarSize; Revision 1.36 2005/03/12 09:52:42 mmorozov new: global function _nsControlIndents; Revision 1.35 2005/03/10 10:28:28 mmorozov change: префикс "mm" в названии классов заменен на "ns"; Revision 1.34 2005/03/09 14:54:08 mmorozov new: function IsItemExists; Revision 1.33 2005/02/28 14:53:45 mmorozov Механизм навигации по таблице, ячейки которой представлены списками, адаптируются для любых компонентов: - new: types TmmKey, TmmOnProcessKey - new: classes TakTreeView, TakCustomLister, TmmProcessKey, - TmmColumn, TmmColumns; - new: interface ImmAdapterControl; Revision 1.32 2004/12/29 07:50:45 mmorozov new behaviour: при чтение истории последних открытых документов не обрабатываем элементы с пустыми Bookmark; Revision 1.31 2004/12/23 08:41:37 lulin - вычищен ненужный модуль. Revision 1.30 2004/12/09 10:20:35 mmorozov change: TnsQueryHistory.LoadQueries перенесен в public; Revision 1.29 2004/12/06 10:34:07 mmorozov - add log; -----------------------------------------------------------------------------*) interface uses Graphics, ImgList, Controls, Types, Classes, Forms, Messages, l3Base, l3Tree_TLB, l3TreeInterfaces, l3Interfaces, afwInterfaces, vcmBase, vcmInterfaces, vcmExternalInterfaces, evTypes, eeInterfaces, eeTreeView, vtOutliner, vtLister, vtHideField, nscInterfaces, nscArrangeGrid, nscTreeViewHotTruck, nsNodes, nsTypes, DocumentUnit, DynamicTreeUnit, SearchUnit, StartUnit, nsDataResetTree, nsBaseMainMenuTree, nsHistoryTree, nsLastOpenDocTree, smTree, smLawNewsTree, MainMenuDomainInterfaces ; type TnsQueryHistory = class(TvcmInterfaceList) {* - содержит историю запросов. } private f_MaxCount : Integer; f_QueryType : TQueryType; private // property methods function pm_GetQueryNode(const aIndex : Integer) : InsQueryNode; {-} public // public methods constructor Create(const aMaxCount : Integer; const aQueryType : TQueryType); reintroduce; virtual; {-} procedure LoadQueries; {-} public // public properties property Items[const aIndex : Integer] : InsQueryNode read pm_GetQueryNode; Default; {* - получить обертку запроса. } end;//TnsQueryHistory TQHRec = record rH : TnsQueryHistory; end;//TQHRec TnsTreeStyleManager = class(TvcmBase) {* - менеджер стилей деревьев для основного меню. } private // fields f_MainMenuColor : TColor; f_NewSchool : Boolean; private // methods procedure TreeGetItemStyle(Sender : TObject; aItemIndex : Integer; const aFont : Il3Font; var aTextBackColor : TColor; var aItemBackColor : TColor; var aVJustify : TvtVJustify); {-} function TreeGetItemImage(Sender : TObject; Index : Integer; var aImages : TCustomImageList): Integer; {-} public // methods procedure Init(const aTree: TeeTreeView); {-} constructor Create(const aMainMenuColor: TColor; aNewSchool : Boolean); reintroduce; {-} end;//TnsTreeStyleManager TnsLastOpenDocsManager = class(TvcmBase) {* - менеджер дерева последних открытых документов. } private // fields f_MainMenuColor : TColor; f_NewSchool : Boolean; private // methods function GetItemCursor(aSender : TObject; aIndex : Integer): TCursor; {-} procedure ActionElement(Sender : TObject; Index : Integer); {-} procedure GetItemStyle(Sender : TObject; aItemIndex : Integer; const aFont : Il3Font; var aTextBackColor : TColor; var aItemBackColor : TColor; var aVJustify : TvtVJustify); {-} function GetItemTextHint(Sender : TObject; Index : Integer): Il3CString; {-} procedure AllowHotTruck(Sender: TObject; anIndex: Integer; var Allow: Boolean); {-} function IsBookmark(const aNode: Il3SimpleNode): Boolean; {-} procedure Init(const aTree: TnscTreeViewHotTruck); {* - инициализировать дерево последних открытых. } public // methods constructor Create(const aMainMenuColor : TColor; const aTree : TnscTreeViewHotTruck; aNewSchool : Boolean); reintroduce; {-} end;//TnsLastOpenDocsManager function nsMakeMainMenuCaption: Il3CString; {* - название заголовка для основного меню. } function nsMakeQueryStr(var aBuf : TQHRec; aIndex : Integer; aHint : Boolean = False) : Il3CString; {* - название заголовка для поисков. } function nsScrollMainMenu(const aWindow : TScrollingWinControl; var Message : TWMMouseWheel): Boolean; {* - прокрутить меню. } const c_mmTreeColor = clWhite; {* - основной цвет дереве, не синий. } c_mmSecondItemColor = $00F2F2F2; // - цвет второго элемента в дереве, списке; implementation uses Windows, SysUtils, StdCtrls, Math, ShellAPI, l3Chars, l3String, l3ControlsTypes, afwFacade, OvcConst, evStyleTableSpy, eeNode, BaseTypesUnit, LoggingUnit, bsUtils, nsOpenUtils, nsConst, nsUtils, nsLogEvent, MainMenuNewRes, StdRes, DataAdapter, nsRubricatorCache, nsQueryNode ; type TnsOpenDocumentFromHistoryEvent = class(TnsLogEvent) class procedure Log(const aDoc: IDocument); end; //{$Include afwApplicationDataUpdate.imp.pas} function nsScrollMainMenu(const aWindow : TScrollingWinControl; var Message : TWMMouseWheel): Boolean; {* - прокрутить меню. } const c_Delta = 10; var l_Rect : TRect; l_Index : Integer; l_Lister : TvtLister; procedure lpScroll; var l_Delta : Integer; begin with Message, aWindow.VertScrollBar do begin // Определим приращение if WheelDelta < 0 then l_Delta := c_Delta else l_Delta := - c_Delta; // Сместимся если не выходим за пределы if (Position + l_Delta >= 0) and (Position + l_Delta <= Range) then Position := Position + l_Delta else // Смещаемся к началу или к концу if Message.WheelDelta > 0 then Position := 0 else Position := Range; end;//with Message, aWindow.VertScrollBar do end;//lpScroll begin Result := True; // Видима вертикальная полоса прокрутки with aWindow do if VertScrollBar.Visible then for l_Index := 0 to Pred(ComponentCount) do if (Components[l_Index] is TvtLister) or (Components[l_Index] is TeeTreeView) then begin l_Lister := TvtLister(Components[l_Index]); Windows.GetWindowRect(l_Lister.Handle, l_Rect); // Колесо используется списком, который имеет вертикальную полосу прокрутки if PtInRect(l_Rect, Point(Message.XPos, Message.YPos)) then begin Result := not l_Lister.IsVScrollVisible; Break; end;//if PtInRect(l_Rect, Point(Message.XPos, Message.YPos)) then end;//if (Components[l_Index] is TnscLister).. if Result then lpScroll; end;//nsScrollMainMenu function nsMakeQueryStr(var aBuf : TQHRec; aIndex : Integer; aHint : Boolean = False) : Il3CString; begin Result := nil; if Assigned(aBuf.rH) then begin if (aBuf.rH.Count = 0) then begin // Выводим название элемента, но не показываем hint if not aHint then Result := vcmCStr(str_NotQueries); end else with aBuf.rH.Items[aIndex] do if not aHint then Result := nsCStr(Name) {$IfDef mmQueryHistoryUseColumns} + #9 + IntToStr(DocCount) {$EndIf mmQueryHistoryUseColumns} else Result := vcmFmt(str_QueryHintFrmt, [DocCount]); end;//aBuf.rH end; function nsMakeMainMenuCaption: Il3CString; {* - название заголовка для основного меню. } function lp_MakeDate: Il3CString; begin with DefDataAdapter.CurrentBaseDate do try Result := nsCStr(nsDateToStr(EncodeDate(rYear, rMonth, rDay))); except on EConvertError do begin Result := nsCStr(''); Assert(False); end;//on EConvertError do end;//try..except end;//lp_MakeDate function lp_MakeComplectName: Il3CString; begin Result := l3RTrim(DefDataAdapter.ComplectName, [cc_Dot]); // - отрежем точку в конце названия комплекта, подготовим к использованию в // str_SimpleMainMenuCaptionF; end;//lp_MakeComplectName begin Result := vcmFmt(str_SimpleMainMenuCaptionF, [lp_MakeComplectName, lp_MakeDate]); end;//nsMakeMainMenuCaption { TnsQueryHistory } procedure TnsQueryHistory.LoadQueries; var l_Index : Integer; l_List : IQueryList; l_Item : IQuery; begin Clear; try l_List := TdmStdRes.MakeWorkJournal.MakeQueryHistory(f_QueryType, f_MaxCount); if Assigned(l_List) then for l_Index := 0 to Pred(l_List.Count) do begin l_List.pm_GetItem(l_Index, l_Item); Add(TnsQueryNode.Make(l_Item)); end; except // в истории запросов нет on ECanNotFindData do end; end; constructor TnsQueryHistory.Create(const aMaxCount : Integer; const aQueryType : TQueryType); begin inherited Create; f_MaxCount := aMaxCount; f_QueryType := aQueryType; end; function TnsQueryHistory.pm_GetQueryNode(const aIndex : Integer) : InsQueryNode; begin Supports(inherited Items[aIndex], InsQueryNode, Result); end; { TnsTreeStyleManager } function TnsTreeStyleManager.TreeGetItemImage(Sender : TObject; Index : Integer; var aImages : TCustomImageList): Integer; begin Result := vtItemWithoutImage; end;//TreeGetItemImage procedure TnsTreeStyleManager.TreeGetItemStyle(Sender : TObject; aItemIndex : Integer; const aFont : Il3Font; var aTextBackColor : TColor; var aItemBackColor : TColor; var aVJustify : TvtVJustify); {-} var l_Node : Il3SimpleNode; begin if not f_NewSchool then aFont.ForeColor := f_MainMenuColor else aFont.ForeColor := TvtCustomOutliner(Sender).Font.Color; aVJustify := vt_vjCenter; l_Node := TeeTreeView(Sender).GetNode(aItemIndex); try if f_NewSchool then begin aTextBackColor := c_mmTreeColor; aItemBackColor := aTextBackColor; end//l_Node <> nil else if (l_Node <> nil) and ((Succ(l_Node.IndexInParent) mod 2) = 1) then begin aTextBackColor := c_mmTreeColor; aItemBackColor := aTextBackColor; end//l_Node <> nil else begin aTextBackColor := c_mmSecondItemColor; aItemBackColor := aTextBackColor; end;//l_Node <> nil finally l_Node := nil; end;//try..finally end;//TreeGetItemStyle procedure TnsTreeStyleManager.Init(const aTree: TeeTreeView); begin with aTree do begin ScrollStyle := ssNone; EditOptions := EditOptions - [eoItemExpand]; ActionElementMode := l3_amSingleClick; OnGetItemStyle := TreeGetItemStyle; // В данный момент дерево не поддерживает опцию voShowInterRowSpace для // однострочных элементов дерева, поэтому разряжаем элементы сами: if f_NewSchool then ViewOptions := ViewOptions - [voShowInterRowSpace] else ViewOptions := ViewOptions + [voShowInterRowSpace]; OnGetItemImage := TreeGetItemImage; Color := c_mmTreeColor; end;//with aTree do end;//Init constructor TnsTreeStyleManager.Create(const aMainMenuColor: TColor; aNewSchool : Boolean); begin inherited Create; f_MainMenuColor := aMainMenuColor; f_NewSchool := aNewSchool; end;//Create { TnsLastOpenDocsManager } function TnsLastOpenDocsManager.GetItemCursor(aSender : TObject; aIndex : Integer): TCursor; {-} begin if not IsBookmark(TnscTreeViewHotTruck(aSender).GetNode(aIndex)) then Result := crDefault else Result := crHandPoint; end;//GetItemCursor function TnsLastOpenDocsManager.GetItemTextHint(Sender : TObject; Index : Integer): Il3CString; {-} var l_Node : Il3SimpleNode; l_Book : InsJournalBookmarkNode; l_N : Il3CString; begin Result := nil; l_Node := TnscTreeViewHotTruck(Sender).GetNode(Index); try if Supports(l_Node, InsJournalBookmarkNode, l_Book) then try l_N := l_Book.DocName; if not l3Same(l_N, l_Node.Text) then Result := l_N; finally l_Book := nil; end;//try..finally finally l_Node := nil; end;//try..finally end; procedure TnsLastOpenDocsManager.GetItemStyle(Sender : TObject; aItemIndex : Integer; const aFont : Il3Font; var aTextBackColor : TColor; var aItemBackColor : TColor; var aVJustify : TvtVJustify); {-} begin aVJustify := vt_vjCenter; if not f_NewSchool then aFont.ForeColor := f_MainMenuColor else aFont.ForeColor := TnscTreeViewHotTruck(Sender).Font.Color; if f_NewSchool then aItemBackColor := c_mmTreeColor else begin if aItemIndex mod 2 = 1 then aItemBackColor := c_mmSecondItemColor else aItemBackColor := c_mmTreeColor; end;//f_NewSchool aTextBackColor := aItemBackColor; end;//GetItemStyle procedure TnsLastOpenDocsManager.ActionElement(Sender : TObject; Index : Integer); {-} var l_Node : Il3SimpleNode; l_MyNode : InsJournalBookmarkNode; l_Document : IDocument; begin l_Node := TnscTreeViewHotTruck(Sender).GetNode(Index); try if IsBookmark(l_Node) and Supports(l_Node, InsJournalBookmarkNode, l_MyNode) then try l_Document := TdmStdRes.SafeOpenDocument(l_MyNode.Bookmark); // Регистрируем открытие документа из истории: if l_Document <> nil then try if l_Document.GetDocType in [DT_DOCUMENT, DT_ACTUAL_ANALYTICS, DT_ACTUAL_ANALYTICS_CONTENTS] then TnsOpenDocumentFromHistoryEvent.Log(l_Document); finally l_Document := nil; end;//try..finally finally l_MyNode := nil; end;//try..finally finally l_Node := nil; end;//try..finally end;//ActionElement function TnsLastOpenDocsManager.IsBookmark(const aNode : Il3SimpleNode) : Boolean; var l_Book: InsJournalBookmarkNode; begin Result := Supports(aNode, InsJournalBookmarkNode, l_Book) and Assigned(l_Book.Bookmark); end; procedure TnsLastOpenDocsManager.Init(const aTree: TnscTreeViewHotTruck); begin with aTree do begin OnActionElement := ActionElement; OnGetItemStyle := GetItemStyle; OnGetItemTextHint := GetItemTextHint; OnGetItemCursor := GetItemCursor; OnAllowHotTruck := AllowHotTruck; end;//with aTree do end;//Init constructor TnsLastOpenDocsManager.Create(const aMainMenuColor : TColor; const aTree : TnscTreeViewHotTruck; aNewSchool : Boolean); //reintroduce; {-} begin inherited Create; f_MainMenuColor := aMainMenuColor; f_NewSchool := aNewSchool; Init(aTree); end;//Create procedure TnsLastOpenDocsManager.AllowHotTruck(Sender: TObject; anIndex: Integer; var Allow: Boolean); begin Allow := IsBookmark(TnscTreeViewHotTruck(Sender).GetNode(anIndex)) end; { TnsOpenDocumentFromHistoryEvent } class procedure TnsOpenDocumentFromHistoryEvent.Log(const aDoc: IDocument); var l_Data: ILogEventData; begin l_Data := MakeParamsList; l_Data.AddObject(aDoc); GetLogger.AddEvent(LE_OPEN_DOCUMENT_FROM_HISTORY, l_Data); end; end.
{ Subroutine SST_W_C_DTYPE (DTYPE, NAME, PACK) * * Write the data type definition from the data type descriptor DTYPE. * The full data type definition will be written, whether simple or not. * This routine would be used when declaring the data type itself. * When PACK is TRUE, the data type declaration is for a field in a packed * record. This causes some data types to be written as bit fields. * NAME is the name of the symbol being declared with the data type. * It will be inserted in the appropriate place. } module sst_w_c_dtype; define sst_w_c_dtype; %include 'sst_w_c.ins.pas'; procedure sst_w_c_dtype ( {write data type definition} in dtype: sst_dtype_t; {data type descriptor block} in name: univ string_var_arg_t; {name of symbol to declare with this dtype} in pack: boolean); {TRUE if part of packed record} val_param; const max_msg_parms = 2; {max parameters we can pass to a message} type int_sign_t = ( {flag to select signed/unsigned integer} int_signed_k, {integer is signed} int_unsigned_k); {integer is unsigned} var i: sys_int_machine_t; {scratch integer and loop counter} fw: sys_int_machine_t; {field width specifier for packed field} sym_p: sst_symbol_p_t; {points to current symbol} token: string_var80_t; {scratch for number conversion} dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor} arg_p: sst_proc_arg_p_t; {points to current routine arg descriptor} name_ele: string_var132_t; {input name of element in union} scope_old_p: sst_scope_p_t; {saved current scope pointer} names_old_p: sst_scope_p_t; {saved current namespace pointer} int_sign: int_sign_t; {flag to select signed/unsigned integer} name_written: boolean; {TRUE if NAME already written} variants: boolean; {TRUE if record has any variants (overlays)} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label do_int, done_case; begin token.max := sizeof(token.str); {init local var strings} name_ele.max := sizeof(name_ele.str); fw := 0; {init field width specifier} name_written := false; {init to NAME not written yet} case dtype.dtype of { ************************************ * * Data type is INTEGER. } sst_dtype_int_k: begin int_sign := int_signed_k; {numeric integers are signed} do_int: {jump here from other dtypes that are ints} case int_sign of int_signed_k: sst_w.appendn^ ('signed', 6); int_unsigned_k: sst_w.appendn^ ('unsigned', 8); end; sst_w.delimit^; if pack then begin {this is field in a packed record ?} sst_w.appendn^ ('int', 3); {field width will be set explicitly later} fw := dtype.bits_min; {set field width for this field in record} if {SGI full size packed field kluge ?} (sst_config.manuf = sst_manuf_sgi_k) and {will be an SGI compiler ?} (fw = sst_config.int_machine_p^.bits_min) {same size as INT ?} then begin fw := 0; {disable field width specifier} end; goto done_case; end; { * Look for target machine integer sizes to match the size of this data type. * The match must be exact, because the front end may have assumed the size * was known. This would be the case, for example, if a SIZE_MIN function * was used on this data type. } for i := 1 to sst_config.n_size_int do begin {once for each avail integer size} with sst_config.size_int[i].dtype_p^: dt do begin {DT is dtype desc for this int} if dt.size_used = dtype.size_used then begin {found the right one ?} sst_w.append_sym_name^ (dt.symbol_p^); {write int dtype name of matching size} goto done_case; end; end; {done with DT abbreviation} end; {back to check next native out integer type} { * None of the native integers are of the right size. This is a hard error. } if (dtype.symbol_p = nil) or else (dtype.symbol_p^.name_in_p = nil) then begin {no name available for input data type} sys_msg_parm_str (msg_parm[1], ''); end else begin {input data type does have a name} sys_msg_parm_vstr (msg_parm[1], dtype.symbol_p^.name_in_p^); end ; sys_msg_parm_int (msg_parm[2], dtype.bits_min); sys_message_bomb ('sst', 'dtype_int_unavailable', msg_parm, 2); end; { ************************************ * * Data type is ENUMERATED TYPE. } sst_dtype_enum_k: begin if {OK to use native ENUM data type ?} (not pack) and (sst_config.size_enum = sst_config.size_enum_native) { * We are allowed to use the native ENUM data type. } then begin sst_w.appendn^ ('enum', 4); sst_w.delimit^; sst_w.appendn^ ('{', 1); sym_p := dtype.enum_first_p; {init current symbol to first symbol} while sym_p <> nil do begin {once for each enumerated value} sst_w.line_close^; {put each name on a new line} sst_w.tab_indent^; sst_w.append_sym_name^ (sym_p^); {write this enumerated value name} if sym_p <> dtype.enum_last_p then begin {this is not last name in list ?} sst_w.appendn^ (',', 1); end; sym_p := sym_p^.enum_next_p; {advance to next enumerated name in list} end; sst_w.appendn^ ('}', 1); end { * We are not allowed to use the native ENUM data type because it is a different * size than what we have been told to use for ENUMs. The data type will * be an integer of the appropriate size. All the mnemonics of the enumerated * type will be declared to their values in #define statements. } else begin int_sign := int_unsigned_k; {this integer type is always unsigned} fw := dtype.bits_min; {field width if field in packed record} sst_w_c_pos_push (frame_scope_p^.sment_type); {switch to before curr statement} sym_p := dtype.enum_first_p; {init current symbol to first symbol} while sym_p <> nil do begin {once for each enumerated value} sst_w.tab_indent^; sst_w.appendn^ ('#define ', 8); sst_w.append_sym_name^ (sym_p^); {write this enumerated value name} sst_w.appendn^ (' ', 1); string_f_int (token, sym_p^.enum_ordval); sst_w.append^ (token); {write value of this enumerated name} sst_w.line_close^; sym_p := sym_p^.enum_next_p; {advance to next enumerated name in list} end; sst_w_c_pos_pop; {pop back to old writing position} goto do_int; {handle data type like other integers} end; ; end; { ************************************ * * Data type is FLOATING POINT. } sst_dtype_float_k: begin for i := 1 to sst_config.n_size_float do begin {once for each avail float size} with sst_config.size_float[i].dtype_p^: dt do begin {DT is dtype for this float} if dt.bits_min < dtype.bits_min {not big enough ?} then next; if dt.bits_min = dtype.bits_min then begin {exact right size ?} sst_w.append_sym_name^ (dt.symbol_p^); {write data type's name} goto done_case; end; end; {done with DT abbreviation} exit; {exact match not available} end; {back to check next native out float type} { * None of the native output floating point formats match. This is a hard * error. } if (dtype.symbol_p = nil) or else (dtype.symbol_p^.name_in_p = nil) then begin {no name available for input data type} sys_msg_parm_str (msg_parm[1], ''); end else begin {input data type does have a name} sys_msg_parm_vstr (msg_parm[1], dtype.symbol_p^.name_out_p^); end ; sys_msg_parm_int (msg_parm[2], dtype.bits_min); sys_message_bomb ('sst', 'dtype_float_unavailable', msg_parm, 2); end; { ************************************ * * Data type is BOOLEAN. } sst_dtype_bool_k: begin if pack then begin {this is field in a packed record ?} sst_w.appendn^ ('unsigned int', 12); fw := 1; goto done_case; end; sst_w.append^ (sst_config.name_bool); end; { ************************************ * * Data type is CHARACTER. } sst_dtype_char_k: begin sst_w.append^ (sst_config.name_char); end; { ************************************ * * Data type is a RECORD. } sst_dtype_rec_k: begin { * Determine whether this record has any variants (overlays). Only * records without any variants are handled here directly. Records * with variants are handled with the help of routine SST_W_C_DTYPE_VREC. * * Variant records are written as UNIONs at the top level, while records * without variants are written as STRUTs. } if sst_rec_variant(dtype) then begin {the record DOES have variants} variants := true; sst_w.appendn^ ('union', 5); end else begin {the record has no variants} variants := false; sst_w.appendn^ ('struct', 6); end ; sst_w.delimit^; sst_w.append^ (name); sst_w.delimit^; sst_w.appendn^ ('{', 1); sst_w.line_close^; scope_old_p := sst_scope_p; {save old scope/namespace context} names_old_p := sst_names_p; sst_scope_p := dtype.rec_scope_p; {temp swap in scope for this record} sst_names_p := sst_scope_p; sym_p := dtype.rec_first_p; {init curr field symbol to first field symbol} while sym_p <> nil do begin {once for each field name in record} if variants then begin {this field is in a variant record} sst_w_c_dtype_vrec ( {write all the fields in this variant} sym_p, {pointer to next field, will be updated} dtype.align_nat = 0); {TRUE if within a packed record} end else begin {this field is not in a variant record} sst_w.tab_indent^; {go to proper indentation level} sst_w.indent^; {indent wrapped lines} sst_w_c_dtype_simple ( {write data type declaration} sym_p^.field_dtype_p^, {descriptor for data type to write} sym_p^.name_out_p^, {name of field to declare} dtype.align_nat = 0); {TRUE if this is a packed record} sst_w.undent^; {undo indent for wrapped lines} sst_w.appendn^ (';', 1); sst_w.line_close^; sym_p := sym_p^.field_next_p; {advance to next field in this record} end ; end; {back and process this new field} sst_w.tab_indent^; sst_w.appendn^ ('}', 1); sst_scope_p := scope_old_p; {restore old scope/namespace} sst_names_p := names_old_p; end; { ************************************ * * Data type is an ARRAY. * * The C declaration for an array looks like this: * * <element data type> <array name>[s1][s2] ... [sn] * * The current writing position is at the start of <element data type>. } sst_dtype_array_k: begin string_copy (name, name_ele); {init symbol "name" to declare} dt_p := addr(dtype); {init to outermost data type} repeat {once for each subscript in array} string_append1 (name_ele, '['); string_f_int (token, max(dt_p^.ar_ind_n, 1)); {string for dimension of this subscr} string_append (name_ele, token); string_append1 (name_ele, ']'); dt_p := dt_p^.ar_dtype_rem_p; {advance to data type after this subscript} until dt_p = nil; {just did last subscript ?} sst_w_c_dtype_simple (dtype.ar_dtype_ele_p^, name_ele, false); {do the declare} name_written := true; {indicate NAME already written} end; { ************************************ * * Data type is a SET. * * The C language has no SET data type. These will be emulated with unsigned * integers. Each element of the set will have a 2**n value. The first element * will have value 1. For now, this implementation only allows set sizes * limited to the number of bits in the largest available integer. } sst_dtype_set_k: begin int_sign := int_unsigned_k; {emulate with unsigned integers} goto do_int; end; { ************************************ * * Data type is a RANGE. * * The C language has no subrange data type. These will be emulated with * either signed or unsigned integers, depending on whether the range includes * any negative numbers. } sst_dtype_range_k: begin if dtype.range_ord_first >= 0 then int_sign := int_unsigned_k {no negative values in subrange} else int_sign := int_signed_k; {range does cover negative values} goto do_int; end; { ************************************ * * Data type is a PROCEDURE * * The C declaration for a pointer to a routine looks like this: * * <function value data type> (*<symbol name>) (<arguments template>) * * Since this translator data type is a routine, not a pointer to a routine, * the call argument NAME already contains the leading "*". } sst_dtype_proc_k: begin name_ele.len := 0; {empty string for writing data type only} { * Write data type of function return, if any. } if dtype.proc_p^.dtype_func_p = nil then begin {subroutine, returns no value} sst_w.appendn^ ('void', 4); end else begin {routine is function, returns a value} sst_w_c_dtype_simple (dtype.proc_p^.dtype_func_p^, name_ele, false); end ; sst_w.delimit^; { * Write name of symbol to declare. } sym_p := dtype.proc_p^.sym_p; {get pointer to routine name symbol} if (sym_p <> nil) and then {we have routine name symbol ?} (sst_symflag_global_k in sym_p^.flags) and {this is a global function ?} (sst_config.os = sys_os_win32_k) {writing for Win32 API ?} then begin sst_w.appends^ ('__stdcall'(0)); {specify linkage conventions} sst_w.delimit^; end; if name.str[1] = '*' then begin {name must be enclosed in parenthesis} sst_w.appendn^ ('(', 1); sst_w.append^ (name); sst_w.appendn^ (')', 1); end else begin sst_w.append^ (name); end ; sst_w.delimit^; name_written := true; {indicate symbol name already written} { * Write arguments template. } sst_w.appendn^ ('(', 1); arg_p := dtype.proc_p^.first_arg_p; {init pointer to first call argument} if arg_p = nil then begin {this routine takes no call arguments} sst_w.appendn^ ('void', 4); end else begin {this routine does take call arguments} while arg_p <> nil do begin {once for each call argument} sst_w.line_close^; {each argument goes on a new line} sst_w.tab_indent^; sst_w.indent^; {for wrapped argument definition} case arg_p^.pass of {how is this argument passed ?} sst_pass_ref_k: begin {argument is passed by reference} if arg_p^.univ and {any calling data type allowed to match ?} (sst_ins or sst_writeall) {declaration not be seen by definition code ?} then begin {don't force caller to write type cast} sst_w.appends^ ('void *'(0)); end else begin {write declaration to match definition} sst_w_c_dtype_simple (arg_p^.dtype_p^, name_ele, false); {write arg dtype name} dt_p := arg_p^.dtype_p; {get argument's base data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; if {not already passed as pointer anyway ?} dt_p^.dtype <> sst_dtype_array_k then begin sst_w.delimit^; sst_w.appendn^ ('*', 1); end; end ; end; sst_pass_val_k: begin {argument is passed by value} sst_w_c_dtype_simple (arg_p^.dtype_p^, name_ele, false); {write arg dtype name} end; otherwise sys_msg_parm_int (msg_parm[1], ord(arg_p^.pass)); sys_message_bomb ('sst_c_write', 'arg_pass_method_bad', msg_parm, 1); end; arg_p := arg_p^.next_p; {advance to next argument in list} if arg_p <> nil then begin {another argument follows this one ?} sst_w.appendn^ (',', 1); sst_w.delimit^; end; sst_w.undent^; {back from extra level for this argument} end; {back and process next call argument} end ; {done with body of call args template} sst_w.appendn^ (')', 1); end; { ************************************ * * Data type is a POINTER. } sst_dtype_pnt_k: begin name_ele.len := 0; string_append1 (name_ele, '*'); string_append (name_ele, name); sst_w_c_dtype_simple (dtype.pnt_dtype_p^, name_ele, false); name_written := true; {indicate symbol name already written} end; { ************************************ * * Data type is a COPY of another data type. } sst_dtype_copy_k: begin sst_w_c_dtype_simple (dtype.copy_dtype_p^, name, pack); name_written := true; {indicate symbol name already written} end; { ************************************ * * Unexpected data type. } otherwise sys_msg_parm_int (msg_parm[1], ord(dtype.dtype)); sys_message_bomb ('sst', 'dtype_unexpected', msg_parm, 1); end; {end of data type cases} done_case: {jump here if done with any one case} { * Done with all the data type cases. For most data types in C, the symbol * being declared comes after the data type. The symbol must now be written * if NAME_WRITTEN is false. Also, the field width for a packed record field * must be written, if appropriate. } if (not name_written) and (name.len > 0) then begin {need to write symbol name ?} sst_w.delimit^; sst_w.append^ (name); end; if pack and (fw > 0) then begin {need to write field width specifier ?} sst_w.appendn^ (':', 1); sst_w.delimit^; string_f_int (token, fw); {make field width string} sst_w.append^ (token); end; end;
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.1 11/29/2004 11:26:00 PM JPMugaas { This should now support SuperTCP 7.1 running under Windows 2000. That does { support long filenames by the dir entry ending with one space followed by the { long-file name. { ShortFileName was added to the listitem class for completeness. } { { Rev 1.0 11/29/2004 2:44:16 AM JPMugaas { New FTP list parsers for some legacy FTP servers. } unit IdFTPListParseSuperTCP; interface uses IdFTPList, IdFTPListParseBase, IdObjs; type TIdSuperTCPFTPListItem = class(TIdFTPListItem) protected FShortFileName : String; public property ShortFileName : String read FShortFileName write FShortFileName; end; TIdFTPLPSuperTCP = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String=''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TIdStrings; const ASysDescript : String =''; const ADetails : Boolean = True): boolean; override; end; implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, IdSys; { TIdFTPLPSuperTCP } class function TIdFTPLPSuperTCP.CheckListing(AListing: TIdStrings; const ASysDescript: String; const ADetails: Boolean): boolean; { Maybe like this: CMT <DIR> 11-21-94 10:17 DESIGN1.DOC 11264 05-11-95 14:20 or this: CMT <DIR> 11/21/94 10:17 DESIGN1.DOC 11264 05/11/95 14:20 or this with SuperTCP 7.1 running under Windows 2000: . <DIR> 11-29-2004 22:04 . .. <DIR> 11-29-2004 22:04 .. wrar341.exe 1164112 11-22-2004 15:34 wrar341.exe test <DIR> 11-29-2004 22:14 test TESTDI~1 <DIR> 11-29-2004 22:16 Test Dir TEST~1 <DIR> 11-29-2004 22:52 Test } var i : Integer; LBuf, LBuf2 : String; begin Result := False; for i := 0 to AListing.Count -1 do begin LBuf := AListing[i]; //filename and extension - we assume an 8.3 filename type because //Windows 3.1 only supports that. Fetch(LBuf); LBuf := Sys.TrimLeft(LBuf); //<DIR> or file size LBuf2 := Fetch(LBuf); Result := (LBuf2='<DIR>') or IsNumeric(LBuf2); {Do not localize} if not result then begin Exit; end; //date LBuf := Sys.TrimLeft(LBuf); LBuf2 := Fetch(LBuf); Result := IsMMDDYY(LBuf2,'/') or IsMMDDYY(LBuf2,'-'); if Result then begin //time LBuf := Sys.TrimLeft(LBuf); LBuf2 := Fetch(LBuf); Result := IsHHMMSS(LBuf2,':'); end; if not result then begin break; end; end; end; class function TIdFTPLPSuperTCP.GetIdent: String; begin Result := 'SuperTCP'; end; class function TIdFTPLPSuperTCP.MakeNewItem( AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdSuperTCPFTPListItem.Create(AOwner); end; class function TIdFTPLPSuperTCP.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LI : TIdSuperTCPFTPListItem; LBuf, LBuf2 : String; { with SuperTCP 7.1 running under Windows 2000: . <DIR> 11-29-2004 22:04 . .. <DIR> 11-29-2004 22:04 .. wrar341.exe 1164112 11-22-2004 15:34 wrar341.exe test <DIR> 11-29-2004 22:14 test TESTDI~1 <DIR> 11-29-2004 22:16 Test Dir TEST~1 <DIR> 11-29-2004 22:52 Test } begin LI := AItem as TIdSuperTCPFTPListItem; LBuf := AItem.Data; //short filename and extension - we assume an 8.3 filename //type because Windows 3.1 only supports that and under Win32, //a short-filename is returned here. That's with my testing. LBuf2 := Fetch(LBuf); LI.FileName := LBuf2; LI.ShortFileName := LBuf2; LBuf := Sys.TrimLeft(LBuf); //<DIR> or file size LBuf2 := Fetch(LBuf); if LBuf2 = '<DIR>' then {Do not localize} begin LI.ItemType := ditDirectory; LI.SizeAvail := False; end else begin LI.ItemType := ditFile; Result := IsNumeric(LBuf2); if not result then begin Exit; end; LI.Size := Sys.StrToInt64(LBuf2,0); end; //date LBuf := Sys.TrimLeft(LBuf); LBuf2 := Fetch(LBuf); if IsMMDDYY(LBuf2,'/') or IsMMDDYY(LBuf2,'-') then begin LI.ModifiedDate := DateMMDDYY(LBuf2); end else begin Result := False; Exit; end; //time LBuf := Sys.TrimLeft(LBuf); LBuf2 := Fetch(LBuf); Result := IsHHMMSS(LBuf2,':'); if Result then begin LI.ModifiedDate := LI.ModifiedDate + IdFTPCommon.TimeHHMMSS(LBuf2); end; // long filename //We do not use TrimLeft here because a space can start a filename in Windows //2000 and the entry would be like this: // //TESTDI~1 <DIR> 11-29-2004 22:16 Test Dir //TEST~1 <DIR> 11-29-2004 22:52 Test // if LBuf<>'' then begin LI.FileName := LBuf; end; end; initialization RegisterFTPListParser(TIdFTPLPSuperTCP); finalization UnRegisterFTPListParser(TIdFTPLPSuperTCP); end.
unit clAcariacoes; interface type TAcariacoes = Class(Tobject) private function getApuracao : String; function getBase : Integer; function getEntregador : Integer; function getEnvio : String; function getExecutor : String; function getExtravio : Double; function getId : String; function getManutencao : TDateTime; function getMotivo : String; function getMulta : Double; function getNossonumero : String; function getObs : String; function getResultado : String; function getRetorno : String; function getSequencia : Integer; function getTratativa : String; function getData : TDateTime; procedure setApuracao (const Value: String); procedure setBase (const Value: Integer); procedure setEntregador (const Value: Integer); procedure setEnvio (const Value: String); procedure setExecutor (const Value: String); procedure setExtravio (const Value: Double); procedure setId (const Value: String); procedure setManutencao (const Value: TDateTime); procedure setMotivo (const Value: String); procedure setMulta (const Value: Double); procedure setNossoNumero (const Value: String); procedure setObs (const Value: String); procedure setResultado (const Value: String); procedure setRetorno (const Value: String); procedure setSequencia (const Value: Integer); procedure setTratativa (const Value: String); procedure setData(const Value: TDateTime); procedure MaxSeq; function Validar() : Boolean; function Delete(sfiltro: String) : Boolean; function GetObject(id, filtro: String) : Boolean; function GetObjects() : Boolean; function Insert() : Boolean; protected _sequencia : Integer; _id : String; _data : TDateTime; _nossonumero : String; _entregador : Integer; _base : Integer; _motivo : String; _tratativa : String; _apuracao : String; _resultado : String; _extravio : Double; _multa : Double; _envio : String; _retorno : String; _obs : String; _executor : String; _manutencao : TDateTime; public property Sequencia : Integer read getSequencia write setSequencia; property Id : String read getId write setId; property Data : TDateTime read getData write setData; property NossoNumero : String read getNossonumero write setNossoNumero; property Entregador : Integer read getEntregador write setEntregador; property Base : Integer read getBase write setBase; property Motivo : String read getMotivo write setMotivo; property Tratativa : String read getTratativa write setTratativa; property Apuracao : String read getApuracao write setApuracao; property Resultado : String read getResultado write setResultado; property Extravio : Double read getExtravio write setExtravio; property Multa : Double read getMulta write setMulta; property Envio : String read getEnvio write setEnvio; property Retorno : String read getRetorno write setRetorno; property Obs : String read getObs write setObs; property Executor : String read getExecutor write setExecutor; property Manutencao : TDateTime read getManutencao write setManutencao; end; const TABLENAME = 'TBACARIACOES'; implementation { TAcariacoes } uses udm, clUtil, System.SysUtils, System.DateUtils, Vcl.Dialogs; function TAcariacoes.getApuracao: String; begin Result := _apuracao; end; function TAcariacoes.getBase: Integer; begin Result := _base; end; function TAcariacoes.getData: TDateTime; begin Result := _data; end; function TAcariacoes.getEntregador: Integer; begin Result := _entregador; end; function TAcariacoes.getEnvio: String; begin Result := _envio; end; function TAcariacoes.getExecutor: String; begin Result := _executor; end; function TAcariacoes.getExtravio: Double; begin Result := _extravio; end; function TAcariacoes.getId: String; begin Result := _id; end; function TAcariacoes.getManutencao: TDateTime; begin Result := _manutencao; end; function TAcariacoes.getMotivo: String; begin Result := _motivo; end; function TAcariacoes.getMulta: Double; begin Result := _multa; end; function TAcariacoes.getNossonumero: String; begin Result := _nossonumero; end; function TAcariacoes.getObs: String; begin Result := _obs; end; function TAcariacoes.getResultado: String; begin Result := _resultado; end; function TAcariacoes.getRetorno: String; begin Result := _retorno; end; function TAcariacoes.getSequencia: Integer; begin Result := _sequencia; end; function TAcariacoes.getTratativa: String; begin Result := _tratativa; end; procedure TAcariacoes.MaxSeq; begin Try with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(SEQ_ACAREACAO) AS SEQUENCIA FROM '+ TABLENAME; dm.ZConn.PingServer; Open; if not (IsEmpty) then First; end; Self.Sequencia := (dm.QryGetObject.FieldByName('SEQUENCIA').AsInteger) + 1; dm.QryGetObject.Close; dm.qryGetObject.SQL.Clear; Except on E : Exception do ShowMessage('Classe: '+ e.ClassName + chr(13) + 'Mensagem: '+ e.Message); end; end; function TAcariacoes.Validar(): Boolean; var iApuracao, iResultado : Integer; begin try Result := False; iApuracao := 0; iResultado := 0; if TUtil.Empty(Self.Id) then begin MessageDlg('Informe um ID válido para esta Acareação!', mtWarning,[mbOK]); Exit; end; if TUtil.Empty(Self.NossoNumero) then begin MessageDlg('Informe o Nosso Número!', mtWarning,[mbOK]); Exit; end; if Self.Entregador = 0 then begin MessageDlg('Informe o Código do Entregador!', mtWarning,[mbOK]); Exit; end; if Self.Base = 0 then begin MessageDlg('Informe o Código da Base!', mtWarning,[mbOK]); Exit; end; if TUtil.Empty(Self.Motivo) then begin MessageDlg('Informe o Motivo desta Acareação!', mtWarning,[mbOK]); Exit; end; if TUtil.Empty(Self.Tratativa) then begin MessageDlg('Informe o Motivo desta Acareação!', mtWarning,[mbOK]); Exit; end; if (not TUtil.Empty(Self.Apuracao)) then begin iApuracao := Copy(Self.Apuracao,1,3); end; if (not TUtil.Empty(Self.Resultado)) then begin if iApuracao = 1 then begin if iResultado < 3 then begin MessageDlg('Resultado da Acareação inválido para o tipo de Apuração informada!', mtWarning,[mbOK]); Exit; end; end; if iApuracao = 3 then begin if iResultado > 2 then begin MessageDlg('Resultado da Acareação inválido para o tipo de Apuração informada!', mtWarning,[mbOK]); Exit; end; end; if iApuracao = 6 then begin if iResultado > 2 then begin MessageDlg('Resultado da Acareação inválido para o tipo de Apuração informada!', mtWarning,[mbOK]); Exit; end; end; if iApuracao = 7 then begin if iResultado > 2 then begin MessageDlg('Resultado da Acareação inválido para o tipo de Apuração informada!', mtWarning,[mbOK]); Exit; end; end; if iApuracao = 10 then begin if iResultado > 2 then begin MessageDlg('Resultado da Acareação inválido para o tipo de Apuração informada!', mtWarning,[mbOK]); Exit; end; end; if iApuracao = 11 then begin if iResultado > 2 then begin MessageDlg('Resultado da Acareação inválido para o tipo de Apuração informada!', mtWarning,[mbOK]); Exit; end; end; if iResultado = 2 then begin if Self.Extravio = 0 then begin MessageDlg('Informe o Valor do Extravio!', mtWarning,[mbOK]); Exit; end; if Self.Multa > 0 then begin MessageDlg('Valor de Multa inválido para o Resultado informado!', mtWarning,[mbOK]); Exit; end; end; if iResultado = 3 then begin if Self.Extravio = 0 then begin MessageDlg('Informe o Valor do Extravio!', mtWarning,[mbOK]); Exit; end; if Self.Multa = 0 then begin MessageDlg('Informe o Valor da Multa!', mtWarning,[mbOK]); Exit; end; end; if iResultado = 4 then begin if Self.Extravio > 0 then begin MessageDlg('Valor do Extravio inválido para o Resultado informado!', mtWarning,[mbOK]); Exit; end; if Self.Multa = 0 then begin MessageDlg('Informe o Valor da Multa!', mtWarning,[mbOK]); Exit; end; end; end; Result := True; except on E : Exception do ShowMessage('Classe: '+ e.ClassName + chr(13) + 'Mensagem: '+ e.Message); end; end; function TAcariacoes.Delete(sfiltro: String): Boolean; begin try Result := False; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Add('DELETE FROM '+ TABLENAME); if sfiltro = 'SEQUENCIA' then begin dm.QryCRUD.SQL.Add('WHERE SEQ_ACAREACAO = :CODIGO'); dm.QryCRUD.ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; end else if sfiltro = 'ID' then begin dm.QryCRUD.SQL.Add('WHERE ID_ACAREACAO = :ID'); dm.QryCRUD.ParamByName('ID').AsString := Self.Id; end else if sfiltro = 'NOSSONUMERO' then begin dm.QryCRUD.SQL.Add('WHERE NUM_NOSSONUMERO = :NOSSONUMERO'); dm.QryCRUD.ParamByName('NOSSORUMERO').AsString := Self.NossoNumero; end else if sfiltro = 'ENTREGADOR' then begin dm.QryCRUD.SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); dm.QryCRUD.ParamByName('ENTREGADOR').AsInteger := Self.Entregador; end else if sfiltro = 'BASE' then begin dm.QryCRUD.SQL.Add('WHERE COD_BASE = :BASE'); dm.QryCRUD.ParamByName('BASE').AsInteger := Self.Base; end; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; except on E : Exception do ShowMessage('Classe: '+ e.ClassName + chr(13) + 'Mensagem: '+ e.Message); end; end; function TAcariacoes.GetObject(id: string; filtro: string): Boolean; begin try Result := False; if TUtil.Empty(Id) then begin Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM '+ TABLENAME); if filtro = 'SEQUENCIA' then begin dm.QryGetObject.SQL.Add('WHERE SEQ_ACAREACAO = :SEQUENCIA'); dm.QryGetObject.ParamByName('SEQUENCIA').AsInteger := StrToInt(id); end else if Filtro = 'ID' then begin dm.QryGetObject.SQL.Add('WHERE ID_ACAREACAO = :ID'); dm.QryGetObject.ParamByName('ID').AsString := id; end else if filtro = 'NOSSONUMERO' then begin dm.QryGetObject.SQL.Add('WHERE NUM_NOSSONUMERO = :NOSSONUMERO'); dm.QryGetObject.ParamByName('NOSSONUMERO').AsString := id; end else if filtro = 'MOTIVO' then begin dm.QryGetObject.SQL.Add('WHERE DES_EXTRAVIO = :MOTIVO'); dm.QryGetObject.ParamByName('MOTIVO').AsString := id; end else if filtro = 'ENVIO' then begin dm.QryGetObject.SQL.Add('WHERE DES_ENVIO_CORRESPONDENCIA = :ENVIO'); dm.QryGetObject.ParamByName('ENVIO').AsString := id; end else if filtro = 'RETORNO' then begin dm.QryGetObject.SQL.Add('WHERE DES_RETORNO_CORRESPONDENCIA = :RETORNO'); dm.QryGetObject.ParamByName('RETORNO').AsString := id; end else if filtro = 'DATA' then begin dm.QryGetObject.SQL.Add('WHERE DAT_EXTRAVIO = :DATA'); dm.QryGetObject.ParamByName('DATA').AsDate := StrToDate(id); end else if filtro = 'ENTREGADOR' then begin dm.QryGetObject.SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); dm.QryGetObject.ParamByName('ENTREGADOR').AsInteger := StrToInt(id); end else if filtro = 'ENTREGADORES' then begin dm.QryGetObject.SQL.Add('WHERE COD_ENTREGADOR IN (:ENTREGADOR)'); dm.QryGetObject.ParamByName('ENTREGADOR').AsString := id; end else if filtro = 'AGENTE' then begin dm.QryGetObject.SQL.Add('WHERE COD_AGENTE = :AGENTE'); dm.QryGetObject.ParamByName('AGENTE').AsInteger := StrToInt(id); end; dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; end; if (not dm.qryGetObject.IsEmpty) then begin Self.Sequencia := dm.QryGetObject.FieldByName('SEQ_ACAREACAO').AsInteger; Self.Id := dm.QryGetObject.FieldByName('ID_ACAREACAO').AsString; self.Data := dm.QryGetObject.FieldByName('DAT_ACAREACAO').AsDateTime; Self.NossoNumero := dm.QryGetObject.FieldByName('NUM_NOSSONUMERO').AsString; Self.Entregador := dm.QryGetObject.FieldByName('COD_ENTREGADOR').AsInteger; Self.Base := dm.QryGetObject.FieldByName('COD_BASE').AsInteger; Self.Motivo := dm.QryGetObject.FieldByName('DES_MOTIVO').AsString; Self.Tratativa := dm.QryGetObject.FieldByName('DES_TRATATIVA').AsString; Self.Apuracao := dm.QryGetObject.FieldByName('DES_APURACAO').AsString; Self.Resultado := dm.QryGetObject.FieldByName('DES_RESULTADO').AsString; Self.Extravio := dm.QryGetObject.FieldByName('VAL_EXTRAVIO').AsFloat; Self.Multa := dm.QryGetObject.FieldByName('VAL_MULTA').AsFloat; Self.Envio := dm.qryGetObject.FieldByName('DES_ENVIO_CORRESPONDENCIA').AsString; Self.Retorno := dm.qryGetObject.FieldByName('DES_RETORNO_CORRESPONDENCIA').AsString; Self.Obs := dm.qryGetObject.FieldByName('DES_OBSERVACOES').AsString; Self.Executor := dm.QryGetObject.FieldByName('NOM_EXECUTOR').AsString; Self.Manutencao := dm.QryGetObject.FieldByName('DAT_MANUTENCAO').AsDateTime; Result := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E : Exception do ShowMessage('Classe: '+ e.ClassName + chr(13) + 'Mensagem: '+ e.Message); end; end; function TAcariacoes.GetObjects(): Boolean; begin try Result := False; if TUtil.Empty(Id) then begin Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM '+ TABLENAME); dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; Result := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E : Exception do ShowMessage('Classe: '+ e.ClassName + chr(13) + 'Mensagem: '+ e.Message); end; end; function TAcariacoes.Insert(): Boolean; begin try Except on E : Exception do ShowMessage('Classe: '+ e.ClassName + chr(13) + 'Mensagem: '+ e.Message); end; end; procedure TAcariacoes.setApuracao(const Value: String); begin _apuracao := Value; end; procedure TAcariacoes.setBase(const Value: Integer); begin _base := Value; end; procedure TAcariacoes.setData(const Value: TDateTime); begin _data := Value; end; procedure TAcariacoes.setEntregador(const Value: Integer); begin _entregador := Value; end; procedure TAcariacoes.setEnvio(const Value: String); begin _envio := Value; end; procedure TAcariacoes.setExecutor(const Value: String); begin _executor := Value; end; procedure TAcariacoes.setExtravio(const Value: Double); begin _extravio := Value; end; procedure TAcariacoes.setId(const Value: String); begin _id := Value; end; procedure TAcariacoes.setManutencao(const Value: TDateTime); begin _manutencao := Value; end; procedure TAcariacoes.setMotivo(const Value: String); begin _motivo := Value; end; procedure TAcariacoes.setMulta(const Value: Double); begin _multa := Value; end; procedure TAcariacoes.setNossoNumero(const Value: String); begin _nossonumero := Value; end; procedure TAcariacoes.setObs(const Value: String); begin _obs := Value; end; procedure TAcariacoes.setResultado(const Value: String); begin _resultado := Value; end; procedure TAcariacoes.setRetorno(const Value: String); begin _retorno := Value; end; procedure TAcariacoes.setSequencia(const Value: Integer); begin _sequencia := Value; end; procedure TAcariacoes.setTratativa(const Value: String); begin _tratativa := Value; end; end.
unit libge.dbroot; interface const libge_dbroot_dll = 'libge.dbroot.dll'; type size_t = Cardinal; uint32_t = Cardinal; dbroot_t = record obj: Pointer; error: PAnsiChar; end; string_t = record data: Pointer; size: size_t; end; function dbroot_open(const data: Pointer; const length: size_t; out dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; function dbroot_close(var dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; function dbroot_get_quadtree_version(out version: uint32_t; var dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; function dbroot_set_quadtree_version(const version: uint32_t; var dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; function dbroot_set_use_ge_logo(const val: Boolean; var dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; function dbroot_set_max_requests_per_query(const val: uint32_t; var dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; function dbroot_set_discoverability_altitude_meters(const val: uint32_t; var dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; function dbroot_clear_copyright_string(out cleared_count: uint32_t; var dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; function dbroot_pack(var str: string_t; var dbroot: dbroot_t): Boolean; cdecl; external libge_dbroot_dll; implementation end.
unit Weather.Settings; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, HGM.Button, System.ImageList, Vcl.ImgList, Vcl.ExtCtrls, HGM.Controls.Labels; type TFormSettings = class(TForm) ButtonFlatSetCancel: TButtonFlat; ButtonFlatSetOk: TButtonFlat; Label1: TLabel; LabelError: TLabel; ImageList24: TImageList; EditCity: TEdit; Label2: TLabel; LabelExColor: TLabelEx; ColorDialog: TColorDialog; procedure ButtonFlatSetOkClick(Sender: TObject); procedure ButtonFlatSetCancelClick(Sender: TObject); procedure LabelExColorClick(Sender: TObject); private { Private declarations } public class function Execute(var City: string; var AColor: TColor): Boolean; end; var FormSettings: TFormSettings; implementation uses Weather.Main, System.UITypes; {$R *.dfm} procedure TFormSettings.ButtonFlatSetCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFormSettings.ButtonFlatSetOkClick(Sender: TObject); begin LabelError.Hide; Application.ProcessMessages; with FormWeather do begin FCheckIt := True; RESTRequest.Params.ParameterByName('q').Value := EditCity.Text; RESTRequest.Execute; FCheckIt := False; if FLocateError then begin LabelError.Show; Exit; end else Self.ModalResult := mrOk; end; end; class function TFormSettings.Execute(var City: string; var AColor: TColor): Boolean; begin with TFormSettings.Create(nil) do begin EditCity.Text := City; LabelExColor.StyledColor(AColor); Result := ShowModal = mrOk; if Result then begin City := EditCity.Text; AColor := LabelExColor.Brush.Color; end; Free; end; end; procedure TFormSettings.LabelExColorClick(Sender: TObject); begin if ColorDialog.Execute(Handle) then begin LabelExColor.StyledColor(ColorDialog.Color); FormWeather.SetThemeColor(ColorDialog.Color); FormWeather.Repaint; end; end; end.
unit uAssets; interface uses glr_scene, glr_math, glr_render, glr_render2d; type { Assets } Assets = class public // Base assets class var GuiAtlas: TglrTextureAtlas; class var GuiMaterial: TglrMaterial; class var GuiCamera: TglrCamera; class var GuiSpriteBatch: TglrSpriteBatch; class var FontMain: TglrFont; class var FontMainBatch: TglrFontBatch; class procedure LoadBase(); class procedure UnloadBase(); // Level specified assets // ... end; { Texts } Texts = class public class var MenuNewGame, MenuSettings, MenuExit, MenuTitle, MenuAuthorName, MenuApply, MenuBack, SettingsMusicVolume, SettingsSoundVolume : UnicodeString; class procedure LoadMenu(); end; { Colors } Colors = class class var Red, White, Black, Gray, MenuButton, MenuButtonText, MenuButtonOver, MenuSlider, MenuSliderOver, MenuText, MenuBackground : TglrVec4f; class procedure Load(); end; const R_GUI_ATLAS_BUTTON = 'button.png'; R_GUI_ATLAS_BUTTON_OVER = 'button_over.png'; R_GUI_ATLAS_SLIDER_BACK = 'slider_back.png'; R_GUI_ATLAS_SLIDER_FILL = 'slider_fill.png'; R_GUI_ATLAS_SLIDER_BTN = 'slider_btn.png'; R_GUI_ATLAS_CHECKBOX = 'checkbox.png'; R_GUI_ATLAS_CHECKBOX_C = 'checkbox_check.png'; implementation uses glr_filesystem, glr_core; const R_BASE = 'data/'; R_GUI_ATLAS_IMG = R_BASE + 'gui.tga'; R_GUI_ATLAS_TXT = R_BASE + 'gui.atlas'; R_FONT_MAIN = R_BASE + 'HelveticaLight19b.fnt'; { Colors } class procedure Colors.Load; begin Red := Color4ub(241, 0, 0); White := Color4ub(255, 255, 255); Black := Color4ub(0, 0, 0); Gray := Color4ub(60, 60, 60); MenuButton := Red; //Color4ub(80, 160, 255); MenuButtonText := White; //Color4ub(230, 230, 230); MenuButtonOver := White; //Color4ub(160, 250, 250); MenuSlider := Red; MenuSliderOver := White; MenuText := Red; MenuBackground := Gray; //:= Color4ub(20, 50, 110); end; { Texts } class procedure Texts.LoadMenu(); begin MenuNewGame := UTF8Decode('Новая игра'); MenuSettings := UTF8Decode('Настройки'); MenuExit := UTF8Decode('Выход'); MenuTitle := UTF8Decode('Arena Shooter для igdc #123'); MenuAuthorName := UTF8Decode('perfect.daemon, 2015 (c)'); MenuApply := UTF8Decode('Применить'); MenuBack := UTF8Decode('Назад'); SettingsMusicVolume := UTF8Decode('Музыка'); SettingsSoundVolume := UTF8Decode('Звуки'); end; { Assets } class procedure Assets.LoadBase(); begin GuiAtlas := TglrTextureAtlas.Create( FileSystem.ReadResource(R_GUI_ATLAS_IMG), FileSystem.ReadResource(R_GUI_ATLAS_TXT), extTga, aextCheetah); GuiMaterial := TglrMaterial.Create(Default.SpriteShader); GuiMaterial.AddTexture(GuiAtlas, 'uDiffuse'); GuiSpriteBatch := TglrSpriteBatch.Create(); GuiCamera := TglrCamera.Create(); GuiCamera.SetProjParams(0, 0, Render.Width, Render.Height, 45, 0.1, 100, pmOrtho, pTopLeft); GuiCamera.SetViewParams( Vec3f(0, 0, 100), Vec3f(0, 0, 0), Vec3f(0, 1, 0)); FontMain := TglrFont.Create(FileSystem.ReadResource(R_FONT_MAIN)); FontMainBatch := TglrFontBatch.Create(FontMain); end; class procedure Assets.UnloadBase(); begin GuiMaterial.Free(); GuiAtlas.Free(); GuiSpriteBatch.Free(); GuiCamera.Free(); FontMainBatch.Free(); FontMain.Free(); end; end.
unit UpdateRoutesCustomDataRequestUnit; interface uses REST.Json.Types, GenericParametersUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, JSONDictionaryIntermediateObjectUnit, HttpQueryMemberAttributeUnit; type TUpdateRoutesCustomDataRequest = class(TGenericParameters) private [JSONMarshalled(False)] [Nullable] [HttpQueryMember('route_id')] FRouteId: NullableString; [JSONMarshalled(False)] [Nullable] [HttpQueryMember('route_destination_id')] FRouteDestinationId: NullableInteger; [JSONName('custom_fields')] [NullableObject(TDictionaryStringIntermediateObject)] FCustomFields: NullableObject; function GetCustomFields: TDictionaryStringIntermediateObject; procedure SetCustomFields(const Value: TDictionaryStringIntermediateObject); public constructor Create; override; destructor Destroy; override; property RouteId: NullableString read FRouteId write FRouteId; property RouteDestinationId: NullableInteger read FRouteDestinationId write FRouteDestinationId; property CustomFields: TDictionaryStringIntermediateObject read GetCustomFields write SetCustomFields; procedure AddCustomField(Key: String; Value: String); end; implementation procedure TUpdateRoutesCustomDataRequest.AddCustomField(Key, Value: String); var Dic: TDictionaryStringIntermediateObject; begin if (FCustomFields.IsNull) then FCustomFields := TDictionaryStringIntermediateObject.Create(); Dic := FCustomFields.Value as TDictionaryStringIntermediateObject; Dic.Add(Key, Value); end; constructor TUpdateRoutesCustomDataRequest.Create; begin Inherited; FRouteId := NullableString.Null; FRouteDestinationId := NullableInteger.Null; FCustomFields := NullableObject.Null; end; destructor TUpdateRoutesCustomDataRequest.Destroy; begin FCustomFields.Free; inherited; end; function TUpdateRoutesCustomDataRequest.GetCustomFields: TDictionaryStringIntermediateObject; begin if FCustomFields.IsNull then Result := nil else Result := FCustomFields.Value as TDictionaryStringIntermediateObject; end; procedure TUpdateRoutesCustomDataRequest.SetCustomFields( const Value: TDictionaryStringIntermediateObject); begin FCustomFields := Value; end; end.
unit EmailOrdering.Models.EmailMsg; interface uses System.Generics.Collections, IdMessage, Wddc.Inventory.Order, System.Classes; type TEmailMsg = class(TObject) private FContents: TIdMessage; public function GetTextFromAttachment(Index: integer): TStringList; property Contents: TIdMessage read FContents write FContents; end; implementation uses System.SysUtils, IdAttachment; { TEmailMsg } /// Returns an email attachment as a TStringList. function TEmailMsg.GetTextFromAttachment(Index: integer): TStringList; var LMStream: TMemoryStream; begin LMStream := TMemoryStream.Create; Result := TStringList.Create; try if (self.Contents.MessageParts.Count < Index + 1) then raise Exception.Create('Attachment does not exist'); // load attachment into LStringList. (self.Contents.MessageParts[Index] as TIdAttachment).SaveToStream(LMStream); LMStream.Position := 0; Result.LoadFromStream(LMStream); finally LMStream.Free; end; end; end.
unit GX_MacroTemplateEdit; interface uses Classes, Controls, Forms, StdCtrls, ComCtrls, GX_MacroFile, GX_BaseForm; type TMacroTemplate = record Name: string; Description: string; ShortCut: TShortCut; InsertPos: TTemplateInsertPos; end; TfmMacroTemplateEdit = class(TfmBaseForm) edtName: TEdit; edtDescription: TEdit; lblName: TLabel; lblDescription: TLabel; btnOK: TButton; btnCancel: TButton; lblShortCut: TLabel; lblInsertPos: TLabel; cbxInsertPos: TComboBox; edtShortCut: THotKey; procedure btnOKClick(Sender: TObject); end; function GetMacroTemplate(var VMacroTemplate: TMacroTemplate): Boolean; function EditMacroObject(AMacroObject: TMacroObject): Boolean; implementation uses SysUtils, Dialogs; {$R *.dfm} function GetMacroTemplate(var VMacroTemplate: TMacroTemplate): Boolean; begin Result := False; with TfmMacroTemplateEdit.Create(Application) do try edtName.Text := VMacroTemplate.Name; edtDescription.Text := VMacroTemplate.Description; edtShortCut.HotKey := VMacroTemplate.ShortCut; cbxInsertPos.ItemIndex := Ord(VMacroTemplate.InsertPos); ShowModal; if ModalResult = mrOk then begin Result := True; VMacroTemplate.Name := edtName.Text; VMacroTemplate.Description := edtDescription.Text; VMacroTemplate.ShortCut := edtShortCut.HotKey; VMacroTemplate.InsertPos := TTemplateInsertPos(cbxInsertPos.ItemIndex); end; finally Free; end; end; function EditMacroObject(AMacroObject: TMacroObject): Boolean; begin Result := False; with TfmMacroTemplateEdit.Create(Application) do try edtName.Text := AMacroObject.Name; edtDescription.Text := AMacroObject.Desc; edtShortCut.HotKey := AMacroObject.ShortCut; cbxInsertPos.ItemIndex := Ord(AMacroObject.InsertPos); ShowModal; if ModalResult = mrOk then begin Result := True; AMacroObject.Name := edtName.Text; AMacroObject.Desc := edtDescription.Text; AMacroObject.ShortCut := edtShortCut.HotKey; AMacroObject.InsertPos := TTemplateInsertPos(cbxInsertPos.ItemIndex); end; finally Free; end; end; procedure TfmMacroTemplateEdit.btnOKClick(Sender: TObject); resourcestring NoTemplateName = 'All templates require a name'; InvalidIdentTemplateName = 'Template names must be valid identifiers (no white space or special characters)'; begin if edtDescription.Text = '' then edtDescription.Text := edtName.Text; if (edtName.Text = '') then MessageDlg(NoTemplateName, mtError, [mbOK], 0) else if (not IsValidIdent(edtName.Text)) then MessageDlg(InvalidIdentTemplateName, mtError, [mbOK], 0) else ModalResult := mrOk; end; end.
unit PE_Files; {$H+} {$ALIGN OFF} interface uses Windows; type P_DOS_HEADER = ^T_DOS_HEADER; T_DOS_HEADER = packed record e_magic: Word; e_cblp: Word; e_cp: Word; e_crlc: Word; e_cparhdr: Word; e_minalloc: Word; e_maxalloc: Word; e_ss: Word; e_sp: Word; e_csum: Word; e_ip: Word; e_cs: Word; e_lfarlc: Word; e_ovno: Word; e_res: packed array[0..3] of Word; e_oemid: Word; e_oeminfo: Word; e_res2: packed array[0..9] of Word; e_lfanew: DWORD; end; P_PE_Header = ^T_PE_Header; T_PE_Header = packed record Signature: DWORD; CPU_Type: Word; Number_Of_Object: Word; Time_Date_Stamp: DWORD; Ptr_to_COFF_Table: DWORD; COFF_table_size: DWORD; NT_Header_Size: Word; Flags: Word; Magic: Word; Link_Major: Byte; Link_Minor: Byte; Size_Of_Code: DWORD; Size_Of_Init_Data: DWORD; Size_Of_UnInit_Data: DWORD; Entry_Point_RVA: DWORD; Base_Of_Code: DWORD; Base_Of_Data: DWORD; Image_Base: DWORD; Object_Align: DWORD; File_Align: DWORD; OS_Major: Word; OS_Minor: Word; User_Major: Word; User_Minor: Word; SubSystem_Major: Word; SubSystem_Minor: Word; Reserved_1: DWORD; Image_Size: DWORD; Header_Size: DWORD; File_CheckSum: DWORD; SubSystem: Word; DLL_Flags: Word; Stack_Reserve_Size: DWORD; Stack_Commit_Size: DWORD; Heap_Reserve_Size: DWORD; Heap_Commit_Size: DWORD; Loader_Flags: DWORD; Number_of_RVA_and_Sizes: DWORD; Export_Table_RVA: DWORD; Export_Data_Size: DWORD; Import_Table_RVA: DWORD; Import_Data_Size: DWORD; Resource_Table_RVA: DWORD; Resource_Data_Size: DWORD; Exception_Table_RVA: DWORD; Exception_Data_Size: DWORD; Security_Table_RVA: DWORD; Security_Data_Size: DWORD; Fix_Up_Table_RVA: DWORD; Fix_Up_Data_Size: DWORD; Debug_Table_RVA: DWORD; Debug_Data_Size: DWORD; Image_Description_RVA: DWORD; Desription_Data_Size: DWORD; Machine_Specific_RVA: DWORD; Machine_Data_Size: DWORD; TLS_RVA: DWORD; TLS_Data_Size: DWORD; Load_Config_RVA: DWORD; Load_Config_Data_Size: DWORD; Bound_Import_RVA: DWORD; Bound_Import_Size: DWORD; IAT_RVA: DWORD; IAT_Data_Size: DWORD; Reserved_3: array[1..8] of Byte; Reserved_4: array[1..8] of Byte; Reserved_5: array[1..8] of Byte; end; T_Object_Name = array[0..7] of Char; type P_Object_Entry = ^T_Object_Entry; T_Object_Entry = packed record Object_Name: T_Object_Name; Virtual_Size: DWORD; Section_RVA: DWORD; Physical_Size: DWORD; Physical_Offset: DWORD; Reserved: array[1..$0C] of Byte; Object_Flags: DWORD; end; P_Resource_Directory_Table = ^T_Resource_Directory_Table; T_Resource_Directory_Table = packed record Flags: DWORD; Time_Date_Stamp: DWORD; Major_Version: Word; Minor_Version: Word; Name_Entry: Word; ID_Number_Entry: Word; end; P_Resource_Entry_Item = ^T_Resource_Entry_Item; T_Resource_Entry_Item = packed record Name_RVA_or_Res_ID: DWORD; Data_Entry_or_SubDir_RVA: DWORD; end; P_Resource_Entry = ^T_Resource_Entry; T_Resource_Entry = packed record Data_RVA: DWORD; Size: DWORD; CodePage: DWORD; Reserved: DWORD; end; P_Export_Directory_Table = ^T_Export_Directory_Table; T_Export_Directory_Table = packed record Flags: DWORD; Time_Date_Stamp: DWORD; Major_Version: Word; Minor_Version: Word; Name_RVA: DWORD; Ordinal_Base: DWORD; Number_of_Functions: DWORD; Number_of_Names: DWORD; Address_of_Functions: DWORD; Address_of_Names: DWORD; Address_of_Ordinals: DWORD; end; P_Import_Directory_Entry = ^T_Import_Directory_Entry; T_Import_Directory_Entry = packed record Original_First_Thunk: DWORD; Time_Date_Stamp: DWORD; Forward_Chain: DWORD; Name_RVA: DWORD; First_Thunk: DWORD; end; const E_OK = 0; E_FILE_NOT_FOUND = 1; E_CANT_OPEN_FILE = 2; E_ERROR_READING = 3; E_ERROR_WRITING = 4; E_NOT_ENOUGHT_MEMORY = 5; E_INVALID_PE_FILE = 6; M_ERR_CAPTION = 'PE File Error...'; M_FILE_NOT_FOUND = 'Can''t find file. '; M_CANT_OPEN_FILE = 'Can''t open file. '; M_ERROR_READING = 'Error reading file. '; M_ERROR_WRITING = 'Error writing file. '; M_NOT_ENOUGHT_MEMORY = 'Can''t alloc memory. '; M_INVALID_PE_FILE = 'Invalid PE file. '; Minimum_File_Align = $0200; Minimum_Virtual_Align = $1000; type PE_File = class(TObject) public DOS_HEADER: P_DOS_HEADER; PE_Header: P_PE_Header; LastError: DWORD; ShowDebugMessages: Boolean; pMap: Pointer; PreserveOverlay: Boolean; IsDLL: Boolean; File_Size: DWORD; OverlayData: Pointer; OverlaySize: DWORD; constructor Create; destructor Destroy; override; procedure LoadFromFile(FileName: string); procedure SaveToFile(FileName: string); procedure FlushFileCheckSum; procedure OptimizeHeader(WipeJunk: Boolean); procedure OptimizeFileAlignment; procedure FlushRelocs(ProcessDll: Boolean); procedure OptimizeFile(AlignHeader,WipeJunk,KillRelocs,KillInDll: Boolean); private PObject: P_Object_Entry; Data_Size: DWORD; function IsPEFile(pMap: Pointer): Boolean; procedure DebugMessage(MessageText: string); procedure GrabInfo; function IsAlignedTo(Offs, AlignTo: DWORD): Boolean; function AlignBlock(Start: Pointer; Size: DWORD; AlignTo: DWORD): DWORD; end; implementation constructor PE_File.Create; begin inherited Create; LastError:= E_OK; ShowDebugMessages:= False; DOS_HEADER:= nil; PE_Header:= nil; pMap:= nil; IsDLL:= False; File_Size:= 0; Data_Size:= 0; PreserveOverlay:= False; OverlayData:= nil; OverlaySize:= 0; end; destructor PE_File.Destroy; begin if pMap <> nil then FreeMem(pMap); if OverlayData <> nil then FreeMem(OverlayData); inherited Destroy; end; procedure PE_File.DebugMessage(MessageText: string); begin MessageBox(0, PChar(MessageText), M_ERR_CAPTION, MB_OK or MB_ICONSTOP); end; function PE_File.IsPEFile(pMap: Pointer): Boolean; var DOS_Header: P_DOS_Header; PE_Header: P_PE_Header; begin Result:= False; if pMap = nil then Exit; DOS_Header:= pMap; if DOS_Header.e_magic <> IMAGE_DOS_SIGNATURE then Exit; if (DOS_Header.e_lfanew < $40) or (DOS_Header.e_lfanew > $F08) then Exit; PE_Header:= Pointer(DOS_Header.e_lfanew + DWORD(pMap)); if PE_Header.Signature <> IMAGE_NT_SIGNATURE then Exit; Result:= True; end; procedure PE_File.GrabInfo; var I: Integer; begin IsDLL:= (PE_Header.Flags and IMAGE_FILE_DLL) <> 0; Data_Size:= PE_Header^.Header_Size; if PE_Header.Number_Of_Object > 0 then begin PObject:= Pointer(DWORD(PE_Header) + SizeOf(T_PE_Header)); for I:= 1 to PE_Header.Number_Of_Object do begin if (PObject.Physical_Offset > 0) and (PObject.Physical_Size > 0) then Inc(Data_Size, PObject.Physical_Size); Inc(DWORD(PObject), SizeOf(T_Object_Entry)); end; end; end; procedure PE_File.LoadFromFile(FileName: string); var Header: Pointer; hFile: DWORD; Readed, I: DWORD; FindData: _WIN32_FIND_DATAA; begin if FindFirstFile(PChar(FileName), FindData) = INVALID_HANDLE_VALUE then begin LastError:= E_FILE_NOT_FOUND; if ShowDebugMessages then DebugMessage(M_FILE_NOT_FOUND + FileName); Exit; end; hFile:= CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if hFile = INVALID_HANDLE_VALUE then begin LastError:= E_CANT_OPEN_FILE; if ShowDebugMessages then DebugMessage(M_CANT_OPEN_FILE + FileName); Exit; end; GetMem(Header, $1000); if Header = nil then begin LastError:= E_NOT_ENOUGHT_MEMORY; if ShowDebugMessages then DebugMessage(M_NOT_ENOUGHT_MEMORY); Exit; end; ReadFile(hFile, Header^, $1000, Readed, nil); if (Readed < $200) or (not IsPEFile(Header)) then begin LastError:= E_INVALID_PE_FILE; if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); CloseHandle(hFile); FreeMem(Header); Exit; end; DOS_Header:= Header; PE_Header:= Pointer(DOS_Header.e_lfanew + DWORD(Header)); if pMap <> nil then FreeMem(pMap); if OverlayData <> nil then FreeMem(OverlayData); GetMem(pMap, PE_Header.Image_Size); if pMap = nil then begin LastError:= E_NOT_ENOUGHT_MEMORY; if ShowDebugMessages then DebugMessage(M_NOT_ENOUGHT_MEMORY); CloseHandle(hFile); FreeMem(Header); Exit; end; FillChar(pMap^, PE_Header.Image_Size, 0); Move(Header^, pMap^, PE_Header.Header_Size); FreeMem(Header); DOS_Header:= pMap; PE_Header:= Pointer(DOS_Header.e_lfanew + DWORD(pMap)); PObject:= Pointer(DWORD(PE_Header) + SizeOf(T_PE_Header)); for I:= 1 to PE_Header.Number_Of_Object do begin if PE_Header.Header_Size > PObject.Section_RVA then PE_Header.Header_Size:= PObject.Section_RVA; Inc(DWORD(PObject), SizeOf(T_Object_Entry)); end; GrabInfo; File_Size:= GetFileSize(hFile, nil); if (PreserveOverlay = True) and (File_Size > Data_Size) then begin OverlaySize:= File_Size - Data_Size; GetMem(OverlayData, OverlaySize); if OverlayData = nil then begin LastError:= E_NOT_ENOUGHT_MEMORY; if ShowDebugMessages then DebugMessage(M_NOT_ENOUGHT_MEMORY); CloseHandle(hFile); Exit; end; SetFilePointer(hFile, Data_Size, nil, FILE_BEGIN); ReadFile(hFile, OverlayData^, OverlaySize, Readed, nil); end; if PE_Header.Number_Of_Object = 0 then begin LastError:= E_OK; CloseHandle(hFile); Exit; end; PObject:= Pointer(DWORD(PE_Header) + SizeOf(T_PE_Header)); for I:= 1 to PE_Header.Number_Of_Object do begin if (PObject.Physical_Offset = 0) and (PObject.Physical_Size <> 0) then begin PObject.Virtual_Size:= PObject.Physical_Size; PObject.Physical_Size:= 0; end; if (PObject.Physical_Offset > 0) and (PObject.Physical_Size > 0) then begin SetFilePointer(hFile, PObject.Physical_Offset, nil, FILE_BEGIN); ReadFile(hFile, Pointer(DWORD(pMap) + PObject.Section_RVA)^, PObject.Physical_Size, Readed, nil); if Readed <> PObject.Physical_Size then begin LastError:= E_ERROR_READING; if ShowDebugMessages then DebugMessage(M_ERROR_READING + FileName); CloseHandle(hFile); Exit; end; end; Inc(DWORD(PObject), SizeOf(T_Object_Entry)); end; CloseHandle(hFile); LastError:= E_OK; end; procedure PE_File.SaveToFile(FileName: string); var I: DWORD; hFile: DWORD; Written: DWORD; begin if (pMap = nil) or (not IsPEFile(pMap)) then begin LastError:= E_INVALID_PE_FILE; if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); Exit; end; hFile:= CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if hFile = INVALID_HANDLE_VALUE then begin LastError:= E_CANT_OPEN_FILE; if ShowDebugMessages then DebugMessage(M_CANT_OPEN_FILE + FileName); Exit; end; File_Size:= PE_Header.Header_Size; SetFilePointer(hFile, 0, nil, FILE_BEGIN); if (not WriteFile(hFile, pMap^, PE_Header.Header_Size, Written, nil)) or (Written <> PE_Header.Header_Size) then begin LastError:= E_ERROR_WRITING; if ShowDebugMessages then DebugMessage(M_ERROR_WRITING + FileName); CloseHandle(hFile); Exit; end; if PE_Header.Number_Of_Object > 0 then begin PObject:= Pointer(DWORD(PE_Header) + SizeOf(T_PE_Header)); for I:= 1 to PE_Header.Number_Of_Object do begin if (not WriteFile(hFile, Pointer(DWORD(pMap) + PObject.Section_RVA)^, PObject.Physical_Size, Written, nil)) or (Written <> PObject.Physical_Size) then begin LastError:= E_ERROR_WRITING; if ShowDebugMessages then DebugMessage(M_ERROR_WRITING + FileName); CloseHandle(hFile); Exit; end; Inc(File_Size, PObject.Physical_Size); Inc(DWORD(PObject), SizeOf(T_Object_Entry)); end; end; if (PreserveOverlay = True) and (OverlaySize > 0) then begin Inc(File_Size, OverlaySize); SetFilePointer(hFile, 0, nil, FILE_END); WriteFile(hFile, OverlayData^, OverlaySize, Written, nil); end; CloseHandle(hFile); LastError:= E_OK; end; function PE_File.IsAlignedTo(Offs, AlignTo: DWORD): Boolean; begin Result:= (Offs mod AlignTo) = 0; end; function PE_File.AlignBlock(Start: Pointer; Size: DWORD; AlignTo: DWORD): DWORD; var P: ^Byte; begin Result:= 0; if Size = 0 then Exit; P:= Pointer(DWORD(Start) + Size - 1); while (P^ = 0) and (DWORD(P) > DWORD(Start)) do Dec(DWORD(P)); if (DWORD(P) = DWORD(Start)) and (P^ = 0) then Exit; while (not IsAlignedTo(DWORD(P) - DWORD(Start), AlignTo)) and (DWORD(P) < (DWORD(Start) + Size)) do Inc(DWORD(P)); Result:= DWORD(P) - DWORD(Start); end; procedure PE_File.OptimizeHeader(WipeJunk: Boolean); var AllObjSize: DWORD; NewHdrSize: DWORD; HdrSize, I: DWORD; NewHdrOffs: ^Word; begin if (pMap = nil) or (not IsPEFile(pMap)) then begin LastError:= E_INVALID_PE_FILE; if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); Exit; end; NewHdrOffs:= Pointer(DWORD(pMap) + $40); while ((NewHdrOffs^ <> 0) or (not IsAlignedTo(DWORD(NewHdrOffs) - DWORD(pMap), 16)) and (DWORD(NewHdrOffs) < DWORD(PE_Header)) ) do Inc(DWORD(NewHdrOffs)); AllObjSize:= PE_Header.Number_Of_Object * SizeOf(T_Object_Entry); if (DWORD(NewHdrOffs) - DWORD(pMap)) < DOS_Header^.e_lfanew then begin DOS_Header.e_lfanew:= DWORD(NewHdrOffs) - DWORD(pMap); Move(PE_Header^, NewHdrOffs^, SizeOf(T_PE_Header) + AllObjSize); PE_Header:= Pointer(NewHdrOffs); if WipeJunk = False then FillChar(Pointer(DWORD(NewHdrOffs) + SizeOf(T_PE_Header) + AllObjSize)^, DWORD(PE_Header) - DWORD(NewHdrOffs), 0); end; if WipeJunk = True then begin HdrSize:= DOS_Header.e_lfanew + SizeOf(T_PE_Header) + AllObjSize; FillChar(Pointer(DWORD(pMap) + HdrSize)^, PE_Header.Header_Size-HdrSize, 0); if (PE_Header.Bound_Import_RVA <> 0) or (PE_Header.Bound_Import_Size <> 0) then begin PE_Header.Bound_Import_RVA:= 0; PE_Header.Bound_Import_Size:= 0; end; end; NewHdrSize:= AlignBlock(pMap, PE_Header.Header_Size, Minimum_File_Align); if NewHdrSize < PE_Header.Header_Size then begin if PE_Header.Number_Of_Object > 0 then begin PObject:= Pointer(DWORD(PE_Header) + SizeOf(T_PE_Header)); for I:= 1 to PE_Header.Number_Of_Object do begin Dec(PObject.Physical_Offset, PE_Header.Header_Size - NewHdrSize); Inc(DWORD(PObject), SizeOf(T_Object_Entry)); end; end; PE_Header.Header_Size:= NewHdrSize; end; LastError:= E_OK; end; procedure PE_File.FlushRelocs(ProcessDll: Boolean); begin if (pMap = nil) or (not IsPEFile(pMap)) then begin LastError:= E_INVALID_PE_FILE; if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); Exit; end; LastError:= E_OK; if (not ProcessDll) and IsDLL then Exit; if (PE_Header.Fix_Up_Table_RVA = 0) or (PE_Header.Fix_Up_Data_Size = 0) then Exit; FillChar(Pointer(DWORD(pMap) + PE_Header^.Fix_Up_Table_RVA)^, PE_Header^.Fix_Up_Data_Size, 0); PE_Header^.Fix_Up_Table_RVA:= 0; PE_Header^.Fix_Up_Data_Size:= 0; end; procedure PE_File.OptimizeFileAlignment; var OldSize: DWORD; NewSize: DWORD; LastOffs: DWORD; I: Integer; begin if (pMap = nil) or (not IsPEFile(pMap)) then begin LastError:= E_INVALID_PE_FILE; if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); Exit; end; LastError:= E_OK; PE_Header.File_Align:= Minimum_File_Align; if PE_Header.Number_Of_Object = 0 then Exit; LastOffs:= PE_Header.Header_Size; PObject:= Pointer(DWORD(PE_Header) + SizeOf(T_PE_Header)); for I:= 1 to PE_Header.Number_Of_Object do begin if (PObject.Physical_Size > 0) and (PObject^.Physical_Offset >= LastOffs) then begin OldSize:= PObject.Physical_Size; NewSize:= AlignBlock(Pointer(DWORD(pMap) + PObject.Section_RVA), PObject.Physical_Size, Minimum_File_Align); if NewSize < OldSize then PObject.Physical_Size:= NewSize; end; PObject.Physical_Offset:= LastOffs; Inc(LastOffs, PObject.Physical_Size); Inc(DWORD(PObject), SizeOf(T_Object_Entry)); end; end; procedure PE_File.FlushFileCheckSum; begin PE_Header.File_CheckSum:= 0; end; procedure PE_File.OptimizeFile(AlignHeader: Boolean; WipeJunk: Boolean; KillRelocs: Boolean; KillInDll: Boolean); begin if (pMap = nil) or (not IsPEFile(pMap)) then begin LastError:= E_INVALID_PE_FILE; if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); Exit; end; if AlignHeader then begin OptimizeHeader(WipeJunk); if LastError <> E_OK then begin if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); Exit; end; end; if KillRelocs then begin FlushRelocs(KillInDll); if LastError <> E_OK then begin if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); Exit; end; end; OptimizeFileAlignment; if LastError <> E_OK then begin if ShowDebugMessages then DebugMessage(M_INVALID_PE_FILE); Exit; end; FlushFileCheckSum; end; end.
unit MFichas.View.Relatorio; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Layouts, FMX.ListBox, FMX.StdCtrls, FMX.Controls.Presentation, FMX.TabControl, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Platform, FMX.VirtualKeyBoard, MultiDetailAppearanceU, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, MFichas.Model.Impressao.Interfaces, MFichas.Model.Impressao, MFichas.Controller.Types; type TRelatorioView = class(TForm) LayoutPrincipal: TLayout; TabControlPrincipal: TTabControl; TabItemListarRelatorio: TTabItem; RectangleListar: TRectangle; ToolBarListar: TToolBar; LabelToolBarListar: TLabel; ButtonBackListar: TButton; LayoutRelatorioBottom: TLayout; RoundRectSalvarAlteracoes: TRoundRect; LabelBotaoSalvarAlteracoes: TLabel; ListView1: TListView; procedure FormCreate(Sender: TObject); procedure RoundRectSalvarAlteracoesClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure ButtonBackListarClick(Sender: TObject); private { Private declarations } FConexao : iModelConexaoSQL; FImpressao: iModelImpressao; FListItem: TListViewItem; function StatusCaixa: String; function DataFechamento: String; procedure BuscarCaixas; procedure VoltarAbas; procedure FecharForm; public { Public declarations } end; var RelatorioView: TRelatorioView; implementation {$R *.fmx} procedure TRelatorioView.BuscarCaixas; const _SELECT = ' SELECT * FROM CAIXA '; _WHERE = ' ORDER BY DATAABERTURA DESC '; var LCountRecords: Integer; I: Integer; begin FConexao.Query.Active := False; FConexao.Query.SQL.Text := ''; FConexao.Query.SQL.Text := _SELECT + _WHERE; FConexao.Query.Active := True; FConexao.Query.Last; LCountRecords := FConexao.Query.RecordCount; I := 0; if LCountRecords > 0 then begin FConexao.Query.First; while not FConexao.Query.Eof do begin FListItem := ListView1.Items.Add; FListItem.Text := 'CAIXA ' + (LCountRecords - I).ToString; FListItem.Detail := FConexao.Query.FieldByName('GUUID').AsString; FListItem.Data[TMultiDetailAppearanceNames.Detail1] := StatusCaixa; FListItem.Data[TMultiDetailAppearanceNames.Detail2] := 'Abertura: ' + FormatDateTime('dd/mm/yyyy hh:nn:ss', FConexao.Query.FieldByName('DATAABERTURA').AsDateTime); FListItem.Data[TMultiDetailAppearanceNames.Detail3] := DataFechamento; Inc(I); FConexao.Query.Next; end; end; end; procedure TRelatorioView.ButtonBackListarClick(Sender: TObject); begin VoltarAbas; end; function TRelatorioView.DataFechamento: String; var LDate: TDate; begin LDate := FConexao.Query.FieldByName('DATAFECHAMENTO').AsDateTime; if FormatDateTime('dd/mm/yyyy', LDate) = '30/12/1899' then Result := 'Fechamento:' else Result := 'Fechamento: ' + FormatDateTime('dd/mm/yyyy hh:nn:ss', FConexao.Query.FieldByName('DATAFECHAMENTO').AsDateTime); end; procedure TRelatorioView.FecharForm; begin RelatorioView.Close; {$IFDEF ANDROID OR IOS} if Assigned(RelatorioView) then begin RelatorioView.DisposeOf; RelatorioView.Free; end; {$ENDIF} end; procedure TRelatorioView.FormCreate(Sender: TObject); begin FConexao := TModelConexaoFactory.New.ConexaoSQL; FImpressao := TModelImpressao.New; TabControlPrincipal.TabPosition := TTabPosition.None; TabControlPrincipal.ActiveTab := TabItemListarRelatorio; BuscarCaixas; end; procedure TRelatorioView.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var LTeclado: IFMXVirtualKeyboardService; begin if (Key = vkHardwareBack) then begin TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(LTeclado)); if (LTeclado <> nil) and (TVirtualKeyboardState.Visible in LTeclado.VirtualKeyboardState) then begin end else begin Key := 0; VoltarAbas; end; end; end; procedure TRelatorioView.RoundRectSalvarAlteracoesClick(Sender: TObject); begin FImpressao .Caixa .Fechamento .TituloDaImpressao('RELATORIO GERENCIAL') .CodigoDoCaixa(ListView1.Items.AppearanceItem[ListView1.ItemIndex].Detail) .ExecutarImpressao .&End .&End; end; function TRelatorioView.StatusCaixa: String; begin case FConexao.Query.FieldByName('STATUS').AsInteger of 0: Result := 'Status: Fechado'; 1: Result := 'Status: Aberto'; end; end; procedure TRelatorioView.VoltarAbas; begin FecharForm; end; end.
unit iaStressTest.TThreadedQueue.PopItem; interface uses System.Classes, System.Generics.Collections, System.SyncObjs; const POP_TIMEOUT = 10; //the lower the timeout, the more pronounced the problem MAX_TEST_RUNTIME_SECONDS = 600; ACCEPTABLE_TIMEOUTVARIANCE_MS = 60; {$IFDEF MSWINDOWS} RESERVED_STACK_SIZE = 65536; {$IFDEF WIN32} MAX_WORKER_THREADS = 6000; {$ELSE} //WIN64 MAX_WORKER_THREADS = 30000; {$ENDIF} {$ENDIF} type TItem = class (TObject); TThreadCreator = Class(TThread) public procedure Execute(); override; end; TTestThread = class (TThread) private FQueue: TThreadedQueue<TItem>; public procedure AfterConstruction(); override; procedure BeforeDestruction(); override; procedure Execute(); override; end; function StressTestPopItem():Boolean; var pubTestCompletionCheck:TEvent; implementation uses System.SysUtils, System.DateUtils, System.Diagnostics, System.RTTI, System.TimeSpan, iaTestSupport.Log; function StressTestPopItem():Boolean; var vMaxTestRuntime:TTimeSpan; vTestCompletion:TWaitResult; vStartedTest:TDateTime; begin vMaxTestRuntime.Create(0, 0, MAX_TEST_RUNTIME_SECONDS); LogIt('StressTestPopItem Start: Waiting up to [' + IntToStr(MAX_TEST_RUNTIME_SECONDS) + '] seconds for PopItem to prematurely timeout.'); LogIt('Note: Using [' + IntToStr(POP_TIMEOUT) + '] as PopTimeout on TThreadedQueue creation'); vStartedTest := Now; //create a bunch of threads, all continuously calling PopItem on an empty TThreadQueue TThreadCreator.Create(False); //wait until a PopItem fails or test times-out vTestCompletion := pubTestCompletionCheck.WaitFor(vMaxTestRuntime); Result := (vTestCompletion = TWaitResult.wrTimeout); if Result then begin pubTestCompletionCheck.SetEvent(); //tell threads to terminate LogIt('StressTestPopItem End: Overall maximum time limit reached for this test without an error detected...we will call this a success!'); end else begin LogIt('StressTestPopItem End: After [' + IntToStr(SecondsBetween(Now, vStartedTest)) + '] seconds, a failure of PopItem was detected in at least one thread'); end; end; procedure TThreadCreator.Execute(); var vThreadsCreated:Integer; begin Sleep(1000);//More than enough time to ensure the main thread completely settles-in on WaitFor() LogIt('TThreadCreator Start: Creating up to [' + IntToStr(MAX_WORKER_THREADS) + '] threads'); {$IFDEF MSWINDOWS} LogIt('Note: Creating threads with a StackSize of [' + IntToStr(RESERVED_STACK_SIZE) + ']'); {$ENDIF} vThreadsCreated := 0; while vThreadsCreated < MAX_WORKER_THREADS do begin if pubTestCompletionCheck.WaitFor(0) = wrSignaled then begin LogIt('TThreadCreator Note: aborting thread creation at [' + IntToStr(vThreadsCreated) + '] threads as a failure has already been detected.'); Break; end; try TTestThread.Create(False {$IFDEF MSWINDOWS}, RESERVED_STACK_SIZE{$ENDIF}); Inc(vThreadsCreated); except on E: Exception do begin LogIt('TThreadCreator Note: created the maximum number of threads before experiencing system error [' + IntToStr(GetLastError) + ']'); Break; end; end; end; LogIt('TThreadCreator End: [' + IntToStr(vThreadsCreated) + '] worker threads created'); end; procedure TTestThread.AfterConstruction(); begin FQueue := TThreadedQueue<TItem>.Create(10, 10, POP_TIMEOUT); FreeOnTerminate := True; inherited; end; procedure TTestThread.BeforeDestruction(); begin FQueue.DoShutDown(); FQueue.Free; inherited; end; procedure TTestThread.Execute(); var Item: TItem; vWaitResult:TWaitResult; vStopwatch:TStopwatch; begin while not Terminated do begin vStopwatch := TStopwatch.StartNew; vWaitResult := FQueue.PopItem( Item ); vStopWatch.Stop(); if fQueue.ShutDown then Break; if pubTestCompletionCheck.WaitFor(0) = wrSignaled then Break; //Note: Reason for ACCEPTABLE_VARIANCE_MS is that on some low timeout values (like 200ms) it occasionally times out a little early (like 180ms) if (vWaitResult = wrTimeout) and (vStopWatch.ElapsedMilliseconds > 0) and (vStopWatch.ElapsedMilliseconds >= POP_TIMEOUT-ACCEPTABLE_TIMEOUTVARIANCE_MS) then begin //successful PopItem operation as we aren't adding anything into our queue Continue; end else begin LogIt('TTestThread ERROR: TThreadedQueue.PopItem returned [' + TRttiEnumerationType.GetName(vWaitResult) + '] unexpectedly after [' + IntToStr(vStopWatch.ElapsedMilliseconds) + 'ms]'); pubTestCompletionCheck.SetEvent(); Break; end; end; end; //error trapping System.MonitorSupport.NewWaitObject added by Kiriakos Vlahos //this reveals the underlying failure of this stress test: //GetLastError of 87 when creating a new event. (ERROR_INVALID_PARAMETER) //Very likely due to # of array items being passed to WaitForMultipleXXX being greater than MAXIMUM_WAIT_OBJECTS (64) var OldNewWaitObj : function: Pointer; function NewWaitObject: Pointer; inline; begin try SetLastError(0); //not all API calls reset LastError Result := OldNewWaitObj(); CheckOSError(GetLastError); except on E: Exception do begin Logit(E.Message); end; end; end; initialization pubTestCompletionCheck := TEvent.Create(); OldNewWaitObj := System.MonitorSupport.NewWaitObject; System.MonitorSupport.NewWaitObject := NewWaitObject; finalization pubTestCompletionCheck.Free(); end.
unit nevMeasureView; {* Область вывода для измерений. } // Модуль: "w:\common\components\gui\Garant\Everest\new\nevMeasureView.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnevMeasureView" MUID: (481201700007) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , nevVirtualView , nevTools , afwInterfaces , nevBase ; type TnevMeasureView = class(TnevVirtualView, InevMeasureView) {* Область вывода для измерений. } private f_CaretPoint: InevBasePoint; f_Caret: IafwScrollCaret; protected function IsCaretInited: Boolean; function IsCaretVisible: Boolean; procedure CheckShapes; procedure MakePointVisible(const aTop: InevAnchor; const aPoint: InevBasePoint; var thePos: Integer); {* Делает так, чтобы курсор был видим на заданном экране } procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DoSignalScroll(aTopDiff: Integer; aDeltaY: Integer); override; function GetCanvas(const anExtent: TnevPoint): InevCanvas; override; function CaretCursor: InevBasePoint; override; procedure LinkControl(const aControl: InevControl); override; procedure DoUnlinkControl(const aControl: InevControl); override; public constructor Create(const aControl: InevControl); reintroduce; class function Make(const aControl: InevControl): InevMeasureView; reintroduce; end;//TnevMeasureView implementation uses l3ImplUses , afwMeasureCanvas , SysUtils , nevFacade , afwVirtualCaret , l3MinMax , l3Units //#UC START# *481201700007impl_uses* //#UC END# *481201700007impl_uses* ; constructor TnevMeasureView.Create(const aControl: InevControl); //#UC START# *4CB5C07B03E3_481201700007_var* //#UC END# *4CB5C07B03E3_481201700007_var* begin //#UC START# *4CB5C07B03E3_481201700007_impl* inherited Create; LinkControl(aControl); //#UC END# *4CB5C07B03E3_481201700007_impl* end;//TnevMeasureView.Create class function TnevMeasureView.Make(const aControl: InevControl): InevMeasureView; var l_Inst : TnevMeasureView; begin l_Inst := Create(aControl); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnevMeasureView.Make function TnevMeasureView.IsCaretInited: Boolean; //#UC START# *481203AD0062_481201700007_var* //#UC END# *481203AD0062_481201700007_var* begin //#UC START# *481203AD0062_481201700007_impl* if (f_Caret = nil) then Result := false else begin CheckShapes; Result := f_Caret.IsInited; end;//f_Caret = nil //#UC END# *481203AD0062_481201700007_impl* end;//TnevMeasureView.IsCaretInited function TnevMeasureView.IsCaretVisible: Boolean; //#UC START# *481203CD0044_481201700007_var* //#UC END# *481203CD0044_481201700007_var* begin //#UC START# *481203CD0044_481201700007_impl* if (f_Caret = nil) then Result := true else begin CheckShapes; if not f_Caret.IsInited then // http://mdp.garant.ru/pages/viewpage.action?pageId=268339552 Result := false else Result := f_Caret.IsOnScreen; end;//f_Caret = nil //#UC END# *481203CD0044_481201700007_impl* end;//TnevMeasureView.IsCaretVisible procedure TnevMeasureView.CheckShapes; //#UC START# *481203E001FE_481201700007_var* var l_Ex : InevMap; //#UC END# *481203E001FE_481201700007_var* begin //#UC START# *481203E001FE_481201700007_impl* if (ShapesPainted = nil) OR ShapesPainted.Empty then begin f_Caret.Reset; Draw(nil, l_Ex); end;//ShapesPainted = nil //#UC END# *481203E001FE_481201700007_impl* end;//TnevMeasureView.CheckShapes procedure TnevMeasureView.MakePointVisible(const aTop: InevAnchor; const aPoint: InevBasePoint; var thePos: Integer); {* Делает так, чтобы курсор был видим на заданном экране } //#UC START# *47C7D0950051_481201700007_var* const l_D = 1; var l_Page : Integer; l_Line : Integer; l_Index : Integer; l_View : IafwScrollListener; l_WasInited : Boolean; l_LoopCount: Integer; //#UC END# *47C7D0950051_481201700007_var* begin //#UC START# *47C7D0950051_481201700007_impl* Top := aTop; try f_CaretPoint := aPoint; try l_View := aTop.LinkListener(Self); try l_WasInited := false; for l_Index := 0 to 30 do begin l_Line := l_D; CheckShapes; // CheckShapes - это здесь обязательно надо! иначе карта форматирования ПУСТАЯ. // Последующий вызов IncLine может неправильно отработать - если на // экран влезает ТОЛЬКО один параграф, который в данном View еще не // сформатирован. В результате - прыгаем на следующий большой параграф // и выходим из for по-условию if not IsCaretInited // а код: // <code> // aTop.M.AssignPoint(aPoint); // l_Line := -l_Page; // aTop.IncLine(Self, l_Line, true); // <code> // - переставляет обратно. И начинаются бесконечные "качели". // Например при контекстном поиске. CQ 27042. Inc(thePos, aTop.IncLine(Self, l_Line, true)); if not IsCaretInited then begin if l_WasInited then // - проверяем, что каретка была уже показана, но убежала за верх экрана - http://mdp.garant.ru/pages/viewpage.action?pageId=121143369 begin l_Line := -1; Inc(thePos, aTop.IncLine(Self, l_Line, true)); Exit; end;//l_WasInited break; end//not IsCaretInited else l_WasInited := true; if IsCaretVisible then Exit; if (l_Line = l_D) then break; end;//for l_Index thePos := -1; l_Page := ShapesPainted.SubShapesCount; if (l_Page <= 0) then l_Page := (ViewExtent.Y div nev.LineScrollDelta.Y); while (l_Page > 0) do begin aTop.AssignPoint(Self, aPoint); l_Line := -l_Page; aTop.IncLine(Self, l_Line, true); if (l_Line = -l_Page) then break; if IsCaretInited then break; l_Page := l_Page - Max(1, (l_Page div 4)); end;//while (l_Page > 0) if not IsCaretInited then // Если каретку так и не прорисовывали - ставим ее вверх экрана aTop.AssignPoint(Self, aPoint) // Revision 1.18.2.4.2.4 2006/11/13 11:58:09 oman // - fix: Если не удалось сойтись к каретке - показываем ее верху // экрана - иначе срабатывал Assert (cq23605) // else begin l_LoopCount := 0; // Пытаемся спозиционироваться while not IsCaretVisible do begin l_Line := l_D; aTop.IncLine(Self, l_Line, true); if (l_Line = l_D) then break; Inc(l_LoopCount); if l_LoopCount >= 100 then // http://mdp.garant.ru/pages/viewpage.action?pageId=271190964 begin aTop.AssignPoint(Self, aPoint); // здесь бы еще надо промотать вниз чуть меньше чем на экран, // чтоб найденное слово оказалось внизу Exit; end; end;//while not IsCaretVisible end; finally aTop.LinkListener(l_View); end;//try..finally finally f_CaretPoint := nil; end;//try..finally finally Top := nil; UnlinkControl(pm_GetControl); end;//try..finally //#UC END# *47C7D0950051_481201700007_impl* end;//TnevMeasureView.MakePointVisible procedure TnevMeasureView.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_481201700007_var* //#UC END# *479731C50290_481201700007_var* begin //#UC START# *479731C50290_481201700007_impl* f_CaretPoint := nil; f_Caret := nil; inherited; //#UC END# *479731C50290_481201700007_impl* end;//TnevMeasureView.Cleanup procedure TnevMeasureView.DoSignalScroll(aTopDiff: Integer; aDeltaY: Integer); //#UC START# *4811EAEB030F_481201700007_var* //#UC END# *4811EAEB030F_481201700007_var* begin //#UC START# *4811EAEB030F_481201700007_impl* inherited; if (aDeltaY <> 0) AND (f_Caret <> nil) then f_Caret.Scroll(pm_GetInfoCanvas.LP2DP(l3PointY(aDeltaY))) //#UC END# *4811EAEB030F_481201700007_impl* end;//TnevMeasureView.DoSignalScroll function TnevMeasureView.GetCanvas(const anExtent: TnevPoint): InevCanvas; //#UC START# *4811F0AC0140_481201700007_var* //#UC END# *4811F0AC0140_481201700007_var* begin //#UC START# *4811F0AC0140_481201700007_impl* Result := TafwMeasureCanvas.Make(anExtent, f_Caret); //#UC END# *4811F0AC0140_481201700007_impl* end;//TnevMeasureView.GetCanvas function TnevMeasureView.CaretCursor: InevBasePoint; //#UC START# *4811F158015E_481201700007_var* //#UC END# *4811F158015E_481201700007_var* begin //#UC START# *4811F158015E_481201700007_impl* Result := f_CaretPoint; //#UC END# *4811F158015E_481201700007_impl* end;//TnevMeasureView.CaretCursor procedure TnevMeasureView.LinkControl(const aControl: InevControl); //#UC START# *4811F4A502F6_481201700007_var* //#UC END# *4811F4A502F6_481201700007_var* begin //#UC START# *4811F4A502F6_481201700007_impl* inherited; if (aControl = nil) then f_Caret := nil else f_Caret := TafwVirtualCaret.Make(aControl.WindowExtent); //#UC END# *4811F4A502F6_481201700007_impl* end;//TnevMeasureView.LinkControl procedure TnevMeasureView.DoUnlinkControl(const aControl: InevControl); //#UC START# *4811F4B801DC_481201700007_var* //#UC END# *4811F4B801DC_481201700007_var* begin //#UC START# *4811F4B801DC_481201700007_impl* inherited; f_Caret := nil; //#UC END# *4811F4B801DC_481201700007_impl* end;//TnevMeasureView.DoUnlinkControl end.
unit Notifications; interface const NullId = 0; type TEventClass = byte; IHook = interface procedure Handle( EventClass : TEventClass; var Info ); end; procedure InitNotificationEngine; procedure DoneNotificationEngine; procedure RegisterEventClass( EventClass : TEventClass; Parent : TEventClass ); procedure AddNotifier( EventClass : TEventClass; Hook : IHook ); procedure DeleteNotifier( EventClass : TEventClass; Hook : IHook ); procedure DispatchEvent( EventClass : TEventClass; var Info ); implementation uses Windows, InterfaceCollection; type TEventId = byte; type TEventClassInfo = class public constructor Create( aParent : TEventId ); destructor Destroy; override; private fParent : TEventId; fNotifiers : TInterfaceCollection; public property Parent : TEventId read fParent; property Notifiers : TInterfaceCollection read fNotifiers; end; // TEventClassInfo constructor TEventClassInfo.Create( aParent : TEventId ); begin inherited Create; fParent := aParent; fNotifiers := TInterfaceCollection.Create; end; destructor TEventClassInfo.Destroy; begin fNotifiers.Free; inherited; end; var EventClasses : array[TEventId] of TEventClassInfo; procedure InitNotificationEngine; begin ZeroMemory( @EventClasses, sizeof(EventClasses) ); end; procedure DoneNotificationEngine; var i : byte; begin for i := 0 to high(TEventId) do if EventClasses[i] <> nil then EventClasses[i].Free; end; procedure RegisterEventClass( EventClass : TEventClass; Parent : TEventClass ); var EventId : TEventId; begin EventId := TEventId(EventClass); EventClasses[EventId] := TEventClassInfo.Create( Parent ); end; procedure AddNotifier( EventClass : TEventClass; Hook : IHook ); var EventClassInfo : TEventClassInfo; begin EventClassInfo := EventClasses[EventClass]; if EventClassInfo <> nil then EventClassInfo.Notifiers.Insert( Hook ); end; procedure DeleteNotifier( EventClass : TEventClass; Hook : IHook ); var EventClassInfo : TEventClassInfo; begin EventClassInfo := EventClasses[EventClass]; if EventClassInfo <> nil then EventClassInfo.Notifiers.Delete( Hook ); end; procedure DispatchEvent( EventClass : TEventClass; var Info ); var EventClassInfo : TEventClassInfo; i : integer; begin EventClassInfo := EventClasses[EventClass]; if EventClassInfo <> nil then begin for i := 0 to pred(EventClassInfo.Notifiers.Count) do IHook(EventClassInfo.Notifiers[i]).Handle( EventClass, Info ); if EventClassInfo.Parent <> NullId then DispatchEvent( EventClassInfo.Parent, Info ); end; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} (* Version History 03/16/2002 ElDBLabel made unicode *) unit ElDBLbl; interface uses DB, DBCtrls, ElDBConst, ElHTMLLbl, ElStrUtils, Forms, Windows, Controls, StdCtrls, Messages, Classes, SysUtils; type TElDBLabel = class(TElHTMLLabel) private FDataLink: TFieldDataLink; procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK; procedure DataChange(Sender: TObject); function GetDataField: string; function GetDataSource: TDataSource; function GetField: TField; procedure SetDataField(const Value: string); procedure SetDataSource(Value: TDataSource); protected FUnicodeMode: TElDBUnicodeMode; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetFieldText: TElFString; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {$ifdef VCL_4_USED} function ExecuteAction(Action: TBasicAction): Boolean; override; function UpdateAction(Action: TBasicAction): Boolean; override; function UseRightToLeftAlignment: Boolean; override; {$endif} property Field: TField read GetField; published property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property UnicodeMode: TElDBUnicodeMode read FUnicodeMode write FUnicodeMode default umFieldType; end; implementation constructor TElDBLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; end; destructor TElDBLabel.Destroy; begin FDataLink.Free; FDataLink := nil; inherited Destroy; end; procedure TElDBLabel.CMGetDataLink(var Message: TMessage); begin Message.Result := Integer(FDataLink); end; procedure TElDBLabel.DataChange(Sender: TObject); begin Caption := GetFieldText; end; {$ifdef VCL_4_USED} function TElDBLabel.ExecuteAction(Action: TBasicAction): Boolean; begin Result := inherited ExecuteAction(Action) or (FDataLink <> nil) and FDataLink.ExecuteAction(Action); end; {$endif} function TElDBLabel.GetDataField: string; begin Result := FDataLink.FieldName; end; function TElDBLabel.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; function TElDBLabel.GetField: TField; begin Result := FDataLink.Field; end; procedure TElDBLabel.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; procedure TElDBLabel.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; procedure TElDBLabel.SetDataSource(Value: TDataSource); begin {$ifdef VCL_5_USED} if FDataLink.DataSource <> nil then if not (csDestroying in FDatALink.DataSource.ComponentState) then FDataLink.DataSource.RemoveFreeNotification(Self); {$endif} if not (FDataLink.DataSourceFixed and (csLoading in ComponentState)) then FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; {$ifdef VCL_4_USED} function TElDBLabel.UpdateAction(Action: TBasicAction): Boolean; begin Result := inherited UpdateAction(Action) or (FDataLink <> nil) and FDataLink.UpdateAction(Action); end; function TElDBLabel.UseRightToLeftAlignment: Boolean; begin Result := DBUseRightToLeftAlignment(Self, Field); end; {$endif} function TElDBLabel.GetFieldText: TElFString; {$ifdef ELPACK_UNICODE} var W : WideString; {$endif} begin if not FDataLink.Active then begin if csDesigning in ComponentState then Result := Name else Result := '' end else if FDataLink.Field <> nil then {$ifdef ELPACK_UNICODE} if FDataLink.Field.isNull then W := '' else if (UnicodeMode = umForceUTF8) and (ConvertUTF8toUTF16(FDataLink.Field.DisplayText, W, strictConversion, false) <> sourceIllegal) then else begin if (FDataLink.Field.DataType = ftWideString) then W := FDataLink.Field.Value else W := FDataLink.Field.DisplayText; end; Result := W; {$else} Result := FDataLink.Field.DisplayText; {$endif} end; end.
unit UseBranchStatementParsingTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FpcUnit, TestRegistry, ParserBaseTestCase, WpcScriptCommons, WpcStatements, WpcScriptParser, WpcExceptions; type { TUseBranchStatementParsingTest } TUseBranchStatementParsingTest = class(TParserBaseTestCase) public const USE_BRANCH = USE_KEYWORD + ' ' + BRANCH_KEYWORD + ' '; ADDITIONAL_BRANCH_NAME = 'SomeBranch'; protected UseBranchStatement : TWpcUseBranchStatement; published procedure ShouldParseBaseUseBranchStatement(); procedure ShouldParseUsehBranchStatementWithProbabilityProperty(); procedure ShouldParseUseBranchStatementWithTimesProperty(); procedure ShouldParseUseBranchStatementWithAllProperties(); procedure SholudRaiseScriptParseExceptionWhenStatementKeywordsUncompleted(); procedure SholudRaiseScriptParseExceptionWhenNoBranchSpecified(); procedure SholudRaiseScriptParseExceptionWhenReferencedBranchDoesntExist(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties(); end; implementation { TUseBranchStatementParsingTest } // USE BRANCH SomeBranch procedure TUseBranchStatementParsingTest.ShouldParseBaseUseBranchStatement(); begin ScriptLines.Add(USE_BRANCH + ADDITIONAL_BRANCH_NAME); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_USE_BRANCH_STATEMENT_ID = MainBranchStatements[0].GetId()); UseBranchStatement := TWpcUseBranchStatement(MainBranchStatements[0]); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, ADDITIONAL_BRANCH_NAME, UseBranchStatement.GetBranchName()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_PROBABILITY, UseBranchStatement.GetProbability()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_TIMES, UseBranchStatement.GetTimes()); end; // USE BRANCH SomeBranch WITH PROBABILY 50 procedure TUseBranchStatementParsingTest.ShouldParseUsehBranchStatementWithProbabilityProperty(); begin ScriptLines.Add(USE_BRANCH + ADDITIONAL_BRANCH_NAME + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_USE_BRANCH_STATEMENT_ID = MainBranchStatements[0].GetId()); UseBranchStatement := TWpcUseBranchStatement(MainBranchStatements[0]); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, ADDITIONAL_BRANCH_NAME, UseBranchStatement.GetBranchName()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, UseBranchStatement.GetProbability()); end; // USE BRANCH SomeBranch 4 TIMES procedure TUseBranchStatementParsingTest.ShouldParseUseBranchStatementWithTimesProperty(); begin ScriptLines.Add(USE_BRANCH + ADDITIONAL_BRANCH_NAME + X_TIMES_PROPERTY); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_USE_BRANCH_STATEMENT_ID = MainBranchStatements[0].GetId()); UseBranchStatement := TWpcUseBranchStatement(MainBranchStatements[0]); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, ADDITIONAL_BRANCH_NAME, UseBranchStatement.GetBranchName()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_TIMES_VALUE, UseBranchStatement.GetTimes()); end; // USE BRANCH SomeBranch 4 TIMES WITH PROBABILY 50 procedure TUseBranchStatementParsingTest.ShouldParseUseBranchStatementWithAllProperties(); begin ScriptLines.Add(USE_BRANCH + ADDITIONAL_BRANCH_NAME + X_TIMES_PROPERTY + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_USE_BRANCH_STATEMENT_ID = MainBranchStatements[0].GetId()); UseBranchStatement := TWpcUseBranchStatement(MainBranchStatements[0]); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, ADDITIONAL_BRANCH_NAME, UseBranchStatement.GetBranchName()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, UseBranchStatement.GetProbability()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_TIMES_VALUE, UseBranchStatement.GetTimes()); end; // USE SomeBranch procedure TUseBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenStatementKeywordsUncompleted(); begin ScriptLines.Add(USE_KEYWORD + ' ' + ADDITIONAL_BRANCH_NAME); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 1); end; // USE BRANCH procedure TUseBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenNoBranchSpecified(); begin ScriptLines.Add(USE_BRANCH); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 2); end; // USE BRANCH SomeNonexistentBranch procedure TUseBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenReferencedBranchDoesntExist(); begin ScriptLines.Add(USE_BRANCH + ' SomeNonexistentBranch '); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(); end; // USE BRANCH SomeBranch ONCE procedure TUseBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase(); begin ScriptLines.Add(USE_BRANCH + ADDITIONAL_BRANCH_NAME + ' ONCE '); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 3); end; // USE BRANCH SomeBranch ONCE WITH PROBABILITY 50 procedure TUseBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties(); begin ScriptLines.Add(USE_BRANCH + ADDITIONAL_BRANCH_NAME + ' ONCE ' + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 3); end; // USE BRANCH SomeBranch 4 TIMES ALWAYS procedure TUseBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties(); begin ScriptLines.Add(USE_BRANCH + ADDITIONAL_BRANCH_NAME + X_TIMES_PROPERTY + ' ALWAYS '); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 5); end; initialization RegisterTest(PARSER_TEST_SUITE_NAME, TUseBranchStatementParsingTest); end.
unit UnitDocAbstrato; interface type TDocumentoAbstrato = class private FNumero: String; FDV: String; FDV_Calc: String; FTamanho: Integer; FTamanhoDV: Integer; function EstaEmBranco: Boolean; function EstaFaltandoDigitos: Boolean; function EstaSobrandoDigitos: Boolean; function GetDigitoVerificadorEhValido: Boolean; protected procedure SetTamanho(const Value: Integer); procedure SetTamanhoDV(const Value: Integer); procedure SetDV(const Value: String); procedure SetDV_Calc(const Value: String); procedure DoParseDV; function PodeCalcularDigitoVerificador: Boolean; function CalcularModulo11(const Value: Integer): Integer; public procedure SetNumero(const Value: String); virtual; function GetNumero: String; procedure CalcularDigitoVerificador; virtual; abstract; function DigitoVerificadorEhValido: Boolean; end; implementation uses SysUtils; { TDocumentoAbstrato } function TDocumentoAbstrato.CalcularModulo11(const Value: Integer): Integer; var Resto, Valor: Byte; begin Valor := 0; Resto := Value mod 11; if (Resto = 0) or (Resto = 1) then Valor := 0 else Valor := 11 - Resto; Result := Valor; end; function TDocumentoAbstrato.DigitoVerificadorEhValido: Boolean; begin Result := GetDigitoVerificadorEhValido; end; procedure TDocumentoAbstrato.DoParseDV; begin FDV := EmptyStr; if FTamanhoDV >= 4 then FDV := FDV + copy(FNumero, FTamanho - 3, 1); if FTamanhoDV >= 3 then FDV := FDV + copy(FNumero, FTamanho - 2, 1); if FTamanhoDV >= 2 then FDV := FDV + copy(FNumero, FTamanho - 1, 1); if FTamanhoDV >= 1 then FDV := FDV + copy(FNumero, FTamanho, 1); end; function TDocumentoAbstrato.EstaEmBranco: Boolean; begin Result := (FNumero = EmptyStr); end; function TDocumentoAbstrato.EstaFaltandoDigitos: Boolean; begin Result := Length(FNumero) < FTamanho; end; function TDocumentoAbstrato.EstaSobrandoDigitos: Boolean; begin Result := Length(FNumero) > FTamanho; end; function TDocumentoAbstrato.GetDigitoVerificadorEhValido: Boolean; begin if PodeCalcularDigitoVerificador then Result := (FDV = FDV_Calc) else Result := False; end; function TDocumentoAbstrato.GetNumero: String; begin Result := FNumero; end; function TDocumentoAbstrato.PodeCalcularDigitoVerificador: Boolean; begin if EstaEmBranco or EstaFaltandoDigitos or EstaSobrandoDigitos then Result := False else Result := True; end; procedure TDocumentoAbstrato.SetDV(const Value: String); begin FDV := Value; end; procedure TDocumentoAbstrato.SetDV_Calc(const Value: String); begin FDV_Calc := Value; end; procedure TDocumentoAbstrato.SetNumero(const Value: String); begin FNumero := Value; end; procedure TDocumentoAbstrato.SetTamanho(const Value: Integer); begin FTamanho := Value; end; procedure TDocumentoAbstrato.SetTamanhoDV(const Value: Integer); begin FTamanhoDV := Value; end; end.
{******************************************************************************} { } { Library: Fundamentals TLS } { File name: flcTLSKeys.pas } { File version: 5.02 } { Description: TLS Keys } { } { Copyright: Copyright (c) 2008-2020, David J Butler } { All rights reserved. } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { 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: } { } { 2008/01/18 0.01 Initial development. } { 2020/05/09 5.02 Create flcTLSKeys unit from flcTLSUtils unit. } { } {******************************************************************************} {$INCLUDE flcTLS.inc} unit flcTLSKeys; interface uses { Utils } flcStdTypes, { TLS } flcTLSProtocolVersion; { } { Key block } { } function tls10KeyBlock(const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; function tls12SHA256KeyBlock(const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; function tls12SHA512KeyBlock(const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; function TLSKeyBlock(const ProtocolVersion: TTLSProtocolVersion; const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; { } { Master secret } { } function tls10MasterSecret(const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; function tls12SHA256MasterSecret(const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; function tls12SHA512MasterSecret(const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; function TLSMasterSecret(const ProtocolVersion: TTLSProtocolVersion; const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; { } { TLS Keys } { } type TTLSKeys = record KeyBlock : RawByteString; ClientMACKey : RawByteString; ServerMACKey : RawByteString; ClientEncKey : RawByteString; ServerEncKey : RawByteString; ClientIV : RawByteString; ServerIV : RawByteString; end; procedure GenerateTLSKeys( const ProtocolVersion: TTLSProtocolVersion; const MACKeyBits, CipherKeyBits, IVBits: Integer; const MasterSecret, ServerRandom, ClientRandom: RawByteString; var TLSKeys: TTLSKeys); procedure GenerateFinalTLSKeys( const ProtocolVersion: TTLSProtocolVersion; const IsExportable: Boolean; const ExpandedKeyBits: Integer; const ServerRandom, ClientRandom: RawByteString; var TLSKeys: TTLSKeys); { } { Test } { } {$IFDEF TLS_TEST} procedure Test; {$ENDIF} implementation uses { Utils } flcStrings, { Crypto } flcCryptoHash, { TLS } flcTLSErrors, flcTLSPRF; { } { Key block } { } { SSL 3.0: } { key_block = } { MD5(master_secret + SHA('A' + master_secret + } { ServerHello.random + ClientHello.random)) + } { MD5(master_secret + SHA('BB' + master_secret + } { ServerHello.random + ClientHello.random)) + } { MD5(master_secret + SHA('CCC' + master_secret + } { ServerHello.random + ClientHello.random)) + } { [...]; } { } { TLS 1.0 / 1.1 / 1.2: } { key_block = PRF(SecurityParameters.master_secret, } { "key expansion", } { SecurityParameters.server_random + } { SecurityParameters.client_random); } { } function ssl30KeyBlockP(const Prefix, MasterSecret, ServerRandom, ClientRandom: RawByteString): RawByteString; begin Result := MD5DigestToStrA( CalcMD5(MasterSecret + SHA1DigestToStrA( CalcSHA1(Prefix + MasterSecret + ServerRandom + ClientRandom)))); end; function ssl30KeyBlockPF(const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; var Salt : RawByteString; I : Integer; begin Result := ''; I := 1; while Length(Result) < Size do begin if I > 26 then raise ETLSError.Create(TLSError_InvalidParameter); Salt := DupCharB(ByteChar(Ord('A') + I - 1), I); Result := Result + ssl30KeyBlockP(Salt, MasterSecret, ServerRandom, ClientRandom); Inc(I); end; SetLength(Result, Size); end; function ssl30KeyBlock(const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; begin Result := ssl30KeyBlockPF(MasterSecret, ServerRandom, ClientRandom, Size); end; const LabelKeyExpansion = 'key expansion'; function tls10KeyBlock(const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; var S : RawByteString; begin S := ServerRandom + ClientRandom; Result := tls10PRF(MasterSecret, LabelKeyExpansion, S, Size); end; function tls12SHA256KeyBlock(const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; var S : RawByteString; begin S := ServerRandom + ClientRandom; Result := tls12PRF_SHA256(MasterSecret, LabelKeyExpansion, S, Size); end; function tls12SHA512KeyBlock(const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; var S : RawByteString; begin S := ServerRandom + ClientRandom; Result := tls12PRF_SHA512(MasterSecret, LabelKeyExpansion, S, Size); end; function TLSKeyBlock(const ProtocolVersion: TTLSProtocolVersion; const MasterSecret, ServerRandom, ClientRandom: RawByteString; const Size: Integer): RawByteString; begin if IsTLS12OrLater(ProtocolVersion) then Result := tls12SHA256KeyBlock(MasterSecret, ServerRandom, ClientRandom, Size) else if IsTLS10OrLater(ProtocolVersion) then Result := tls10KeyBlock(MasterSecret, ServerRandom, ClientRandom, Size) else if IsSSL3(ProtocolVersion) then Result := ssl30KeyBlock(MasterSecret, ServerRandom, ClientRandom, Size) else raise ETLSError.Create(TLSError_InvalidParameter); end; { } { Master secret } { } { SSL 3: } { master_secret = } { MD5(pre_master_secret + SHA('A' + pre_master_secret + } { ClientHello.random + ServerHello.random)) + } { MD5(pre_master_secret + SHA('BB' + pre_master_secret + } { ClientHello.random + ServerHello.random)) + } { MD5(pre_master_secret + SHA('CCC' + pre_master_secret + } { ClientHello.random + ServerHello.random)); } { } { TLS 1.0 1.1 1.2: } { master_secret = PRF(pre_master_secret, } { "master secret", } { ClientHello.random + ServerHello.random) } { } { The master secret is always exactly 48 bytes in length. The length of } { the premaster secret will vary depending on key exchange method. } { } const LabelMasterSecret = 'master secret'; MasterSecretSize = 48; function ssl30MasterSecretP(const Prefix, PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; begin Result := MD5DigestToStrA( CalcMD5(PreMasterSecret + SHA1DigestToStrA( CalcSHA1(Prefix + PreMasterSecret + ClientRandom + ServerRandom)))); end; function ssl30MasterSecret(const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; begin Result := ssl30MasterSecretP('A', PreMasterSecret, ClientRandom, ServerRandom) + ssl30MasterSecretP('BB', PreMasterSecret, ClientRandom, ServerRandom) + ssl30MasterSecretP('CCC', PreMasterSecret, ClientRandom, ServerRandom); end; function tls10MasterSecret(const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; var S : RawByteString; begin S := ClientRandom + ServerRandom; Result := tls10PRF(PreMasterSecret, LabelMasterSecret, S, MasterSecretSize); end; function tls12SHA256MasterSecret(const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; var S : RawByteString; begin S := ClientRandom + ServerRandom; Result := tls12PRF_SHA256(PreMasterSecret, LabelMasterSecret, S, MasterSecretSize); end; function tls12SHA512MasterSecret(const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; var S : RawByteString; begin S := ClientRandom + ServerRandom; Result := tls12PRF_SHA512(PreMasterSecret, LabelMasterSecret, S, MasterSecretSize); end; function TLSMasterSecret(const ProtocolVersion: TTLSProtocolVersion; const PreMasterSecret, ClientRandom, ServerRandom: RawByteString): RawByteString; begin if IsTLS12OrLater(ProtocolVersion) then Result := tls12SHA256MasterSecret(PreMasterSecret, ClientRandom, ServerRandom) else if IsTLS10OrLater(ProtocolVersion) then Result := tls10MasterSecret(PreMasterSecret, ClientRandom, ServerRandom) else if IsSSL3(ProtocolVersion) then Result := ssl30MasterSecret(PreMasterSecret, ClientRandom, ServerRandom) else raise ETLSError.Create(TLSError_InvalidParameter); end; { } { TLS Keys } { } procedure GenerateTLSKeys( const ProtocolVersion: TTLSProtocolVersion; const MACKeyBits, CipherKeyBits, IVBits: Integer; const MasterSecret, ServerRandom, ClientRandom: RawByteString; var TLSKeys: TTLSKeys); var L, I, N : Integer; S : RawByteString; begin Assert(MACKeyBits mod 8 = 0); Assert(CipherKeyBits mod 8 = 0); Assert(IVBits mod 8 = 0); L := MACKeyBits * 2 + CipherKeyBits * 2 + IVBits * 2; L := L div 8; S := TLSKeyBlock(ProtocolVersion, MasterSecret, ServerRandom, ClientRandom, L); TLSKeys.KeyBlock := S; I := 1; N := MACKeyBits div 8; TLSKeys.ClientMACKey := Copy(S, I, N); TLSKeys.ServerMACKey := Copy(S, I + N, N); Inc(I, N * 2); N := CipherKeyBits div 8; TLSKeys.ClientEncKey := Copy(S, I, N); TLSKeys.ServerEncKey := Copy(S, I + N, N); Inc(I, N * 2); N := IVBits div 8; TLSKeys.ClientIV := Copy(S, I, N); TLSKeys.ServerIV := Copy(S, I + N, N); end; { TLS 1.0: } { final_client_write_key = PRF(SecurityParameters.client_write_key, } { "client write key", } { SecurityParameters.client_random + SecurityParameters.server_random); } { final_server_write_key = PRF(SecurityParameters.server_write_key, } { "server write key", } { SecurityParameters.client_random + SecurityParameters.server_random); } { iv_block = PRF("", "IV block", } { SecurityParameters.client_random + SecurityParameters.server_random); } const LabelClientWriteKey = 'client write key'; LabelServerWriteKey = 'server write key'; LabelIVBlock = 'IV block'; procedure GenerateFinalTLSKeys( const ProtocolVersion: TTLSProtocolVersion; const IsExportable: Boolean; const ExpandedKeyBits: Integer; const ServerRandom, ClientRandom: RawByteString; var TLSKeys: TTLSKeys); var S : RawByteString; L : Integer; V : RawByteString; begin if IsTLS11OrLater(ProtocolVersion) then exit; if not IsExportable then exit; if IsSSL2(ProtocolVersion) or IsSSL3(ProtocolVersion) then raise ETLSError.Create(TLSError_InvalidParameter, 'Unsupported version'); S := ClientRandom + ServerRandom; Assert(ExpandedKeyBits mod 8 = 0); L := ExpandedKeyBits div 8; TLSKeys.ClientEncKey := tls10PRF(TLSKeys.ClientEncKey, LabelClientWriteKey, S, L); TLSKeys.ServerEncKey := tls10PRF(TLSKeys.ServerEncKey, LabelServerWriteKey, S, L); L := Length(TLSKeys.ClientIV); if L > 0 then begin V := tls10PRF('', LabelIVBlock, S, L * 2); TLSKeys.ClientIV := Copy(V, 1, L); TLSKeys.ServerIV := Copy(V, L + 1, L); end; end; { } { Test } { } {$IFDEF TLS_TEST} {$ASSERTIONS ON} const PreMasterSecret = RawByteString( #$03#$01#$84#$54#$F5#$D6#$EB#$F5#$A8#$08#$BA#$FA#$7A#$22#$61#$2D + #$75#$DC#$40#$E8#$98#$F9#$0E#$B2#$87#$80#$B8#$1A#$8F#$68#$25#$B8 + #$51#$D0#$54#$45#$61#$8A#$50#$C9#$BB#$0E#$39#$53#$45#$78#$BE#$79); ClientRandom = RawByteString( #$40#$FC#$30#$AE#$2D#$63#$84#$BB#$C5#$4B#$27#$FD#$58#$21#$CA#$90 + #$05#$F6#$A7#$7B#$37#$BB#$72#$E1#$FC#$1D#$1B#$6A#$F5#$1C#$C8#$9F); ServerRandom = RawByteString( #$40#$FC#$31#$10#$79#$AB#$17#$66#$FA#$8B#$3F#$AA#$FD#$5E#$48#$23 + #$FA#$90#$31#$D8#$3C#$B9#$A3#$2C#$8C#$F5#$E9#$81#$9B#$A2#$63#$6C); MasterSecret = RawByteString( #$B0#$00#$22#$34#$59#$03#$16#$B7#$7A#$6C#$56#$9B#$89#$D2#$7A#$CC + #$F3#$85#$55#$59#$3A#$14#$76#$3D#$54#$BF#$EB#$3F#$E0#$2F#$B1#$4B + #$79#$8C#$75#$A9#$78#$55#$6C#$8E#$A2#$14#$60#$B7#$45#$EB#$77#$B2); MACWriteKey = RawByteString( #$85#$F0#$56#$F8#$07#$1D#$B1#$89#$89#$D0#$E1#$33#$3C#$CA#$63#$F9); procedure TestKeyBlock; var S : RawByteString; begin // // // Example from http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/ReadDebug.html // // // Assert(tls10MasterSecret(PreMasterSecret, ClientRandom, ServerRandom) = MasterSecret); S := tls10KeyBlock(MasterSecret, ServerRandom, ClientRandom, 64); Assert(Copy(S, 1, 48) = MACWriteKey + #$1E#$4D#$D1#$D3#$0A#$78#$EE#$B7#$4F#$EC#$15#$79#$B2#$59#$18#$40 + #$10#$D0#$D6#$C2#$D9#$B7#$62#$CB#$2C#$74#$BF#$5F#$85#$3C#$6F#$E7); end; procedure Test; begin TestKeyBlock; end; {$ENDIF} 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_TGA * Implements TGA loader *********************************************************************************************************************** } Unit TERRA_TGA; {$I terra.inc} Interface Implementation Uses TERRA_String, TERRA_Error, TERRA_Utils, TERRA_Stream, TERRA_Image, TERRA_Application, TERRA_Color; Type LTGAHeader=Packed Record // Header type for TGA images FileType:Byte; ColorMapType:Byte; ImageType:Byte; ColorMapSpec:Array[0..4] of Byte; OrigX:Word; OrigY:Word; Width:Word; Height:Word; BPP:Byte; ImageInfo:Byte; End; Procedure TGALoad(Source:Stream; Image:Image); Var Header:LTGAHeader; ColorDepth:Cardinal; PacketHdr,PacketLen:Byte; I,J:Integer; Color:TERRA_Color.Color; PixelSize:Integer; N, Count:Integer; Flags:Cardinal; Dest, Buffer:PColor; Begin // Read in the bitmap file header Source.Read(@Header,SizeOf(Header)); // Only support 24, 32 bit images If (Header.ImageType<>2) And // TGA_RGB (Header.ImageType<>10) Then // Compressed RGB Begin RaiseError('Invalid header.'); Exit; End; // Don't support colormapped files If Header.ColorMapType<>0 Then Begin RaiseError('Colormapped texture not supported.'); Exit; End; // Get the width, height, and color depth ColorDepth:=Header.BPP; If ColorDepth<24 Then Begin RaiseError('Invalid color format.'); Exit; End; Image.New(Header.Width,Header.Height); PixelSize:=ColorDepth Div 8; Color := ColorWhite; Case Header.ImageType Of 2: Begin // Standard TGA file // Get the actual pixel data For J:=0 To Pred(Image.Height) Do For I:=0 To Pred(Image.Width) Do Begin Source.Read(@Color,PixelSize); Image.SetPixel(I,J, Color); End; End; 10: Begin // Compressed TGA files Count:=Image.Width*Image.Height; GetMem(Buffer, Image.Width); Dest:=Buffer; J:=Pred(Image.Height); N:=0; Color.A := 255; // Extract pixel information from compressed data Repeat Source.Read(@PacketHdr,1); PacketLen:=Succ(PacketHdr And $7F); If (PacketHdr And $80 <> 0) Then Begin // Run-length packet. Source.Read(@Color, PixelSize); // Replicate the packet in the destination buffer. For I:=0 To Pred(PacketLen) Do Begin Dest^:=Color; Inc(Dest); Dec(Count); Inc(N); If (N=Image.Width) Then Begin Image.LineDecodeBGR32(Buffer, J); Dec(J); Dest:=Buffer; N:=0; End; End; End Else Begin // Raw packet. For I:=0 To Pred(packetLen) Do Begin Source.Read(@Color, PixelSize); Dest^:=Color; Inc(Dest); Dec(Count); Inc(N); If (N=Image.Width) Then Begin Image.LineDecodeBGR32(Buffer, J); Dec(J); Dest:=Buffer; N:=0; End; End; End; Until Count<=0; FreeMem(Buffer); End; End; Image.Process(IMP_SwapChannels Or IMP_FlipVertical); End; Procedure TGASave(Dest:Stream; Image:Image; Const Options:TERRAString); Var I,J:Integer; Header:LTGAHeader; Color:TERRA_Color.Color; Begin FillChar(Header,SizeOf(Header),0); Header.ImageType:=2; Header.BPP:=32; Header.Width:=Image.Width; Header.Height:=Image.Height; Dest.Write(@Header,SizeOf(Header)); For J:=0 To Pred(Image.Height) Do For I:=0 To Pred(Image.Width) Do Begin Color := ColorSwap(Image.GetPixel(I, Pred(Image.Height) - J)); Dest.Write(@Color, SizeOf(Color)); End; End; Function ValidateTGA(Stream:Stream):Boolean; Var ID:Word; Begin Stream.ReadWord(ID); Result := (ID=0); End; Begin RegisterImageFormat('TGA', ValidateTGA, TGALoad, TGASave); End.
unit BuildIndustryTask; interface uses Tasks, Kernel, Collection, BuildFacilitiesTask, FacIds; type PFacIdArray = ^TFacIdArray; TFacIdArray = array[0..0] of TFacId; type TMetaChoice = class public constructor Create(aBlockClass, aServiceId : string; FacIds : array of TFacId); destructor Destroy; override; private fBlockClass : string; fServiceId : string; fFacIds : PFacIdArray; fCount : integer; public property BlockClass : string read fBlockClass; property ServiceId : string read fServiceId; property FacIds : PFacIdArray read fFacIds; property FacIdCount : integer read fCount; end; TMetaBuildIndustryTask = class(TMetaBuildFacilitiesTask) public constructor Create(anId, aName, aDesc, aSuperTaskId : string; aPeriod : integer; aTaskClass : CTask); destructor Destroy; override; private fMetaChoices : TCollection; public procedure AddChoice(Choice : TMetaChoice); private function GetChoiceCount : integer; function GetChoice(index : integer) : TMetaChoice; public property ChoiceCount : integer read GetChoiceCount; property Choices[index : integer] : TMetaChoice read GetChoice; end; TBuildIndustryTask = class(TBuildFacilitiesTask) private fChoiceIndex : integer; protected procedure DefineTarget; override; function GetTargetBlock : string; override; end; implementation uses SysUtils, ServiceInfo, Population, MathUtils, TaskUtils; type PChoiceIndex = ^TChoiceIndex; TChoiceIndex = array[0..0] of integer; // TMetaChoice constructor TMetaChoice.Create(aBlockClass, aServiceId : string; FacIds : array of TFacId); begin inherited Create; fBlockClass := aBlockClass; fServiceId := aServiceId; if FacIds[0] = FID_None then fCount := 0 else begin fCount := high(FacIds) - low(FacIds) + 1; GetMem(fFacIds, fCount*sizeof(fFacIds[0])); move(FacIds, fFacIds^, fCount*sizeof(fFacIds[0])); end; end; destructor TMetaChoice.Destroy; begin if fFacIds <> nil then FreeMem(fFacIds); inherited; end; // TMetaBuildIndustryTask constructor TMetaBuildIndustryTask.Create(anId, aName, aDesc, aSuperTaskId : string; aPeriod : integer; aTaskClass : CTask); begin inherited Create(anId, aName, aDesc, aSuperTaskId, aPeriod, aTaskClass); fMetaChoices := TCollection.Create(0, rkBelonguer); end; destructor TMetaBuildIndustryTask.Destroy; begin fMetaChoices.Free; inherited; end; procedure TMetaBuildIndustryTask.AddChoice(Choice : TMetaChoice); begin fMetaChoices.Insert(Choice); end; function TMetaBuildIndustryTask.GetChoiceCount : integer; begin result := fMetaChoices.Count; end; function TMetaBuildIndustryTask.GetChoice(index : integer) : TMetaChoice; begin result := TMetaChoice(fMetaChoices[index]); end; // TBuildIndustryTask procedure TBuildIndustryTask.DefineTarget; var Indexes : PChoiceIndex; Ratios : PChoiceIndex; count : integer; i, j : integer; TownHall : TTownHall; Choice : TMetaChoice; Service : TServiceInfo; procedure Swap(var v1, v2 : integer); var t : integer; begin t := v1; v1 := v2; v2 := t; end; function PossibleChoice(idx : integer) : boolean; begin Choice := TMetaBuildIndustryTask(MetaTask).Choices[idx]; result := (Choice.FacIdCount = 0) or TaskUtils.TownHasFacilities(TTown(Context.getContext(tcIdx_Town)), Slice(Choice.FacIds^, Choice.FacIdCount)); if Choice.FacIdCount <> 0 then else result := true; end; begin count := TMetaBuildIndustryTask(MetaTask).ChoiceCount; GetMem(Indexes, count*sizeof(Indexes[0])); GetMem(Ratios, count*sizeof(Ratios[0])); try FillChar(Indexes^, count*sizeof(Indexes[0]), 0); TownHall := TTownHall(TInhabitedTown(Context.getContext(tcIdx_Town)).TownHall); // Get the ratios for i := 0 to pred(count) do begin Choice := TMetaBuildIndustryTask(MetaTask).Choices[i]; Service := TServiceInfo(TownHall.ServiceInfoById[Choice.ServiceId]); if Service <> nil then Ratios[i] := min(100, round(100*Service.Ratio)) else Ratios[i] := 100; Indexes[i] := i; end; // Sort the indexes usising bubble sort for i := 0 to pred(pred(count)) do for j := succ(i) to pred(count) do if Ratios[i] > Ratios[j] then begin Swap(Ratios[i], Ratios[j]); Swap(Indexes[i], Indexes[j]); end; // Get the best choice i := 0; while (i < count) and not PossibleChoice(i) do inc(i); if i < count then fChoiceIndex := i else fChoiceIndex := -1; finally FreeMem(Indexes); FreeMem(Ratios); end; end; function TBuildIndustryTask.GetTargetBlock : string; begin if fChoiceIndex <> -1 then result := TMetaBuildIndustryTask(MetaTask).Choices[fChoiceIndex].BlockClass else result := ''; end; end.
// Filename : SAXAElfred2.pas // Version : 1.1 (Delphi) // Date : July 4, 2003 // Author : Jeff Rafter // Details : http://xml.defined.net/SAX/aelfred2 // License : Please read License.txt unit SAXAElfred2; interface uses Classes, SAX, XmlReader, SAXDriver; type // Streamlined Driver TSAXAelfred2Vendor = class(TSAXVendor) function Description: string; override; function XMLReader: IXMLReader; override; end; // Validation Support Reader TSAXAelfred2XmlReaderVendor = class(TSAXVendor) function Description: string; override; function XMLReader: IXMLReader; override; end; TSAXAElfred2 = class(TComponent) private function GetVendor: string; published property Vendor: string read GetVendor; end; TSAXAElfred2XMLReader = class(TComponent) private function GetVendor: string; published property Vendor: string read GetVendor; end; procedure FormatDocument(const Input, Output : TStream; const Canonical : Boolean = False); procedure InitializeVendor; const SAX_VENDOR_AELFRED2 = SAXString('AElfred2'); SAX_VENDOR_AELFRED2_XMLREADER = SAXString('AElfred2 XMLReader'); implementation uses SAXWriter; procedure FormatDocument(const Input, Output : TStream; const Canonical : Boolean = False); var AXMLReader : IXMLReader; ASAXVendor : TSAXVendor; ASAXWriter : TSAXWriter; begin Input.Seek(0, 0); ASAXVendor:= GetSAXVendor(SAX_VENDOR_AELFRED2); if not Assigned(ASAXVendor) then raise ESAXException.CreateFmt(SUnknownVendor, [SAX_VENDOR_AELFRED2]); AXMLReader:= ASAXVendor.XMLReader as IXMLReader; ASAXWriter:= TSAXWriter.Create(Canonical); ASAXWriter.setOutput(Output); ASAXWriter.setEncoding('UTF-8'); ASAXWriter.setTrimOutput(true); AXMLReader.setContentHandler(ASAXWriter as IContentHandler); AXMLReader.parse(TStreamInputSource.Create(Input, soReference) as IStreamInputSource); Output.Seek(0, 0); end; { TSAXAelfred2Vendor } function TSAXAelfred2Vendor.Description: string; begin Result := SAX_VENDOR_AELFRED2; end; function TSAXAelfred2Vendor.XMLReader: IXMLReader; begin Result := TSAXDriver.Create(nil) as IXMLReader; end; { TSAXAelfred2XmlReaderVendor } function TSAXAelfred2XmlReaderVendor.Description: string; begin Result := SAX_VENDOR_AELFRED2_XMLREADER; end; function TSAXAelfred2XmlReaderVendor.XMLReader: IXMLReader; begin Result := TXmlReader.Create(nil); end; var SAXVendor: TSAXVendor; SAXXmlReaderVendor: TSAXVendor; function TSAXAElfred2.GetVendor: string; begin Result := SAXVendor.Description; end; function TSAXAElfred2XMLReader.GetVendor: string; begin Result := SAXXmlReaderVendor.Description; end; procedure InitializeVendor; begin SAXVendor:= TSAXAelfred2Vendor.Create; RegisterSAXVendor(SAXVendor); SAXXmlReaderVendor:= TSAXAelfred2XmlReaderVendor.Create; RegisterSAXVendor(SAXXmlReaderVendor); DefaultSAXVendor:= SAXXmlReaderVendor.Description; end; initialization InitializeVendor; finalization UnRegisterSAXVendor(SAXVendor); UnRegisterSAXVendor(SAXXmlReaderVendor); end.
unit MdiChilds.UnionDTX; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.ExtCtrls, MDIChilds.ProgressForm, DataTable, ActionHandler; type TFmUnionDTX = class(TFmProcess) ListBox1: TListBox; JvDragDrop1: TJvDragDrop; SaveDialog: TSaveDialog; procedure JvDragDrop1Drop(Sender: TObject; Pos: TPoint; Value: TStrings); private { Private declarations } public procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; end; TUnionDTXActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmUnionDTX: TFmUnionDTX; implementation {$R *.dfm} procedure TFmUnionDTX.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; DTX: TDTXBook; Table: TFormattedStringDataTable; begin ShowMessage := False; ProgressForm.InitPB(ListBox1.Count); ProgressForm.Show; DTX := TDTXBook.Create(); try for I := 0 to ListBox1.Count - 1 do begin ProgressForm.StepIt(ListBox1.Items[I]); if not ProgressForm.InProcess then Break; Table := TFormattedStringDataTable.Create; Table.LoadFromFile(ListBox1.Items[I]); Table.RemoveEmptyColumns; DTX.Add(Table); end; if SaveDialog.Execute then begin DTX.SaveToFile(SaveDialog.FileName); ShowMessage := True; end; finally DTX.Free; end; end; procedure TFmUnionDTX.JvDragDrop1Drop(Sender: TObject; Pos: TPoint; Value: TStrings); begin ListBox1.Items.Assign(Value); end; { TUnionDTXActionHandler } procedure TUnionDTXActionHandler.ExecuteAction(UserData: Pointer); begin TFmUnionDTX.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Объединение DTX', hkDefault, TUnionDTXActionHandler); end.
{ vclutils unit Copyright (C) 2005-2013 Lagunov Aleksey alexs@hotbox.ru original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit vclutils; {$I rx.inc} interface uses {$IFDEF WIN32} windows, {$ENDIF} Classes, SysUtils, Graphics, Controls, Forms, LResources ; type TTextOrientation = (toHorizontal, toVertical90, toHorizontal180, toVertical270, toHorizontal360); function WidthOf(R: TRect): Integer; inline; function HeightOf(R: TRect): Integer; inline; procedure RxFrame3D(Canvas: TCanvas; var Rect: TRect; TopColor, BottomColor: TColor; Width: Integer); function DrawButtonFrame(Canvas: TCanvas; const Client: TRect; IsDown, IsFlat: Boolean): TRect; function DrawButtonFrameXP(Canvas: TCanvas; const Client: TRect; IsDown, IsFlat: Boolean): TRect; //Code from TAChartUtils procedure RotateLabel(Canvas: TCanvas; x, y: Integer; const St: String; RotDegree: Integer); procedure OutTextXY90(Canvas:TCanvas; X,Y:integer; Text:string; Orientation:TTextOrientation); function IsForegroundTask: Boolean; function ValidParentForm(Control: TControl): TCustomForm; function CreateArrowBitmap:TBitmap; function LoadLazResBitmapImage(const ResName: string): TBitmap; {functions from DBGrid} function GetWorkingCanvas(const Canvas: TCanvas): TCanvas; procedure FreeWorkingCanvas(canvas: TCanvas); { function AllocMemo(Size: Longint): Pointer; function ReallocMemo(fpBlock: Pointer; Size: Longint): Pointer; procedure FreeMemo(var fpBlock: Pointer); } procedure RaiseIndexOutOfBounds(Control: TControl; Items:TStrings; Index: integer); {$IFDEF WIN32} type PCursorOrIcon = ^TCursorOrIcon; TCursorOrIcon = packed record Reserved: Word; wType: Word; Count: Word; end; PIconRec = ^TIconRec; TIconRec = packed record Width: Byte; Height: Byte; Colors: Word; Reserved1: Word; Reserved2: Word; DIBSize: Longint; DIBOffset: Longint; end; procedure ReadIcon(Stream: TStream; var Icon: HICON; ImageCount: Integer; StartOffset: Integer; const RequestedSize: TPoint; var IconSize: TPoint); procedure OutOfResources; {$ENDIF} implementation uses LCLProc, LCLIntf, LCLType, LCLStrConsts; function WidthOf(R: TRect): Integer; begin Result := R.Right - R.Left; end; function HeightOf(R: TRect): Integer; begin Result := R.Bottom - R.Top; end; procedure RxFrame3D(Canvas: TCanvas; var Rect: TRect; TopColor, BottomColor: TColor; Width: Integer); procedure DoRect; var TopRight, BottomLeft: TPoint; begin TopRight.X := Rect.Right; TopRight.Y := Rect.Top; BottomLeft.X := Rect.Left; BottomLeft.Y := Rect.Bottom; Canvas.Pen.Color := TopColor; Canvas.PolyLine([BottomLeft, Rect.TopLeft, TopRight]); Canvas.Pen.Color := BottomColor; Dec(BottomLeft.X); Canvas.PolyLine([TopRight, Rect.BottomRight, BottomLeft]); end; begin Canvas.Pen.Width := 1; Dec(Rect.Bottom); Dec(Rect.Right); while Width > 0 do begin Dec(Width); DoRect; InflateRect(Rect, -1, -1); end; Inc(Rect.Bottom); Inc(Rect.Right); end; function DrawButtonFrame(Canvas: TCanvas; const Client: TRect; IsDown, IsFlat: Boolean): TRect; begin Result := Client; if IsDown then begin RxFrame3D(Canvas, Result, clWindowFrame, clBtnHighlight, 1); if not IsFlat then RxFrame3D(Canvas, Result, clBtnShadow, clBtnFace, 1); end else begin if IsFlat then RxFrame3D(Canvas, Result, clBtnHighlight, clBtnShadow, 1) else begin RxFrame3D(Canvas, Result, clBtnHighlight, clWindowFrame, 1); RxFrame3D(Canvas, Result, clBtnFace, clBtnShadow, 1); end; end; InflateRect(Result, -1, -1); end; function DrawButtonFrameXP(Canvas: TCanvas; const Client: TRect; IsDown, IsFlat: Boolean): TRect; begin Result := Client; Canvas.Brush.Color := $00EFD3C6; Canvas.FillRect(Client); RxFrame3D(Canvas, Result, $00C66931, $00C66931, 1); end; {$IFDEF WIN32} type PCheckTaskInfo = ^TCheckTaskInfo; TCheckTaskInfo = packed record FocusWnd: HWnd; Found: Boolean; end; //function CheckTaskWindow(Window: HWnd; Data: Longint): WordBool; stdcall; function CheckTaskWindow(Window:HWND; Data:LPARAM):WINBOOL;stdcall; begin Result := True; if PCheckTaskInfo(Data)^.FocusWnd = Window then begin Result := False; PCheckTaskInfo(Data)^.Found := True; end; end; {$ENDIF} function IsForegroundTask: Boolean; {$IFDEF WIN32} var Info: TCheckTaskInfo; {$ENDIF} begin {$IFDEF WIN32} Info.FocusWnd := GetActiveWindow; Info.Found := False; EnumThreadWindows(GetCurrentThreadID, @CheckTaskWindow, Longint(@Info)); Result := Info.Found; {$ELSE} Result:=true; {$ENDIF} end; function ValidParentForm(Control: TControl): TCustomForm; begin Result := GetParentForm(Control); if Result = nil then raise EInvalidOperation.CreateFmt('ParentRequired %s', [Control.Name]); end; procedure RotateLabel(Canvas: TCanvas; x, y: Integer; const St: String; RotDegree: Integer); var L:integer; begin L:=Canvas.Font.Orientation; SetBkMode(Canvas.Handle, TRANSPARENT); Canvas.Font.Orientation:=RotDegree * 10; Canvas.TextOut(X, Y, St); { DrawText(ACanvas.Handle, PChar(Text), Length(Text), DrawRect, ALIGN_FLAGS_HEADER[Alignment] or DT_WORDBREAK );} Canvas.Font.Orientation:=L; end; procedure OutTextXY90(Canvas:TCanvas; X,Y:integer; Text:string; Orientation:TTextOrientation); {$IFDEF OLD_STYLE_TEXT_ROTATE} var W,H, i,j:integer; Bmp:TBitmap; begin if Orientation = toHorizontal then Canvas.TextOut(X, Y, Text) else begin W:=Canvas.TextWidth(Text); H:=Canvas.TextHeight(Text); Bmp:=TBitMap.Create; try Bmp.Width:=W; Bmp.Height:=H; Bmp.Canvas.Brush.Style:=bsSolid; Bmp.Canvas.Brush.Color:=clWhite; Bmp.Canvas.FillRect(Rect(0,0,W,H)); Bmp.Canvas.Font:=Canvas.Font; Bmp.Canvas.TextOut(0, 0, Text); Canvas.Lock; if Orientation = toVertical90 then begin for i:=0 to W-1 do for j:=0 to H-1 do if Bmp.Canvas.Pixels[i,j]<>clWhite then Canvas.Pixels[(H-j)+X,i+Y]:=Bmp.Canvas.Pixels[i,j]; end else if Orientation = toVertical270 then begin for i:=0 to W-1 do for j:=0 to H-1 do if Bmp.Canvas.Pixels[i,j]<>clWhite then Canvas.Pixels[j+X,(W-i)+Y]:=Bmp.Canvas.Pixels[i,j]; end else if Orientation = toHorizontal180 then begin for i:=0 to W-1 do for j:=0 to H-1 do if Bmp.Canvas.Pixels[i,j]<>clWhite then Canvas.Pixels[i+X,(H-j)+Y]:=Bmp.Canvas.Pixels[i,j]; end else if Orientation = toHorizontal360 then begin for i:=0 to W-1 do for j:=0 to H-1 do if Bmp.Canvas.Pixels[i,j]<>clWhite then Canvas.Pixels[(W-i)+X,j+Y]:=Bmp.Canvas.Pixels[i,j]; end; Canvas.Unlock; finally Bmp.Free; end; end; end; {$ELSE} const TextAngle: array [TTextOrientation] of integer = (0 {toHorizontal}, 90 {toVertical90}, 180 {toHorizontal180}, 270 {toVertical270}, 0 {toHorizontal360}); var W, H:integer; begin W:=0; H:=0; case Orientation of toVertical90: begin H:=Canvas.TextWidth(Text); end; toVertical270: begin W:=Canvas.TextHeight(Text); end; toHorizontal180: begin H:=Canvas.TextHeight(Text); W:=Canvas.TextWidth(Text); end; end; RotateLabel(Canvas, X+W, Y+H, Text, TextAngle[Orientation]); end; {$ENDIF} { function AllocMemo(Size: Longint): Pointer; begin if Size > 0 then Result := GlobalAllocPtr(HeapAllocFlags or GMEM_ZEROINIT, Size) else Result := nil; end; function ReallocMemo(fpBlock: Pointer; Size: Longint): Pointer; begin Result := GlobalReallocPtr(fpBlock, Size, HeapAllocFlags or GMEM_ZEROINIT); end; procedure FreeMemo(var fpBlock: Pointer); begin if fpBlock <> nil then begin GlobalFreePtr(fpBlock); fpBlock := nil; end; end; } {$IFDEF WIN32} function CreateIcon(hInstance: HINST; nWidth, nHeight: Integer; cPlanes, cBitsPixel: Byte; lpbANDbits, lpbXORbits: Pointer): HICON; stdcall; external user32 name 'CreateIcon'; procedure GDIError; var ErrorCode: Integer; Buf: array [Byte] of Char; begin ErrorCode := GetLastError; if (ErrorCode <> 0) and (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrorCode, LOCALE_USER_DEFAULT, Buf, sizeof(Buf), nil) <> 0) then raise EOutOfResources.Create(Buf) else OutOfResources; end; function DupBits(Src: HBITMAP; Size: TPoint; Mono: Boolean): HBITMAP; var DC, Mem1, Mem2: HDC; Old1, Old2: HBITMAP; Bitmap: Windows.TBitmap; begin Mem1 := CreateCompatibleDC(0); Mem2 := CreateCompatibleDC(0); try GetObject(Src, SizeOf(Bitmap), @Bitmap); if Mono then Result := CreateBitmap(Size.X, Size.Y, 1, 1, nil) else begin DC := GetDC(0); if DC = 0 then GDIError; try Result := CreateCompatibleBitmap(DC, Size.X, Size.Y); if Result = 0 then GDIError; finally ReleaseDC(0, DC); end; end; if Result <> 0 then begin Old1 := SelectObject(Mem1, Src); Old2 := SelectObject(Mem2, Result); StretchBlt(Mem2, 0, 0, Size.X, Size.Y, Mem1, 0, 0, Bitmap.bmWidth, Bitmap.bmHeight, SrcCopy); if Old1 <> 0 then SelectObject(Mem1, Old1); if Old2 <> 0 then SelectObject(Mem2, Old2); end; finally DeleteDC(Mem1); DeleteDC(Mem2); end; end; function GDICheck(Value: Integer): Integer; begin if Value = 0 then GDIError; Result := Value; end; function GetDInColors(BitCount: Word): Integer; begin case BitCount of 1, 4, 8: Result := 1 shl BitCount; else Result := 0; end; end; function BytesPerScanline(PixelsPerScanline, BitsPerPixel, Alignment: Longint): Longint; begin Dec(Alignment); Result := ((PixelsPerScanline * BitsPerPixel) + Alignment) and not Alignment; Result := Result div 8; end; procedure TwoBitsFromDIB(var BI: TBitmapInfoHeader; var XorBits, AndBits: HBITMAP; const IconSize: TPoint); type PLongArray = ^TLongArray; TLongArray = array[0..1] of Longint; var Temp: HBITMAP; NumColors: Integer; DC: HDC; Bits: Pointer; Colors: PLongArray; begin with BI do begin biHeight := biHeight shr 1; { Size in record is doubled } biSizeImage := BytesPerScanline(biWidth, biBitCount, 32) * biHeight; NumColors := GetDInColors(biBitCount); end; DC := GetDC(0); if DC = 0 then OutOfResources; try Bits := Pointer(Longint(@BI) + SizeOf(BI) + NumColors * SizeOf(TRGBQuad)); Temp := GDICheck(CreateDIBitmap(DC, BI, CBM_INIT, Bits, PBitmapInfo(@BI)^, DIB_RGB_COLORS)); try XorBits := DupBits(Temp, IconSize, False); finally DeleteObject(Temp); end; with BI do begin Inc(Longint(Bits), biSizeImage); biBitCount := 1; biSizeImage := BytesPerScanline(biWidth, biBitCount, 32) * biHeight; biClrUsed := 2; biClrImportant := 2; end; Colors := Pointer(Longint(@BI) + SizeOf(BI)); Colors^[0] := 0; Colors^[1] := $FFFFFF; Temp := GDICheck(CreateDIBitmap(DC, BI, CBM_INIT, Bits, PBitmapInfo(@BI)^, DIB_RGB_COLORS)); try AndBits := DupBits(Temp, IconSize, True); finally DeleteObject(Temp); end; finally ReleaseDC(0, DC); end; end; procedure ReadIcon(Stream: TStream; var Icon: HICON; ImageCount: Integer; StartOffset: Integer; const RequestedSize: TPoint; var IconSize: TPoint); type PIconRecArray = ^TIconRecArray; TIconRecArray = array[0..300] of TIconRec; var List: PIconRecArray; HeaderLen, Length: Integer; BitsPerPixel: Word; Colors, BestColor, C1, N, Index: Integer; DC: HDC; BI: PBitmapInfoHeader; ResData: Pointer; XorBits, AndBits: HBITMAP; XorInfo, AndInfo: Windows.TBitmap; XorMem, AndMem: Pointer; XorLen, AndLen: Integer; function AdjustColor(I: Integer): Integer; begin if I = 0 then Result := MaxInt else Result := I; end; function BetterSize(const Old, New: TIconRec): Boolean; var NewX, NewY, OldX, OldY: Integer; begin NewX := New.Width - IconSize.X; NewY := New.Height - IconSize.Y; OldX := Old.Width - IconSize.X; OldY := Old.Height - IconSize.Y; Result := (Abs(NewX) <= Abs(OldX)) and ((NewX <= 0) or (NewX <= OldX)) and (Abs(NewY) <= Abs(OldY)) and ((NewY <= 0) or (NewY <= OldY)); end; begin HeaderLen := SizeOf(TIconRec) * ImageCount; List := AllocMem(HeaderLen); try Stream.Read(List^, HeaderLen); if (RequestedSize.X or RequestedSize.Y) = 0 then begin IconSize.X := GetSystemMetrics(SM_CXICON); IconSize.Y := GetSystemMetrics(SM_CYICON); end else IconSize := RequestedSize; DC := GetDC(0); if DC = 0 then OutOfResources; try BitsPerPixel := GetDeviceCaps(DC, PLANES) * GetDeviceCaps(DC, BITSPIXEL); if BitsPerPixel > 8 then Colors := MaxInt else Colors := 1 shl BitsPerPixel; finally ReleaseDC(0, DC); end; { Find the image that most closely matches (<=) the current screen color depth and the requested image size. } Index := 0; BestColor := AdjustColor(List^[0].Colors); for N := 1 to ImageCount-1 do begin C1 := AdjustColor(List^[N].Colors); if (C1 <= Colors) and (C1 >= BestColor) and BetterSize(List^[Index], List^[N]) then begin Index := N; BestColor := C1; end; end; with List^[Index] do begin IconSize.X := Width; IconSize.Y := Height; BI := AllocMem(DIBSize); try Stream.Seek(DIBOffset - (HeaderLen + StartOffset), 1); Stream.Read(BI^, DIBSize); TwoBitsFromDIB(BI^, XorBits, AndBits, IconSize); GetObject(AndBits, SizeOf(Windows.TBitmap), @AndInfo); GetObject(XorBits, SizeOf(Windows.TBitmap), @XorInfo); with AndInfo do AndLen := bmWidthBytes * bmHeight * bmPlanes; with XorInfo do XorLen := bmWidthBytes * bmHeight * bmPlanes; Length := AndLen + XorLen; ResData := AllocMem(Length); try AndMem := ResData; with AndInfo do XorMem := Pointer(Longint(ResData) + AndLen); GetBitmapBits(AndBits, AndLen, AndMem); GetBitmapBits(XorBits, XorLen, XorMem); DeleteObject(XorBits); DeleteObject(AndBits); Icon := CreateIcon(HInstance, IconSize.X, IconSize.Y, XorInfo.bmPlanes, XorInfo.bmBitsPixel, AndMem, XorMem); if Icon = 0 then GDIError; finally FreeMem(ResData, Length); end; finally FreeMem(BI, DIBSize); end; end; finally FreeMem(List, HeaderLen); end; end; procedure OutOfResources; begin raise Exception.Create('SOutOfResources'); end; {$ENDIF} function CreateArrowBitmap:TBitmap; begin Result:=LoadLazResBitmapImage('rxbtn_downarrow') { Result:=Graphics.TBitmap.Create; Result.LoadFromLazarusResource('rxbtn_downarrow');} end; //Code from DBGrid function LoadLazResBitmapImage(const ResName: string): TBitmap; var C: TCustomBitmap; begin C := CreateBitmapFromLazarusResource(ResName); if C<>nil then begin Result := TBitmap.Create; Result.Assign(C); C.Free; end else Result:=nil; end; function GetWorkingCanvas(const Canvas: TCanvas): TCanvas; var DC: HDC; begin if (Canvas=nil) or (not Canvas.HandleAllocated) then begin DC := GetDC(0); Result := TCanvas.Create; Result.Handle := DC; end else Result := Canvas; end; procedure FreeWorkingCanvas(canvas: TCanvas); begin ReleaseDC(0, Canvas.Handle); Canvas.Free; end; procedure RaiseIndexOutOfBounds(Control: TControl; Items:TStrings; Index: integer); begin raise Exception.CreateFmt(rsIndexOutOfBounds, [Control.Name, Index, Items.Count - 1]); end; initialization LazarusResources.Add('rxbtn_downarrow','XPM',[ '/* XPM */'#13#10'static char * btn_downarrow_xpm[] = {'#13#10'"5 3 2 1",'#13 +#10'" '#9'c None",'#13#10'".'#9'c #000000",'#13#10'".....",'#13#10'" ... ",' +#13#10'" . "};'#13#10]); end.
unit uMainForm; interface uses System.Classes, System.PushNotification, FMX.Controls, FMX.Controls.Presentation, FMX.Forms, FMX.Memo, FMX.Memo.Types, FMX.ScrollBox, FMX.Types; type TMainForm = class(TForm) memLog: TMemo; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); private FPushService: TPushService; FPushServiceConnection: TPushServiceConnection; procedure OnServiceConnectionChange(Sender: TObject; PushChanges: TPushService.TChanges); procedure OnServiceConnectionReceiveNotification(Sender: TObject; const ServiceNotification: TPushServiceNotification); end; implementation {$R *.fmx} uses {$IF Defined(ANDROID)} FMX.PushNotification.Android; {$ENDIF} {$IF Defined(IOS)} FMX.PushNotification.FCM.iOS; {$ENDIF} procedure TMainForm.FormCreate(Sender: TObject); begin FPushService := TPushServiceManager.Instance.GetServiceByName (TPushService.TServiceNames.FCM); FPushServiceConnection := TPushServiceConnection.Create(FPushService); FPushServiceConnection.OnChange := OnServiceConnectionChange; FPushServiceConnection.OnReceiveNotification := OnServiceConnectionReceiveNotification; FPushServiceConnection.Active := True; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FPushServiceConnection.Free; end; procedure TMainForm.OnServiceConnectionChange(Sender: TObject; PushChanges: TPushService.TChanges); begin if TPushService.TChange.Status in PushChanges then begin if FPushService.Status = TPushService.TStatus.Started then begin memLog.Lines.BeginUpdate; memLog.Lines.Add('Push service succeeded to start'); memLog.Lines.Add(''); memLog.Lines.EndUpdate; end else if FPushService.Status = TPushService.TStatus.StartupError then begin FPushServiceConnection.Active := False; memLog.Lines.BeginUpdate; memLog.Lines.Add('Push service failed to start'); memLog.Lines.Add(FPushService.StartupError); memLog.Lines.Add(''); memLog.Lines.EndUpdate; end; end; if TPushService.TChange.DeviceToken in PushChanges then begin memLog.Lines.BeginUpdate; memLog.Lines.Add('Device token received'); memLog.Lines.Add('Device identifier: ' + FPushService.DeviceIDValue [TPushService.TDeviceIDNames.DeviceId]); memLog.Lines.Add('Device token: ' + FPushService.DeviceTokenValue [TPushService.TDeviceTokenNames.DeviceToken]); memLog.Lines.Add(''); memLog.Lines.EndUpdate; end; end; procedure TMainForm.OnServiceConnectionReceiveNotification(Sender: TObject; const ServiceNotification: TPushServiceNotification); begin memLog.Lines.BeginUpdate; memLog.Lines.Add('Push notification received'); memLog.Lines.Add('DataKey: ' + ServiceNotification.DataKey); memLog.Lines.Add('Json: ' + ServiceNotification.Json.ToString); memLog.Lines.Add('DataObject: ' + ServiceNotification.DataObject.ToString); memLog.Lines.Add(''); memLog.Lines.EndUpdate; end; end.
unit parser; interface Uses System.Classes; type TObjectType = (otUnck, otString, otStringEx, otComboEx); TStringArray = array of String; TSimpleObject = class private slArguments : TStringArray; FName: string; FObjTyp : TObjectType; procedure SetArguments(const Value: TStringArray); public // создаем объект, распарсив входную строку constructor Create (const Name : String); destructor Destroy; override; procedure Parse (const Input : String); virtual; // на всякий случай если кто-то захочет поменять function ObjTypeToString : String; function ToString : String; property Name : string read FName write FName; property ObjType : TObjectType read FObjTyp write FObjTyp; property Arguments : TStringArray read slArguments write SetArguments; end; TStringParser = class (TSimpleObject) private public constructor Create (const Name : String); end; //*** Igor *** Конструктор для TStingParser ************************************ TStringExParser = class (TSimpleObject) private public constructor Create (const Name : String); end; //****************************************************************************** TComboParser = class (TSimpleObject) private public constructor Create (const Name : String); end; implementation Uses IdGlobal, System.SysUtils; const topc_string = 'topc_string'; topc_string_min_max = 'topc_string_min_max'; topc_combo_ex = 'topc_combo_ex'; { TSimpleObject } constructor TSimpleObject.Create (const Name : String); begin FName := name; FObjTyp := otUnck; SetLength(slArguments,1); Arguments [0] := '[Комментарий]'; end; destructor TSimpleObject.Destroy; begin inherited; end; function TSimpleObject.ObjTypeToString: String; begin case FObjTyp of otString: Result := topc_string; otStringEx: Result := topc_string_min_max; otComboEx : Result := topc_combo_ex; end; end; procedure TSimpleObject.Parse(const Input: String); var tmp : String; tmpType : String; Starguments : string; // строка аргументов i : Integer; sl : TStringList; begin tmp := Input; Name := Fetch (tmp , ' = '); tmpType := Fetch (tmp , ' ('); FObjTyp := otUnck; if tmpType = topc_string then // простая строка FObjTyp := otString else if tmpType = topc_string_min_max then // строка с граничными значениями FObjTyp := otStringEx else if tmpType = topc_combo_ex then // расширенное окно с выпадающим списком FObjTyp := otComboEx; // Пробую распарсить в arguments Starguments := Fetch(tmp, ')'); // удаляем скобку i := 0; SetLength(slArguments,10); while (Starguments <> '') do begin slArguments [i] := Fetch (Starguments,','); if i = 0 then slArguments [i] := StringsReplace(slArguments [i],['"'],['']) else slArguments [i] := StringsReplace(slArguments [i],['"','{','}','[',']'],['','','','','']); // удаляем все спец символы inc (i); if i = Length (slArguments) then SetLength (slArguments, i+10); end; SetLength (slArguments, i); end; procedure TSimpleObject.SetArguments(const Value: TStringArray); var I: Integer; begin SetLength(slArguments,Length(Value) + 1 ); // 1 это комментарий for I := 0 to High(Value) do slArguments [i + 1] := Value[i]; end; //************************************************************ function TSimpleObject.ToString: String; var I: Integer; tmp : String; begin if FObjTyp = otUnck then begin // не знаю что это за тип был Result := ''; Exit; end; Result := FName + ' = ' + ObjTypeToString + ' ('; for I := 0 to High(slArguments) do begin if i = 0 then begin Result := Result + '"'; if Length(slArguments[i]) > 0 then // Result := Result + ''; Result := Result + slArguments[i] + '",'; end else begin if (ObjType = otComboEx) then begin if (i = 1) then Result := Result + '{'; tmp := slArguments[i]; Result := Result + Format('[%s]="%s",',[Fetch(tmp,'='),tmp]); if (i = High(slArguments)) then begin Result[Length(Result)] := '}'; Result := Result + ','; end; end else Result := Result + slArguments[i] + ','; end; end; // в конце появится лишняя запятая, удаляем ее Delete(Result, Length(Result),1); // устанавливаем закрывающую скобку и возвращаем строку Result := Result + ')'; end; //*********************************************************** { TStringParser } constructor TStringParser.Create (const Name : String); begin inherited; ObjType := otString; end; //*** Igor *** Конструктор для TStingParser ************************************ { TStringExParser } constructor TStringExParser.Create (const Name : String); begin inherited; ObjType := otStringEx; SetLength(slArguments,3); slArguments[1] := '0'; slArguments[2] := '100'; end; { TComboParser } constructor TComboParser.Create (const Name : String); begin inherited; ObjType := otComboEx; SetLength(slArguments,3); slArguments[1] := '0=Выключить'; slArguments[2] := '1=Включить'; end; end.
unit DcefB_BasicDialog; interface uses Forms, StdCtrls, Controls, Consts, Classes, Graphics, Dialogs, ExtCtrls, Windows, Math, Dcef3_ceflib; type TPasswordDialogForm = class private FForm: TForm; FLabelPassword: TLabel; FEditPassword: TEdit; FOKBtn: TButton; FCancelBtn: TButton; FLabelUserName: TLabel; FEditUserName: TEdit; function GetFormPassword: string; function GetFormUserName: string; public constructor Create; destructor Destroy; override; function ShowModal: Integer; property FormUserName: string read GetFormUserName; property FormPassword: string read GetFormPassword; end; TSearchTextBar = class(TPanel) private FEditSearch: TEdit; FButtonGoBack: TButton; FButtonGoForward: TButton; FButtonClose: TButton; FCefBrowserHost: ICefBrowserHost; procedure ButtonGoBackClick(Sender: TObject); procedure ButtonGoForwardClick(Sender: TObject); procedure ButtonCloseClick(Sender: TObject); public constructor Create(AOwner: TComponent; CefBrowserHost: ICefBrowserHost); reintroduce; procedure EditSetFocus; destructor Destroy; override; procedure Clear; end; procedure MyConfirm(const ACaption: string; const AText: string; var BoolValue: Boolean); // 仿造自InputQuery implementation { TPasswordDlg } constructor TPasswordDialogForm.Create; begin FForm := TForm.Create(nil); with FForm do begin Left := 245; Top := 108; BorderStyle := bsDialog; Caption := #36523#20221#39564#35777; ClientHeight := 128; ClientWidth := 233; Color := clBtnFace; Font.Charset := DEFAULT_CHARSET; Font.Color := clWindowText; Font.Height := -12; Font.Name := #24494#36719#38597#40657; Font.Style := []; OldCreateOrder := True; Position := poScreenCenter; PixelsPerInch := 96; end; FLabelPassword := TLabel.Create(nil); FLabelUserName := TLabel.Create(nil); FEditPassword := TEdit.Create(nil); FEditUserName := TEdit.Create(nil); FOKBtn := TButton.Create(nil); FCancelBtn := TButton.Create(nil); with FLabelPassword do begin Parent := FForm; Left := 8; Top := 49; Width := 24; Height := 13; Caption := '密码'; end; with FLabelUserName do begin Parent := FForm; Left := 8; Top := 3; Width := 36; Height := 13; Caption := '用户名'; end; with FEditPassword do begin Parent := FForm; Left := 24; Top := 68; Width := 201; Height := 21; PasswordChar := '*'; TabOrder := 1; end; with FOKBtn do begin Parent := FForm; Left := 62; Top := 98; Width := 75; Height := 25; Caption := '确定'; Default := True; ModalResult := 1; TabOrder := 2; end; with FCancelBtn do begin Parent := FForm; Left := 150; Top := 98; Width := 75; Height := 25; Cancel := True; Caption := '取消'; ModalResult := 2; TabOrder := 3; end; with FEditUserName do begin Parent := FForm; Left := 24; Top := 22; Width := 201; Height := 21; TabOrder := 0; end; end; destructor TPasswordDialogForm.Destroy; begin FLabelPassword.Free; FEditPassword.Free; FOKBtn.Free; FCancelBtn.Free; FLabelUserName.Free; FEditUserName.Free; FForm.Free; inherited; end; function TPasswordDialogForm.GetFormPassword: string; begin Result := FEditPassword.Text; end; function TPasswordDialogForm.GetFormUserName: string; begin Result := FEditUserName.Text; end; function TPasswordDialogForm.ShowModal: Integer; begin Result := FForm.ShowModal; end; { TSearchTextDialogForm } procedure TSearchTextBar.ButtonCloseClick(Sender: TObject); begin FCefBrowserHost.StopFinding(True); Hide; FCefBrowserHost.SetFocus(True); end; procedure TSearchTextBar.ButtonGoBackClick(Sender: TObject); begin FCefBrowserHost.find(-1, FEditSearch.Text, False, False, True); // 不匹配大小写 FCefBrowserHost.SetFocus(True); end; procedure TSearchTextBar.ButtonGoForwardClick(Sender: TObject); begin FCefBrowserHost.find(-1, FEditSearch.Text, True, False, True); // 不匹配大小写 FCefBrowserHost.SetFocus(True); end; procedure TSearchTextBar.Clear; begin FEditSearch.Text := ''; end; constructor TSearchTextBar.Create(AOwner: TComponent; CefBrowserHost: ICefBrowserHost); begin inherited Create(AOwner); FCefBrowserHost := CefBrowserHost; Top := 0; Width := 372; Height := 35; BevelInner := bvNone; BevelKind := bksoft; BevelOuter := bvNone; {$IFDEF DELPHI14_UP} ShowCaption := False; {$ENDIF} FEditSearch := TEdit.Create(nil); FButtonGoBack := TButton.Create(nil); FButtonGoForward := TButton.Create(nil); FButtonClose := TButton.Create(nil); with FEditSearch do begin Parent := Self; Left := 3; Top := 3; Width := 268; Height := 25; TabOrder := 0; end; with FButtonGoBack do begin Parent := Self; Left := 279; Top := 3; Width := 25; Height := 25; Caption := #9650; TabOrder := 1; OnClick := ButtonGoBackClick; end; with FButtonGoForward do begin Parent := Self; Left := 310; Top := 3; Width := 25; Height := 25; Caption := #9660; TabOrder := 2; OnClick := ButtonGoForwardClick; end; with FButtonClose do begin Parent := Self; Left := 341; Top := 3; Width := 25; Height := 25; Caption := #10006; TabOrder := 3; OnClick := ButtonCloseClick; end; end; destructor TSearchTextBar.Destroy; begin FCefBrowserHost := nil; FEditSearch.Free; FButtonGoBack.Free; FButtonGoForward.Free; FButtonClose.Free; inherited; end; procedure TSearchTextBar.EditSetFocus; begin FEditSearch.SetFocus; end; function GetAveCharSize(Canvas: TCanvas): TPoint; {$IFDEF CLR} var I: Integer; Buffer: string; Size: TSize; begin SetLength(Buffer, 52); for I := 0 to 25 do Buffer[I + 1] := Chr(I + Ord('A')); for I := 0 to 25 do Buffer[I + 27] := Chr(I + Ord('a')); GetTextExtentPoint(Canvas.Handle, Buffer, 52, Size); Result.X := Size.cx div 52; Result.Y := Size.cy; end; {$ELSE} var I: Integer; Buffer: array [0 .. 51] of Char; begin for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A')); for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a')); GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result)); Result.X := Result.X div 52; end; {$ENDIF} function GetTextBaseline(AControl: TControl; ACanvas: TCanvas): Integer; var tm: TTextMetric; ClientRect: TRect; Ascent: Integer; P: TPoint; begin ClientRect := AControl.ClientRect; GetTextMetrics(ACanvas.Handle, tm); Ascent := tm.tmAscent + 1; Result := ClientRect.Top + Ascent; {$IFDEF DELPHI14_UP} P := TPoint.Create(0, Result) {$ELSE} P.X := 0; P.Y := Result; {$ENDIF} Result := AControl.Parent.ScreenToClient (AControl.ClientToScreen(P)).Y - AControl.Top; end; procedure MyConfirm(const ACaption: string; const AText: string; var BoolValue: Boolean); var Form: TForm; Prompt: TLabel; DialogUnits: TPoint; CurPrompt: Integer; MaxPromptWidth: Integer; ButtonTop, ButtonWidth, ButtonHeight: Integer; function GetPromptCaption(const ACaption: string): string; begin if (Length(ACaption) > 1) and (ACaption[1] < #32) then Result := Copy(ACaption, 2, MaxInt) else Result := ACaption; end; function GetMaxPromptWidth(Canvas: TCanvas): Integer; var LLabel: TLabel; begin Result := 0; // Use a TLabel rather than an API such as GetTextExtentPoint32 to // avoid differences in handling characters such as line breaks. LLabel := TLabel.Create(nil); try LLabel.Caption := GetPromptCaption(AText); Result := Max(Result, LLabel.Width + DialogUnits.X); finally LLabel.Free; end; end; function GetPasswordChar(const ACaption: string): Char; begin if (Length(ACaption) > 1) and (ACaption[1] < #32) then Result := '*' else Result := #0; end; begin Form := TForm.CreateNew(Application); with Form do try Canvas.Font := Font; DialogUnits := GetAveCharSize(Canvas); MaxPromptWidth := GetMaxPromptWidth(Canvas); BorderStyle := bsDialog; Caption := ACaption; ClientWidth := MulDiv(180 + MaxPromptWidth, DialogUnits.X, 4); {$IFDEF DELPHI14_UP} PopupMode := pmAuto; {$ENDIF} Position := poScreenCenter; CurPrompt := MulDiv(8, DialogUnits.Y, 8); Prompt := TLabel.Create(Form); with Prompt do begin Parent := Form; Caption := GetPromptCaption(AText); Left := MulDiv(8, DialogUnits.X, 4); Top := CurPrompt; Constraints.MaxWidth := MaxPromptWidth; WordWrap := True; end; ButtonTop := Prompt.Top + Prompt.Height + 15; ButtonWidth := MulDiv(50, DialogUnits.X, 4); ButtonHeight := MulDiv(14, DialogUnits.Y, 8); with TButton.Create(Form) do begin Parent := Form; Caption := SMsgDlgOK; ModalResult := mrOk; Default := True; SetBounds(Form.ClientWidth - (ButtonWidth + MulDiv(8, DialogUnits.X, 4)) * 2, ButtonTop, ButtonWidth, ButtonHeight); end; with TButton.Create(Form) do begin Parent := Form; Caption := SMsgDlgCancel; ModalResult := mrCancel; Cancel := True; SetBounds(Form.ClientWidth - (ButtonWidth + MulDiv(8, DialogUnits.X, 4) ), ButtonTop, ButtonWidth, ButtonHeight); Form.ClientHeight := Top + Height + 13; end; BoolValue := ShowModal = mrOk; finally Form.Free; end; end; end.
unit MFichas.Model.Entidade.EMPRESA; interface uses DB, Classes, SysUtils, Generics.Collections, /// orm ormbr.types.blob, ormbr.types.lazy, ormbr.types.mapping, ormbr.types.nullable, ormbr.mapping.classes, ormbr.mapping.register, ormbr.mapping.attributes; type [Entity] [Table('EMPRESA', '')] [PrimaryKey('GUUID', NotInc, NoSort, False, 'Chave primária')] TEMPRESA = class private { Private declarations } FGUUID: String; FDESCRICAO: String; FLOGOTIPO: TBlob; FDATACADASTRO: TDateTime; FDATAALTERACAO: TDateTime; function GetDATAALTERACAO: TDateTime; function GetDATACADASTRO: TDateTime; function GetGUUID: String; public { Public declarations } [Column('GUUID', ftString, 38)] [Dictionary('GUUID', 'Mensagem de validação', '', '', '', taLeftJustify)] property GUUID: String read GetGUUID write FGUUID; [Column('DESCRICAO', ftString, 128)] [Dictionary('DESCRICAO', 'Mensagem de validação', '', '', '', taLeftJustify)] property DESCRICAO: String read FDESCRICAO write FDESCRICAO; [Column('LOGOTIPO', ftBlob)] [Dictionary('LOGOTIPO', 'Mensagem de validação', '', '', '', taLeftJustify)] property LOGOTIPO: TBlob read FLOGOTIPO write FLOGOTIPO; [Column('DATACADASTRO', ftDateTime)] [Dictionary('DATACADASTRO', 'Mensagem de validação', '', '', '', taCenter)] property DATACADASTRO: TDateTime read GetDATACADASTRO write FDATACADASTRO; [Column('DATAALTERACAO', ftDateTime)] [Dictionary('DATAALTERACAO', 'Mensagem de validação', '', '', '', taCenter)] property DATAALTERACAO: TDateTime read GetDATAALTERACAO write FDATAALTERACAO; end; implementation { TEMPRESA } function TEMPRESA.GetDATAALTERACAO: TDateTime; begin FDATAALTERACAO := Now; Result := FDATAALTERACAO; end; function TEMPRESA.GetDATACADASTRO: TDateTime; begin if FDATACADASTRO = StrToDateTime('30/12/1899') then FDATACADASTRO := Now; Result := FDATACADASTRO; end; function TEMPRESA.GetGUUID: String; begin if FGUUID.IsEmpty then FGUUID := TGUID.NewGuid.ToString; Result := FGUUID; end; initialization TRegisterClass.RegisterEntity(TEMPRESA) 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: StList.pas 4.04 *} {*********************************************************} {* SysTools: Linked list class *} {*********************************************************} {$I StDefine.inc} {Notes: Nodes stored in the list can be of type TStListNode or of a derived type. Pass the node class to the list constructor. TStList is a doubly-linked list that can be scanned backward just as efficiently as forward. The list retains the index and node of the last node found by Nth (or by the indexed array property). This makes For loops that scan a list much faster and speeds up random calls to Nth by about a factor of two. } unit StList; interface uses Windows, SysUtils, Classes, StConst, StBase; type TStListNode = class(TStNode) {.Z+} protected FNext : TStListNode; {Next node} FPrev : TStListNode; {Previous node} {.Z-} public constructor Create(AData : Pointer); override; {-Initialize node} end; TStList = class(TStContainer) {.Z+} protected {property instance variables} FHead : TStListNode; {Start of list} FTail : TStListNode; {End of list} {private instance variables} lsLastI : Integer; {Last index requested from Nth} lsLastP : TStListNode; {Last node returned by Nth} {protected undocumented methods} procedure ForEachPointer(Action : TIteratePointerFunc; OtherData : pointer); override; function StoresPointers : boolean; override; {.Z-} public constructor Create(NodeClass : TStNodeClass); virtual; {-Initialize an empty list} procedure LoadFromStream(S : TStream); override; {-Create a list and its data from a stream} procedure StoreToStream(S : TStream); override; {-Write a list and its data to a stream} procedure Clear; override; {-Remove all nodes from container but leave it instantiated} function Append(Data : Pointer) : TStListNode; {-Add a new node to the end of a list} function Insert(Data : Pointer) : TStListNode; {-Insert a new node at the start of a list} function Place(Data : Pointer; P : TStListNode) : TStListNode; {-Place a new node into a list after an existing node P} function PlaceBefore(Data : Pointer; P : TStListNode) : TStListNode; {-Place a new node into a list before an existing node P} function InsertSorted(Data : Pointer) : TStListNode; {-Insert a new node in sorted order} procedure MoveToHead(P : TStListNode); {-Move P to the head of the list} procedure Assign(Source: TPersistent); override; {-Assign another container's contents to this one} procedure Join(P : TStListNode; L : TStList); {-Join list L after P in the current list. L is freed} function Split(P : TStListNode) : TStList; {-Split list, creating a new list that starts with P} procedure Sort; {-Put the list into sorted order} procedure Delete(P : TStListNode); {-Remove an element and dispose of its contents} function Next(P : TStListNode) : TStListNode; {-Return the node after P, nil if none} function Prev(P : TStListNode) : TStListNode; {-Return the node before P, nil if none} function Nth(Index : Integer) : TStListNode; {-Return the Index'th node in the list, Index >= 0 (cached)} function NthFrom(P : TStListNode; Index : Integer) : TStListNode; {-Return the Index'th node from P, either direction} function Posn(P : TStListNode) : Integer; {-Return the ordinal position of an element in the list} function Distance(P1, P2 : TStListNode) : Integer; {-Return the number of nodes separating P1 and P2 (signed)} function Find(Data : Pointer) : TStListNode; {-Return the first node whose data equals Data} function Iterate(Action : TIterateFunc; Up : Boolean; OtherData : Pointer) : TStListNode; {-Call Action for all the nodes, returning the last node visited} property Head : TStListNode {-Return the head node} read FHead; property Tail : TStListNode {-Return the tail node} read FTail; property Items[Index : Integer] : TStListNode {-Return the Index'th node, 0-based} read Nth; default; end; {.Z+} TStListClass = class of TStList; {.Z-} {======================================================================} implementation {$IFDEF ThreadSafe} var ClassCritSect : TRTLCriticalSection; {$ENDIF} procedure EnterClassCS; begin {$IFDEF ThreadSafe} EnterCriticalSection(ClassCritSect); {$ENDIF} end; procedure LeaveClassCS; begin {$IFDEF ThreadSafe} LeaveCriticalSection(ClassCritSect); {$ENDIF} end; constructor TStListNode.Create(AData : Pointer); begin inherited Create(AData); end; {----------------------------------------------------------------------} function FindNode(Container : TStContainer; Node : TStNode; OtherData : Pointer) : Boolean; far; begin Result := (Node.Data <> OtherData); end; function AssignData(Container : TStContainer; Data, OtherData : Pointer) : Boolean; far; var OurList : TStList absolute OtherData; begin OurList.Append(Data); Result := true; end; {----------------------------------------------------------------------} function TStList.Append(Data : Pointer) : TStListNode; var N : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := TStListNode(conNodeClass.Create(Data)); N.FPrev := FTail; if not Assigned(FHead) then begin {Special case for first node} FHead := N; FTail := N; end else begin {Add at end of existing list} FTail.FNext := N; FTail := N; end; Inc(FCount); Result := N; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStList.Assign(Source: TPersistent); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {The only containers that we allow to be assigned to a linked list are - another SysTools linked list (TStList) - a SysTools binary search tree (TStTree) - a SysTools collection (TStCollection, TStSortedCollection)} if not AssignPointers(Source, AssignData) then inherited Assign(Source); {$IFDEF ThreadSafe} finally LeaveCS; end;{try..finally} {$ENDIF} end; procedure TStList.Clear; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Count > 0 then begin Iterate(DestroyNode, True, nil); FCount := 0; end; FHead := nil; FTail := nil; lsLastI := -1; lsLastP := nil; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; constructor TStList.Create(NodeClass : TStNodeClass); begin CreateContainer(NodeClass, 0); Clear; end; procedure TStList.Delete(P : TStListNode); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if (not Assigned(P)) or (Count <= 0) then Exit; if not (P is conNodeClass) then RaiseContainerError(stscBadType); with P do begin {Fix pointers of surrounding nodes} if Assigned(FNext) then FNext.FPrev := FPrev; if Assigned(FPrev) then FPrev.FNext := FNext; end; {Fix head and tail of list} if FTail = P then FTail := FTail.FPrev; if FHead = P then FHead := FHead.FNext; {Dispose of the node} DisposeNodeData(P); P.Free; Dec(FCount); lsLastI := -1; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Distance(P1, P2 : TStListNode) : Integer; var I : Integer; N : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {Count forward} I := 0; N := P1; while Assigned(N) and (N <> P2) do begin Inc(I); N := N.FNext; end; if N = P2 then begin Result := I; Exit; end; {Count backward} I := 0; N := P1; while Assigned(N) and (N <> P2) do begin Dec(I); N := N.FPrev; end; if N = P2 then begin Result := I; Exit; end; {Not on same list} Result := MaxLongInt; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Find(Data : Pointer) : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Result := Iterate(FindNode, True, Data); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStList.ForEachPointer(Action : TIteratePointerFunc; OtherData : pointer); var N : TStListNode; P : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := FHead; while Assigned(N) do begin P := N.FNext; if Action(Self, N.Data, OtherData) then N := P else Exit; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Insert(Data : Pointer) : TStListNode; var N : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := TStListNode(conNodeClass.Create(Data)); {N.FPrev := nil;} N.FNext := FHead; if not Assigned(FHead) then {Special case for first node} FTail := N else {Add at start of existing list} FHead.FPrev := N; FHead := N; Inc(FCount); lsLastI := -1; Result := N; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.InsertSorted(Data : Pointer) : TStListNode; var N : TStListNode; P : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := TStListNode(conNodeClass.Create(Data)); Result := N; Inc(FCount); lsLastI := -1; if not Assigned(FHead) then begin {First element added to list} FHead := N; FTail := N; end else begin P := FHead; while Assigned(P) do begin if DoCompare(N.Data, P.Data) < 0 then begin if not Assigned(P.FPrev) then begin {New head} FHead := N; end else begin P.FPrev.FNext := N; N.FPrev := P.FPrev; end; P.FPrev := N; N.FNext := P; Exit; end; P := P.FNext; end; {New tail} FTail.FNext := N; N.FPrev := FTail; FTail := N; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Iterate(Action : TIterateFunc; Up : Boolean; OtherData : Pointer) : TStListNode; var N : TStListNode; P : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Up then begin N := FHead; while Assigned(N) do begin P := N.FNext; if Action(Self, N, OtherData) then N := P else begin Result := N; Exit; end; end; end else begin N := FTail; while Assigned(N) do begin P := N.FPrev; if Action(Self, N, OtherData) then N := P else begin Result := N; Exit; end; end; end; Result := nil; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStList.Join(P : TStListNode; L : TStList); var N : TStListNode; Q : TStListNode; begin {$IFDEF ThreadSafe} EnterClassCS; EnterCS; L.EnterCS; try {$ENDIF} if Assigned(L) then begin if Assigned(P) and (L.Count > 0) then begin {Patch the list into the current one} N := L.Head; Q := P.FNext; P.FNext := N; N.FPrev := P; if Assigned(Q) then begin N := L.Tail; N.FNext := Q; Q.FPrev := N; end; Inc(FCount, L.Count); lsLastI := -1; end; {Free L (but not its nodes)} L.IncNodeProtection; L.Free; end; {$IFDEF ThreadSafe} finally L.LeaveCS; LeaveCS; LeaveClassCS; end; {$ENDIF} end; procedure TStList.LoadFromStream(S : TStream); var Data : pointer; Reader : TReader; StreamedClass : TPersistentClass; StreamedNodeClass : TPersistentClass; StreamedClassName : string; StreamedNodeClassName : string; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Clear; Reader := TReader.Create(S, 1024); try with Reader do begin StreamedClassName := ReadString; StreamedClass := GetClass(StreamedClassName); if (StreamedClass = nil) then RaiseContainerErrorFmt(stscUnknownClass, [StreamedClassName]); if (not IsOrInheritsFrom(StreamedClass, Self.ClassType)) or (not IsOrInheritsFrom(TStList, StreamedClass)) then RaiseContainerError(stscWrongClass); StreamedNodeClassName := ReadString; StreamedNodeClass := GetClass(StreamedNodeClassName); if (StreamedNodeClass = nil) then RaiseContainerErrorFmt(stscUnknownNodeClass, [StreamedNodeClassName]); if (not IsOrInheritsFrom(StreamedNodeClass, conNodeClass)) or (not IsOrInheritsFrom(TStListNode, StreamedNodeClass)) then RaiseContainerError(stscWrongNodeClass); ReadListBegin; while not EndOfList do begin Data := DoLoadData(Reader); Append(Data); end; ReadListEnd; end; finally Reader.Free; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStList.MoveToHead(P : TStListNode); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Assigned(P) then if P <> Head then begin with P do begin {Fix pointers of surrounding nodes} if FTail = P then FTail := FTail.FPrev else FNext.FPrev := FPrev; FPrev.FNext := FNext; FNext := FHead; FPrev := nil; end; FHead.FPrev := P; FHead := P; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Next(P : TStListNode) : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Result := P.FNext; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Nth(Index : Integer) : TStListNode; var MinI : Integer; MinP : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if (Index < 0) or (Index >= FCount) then Result := nil else begin MinI := Index; MinP := FHead; if lsLastI >= 0 then {scan the fewest possible nodes} if Index <= lsLastI then begin if lsLastI-Index < Index then begin MinI := Index-lsLastI; MinP := lsLastP; end; end else if Index-lsLastI < FCount-1-Index then begin MinI := Index-lsLastI; MinP := lsLastP; end else begin MinI := Index-(FCount-1); MinP := FTail; end; Result := NthFrom(MinP, MinI); lsLastI := Index; lsLastP := Result; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.NthFrom(P : TStListNode; Index : Integer) : TStListNode; var I : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Assigned(P) then begin if not (P is conNodeClass) then RaiseContainerError(stscBadType); if Index > 0 then begin for I := 1 to Index do begin P := P.FNext; if not Assigned(P) then break; end; end else begin for I := 1 to -Index do begin P := P.FPrev; if not Assigned(P) then break; end; end; end; Result := P; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Place(Data : Pointer; P : TStListNode) : TStListNode; var N : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if not Assigned(P) then Result := Insert(Data) else if P = FTail then Result := Append(Data) else begin N := TStListNode(conNodeClass.Create(Data)); N.FPrev := P; N.FNext := P.FNext; P.FNext.FPrev := N; P.FNext := N; Inc(FCount); lsLastI := -1; Result := N; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.PlaceBefore(Data : Pointer; P : TStListNode) : TStListNode; var N : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if (not Assigned(P)) or (P = Head) then {Place the new element at the start of the list} Result := Insert(Data) else begin {Patch in the new element} N := TStListNode(conNodeClass.Create(Data)); N.FNext := P; N.FPrev := P.FPrev; P.FPrev.FNext := N; P.FPrev := N; lsLastI := -1; Inc(FCount); Result := N; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Posn(P : TStListNode) : Integer; var I : Integer; N : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if not Assigned(P) then Result := -1 else begin if not (P is conNodeClass) then RaiseContainerError(stscBadType); I := 0; N := FHead; while Assigned(N) do begin if P = N then begin Result := I; exit; end; Inc(I); N := N.FNext; end; Result := -1; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Prev(P : TStListNode) : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Result := P.FPrev; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStList.Sort; const StackSize = 32; type Stack = array[0..StackSize-1] of TStListNode; var L : TStListNode; R : TStListNode; PL : TStListNode; PR : TStListNode; PivotData : Pointer; TmpData : Pointer; Dist : Integer; DistL : Integer; DistR : Integer; StackP : Integer; LStack : Stack; RStack : Stack; DStack : array[0..StackSize-1] of Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {Need at least 2 elements to sort} if Count <= 1 then Exit; lsLastI := -1; {Initialize the stacks} StackP := 0; LStack[0] := FHead; RStack[0] := FTail; DStack[0] := Count-1; {Repeatedly take top partition from stack} repeat {Pop the stack} L := LStack[StackP]; R := RStack[StackP]; Dist := DStack[StackP]; Dec(StackP); if L <> R then {Sort current partition} repeat {Load the pivot element} PivotData := NthFrom(L, Dist div 2).Data; PL := L; PR := R; DistL := Dist; DistR := Dist; {Swap items in sort order around the pivot index} repeat while DoCompare(PL.Data, PivotData) < 0 do begin PL := PL.FNext; Dec(Dist); Dec(DistR); end; while DoCompare(PivotData, PR.Data) < 0 do begin PR := PR.FPrev; Dec(Dist); Dec(DistL); end; if Dist >= 0 then begin if PL <> PR then begin {Swap the two elements} TmpData := PL.Data; PL.Data := PR.Data; PR.Data := TmpData; end; if Assigned(PL.FNext) then begin PL := PL.FNext; Dec(Dist); Dec(DistR); end; if Assigned(PR.FPrev) then begin PR := PR.FPrev; Dec(Dist); Dec(DistL); end; end; until Dist < 0; {Decide which partition to sort next} if DistL < DistR then begin {Right partition is bigger} if DistR > 0 then begin {Stack the request for sorting right partition} Inc(StackP); LStack[StackP] := PL; RStack[StackP] := R; DStack[StackP] := DistR; end; {Continue sorting left partition} R := PR; Dist := DistL; end else begin {Left partition is bigger} if DistL > 0 then begin {Stack the request for sorting left partition} Inc(StackP); LStack[StackP] := L; RStack[StackP] := PR; DStack[StackP] := DistL; end; {Continue sorting right partition} L := PL; Dist := DistR; end; until Dist <= 0; until StackP < 0; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.Split(P : TStListNode) : TStList; var I : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} I := Posn(P); if I < 0 then begin Result := nil; Exit; end; {Create and initialize the new list} Result := TStListClass(ClassType).Create(conNodeClass); Result.Compare := Compare; Result.OnCompare := OnCompare; Result.DisposeData := DisposeData; Result.OnDisposeData := OnDisposeData; Result.LoadData := LoadData; Result.OnLoadData := OnLoadData; Result.StoreData := StoreData; Result.OnStoreData := OnStoreData; Result.FHead := P; Result.FTail := FTail; Result.FCount := Count-I; Result.lsLastI := -1; {Truncate the old list} if Assigned(P.FPrev) then begin P.FPrev.FNext := nil; FTail := P.FPrev; P.FPrev := nil; end; if P = FHead then FHead := nil; FCount := I; lsLastI := -1; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStList.StoresPointers : Boolean; begin Result := true; end; procedure TStList.StoreToStream(S : TStream); var Writer : TWriter; Walker : TStListNode; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Writer := TWriter.Create(S, 1024); try with Writer do begin WriteString(Self.ClassName); WriteString(conNodeClass.ClassName); WriteListBegin; Walker := Head; while Walker <> nil do begin DoStoreData(Writer, Walker.Data); Walker := Next(Walker); end; WriteListEnd; end; finally Writer.Free; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; {$IFDEF ThreadSafe} initialization Windows.InitializeCriticalSection(ClassCritSect); finalization Windows.DeleteCriticalSection(ClassCritSect); {$ENDIF} end.
unit UploadFileGeocodingUnit; interface uses SysUtils, Classes, BaseExampleUnit, EnumsUnit; type TUploadFileGeocoding = class(TBaseExample) public procedure Execute(FileId: String); end; implementation uses NullableBasicTypesUnit; procedure TUploadFileGeocoding.Execute(FileId: String); var ErrorString: String; FileContent: TStringList; begin FileContent := Route4MeManager.Uploading.UploadFileGeocoding(FileId, ErrorString); try WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn('UploadFileGeocoding successfully'); WriteLn(''); end else WriteLn(Format('UploadFileGeocoding error: "%s"', [ErrorString])); finally FreeAndNil(FileContent); end; end; end.
unit NullableInterceptorUnit; interface uses Windows, REST.JsonReflect, Rtti, SysUtils, System.JSON, System.TypInfo, System.Generics.Collections; type TBaseNullableIntermediateObject = class abstract protected FIsNull: boolean; FIsRequired: boolean; public property IsNull: boolean read FIsNull write FIsNull; property IsRequired: boolean read FIsRequired write FIsRequired; end; TNullableObjectIntermediateObject = class(TBaseNullableIntermediateObject) private FValue: TObject; public constructor Create(Value: TObject); end; TNullableIntegerIntermediateObject = class(TBaseNullableIntermediateObject) private FValue: integer; public constructor Create(Value: integer); end; TNullableBooleanIntermediateObject = class(TBaseNullableIntermediateObject) private FValue: boolean; public constructor Create(Value: boolean); end; TNullableDoubleIntermediateObject = class(TBaseNullableIntermediateObject) private FValue: double; public constructor Create(Value: double); end; TNullableStringIntermediateObject = class(TBaseNullableIntermediateObject) private FValue: String; public constructor Create(Value: String); end; TNullableIntermediateObject = class(TInterfacedObject, IUnknown) private FNullableIntermediateObject: TBaseNullableIntermediateObject; public constructor Create(IntermediateObject: TBaseNullableIntermediateObject); destructor Destroy; override; end; TNullableInterceptor = class(TJSONInterceptor) private type TInternalJSONUnMarshal = class(TJSONUnMarshal); const IsNullFieldCaption = 'FIsNull'; ValueFieldCaption = 'FValue'; var FIntermediateObjects: TObjectList<TObject>; function GetObjectValue(s: String; Clazz: TClass): TValue; public destructor Destroy; override; /// <summary>Converters that transforms a field value into an /// intermediate object</summary> /// <param name="Data">Current object instance being serialized</param> /// <param name="Field">Field name</param> /// <result> a serializable object </result> function ObjectConverter(Data: TObject; Field: string): TObject; override; /// <summary>Field reverter that sets an object field to a value based on /// an array of intermediate objects</summary> /// <param name="Data">Current object instance being populated</param> /// <param name="Field">Field name</param> /// <param name="Args"> an array of objects </param> procedure ObjectsReverter(Data: TObject; Field: string; Args: TListOfObjects); override; /// <summary>Reverter that sets an object field to a value from /// a string</summary> /// <param name="Data">Current object instance being populated</param> /// <param name="Field">Field name</param> /// <param name="Arg">serialized value as a string </param> procedure StringReverter(Data: TObject; Field: string; Arg: string); override; end; implementation uses JSONNullableAttributeUnit, MarshalUnMarshalUnit; var LocaleFormatSettings: TFormatSettings; { TNullableInterceptor } function TNullableInterceptor.ObjectConverter(Data: TObject; Field: string): TObject; var ctx: TRttiContext; RttiType: TRttiType; RttiField, IsNullField, ValueField: TRttiField; RttiRecord: TRttiRecordType; Attr: TCustomAttribute; Ptr: Pointer; IsNull: boolean; Value: TValue; IsRequired: boolean; IsRequiredFound: boolean; ValueIntermediateObject: TBaseNullableIntermediateObject; begin Result := nil; ctx := TRttiContext.Create; try rttiType := ctx.GetType(Data.ClassType); RttiField := rttiType.GetField(Field); Ptr := RttiField.GetValue(Data).GetReferenceToRawData; if (not RttiField.FieldType.IsRecord) then raise Exception.Create('The field marked attribute "Nullable" must be a record.'); IsRequired := False; IsRequiredFound := False; for Attr in RttiField.GetAttributes do begin if Attr is BaseJSONNullableAttribute then begin IsRequired := BaseJSONNullableAttribute(attr).IsRequired; IsRequiredFound := True; end; end; if not IsRequiredFound then raise Exception.Create('This intercepter (TNullableInterceptor) was created not in JSONNullableAttribute.'); RttiRecord := RttiField.FieldType.AsRecord; IsNullField := RttiRecord.GetField(IsNullFieldCaption); if (IsNullField <> nil) and (IsNullField.FieldType.TypeKind = tkEnumeration) then IsNull := IsNullField.GetValue(Ptr).AsBoolean else raise Exception.Create(Format( 'The field marked attribute "JSONNullableAttribute" must have a field "%s: boolean"', [IsNullFieldCaption])); ValueField := RttiRecord.GetField(ValueFieldCaption); if (ValueField <> nil) then begin Value := ValueField.GetValue(Ptr); case ValueField.FieldType.TypeKind of tkEnumeration: ValueIntermediateObject := TNullableBooleanIntermediateObject.Create(Value.AsBoolean); tkInteger: ValueIntermediateObject := TNullableIntegerIntermediateObject.Create(Value.AsInteger); tkFloat: ValueIntermediateObject := TNullableDoubleIntermediateObject.Create(Value.AsExtended); TTypeKind.tkString, TTypeKind.tkLString, TTypeKind.tkWString, TTypeKind.tkUString: ValueIntermediateObject := TNullableStringIntermediateObject.Create(Value.AsString); tkClass: ValueIntermediateObject := TNullableObjectIntermediateObject.Create(Value.AsObject); else raise Exception.Create(Format( 'Unsupported type (%d) of the field marked attribute "JSONNullableAttribute"', [Integer(IsNullField.FieldType.TypeKind)])); end; ValueIntermediateObject.IsNull := IsNull; ValueIntermediateObject.IsRequired := IsRequired; Result := TNullableIntermediateObject.Create(ValueIntermediateObject); end else raise Exception.Create(Format( 'The field marked attribute "JSONNullableAttribute" must have a field "%s"', [ValueFieldCaption])); finally ctx.Free; end; if (Result = nil) then raise Exception.Create('The result can not be undefinded!'); if (FIntermediateObjects = nil) then FIntermediateObjects := TObjectList<TObject>.Create; FIntermediateObjects.Add(Result); end; { TNullableBooleanIntermediateObject } constructor TNullableBooleanIntermediateObject.Create(Value: boolean); begin FValue := Value; end; { TNullableIntegerIntermediateObject } constructor TNullableIntegerIntermediateObject.Create(Value: integer); begin FValue := Value; end; { TNullableDoubleIntermediateObject } constructor TNullableDoubleIntermediateObject.Create(Value: double); begin FValue := Value; end; { TNullableStringIntermediateObject } constructor TNullableStringIntermediateObject.Create(Value: String); begin FValue := Value; end; { TNullableIntermediateObject } constructor TNullableIntermediateObject.Create( IntermediateObject: TBaseNullableIntermediateObject); begin FNullableIntermediateObject := IntermediateObject; end; destructor TNullableIntermediateObject.Destroy; begin FreeAndNil(FNullableIntermediateObject); inherited; end; { TNullableObjectIntermediateObject } constructor TNullableObjectIntermediateObject.Create(Value: TObject); begin FValue := Value; end; { TNullableNumberAndStringInterceptor } destructor TNullableInterceptor.Destroy; begin FreeAndNil(FIntermediateObjects); inherited; end; function TNullableInterceptor.GetObjectValue(s: String; Clazz: TClass): TValue; var Obj: TObject; JsonValue: TJsonValue; begin JsonValue := TJsonObject.ParseJSONValue(s); try Obj := TMarshalUnMarshal.FromJson(Clazz, JsonValue); Result := TValue.From(Obj); finally FreeAndNil(JsonValue) end; end; procedure TNullableInterceptor.ObjectsReverter(Data: TObject; Field: string; Args: TListOfObjects); var ctx: TRttiContext; RttiType: TRttiType; RttiField, IsNullField: TRttiField; RttiRecord: TRttiRecordType; Attr: TCustomAttribute; IsRequiredFound: boolean; Ptr: Pointer; begin if (Args <> nil) then Exit; ctx := TRttiContext.Create; try RttiType := ctx.GetType(Data.ClassType); RttiField := RttiType.GetField(Field); if (not RttiField.FieldType.IsRecord) then raise Exception.Create('The field marked attribute "JSONNullable" must be a record.'); IsRequiredFound := False; for Attr in RttiField.GetAttributes do begin if Attr is BaseJSONNullableAttribute then IsRequiredFound := True; end; if not IsRequiredFound then raise Exception.Create('This intercepter (TNullableInterceptor) was created not in JSONNullableAttribute.'); RttiRecord := RttiField.FieldType.AsRecord; IsNullField := RttiRecord.GetField(IsNullFieldCaption); Ptr := RttiField.GetValue(Data).GetReferenceToRawData; IsNullField.SetValue(Ptr, TValue.From(True)); finally ctx.Free; end; end; procedure TNullableInterceptor.StringReverter(Data: TObject; Field, Arg: String); var ctx: TRttiContext; RttiType, RttiTypeObject: TRttiType; RttiRecordField, IsNullField, ValueField: TRttiField; RttiMethodObject: TRttiMethod; RttiRecord: TRttiRecordType; RecordValue: TValue; Attr: TCustomAttribute; Ptr: Pointer; Value: TValue; InternalUnMarshal: TInternalJSONUnMarshal; Clazz: TClass; ObjectType: TRttiType; NullableAttribute: BaseJSONNullableAttribute; begin ctx := TRttiContext.Create; InternalUnMarshal := TInternalJSONUnMarshal.Create; try RttiType := ctx.GetType(Data.ClassType); RttiRecordField := RttiType.GetField(Field); if (not RttiRecordField.FieldType.IsRecord) then raise Exception.Create('The field marked attribute "JSONNullable" must be a record.'); RttiRecord := RttiRecordField.FieldType.AsRecord; RecordValue := RttiRecordField.GetValue(Data); Ptr := RecordValue.GetReferenceToRawData; NullableAttribute := nil; for Attr in RttiRecordField.GetAttributes do if Attr is BaseJSONNullableAttribute then NullableAttribute := BaseJSONNullableAttribute(Attr); if (NullableAttribute = nil) then raise Exception.Create('This intercepter (TNullableInterceptor) was created not in JSONNullableAttribute.'); IsNullField := RttiRecord.GetField(IsNullFieldCaption); if (IsNullField <> nil) then IsNullField.SetValue(Ptr, TValue.From(False)) else raise Exception.Create(Format( 'The field marked attribute "JSONNullableAttribute" must have a field "%s: boolean"', [IsNullFieldCaption])); ValueField := RttiRecord.GetField(ValueFieldCaption); if (ValueField <> nil) then begin ObjectType := ValueField.FieldType; if (ObjectType.TypeKind = tkClass) then begin if not (NullableAttribute is NullableObjectAttribute) then raise Exception.Create( 'The field class of "NullableObject" must be marked as "NullableObject" Attribute'); Clazz := NullableObjectAttribute(NullableAttribute).Clazz; RttiTypeObject := ctx.GetType(Clazz); RttiMethodObject := RttiTypeObject.GetMethod('FromJsonString'); if (RttiMethodObject <> nil) then begin Value := RttiMethodObject.Invoke(Clazz, [Arg]); end else Value := GetObjectValue(Arg, Clazz); end else begin if (ObjectType.TypeKind = tkFloat) then Arg := FloatToJson(StrToFloat(Arg, LocaleFormatSettings)); Value := InternalUnMarshal.StringToTValue(Arg, ValueField.FieldType.Handle); end; ValueField.SetValue(Ptr, Value); end else raise Exception.Create(Format( 'The field marked attribute "JSONNullableAttribute" must have a field "%s"', [ValueFieldCaption])); RttiRecordField.SetValue(Data, RecordValue); finally FreeAndNil(InternalUnMarshal); ctx.Free; end; end; initialization {$WARN SYMBOL_PLATFORM OFF} LocaleFormatSettings := TFormatSettings.Create(LOCALE_USER_DEFAULT); {$WARN SYMBOL_PLATFORM ON} end.
unit SoundTypes; interface type ISoundTarget = interface function GetSoundName : string; function GetSoundKind : integer; function GetPriority : integer; function IsLooped : boolean; function GetVolume : single; function GetPan : single; function ShouldPlayNow : boolean; function IsCacheable : boolean; function IsEqualTo(const SoundTarget : ISoundTarget) : boolean; function GetObject : TObject; procedure UpdateSoundParameters; end; type TSoundTargetCheck = function (const Target : ISoundTarget; info : array of const) : boolean; type ISoundManager = interface procedure AddTargets(const Targets : array of ISoundTarget); procedure RemoveTarget(const Target : ISoundTarget); procedure CheckRemoveTargets(Check : TSoundTargetCheck; info : array of const); procedure PlayTarget(const Target : ISoundTarget); procedure UpdateTarget(const Target : ISoundTarget); procedure StopTarget(const Target : ISoundTarget); procedure StartCaching; procedure StopCaching; procedure Clear; procedure PlayCachedSounds; procedure Reset; procedure SetGlobalVolume(volume : single); end; type TSoundInfo = record name : string; kind : integer; priority : integer; looped : boolean; volume : single; // 0 .. 1 pan : single; // -1 .. 1 end; const cLeftPan = -1; cCenterPan = 0; cRightPan = 1; cPanDeadZone = 128; cMinVol = 0.6; // these are acceptable values cMaxVol = 1; cMaxHearDist = 50; cZoomVolStep = 0.25; implementation end.
unit MainClientFormU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Net.HttpClientComponent, Vcl.StdCtrls, System.Net.URLClient, System.Net.HttpClient, Data.DB, Vcl.Grids, Vcl.DBGrids, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ComCtrls, Vcl.ExtCtrls, MVCFramework.JSONRPC.Client; type TMainForm = class(TForm) DataSource1: TDataSource; FDMemTable1: TFDMemTable; FDMemTable1Code: TIntegerField; FDMemTable1Name: TStringField; GroupBox1: TGroupBox; edtValue1: TEdit; edtValue2: TEdit; btnSubstract: TButton; edtResult: TEdit; edtReverseString: TEdit; btnReverseString: TButton; edtReversedString: TEdit; PageControl1: TPageControl; TabSheet1: TTabSheet; CheckBox1: TCheckBox; Edit1: TEdit; Edit2: TEdit; btnSubtractWithNamedParams: TButton; Edit3: TEdit; PageControl2: TPageControl; TabSheet3: TTabSheet; edtFilter: TEdit; edtGetCustomers: TButton; DBGrid1: TDBGrid; procedure btnSubstractClick(Sender: TObject); procedure btnReverseStringClick(Sender: TObject); procedure edtGetCustomersClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSubtractWithNamedParamsClick(Sender: TObject); private const RPC_ENDPOINT = '/myobjectrpc'; var FExecutor: IMVCJSONRPCExecutor; // FExecutor2: IMVCJSONRPCExecutor; public { Public declarations } end; var MainForm: TMainForm; implementation uses System.Generics.Collections, MVCFramework.JSONRPC, MVCFramework.Serializer.JsonDataObjects, JsonDataObjects, MVCFramework.Serializer.Commons, MVCFramework.Commons, MVCFramework.Serializer.Defaults, MVCFramework.DataSet.Utils, // BusinessObjectsU, System.Math, System.Rtti; {$R *.dfm} procedure TMainForm.btnReverseStringClick(Sender: TObject); var lReq: IJSONRPCRequest; lResp: IJSONRPCResponse; begin lReq := TJSONRPCRequest.Create; lReq.Method := 'reversestring'; lReq.RequestID := Random(1000); lReq.Params.AddByName('aString', edtReverseString.Text); lReq.Params.AddByName('aUpperCase', CheckBox1.Checked); lResp := FExecutor.ExecuteRequest(RPC_ENDPOINT, lReq); edtReversedString.Text := lResp.Result.AsString; end; procedure TMainForm.btnSubstractClick(Sender: TObject); var lReq: IJSONRPCRequest; lResp: IJSONRPCResponse; begin lReq := TJSONRPCRequest.Create; lReq.Method := 'subtract'; lReq.RequestID := Random(1000); lReq.Params.Add(StrToInt(edtValue1.Text)); lReq.Params.Add(StrToInt(edtValue2.Text)); lResp := FExecutor.ExecuteRequest(RPC_ENDPOINT, lReq); edtResult.Text := lResp.Result.AsInteger.ToString; end; procedure TMainForm.btnSubtractWithNamedParamsClick(Sender: TObject); var lReq: IJSONRPCRequest; lResp: IJSONRPCResponse; begin lReq := TJSONRPCRequest.Create; lReq.Method := 'subtract'; lReq.RequestID := Random(1000); lReq.Params.AddByName('Value1', StrToInt(Edit1.Text)); lReq.Params.AddByName('Value2', StrToInt(Edit2.Text)); lResp := FExecutor.ExecuteRequest(RPC_ENDPOINT, lReq); Edit3.Text := lResp.Result.AsInteger.ToString; end; procedure TMainForm.edtGetCustomersClick(Sender: TObject); var lReq: IJSONRPCRequest; lResp: IJSONRPCResponse; begin FDMemTable1.Active := False; lReq := TJSONRPCRequest.Create(Random(1000), 'getcustomers'); lReq.Params.AddByName('FilterString', edtFilter.Text); lResp := FExecutor.ExecuteRequest(RPC_ENDPOINT, lReq); FDMemTable1.Active := True; FDMemTable1.LoadFromTValue(lResp.Result); FDMemTable1.First; end; procedure TMainForm.FormCreate(Sender: TObject); begin FExecutor := TMVCJSONRPCExecutor.Create('http://localhost:8080'); end; end.
unit Model.RoteirosExpressas; interface uses Common.ENum, FireDAC.Comp.Client, FireDAC.Comp.DataSet, Data.DB, DAO.Conexao; type TRoteirosExpressas = class private FLogradouro: String; FZona: String; FBairro: String; FDescricao: String; FCliente: Integer; FPrazo: String; FCEPFinal: String; FCEPInicial: String; FID: Integer; FTipo: Integer; FCCEP5: String; FAcao: TAcao; FConexao: TConexao; FCodigoPesado: Integer; FCodigoLeve: Integer; FCheck: SmallInt; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; public property ID: Integer read FID write FID; property CCEP5: String read FCCEP5 write FCCEP5; property Descricao: String read FDescricao write FDescricao; property CEPInicial: String read FCEPInicial write FCEPInicial; property CEPFinal: String read FCEPFinal write FCEPFinal; property Prazo: String read FPrazo write FPrazo; property Zona: String read FZona write FZona; property Tipo: Integer read FTipo write FTipo; property Logradouro: String read FLogradouro write FLogradouro; property Bairro: String read FBairro write FBairro; property Cliente: Integer read FCliente write FCliente; property CodigoLeve: Integer read FCodigoLeve write FCodigoLeve; property CodigoPesado: Integer read FCodigoPesado write FCodigoPesado; property Check: SmallInt read FCheck write FCheck; property Acao: TAcao read FAcao write FAcao; constructor Create; function GetID(): Integer; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function DeleteCliente(iCliente: Integer): Boolean; function SaveData(mtbRoteiro: TFDMemTable): Boolean; function ListRoteiro(): TFDQuery; function SetupModel(fdQuery: TFDQuery): Boolean; end; const TABLENAME = 'expressas_roteiros'; SQLINSERT = 'insert into ' + TABLENAME + '(id_roteiro, cod_ccep5, des_roteiro, num_cep_inicial, num_cep_final, ' + 'des_prazo, dom_zona, cod_tipo, des_logradouro, des_bairro, cod_cliente, cod_leve, cod_pesado, dom_check)' + 'values ' + '(id_roteiro, :cod_ccep5, :des_roteiro, :num_cep_inicial, :num_cep_final, :des_prazo, :dom_zona, :cod_tipo, '+ ':des_logradouro, :des_bairro, :cod_cliente, :cod_leve, :cod_pesado, :dom_check);'; SQLUPDATE = 'update ' + TABLENAME + ' set cod_ccep5 = :cod_ccep5, des_roteiro = :des_roteiro, ' + 'num_cep_inicial = :num_cep_inicial, num_cep_final = :num_cep_final, des_prazo = :des_prazo, ' + 'dom_zona = :dom_zona, cod_tipo = :cod_tipo, des_logradouro = :des_logradouro, ' + 'des_bairro = :des_bairro, cod_cliente = :cod_cliente, cod_leve = :cod_leve, cod_pesado = :cod_pesado, ' + 'dom_check = :dom_check ' + 'where id_roteiro = :id_roteiro;'; implementation { TRoteirosExpressas } uses Control.Sistema; function TRoteirosExpressas.Alterar: Boolean; var fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery(); fdQuery.ExecSQL(SQLUPDATE, [FCCEP5, FDescricao,FCEPInicial, FCEPFinal, FPrazo, FZona, FTipo, FLogradouro, FBairro, FCliente, FCodigoLeve, FCodigoPesado, FCheck, FID]); Result := True; finally fdQuery.Connection.Close; fdQuery.Free; end; end; constructor TRoteirosExpressas.Create; begin FConexao := TConexao.Create; end; function TRoteirosExpressas.DeleteCliente(iCliente: Integer): Boolean; var fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery(); if iCliente > 0 then begin fdQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_cliente = :cod_cliente', [iCliente]); end else begin fdQuery.ExecSQL('delete from ' + TABLENAME); end; Result := True; finally fdQuery.Connection.Close; fdquery.Free; end; end; function TRoteirosExpressas.Excluir: Boolean; var fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery(); fdQuery.ExecSQL('delete from ' + TABLENAME + ' where id_roteiro = :id_roteiro', [FID]); Result := True; finally fdQuery.Connection.Close; fdquery.Free; end; end; function TRoteirosExpressas.GetID: Integer; var fdQuery: TFDQuery; begin try fdQuery := FConexao.ReturnQuery(); fdQuery.Open('select coalesce(max(id_roteiro),0) + 1 from ' + TABLENAME); try Result := fdQuery.Fields[0].AsInteger; finally fdQuery.Close; end; finally fdQuery.Connection.Close; fdQuery.Free; end; end; function TRoteirosExpressas.Gravar: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Inserir(); Common.ENum.tacAlterar: Result := Alterar(); Common.ENum.tacExcluir: Result := Excluir(); end; end; function TRoteirosExpressas.Inserir: Boolean; var fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery(); //FID := FGetID(); fdQuery.ExecSQL(SQLINSERT, [FCCEP5, FDescricao,FCEPInicial, FCEPFinal, FPrazo, FZona, FTipo, FLogradouro, FBairro, FCliente, FcodigoLeve, FCodigoPesado, FCheck]); Result := True; finally fdQuery.Connection.Close; fdQuery.Free; end; end; function TRoteirosExpressas.ListRoteiro: TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Clear; FDQuery.SQL.Add('select distinct des_roteiro from ' + TABLENAME); FDQuery.Open; Result := FDQuery; end; function TRoteirosExpressas.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('where id_roteiro = :id_roteiro'); FDQuery.ParamByName('id_roteiro').AsInteger := aParam[1]; end else if aParam[0] = 'CEP' then begin if Length(aParam) = 2 then begin FDQuery.SQL.Add('where num_cep_inicial = :num_cep'); FDQuery.ParamByName('num_cep').AsString := aParam[1]; end else begin if Length(aParam) = 3 then FDQuery.SQL.Add('where num_cep_inicial >= :num_cep'); FDQuery.ParamByName('num_cep').AsString := aParam[1]; FDQuery.SQL.Add(' and num_cep_final <= :num_cep_1'); FDQuery.ParamByName('num_cep_1').AsString := aParam[2]; end; end else if aParam[0] = 'CEPCLIENTE' then begin FDQuery.SQL.Add('where num_cep_inicial = :num_cep and cod_cliente = :cod_cliente'); FDQuery.ParamByName('num_cep').AsString := aParam[1]; FDQuery.ParamByName('cod_cliente').AsInteger := aParam[2]; FDQuery.ParamByName('cod_tipo').AsInteger := aParam[3]; end else if aParam[0] = 'LEVE' then begin FDQuery.SQL.Add('where cod_leve = :cod_leve and cod_cliente = :cod_cliente'); FDQuery.ParamByName('cod_leve').AsInteger := aParam[1]; FDQuery.ParamByName('cod_cliente').AsInteger := aParam[2]; end else if aParam[0] = 'PESADO' then begin FDQuery.SQL.Add('where cod_pesado = :cod_pesado and cod_cliente = :cod_cliente'); FDQuery.ParamByName('cod_pesado').AsInteger := aParam[1]; FDQuery.ParamByName('cod_cliente').AsInteger := aParam[2]; end else if aParam[0] = 'CCEP5' then begin FDQuery.SQL.Add('where cod_ccep5 = :cod_ccep5'); FDQuery.ParamByName('cod_ccep5').AsString := aParam[1]; end else if aParam[0] = 'LOGRADOURO' then begin FDQuery.SQL.Add('where des_descricao_sem_numero like :des_descricao_sem_numero'); FDQuery.ParamByName('des_descricao_sem_numero').AsString := aParam[1]; end else if aParam[0] = 'ROTEIRO' then begin FDQuery.SQL.Add('where des_roteiro like :des_roteiro'); FDQuery.ParamByName('des_roteiro').AsString := aParam[1]; end else if aParam[0] = 'CLIENTE' then begin FDQuery.SQL.Add('where cod_cliente = :cod_cliente'); FDQuery.ParamByName('cod_cliente').AsInteger := aParam[1]; end else if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end else if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; function TRoteirosExpressas.SaveData(mtbRoteiro: TFDMemTable): Boolean; var fdQuery : TFDQuery; icounter : Integer; begin try Result := False; fdQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery(); fdQuery.SQL.Text := SQLINSERT; if not mtbRoteiro.IsEmpty then mtbRoteiro.First; icounter := 0; while not mtbRoteiro.Eof do begin FDQuery.Params.ArraySize := icounter + 1; FDQuery.ParamByName('id_roteiro').AsIntegers[icounter] := mtbRoteiro.FieldByName('id_roteiro').AsInteger; FDQuery.ParamByName('cod_ccep5').AsStrings[icounter] := mtbRoteiro.FieldByName('cod_ccep5').AsString; FDQuery.ParamByName('des_roteiro').AsStrings[icounter] := mtbRoteiro.FieldByName('des_roteiro').AsString; FDQuery.ParamByName('num_cep_inicial').AsStrings[icounter] := mtbRoteiro.FieldByName('num_cep_inicial').AsString; FDQuery.ParamByName('num_cep_final').AsStrings[icounter] := mtbRoteiro.FieldByName('num_cep_final').AsString; FDQuery.ParamByName('num_cep_final').AsStrings[icounter] := mtbRoteiro.FieldByName('des_prazo').AsString; FDQuery.ParamByName('dom_zona').AsStrings[icounter] := mtbRoteiro.FieldByName('dom_zona').AsString; FDQuery.ParamByName('cod_tipo').AsIntegers[icounter] := mtbRoteiro.FieldByName('cod_tipo').AsInteger; FDQuery.ParamByName('des_logradouro').AsStrings[icounter] := mtbRoteiro.FieldByName('des_logradouro').AsString; FDQuery.ParamByName('des_bairro').AsStrings[icounter] := mtbRoteiro.FieldByName('des_bairro').AsString; FDQuery.ParamByName('cod_cliente').AsIntegers[icounter] := mtbRoteiro.FieldByName('cod_cliente').AsInteger; FDQuery.ParamByName('cod_leve').AsIntegers[icounter] := mtbRoteiro.FieldByName('cod_leve').AsInteger; FDQuery.ParamByName('cod_pesado').AsIntegers[icounter] := mtbRoteiro.FieldByName('cod_pesado').AsInteger; FDQuery.ParamByName('dom_check').AsSmallInts[icounter] := mtbRoteiro.FieldByName('dom_check').AsInteger; Inc(icounter); mtbRoteiro.Next; end; FDQuery.Execute(mtbRoteiro.RecordCount, 0); if not mtbRoteiro.IsEmpty then mtbRoteiro.First; Result := True; finally fdQuery.Connection.Close; fdQuery.Free; end; end; function TRoteirosExpressas.SetupModel(fdQuery: TFDQuery): Boolean; begin try Result := False; FID := fdQuery.FieldByName('id_roteiro').AsInteger; FCCEP5 := fdQuery.FieldByName('cod_ccep5').AsString; FDescricao := fdQuery.FieldByName('des_roteiro').AsString; FCEPInicial := fdQuery.FieldByName('num_cep_inicial').AsString; FCEPFinal := fdQuery.FieldByName('num_cep_final').AsString; FPrazo := fdQuery.FieldByName('num_cep_final').AsString; FZona := fdQuery.FieldByName('dom_zona').AsString; FTipo := fdQuery.FieldByName('cod_tipo').AsInteger; FLogradouro := fdQuery.FieldByName('des_logradouro').AsString; FBairro := fdQuery.FieldByName('des_bairro').AsString; FCliente := fdQuery.FieldByName('cod_cliente').AsInteger; FCodigoLeve := fdQuery.FieldByName('cod_leve').AsInteger; FCodigoPesado := fdQuery.FieldByName('cod_pesado').AsInteger; FCheck := fdQuery.FieldByName('dom_check').AsInteger; finally Result := True; end; end; end.
unit uMainDataModule; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sqlite3conn, sqldb, DB, strutils; type { TDM } TDM = class(TDataModule) DataSource1: TDataSource; SQLite3Connection1: TSQLite3Connection; updateSQLQuery: TSQLQuery; SQLQueryCount: TSQLQuery; SQLQueryResult: TSQLQuery; SQLTransaction: TSQLTransaction; tableExistsSQLQuery: TSQLQuery; insertSQLQuery: TSQLQuery; deleteByPathSQLQuery: TSQLQuery; deleteByTagSQLQuery: TSQLQuery; private FDBPath: string; function getDirectory(aPath: string): string; procedure SetDBPath(AValue: string); function TableExists(aTableName: string): boolean; public Constructor Create(AOwner: TComponent); override; function getPath: string; function getDir: string; function getCommand: string; function getIcon: String; function getItemName: string; function isAnnex: boolean; procedure DBSearch(const aSearchTerm, aPath, aTag: string); property DBPath: string read FDBPath write SetDBPath; end; var DM: TDM; implementation Uses sqlite3; {$R *.lfm} { TDM } Function TDM.getPath: string; var lPath: String; begin lPath := SQLQueryResult.FieldByName('path').AsString; if lPath[1] <> '#' then Result := lPath else Result := ''; end; Function TDM.getDir: string; begin Result := getDirectory(SQLQueryResult.FieldByName('path').AsString); end; Function TDM.getDirectory(aPath: string): string; var isDir: boolean; begin Result := aPath; isDir := DirectoryExists(Result); if not isDir then begin Result := ExtractFilePath(Result); isDir := DirectoryExists(Result); end; if not isDir then Result := ''; end; Procedure TDM.SetDBPath(AValue: string); begin if FDBPath = AValue then Exit; FDBPath := AValue; SQLite3Connection1.Close(); SQLite3Connection1.DatabaseName := FDBPath; SQLite3Connection1.Open; // create database structure if not exists SQLite3Connection1.Transaction.Active := True; SQLite3Connection1.ExecuteDirect('CREATE TABLE IF NOT EXISTS sources (id PRIMARY KEY, path NOT NULL, name NOT NULL, search NOT NULL, command, updated, tag NOT NULL, priority NOT NULL, trash, annex NOT NULL, description, icon)'); SQLite3Connection1.ExecuteDirect('CREATE INDEX IF NOT EXISTS tagIndex ON sources (tag)'); SQLite3Connection1.ExecuteDirect('CREATE INDEX IF NOT EXISTS trashIndex ON sources (trash)'); if not TableExists('sourcesSearch') then SQLite3Connection1.ExecuteDirect('CREATE VIRTUAL TABLE sourcesSearch USING FTS4(id, search)'); SQLite3Connection1.ExecuteDirect('CREATE TRIGGER IF NOT EXISTS insert_sources AFTER INSERT ON sources' + ' BEGIN' + ' INSERT INTO sourcesSearch (id, search) values (new.id, new.search);' + ' END;'); SQLite3Connection1.ExecuteDirect('create trigger IF NOT EXISTS check_unique_source before insert on sources' + ' begin' + ' update or Ignore sources set trash = 0 where path = new.path and tag = new.tag;' + ' select RAISE(ignore) from sources where path = new.path and tag = new.tag;' + ' end'); SQLite3Connection1.ExecuteDirect('create unique index if not exists sourcesUniq on sources (path, tag)'); SQLite3Connection1.ExecuteDirect('create unique index if not exists sourcesUniq2 on sources (id, trash, tag)'); SQLite3Connection1.ExecuteDirect('create index if not exists sourcesTrashTag on sources (trash, tag)'); SQLite3Connection1.Transaction.Commit; DM.SQLite3Connection1.ExecuteDirect('End Transaction'); // End the transaction started by SQLdb SQLite3Connection1.ExecuteDirect('PRAGMA synchronous=OFF'); // SQLite3Connection1.ExecuteDirect('PRAGMA cache_size = -' + IntToStr(1024*1024*2)); // 2GB // SQLite3Connection1.ExecuteDirect('PRAGMA journal_mode=MEMORY'); // SQLite3Connection1.ExecuteDirect('PRAGMA temp_store=2'); // SQLite3Connection1.ExecuteDirect('PRAGMA PAGE_SIZE=4096'); DM.SQLite3Connection1.ExecuteDirect('Begin Transaction'); //Start a transaction for SQLdb to use end; Function TDM.TableExists(aTableName: string): boolean; begin tableExistsSQLQuery.Close; tableExistsSQLQuery.ParamByName('tableName').Value := aTableName; tableExistsSQLQuery.Open; Result := tableExistsSQLQuery.FieldByName('cnt').AsInteger > 0; end; procedure SqlReverse(ctx: psqlite3_context; N: LongInt; V: ppsqlite3_value); cdecl; var S: String; begin SetString(S, sqlite3_value_text(V[0]), sqlite3_value_bytes(V[0])); S := ReverseString(S); sqlite3_result_text(ctx, PAnsiChar(S), Length(S), sqlite3_destructor_type(SQLITE_TRANSIENT)); End; Constructor TDM.Create(AOwner: TComponent); Begin Inherited Create(AOwner); sqlite3_create_function(SQLite3Connection1.Handle, 'reverse', 1, SQLITE_UTF8, nil, @SqlReverse, nil, nil); End; Function TDM.getCommand: string; begin Result := SQLQueryResult.FieldByName('command').AsString; end; Function TDM.getIcon: String; Var lTag, lIconName: String; Begin Result := SQLQueryResult.FieldByName('icon').AsString; if Result = '' then begin lTag := SQLQueryResult.FieldByName('tag').AsString; if lTag <> '' then begin lIconName := GetEnvironmentVariable('HOME') + '/.mlocate.icons/' + lTag + '.png'; if FileExists(lIconName) then Result := lIconName; End; End; if Result = '' then Result := 'NOICON'; End; Function TDM.getItemName: string; Begin Result := SQLQueryResult.FieldByName('name').AsString; End; Function TDM.isAnnex: boolean; Begin Result := SQLQueryResult.FieldByName('annex').AsBoolean; End; Procedure TDM.DBSearch(Const aSearchTerm, aPath, aTag: string); var lSelect: string; lWhere: string; begin lWhere := ' trash = 0 '; if aSearchTerm <> '' then lWhere := lWhere + ' and id in (select id from sourcesSearch where search MATCH ''' + aSearchTerm + ''') '; if aPath <> '' then lWhere := lWhere + ' and path like ''' + aPath + '%'' '; if aTag <> '' then lWhere := lWhere + ' and tag = ''' + aTag + ''' '; //lWhere := lWhere + ' and trash = 0 '; lWhere := lWhere + ' order by priority, name, path'; lSelect := 'select * from sources where ' + lWhere; DM.SQLQueryResult.Close; DM.SQLQueryResult.SQL.Text := lSelect; DM.SQLQueryResult.Open; DM.SQLQueryCount.Close; DM.SQLQueryCount.SQL.Text := 'select count(*) as cnt from sources where ' + lWhere; DM.SQLQueryCount.Open; end; end.
Unit H2Listview; Interface Uses Messages,Windows, Classes,Controls, ExtCtrls, SysUtils,GR32_Image,GR32,gr32_layers,Graphics ,ComCtrls,XMLDoc,XMLIntf; Type TH2ListView = Class(TControl) Private fx, fy, fwidth, fheight:Integer; fvisible:Boolean; ffont:tfont; fbitmap:tbitmaplayer; fdrawmode:tdrawmode; falpha:Cardinal; ftree:ttreeview; Procedure SetFont(font:tfont); Procedure Setvisible(value:Boolean); Procedure Tree2XML(tree: TTreeView;filename:String); Procedure XML2Tree(tree : TTreeView;XMLDoc : TXMLDocument); Public Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Published Property Font:tfont Read ffont Write setfont; Property Alpha:Cardinal Read falpha Write falpha; Property DrawMode:tdrawmode Read fdrawmode Write fdrawmode; Property X:Integer Read fx Write fx; Property Y:Integer Read fy Write fy; Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap; Property Visible:Boolean Read fvisible Write setvisible; Property OnMouseDown; End; Implementation { TH2ListView } Constructor TH2ListView.Create(AOwner: TComponent); Var L: TFloatRect; alayer:tbitmaplayer; Begin Inherited Create(AOwner); fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers); ffont:=tfont.Create; fdrawmode:=dmblend; falpha:=255; fvisible:=True; fx:=0; fy:=0; fwidth:=100; fheight:=100; fbitmap.Bitmap.Width:=fwidth; fbitmap.Bitmap.Height:=fheight; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Tag:=0; fbitmap.Bitmap.DrawMode:=fdrawmode; fbitmap.Bitmap.MasterAlpha:=falpha; fvisible:=True; End; Destructor TH2ListView.Destroy; Begin //here ffont.Free; fbitmap.Free; Inherited Destroy; End; Procedure TH2ListView.SetFont(font: tfont); Begin ffont.Assign(font); End; Procedure TH2ListView.Setvisible(value: Boolean); Begin fbitmap.Visible:=value; End; Procedure TH2ListView.Tree2XML(tree: TTreeView;filename:String); Var tn : TTreeNode; XMLDoc : TXMLDocument; iNode : IXMLNode; Procedure ProcessTreeItem( tn : TTreeNode; iNode : IXMLNode); Var cNode : IXMLNode; Begin If (tn = Nil) Then Exit; cNode := iNode.AddChild('item'); cNode.Attributes['text'] := tn.Text; cNode.Attributes['imageIndex'] := tn.ImageIndex; cNode.Attributes['stateIndex'] := tn.StateIndex; //child nodes tn := tn.getFirstChild; While tn <> Nil Do Begin ProcessTreeItem(tn, cNode); tn := tn.getNextSibling; End; End; (*ProcessTreeItem*) Begin XMLDoc := TXMLDocument.Create(Nil); XMLDoc.Active := True; iNode := XMLDoc.AddChild('tree2xml'); iNode.Attributes['app'] := 'Hydrogen'; tn := tree.TopItem; While tn <> Nil Do Begin ProcessTreeItem (tn, iNode); tn := tn.getNextSibling; End; XMLDoc.SaveToFile(filename); XMLDoc := Nil; End; (* Tree2XML *) Procedure TH2ListView.XML2Tree(tree : TTreeView;XMLDoc : TXMLDocument); Var iNode : IXMLNode; Procedure ProcessNode( Node : IXMLNode; tn : TTreeNode); Var cNode : IXMLNode; Begin If Node = Nil Then Exit; With Node Do Begin tn := tree.Items.AddChild(tn, Attributes['text']); tn.ImageIndex := Integer(Attributes['imageIndex']); tn.StateIndex := Integer(Attributes['stateIndex']); End; cNode := Node.ChildNodes.First; While cNode <> Nil Do Begin ProcessNode(cNode, tn); cNode := cNode.NextSibling; End; End; (*ProcessNode*) Begin tree.Items.Clear; XMLDoc.FileName := ChangeFileExt(ParamStr(0),'.XML'); XMLDoc.Active := True; iNode := XMLDoc.DocumentElement.ChildNodes.First; While iNode <> Nil Do Begin ProcessNode(iNode,Nil); iNode := iNode.NextSibling; End; XMLDoc.Active := False; End; End.
unit Feature; interface uses FeatureIntf, Classes, dCucuberListIntf; type TFeature = class(TInterfacedObject, IFeature) private FScenarios: ICucumberList; FDescricao: string; FTitulo: string; function GetScenarios: ICucumberList; function GetDescricao: string; function GetTitulo: string; procedure SetDescricao(const Value: string); procedure SetTitulo(const Value: string); public constructor Create; function Valid: Boolean; property Scenarios: ICucumberList read GetScenarios; property Descricao: string read GetDescricao write SetDescricao; property Titulo: string read GetTitulo write SetTitulo; end; implementation uses dCucuberList, ScenarioIntf, ValidationRuleIntf; constructor TFeature.Create; begin FScenarios := TCucumberList.Create; FScenarios.ValidationRule.ValidateFunction := function: Boolean var I: Integer; begin Result := FScenarios.Count > 0; if Result then for I := 0 to FScenarios.Count - 1 do begin Result := (FScenarios[i] as IValidationRule).Valid; if not Result then Exit; end; end; end; function TFeature.GetScenarios: ICucumberList; begin Result := FScenarios; end; function TFeature.GetDescricao: string; begin Result := FDescricao; end; function TFeature.GetTitulo: string; begin Result := FTitulo; end; procedure TFeature.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TFeature.SetTitulo(const Value: string); begin FTitulo := Value; end; function TFeature.Valid: Boolean; begin Result := FScenarios.ValidationRule.Valid; end; end.
unit TrainingDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, MarqueeCtrl, FramedButton, VoyagerInterfaces, VoyagerServerInterfaces; type TTrainingDlg = class(TForm) CloseBtn: TFramedButton; HintText: TMarquee; Shape1: TShape; btCreate: TFramedButton; btCancel: TFramedButton; Label13: TLabel; procedure edTeamNameChange(Sender: TObject); procedure btCreateClick(Sender: TObject); procedure btCancelClick(Sender: TObject); private fClientView : IClientView; fMasterURLHandler : IMasterURLHandler; fIllSystem : olevariant; fCriminalName : string; public property ClientView : IClientView write fClientView; property MasterURLHandler : IMasterURLHandler write fMasterURLHandler; property IllSystem : olevariant write fIllSystem; property CriminalName : string write fCriminalName; private procedure threadedNewTeam( const parms : array of const ); procedure syncNewTeam( const parms : array of const ); end; var TrainingDlg: TTrainingDlg; implementation {$R *.DFM} uses Threads; procedure TTrainingDlg.edTeamNameChange(Sender: TObject); begin btCreate.Enabled := edTeamName.Text <> ''; pnError.Visible := false; end; procedure TTrainingDlg.btCreateClick(Sender: TObject); begin Fork( threadedNewTeam, priNormal, [edTeamName.Text] ); end; procedure TTrainingDlg.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TTrainingDlg.threadedNewTeam( const parms : array of const ); var name : string absolute parms[0].vPChar; begin try if fIllSystem.RDOCreateTeam( fCriminalName, name ) <> 'no' then Join( syncNewTeam, [0] ) else Join( syncNewTeam, [1] ); except end; end; procedure TTrainingDlg.syncNewTeam( const parms : array of const ); var ErrorCode : integer absolute parms[0].vInteger; begin case ErrorCode of 0 : ModalResult := mrOk; else begin pnError.Caption := GetLiteral('Literal177'); pnError.Visible := true; end; end; end; end.
unit nsNewCachableNode; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\Tree\nsNewCachableNode.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsNewCachableNode" MUID: (490AF9B0039B) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , l3NodesModelPart , DynamicTreeUnit , l3Tree_TLB , l3Interfaces , l3IID , l3TreeInterfaces ; type TnsNewCachableNode = class(Tl3PlaceNode) private f_AdapterNode: INodeBase; protected procedure Cleanup; override; {* Функция очистки полей объекта. } function GetAsPCharLen: Tl3WString; override; function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } function DoGetLevel: Integer; override; function GetIsSame(const aNode: Il3SimpleNode): Boolean; override; procedure ClearFields; override; public constructor Create(const aNode: INodeBase); reintroduce; class function Make(const aNode: INodeBase): Il3Node; reintroduce; protected property AdapterNode: INodeBase read f_AdapterNode; end;//TnsNewCachableNode implementation uses l3ImplUses , nsTypes , IOUnit , SysUtils , l3InterfacesMisc {$If NOT Defined(NoScripts)} , InterfacedNodeWords {$IfEnd} // NOT Defined(NoScripts) //#UC START# *490AF9B0039Bimpl_uses* //#UC END# *490AF9B0039Bimpl_uses* ; constructor TnsNewCachableNode.Create(const aNode: INodeBase); //#UC START# *4AE058130153_490AF9B0039B_var* //#UC END# *4AE058130153_490AF9B0039B_var* begin //#UC START# *4AE058130153_490AF9B0039B_impl* inherited Create; f_AdapterNode := aNode; //#UC END# *4AE058130153_490AF9B0039B_impl* end;//TnsNewCachableNode.Create class function TnsNewCachableNode.Make(const aNode: INodeBase): Il3Node; var l_Inst : TnsNewCachableNode; begin l_Inst := Create(aNode); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnsNewCachableNode.Make procedure TnsNewCachableNode.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_490AF9B0039B_var* //#UC END# *479731C50290_490AF9B0039B_var* begin //#UC START# *479731C50290_490AF9B0039B_impl* f_AdapterNode := nil; inherited; //#UC END# *479731C50290_490AF9B0039B_impl* end;//TnsNewCachableNode.Cleanup function TnsNewCachableNode.GetAsPCharLen: Tl3WString; //#UC START# *47A869BB02DE_490AF9B0039B_var* var l_Str: IString; //#UC END# *47A869BB02DE_490AF9B0039B_var* begin //#UC START# *47A869BB02DE_490AF9B0039B_impl* if (f_AdapterNode <> nil) then f_AdapterNode.GetCaption(l_Str) else l_Str := nil; Result := nsWStr(l_Str); //#UC END# *47A869BB02DE_490AF9B0039B_impl* end;//TnsNewCachableNode.GetAsPCharLen function TnsNewCachableNode.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {* Реализация запроса интерфейса } //#UC START# *4A60B23E00C3_490AF9B0039B_var* //#UC END# *4A60B23E00C3_490AF9B0039B_var* begin //#UC START# *4A60B23E00C3_490AF9B0039B_impl* Result := inherited COMQueryInterface(IID, Obj); if Result.Fail then begin if (f_AdapterNode = nil) then Result.SetNOINTERFACE else Result := Tl3HResult_C(f_AdapterNode.QueryInterface(IID.IID, Obj)); end;//l3IFail(Result) //#UC END# *4A60B23E00C3_490AF9B0039B_impl* end;//TnsNewCachableNode.COMQueryInterface function TnsNewCachableNode.DoGetLevel: Integer; //#UC START# *54C78D4603D6_490AF9B0039B_var* //#UC END# *54C78D4603D6_490AF9B0039B_var* begin //#UC START# *54C78D4603D6_490AF9B0039B_impl* if (f_AdapterNode = nil) then Result := 0 else Result := f_AdapterNode.GetLevel; //#UC END# *54C78D4603D6_490AF9B0039B_impl* end;//TnsNewCachableNode.DoGetLevel function TnsNewCachableNode.GetIsSame(const aNode: Il3SimpleNode): Boolean; //#UC START# *54C78D9201B9_490AF9B0039B_var* var l_AdapterNode: INodeBase; //#UC END# *54C78D9201B9_490AF9B0039B_var* begin //#UC START# *54C78D9201B9_490AF9B0039B_impl* Result := l3IEQ(Self, aNode); if not Result then begin if Supports(aNode, INodeBase, l_AdapterNode) then try Result := l_AdapterNode.IsSameNode(f_AdapterNode); finally l_AdapterNode := nil; end;//try..finally end;//not Result //#UC END# *54C78D9201B9_490AF9B0039B_impl* end;//TnsNewCachableNode.GetIsSame procedure TnsNewCachableNode.ClearFields; begin f_AdapterNode := nil; inherited; end;//TnsNewCachableNode.ClearFields end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.CloudStorage.Provider.Azure Description : CloudStorage Azure provider Author : Kike Pérez Version : 1.8 Created : 14/10/2018 Modified : 07/10/2019 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.CloudStorage.Provider.Azure; {$i QuickLib.inc} interface uses Classes, System.SysUtils, System.Generics.Collections, IPPeerClient, Quick.Commons, Quick.CloudStorage, Data.Cloud.CloudAPI, Data.Cloud.AzureAPI; type TCloudStorageAzureProvider = class(TCloudStorageProvider) private fAzureConnection : TAzureConnectionInfo; fAzureID : string; fAzureKey : string; procedure SetSecure(aValue: Boolean); override; function ListContainers(azContainersStartWith : string; azResponseInfo : TResponseInfo) : TStrings; public constructor Create; overload; override; constructor Create(const aAccountName, aAccountKey : string); overload; destructor Destroy; override; function GetRootFolders : TStrings; override; procedure OpenDir(const aPath : string); override; function GetFile(const aPath: string; out stream : TStream) : Boolean; override; function GetURL(const aPath : string) : string; override; end; implementation { TCloudExplorerProvider } constructor TCloudStorageAzureProvider.Create; begin fAzureConnection := TAzureConnectionInfo.Create(nil); end; constructor TCloudStorageAzureProvider.Create(const aAccountName, aAccountKey : string); begin inherited Create; Create; fAzureID := aAccountName; fAzureKey := aAccountKey; fAzureConnection.AccountName := aAccountName; fAzureConnection.AccountKey := aAccountKey; end; destructor TCloudStorageAzureProvider.Destroy; begin if Assigned(fAzureConnection) then fAzureConnection.Free; inherited; end; function TCloudStorageAzureProvider.GetFile(const aPath: string; out stream : TStream) : Boolean; var BlobService : TAzureBlobService; CloudResponseInfo : TCloudResponseInfo; begin BlobService := TAzureBlobService.Create(fAzureConnection); try CloudResponseInfo := TCloudResponseInfo.Create; try Result := BlobService.GetBlob(RootFolder,aPath,stream,'',CloudResponseInfo); if not Result then raise Exception.CreateFmt('Cloud error %d : %s',[CloudResponseInfo.StatusCode,CloudResponseInfo.StatusMessage]); finally CloudResponseInfo.Free; end; finally BlobService.Free; end; end; function TCloudStorageAzureProvider.GetRootFolders: TStrings; var respinfo : TResponseInfo; begin Result := ListContainers('',respinfo); end; function TCloudStorageAzureProvider.GetURL(const aPath: string): string; begin Result := Format('https://%s.blob.core.windows.net/%s/%s',[fAzureConnection.AccountName,RootFolder,aPath]); end; function TCloudStorageAzureProvider.ListContainers(azContainersStartWith : string; azResponseInfo : TResponseInfo) : TStrings; var BlobService : TAzureBlobService; CloudResponseInfo : TCloudResponseInfo; cNextMarker : string; AzParams : TStrings; AzContainer : TAzureContainer; AzContainers : TList<TAzureContainer>; begin Result := TStringList.Create; cNextMarker := ''; BlobService := TAzureBlobService.Create(fAzureConnection); CloudResponseInfo := TCloudResponseInfo.Create; try BlobService.Timeout := Timeout; repeat AzParams := TStringList.Create; try if azContainersStartWith <> '' then AzParams.Values['prefix'] := azContainersStartWith; if cNextMarker <> '' then AzParams.Values['marker'] := cNextMarker; AzContainers := BlobService.ListContainers(cNextMarker,AzParams,CloudResponseInfo); try azResponseInfo.Get(CloudResponseInfo); if (azResponseInfo.StatusCode = 200) and (Assigned(AzContainers)) then begin for AzContainer in AzContainers do begin Result.Add(AzContainer.Name); end; end; finally if Assigned(AzContainer) then begin //frees ContainerList objects for AzContainer in AzContainers do AzContainer.Free; AzContainers.Free; end; end; finally AzParams.Free; end; until (cNextMarker = '') or (azResponseInfo.StatusCode <> 200); finally BlobService.Free; CloudResponseInfo.Free; end; end; {$IFDEF DELPHITOKYO_UP} procedure TCloudStorageAzureProvider.OpenDir(const aPath: string); var BlobService : TAzureBlobService; azBlob : TAzureBlobItem; DirItem : TCloudItem; CloudResponseInfo : TCloudResponseInfo; cNextMarker : string; azBlobList : TArray<TAzureBlobItem>; blobprefix : TArray<string>; xmlresp : string; azResponseInfo : TResponseInfo; azContainer : string; folder : string; prop : TPair<string,string>; begin Status := stSearching; cNextMarker := ''; if aPath = '..' then begin CurrentPath := RemoveLastPathSegment(CurrentPath); end else begin if (CurrentPath = '') or (aPath.StartsWith('/')) then CurrentPath := aPath else CurrentPath := CurrentPath + aPath; end; if Assigned(OnBeginReadDir) then OnBeginReadDir(CurrentPath); if CurrentPath.StartsWith('/') then CurrentPath := Copy(CurrentPath,2,CurrentPath.Length); if (not CurrentPath.IsEmpty) and (not CurrentPath.EndsWith('/')) then CurrentPath := CurrentPath + '/'; azContainer := RootFolder; if azContainer = '' then azContainer := '$root'; BlobService := TAzureBlobService.Create(fAzureConnection); try BlobService.Timeout := Timeout; Status := stRetrieving; if Assigned(OnGetListItem) then begin DirItem := TCloudItem.Create; try DirItem.Name := '..'; DirItem.IsDir := True; DirItem.Date := 0; OnGetListItem(DirItem); finally DirItem.Free; end; end; repeat if not (Status in [stSearching,stRetrieving]) then Exit; if fCancelOperation then begin fCancelOperation := False; Exit; end; CloudResponseInfo := TCloudResponseInfo.Create; try azBlobList := BlobService.ListBlobs(azContainer,CurrentPath,'/',cNextMarker,100,[],cNextMarker,blobprefix,xmlresp,CloudResponseInfo); azResponseInfo.Get(CloudResponseInfo); if azResponseInfo.StatusCode = 200 then begin //get folders (prefix) for folder in blobprefix do begin if not (Status in [stSearching,stRetrieving]) then Exit; DirItem := TCloudItem.Create; try if folder.EndsWith('/') then DirItem.Name := RemoveLastChar(folder) else DirItem.Name := folder; DirItem.Name := Copy(DirItem.Name,DirItem.Name.LastDelimiter('/')+2,DirItem.Name.Length); DirItem.IsDir := True; if Assigned(OnGetListItem) then OnGetListItem(DirItem); finally DirItem.Free; end; end; //get files (blobs) for azBlob in azBlobList do begin if not (Status in [stSearching,stRetrieving]) then Exit; if fCancelOperation then begin fCancelOperation := False; Exit; end; DirItem := TCloudItem.Create; try DirItem.Name := azBlob.Name; if DirItem.Name.StartsWith(CurrentPath) then DirItem.Name := StringReplace(DirItem.Name,CurrentPath,'',[]); if DirItem.Name.Contains('/') then begin DirItem.IsDir := True; DirItem.Name := Copy(DirItem.Name,1,DirItem.Name.IndexOf('/')); end else begin DirItem.IsDir := False; for prop in azBlob.Properties do begin if prop.Key = 'Content-Length' then DirItem.Size := StrToInt64Def(prop.Value,0) else if prop.Key = 'Last-Modified' then DirItem.Date := GMT2DateTime(prop.Value); end; end; if Assigned(OnGetListItem) then OnGetListItem(DirItem); finally DirItem.Free; end; end; end else begin Status := stFailed; Exit; end; finally CloudResponseInfo.Free; end; if Assigned(OnRefreshReadDir) then OnRefreshReadDir(CurrentPath); until (cNextMarker = '') or (azResponseInfo.StatusCode <> 200); Status := stDone; finally BlobService.Free; if Assigned(OnEndReadDir) then OnEndReadDir(CurrentPath); end; end; {$ELSE} procedure TCloudStorageAzureProvider.OpenDir(const aPath: string); var BlobService : TAzureBlobService; azBlob : TAzureBlob; DirItem : TCloudItem; CloudResponseInfo : TCloudResponseInfo; cNextMarker : string; azBlobList : TList<TAzureBlob>; AzParams : TStrings; azResponseInfo : TResponseInfo; azContainer : string; begin Status := stSearching; cNextMarker := ''; if aPath = '..' then begin CurrentPath := RemoveLastPathSegment(CurrentPath); end else begin if (CurrentPath = '') or (aPath.StartsWith('/')) then CurrentPath := aPath else CurrentPath := CurrentPath + aPath; end; if Assigned(OnBeginReadDir) then OnBeginReadDir(CurrentPath); if CurrentPath.StartsWith('/') then CurrentPath := Copy(CurrentPath,2,CurrentPath.Length); if (not CurrentPath.IsEmpty) and (not CurrentPath.EndsWith('/')) then CurrentPath := CurrentPath + '/'; azContainer := RootFolder; if azContainer = '' then azContainer := '$root'; BlobService := TAzureBlobService.Create(fAzureConnection); try BlobService.Timeout := Timeout; Status := stRetrieving; if Assigned(OnGetListItem) then begin DirItem := TCloudItem.Create; try DirItem.Name := '..'; DirItem.IsDir := True; DirItem.Date := 0; OnGetListItem(DirItem); finally DirItem.Free; end; end; repeat if not (Status in [stSearching,stRetrieving]) then Exit; AzParams := TStringList.Create; try if fCancelOperation then begin fCancelOperation := False; Exit; end; AzParams.Values['prefix'] := CurrentPath; //if not Recursive then AzParams.Values['delimiter'] := '/'; AzParams.Values['maxresults'] := '100'; if cNextMarker <> '' then AzParams.Values['marker'] := cNextMarker; CloudResponseInfo := TCloudResponseInfo.Create; try azBlobList := BlobService.ListBlobs(azContainer,cNextMarker,AzParams,CloudResponseInfo); azResponseInfo.Get(CloudResponseInfo); if azResponseInfo.StatusCode = 200 then begin try for azBlob in azBlobList do begin if not (Status in [stSearching,stRetrieving]) then Exit; if fCancelOperation then begin fCancelOperation := False; Exit; end; DirItem := TCloudItem.Create; try DirItem.Name := azBlob.Name; if DirItem.Name.StartsWith(CurrentPath) then DirItem.Name := StringReplace(DirItem.Name,CurrentPath,'',[]); if DirItem.Name.Contains('/') then begin DirItem.IsDir := True; DirItem.Name := Copy(DirItem.Name,1,DirItem.Name.IndexOf('/')); end else begin DirItem.IsDir := False; DirItem.Size := StrToInt64Def(azBlob.Properties.Values['Content-Length'],0); DirItem.Date := GMT2DateTime(azBlob.Properties.Values['Last-Modified']); end; if Assigned(OnGetListItem) then OnGetListItem(DirItem); finally DirItem.Free; end; azBlob.Free; end; finally //frees azbloblist objects //for azBlob in azBlobList do azBlob.Free; azBlobList.Free; end; end else begin Status := stFailed; Exit; end; finally CloudResponseInfo.Free; end; finally FreeAndNil(AzParams); end; if Assigned(OnRefreshReadDir) then OnRefreshReadDir(CurrentPath); until (cNextMarker = '') or (azResponseInfo.StatusCode <> 200); Status := stDone; finally BlobService.Free; if Assigned(OnEndReadDir) then OnEndReadDir(CurrentPath); end; end; {$ENDIF} {procedure TCloudStorageAzureProvider.OpenDir(const aPath : string); var lista : TBlobList; Blob : TAzureBlobObject; i : Integer; azurefilter : string; DirItem : TCloudItem; respinfo : TAzureResponseInfo; begin if aPath = '..' then begin CurrentPath := RemoveLastPathSegment(CurrentPath); end else begin if CurrentPath = '' then CurrentPath := aPath else CurrentPath := CurrentPath + aPath; end; if Assigned(OnBeginReadDir) then OnBeginReadDir(CurrentPath); if CurrentPath.StartsWith('/') then CurrentPath := Copy(CurrentPath,2,CurrentPath.Length); if (not CurrentPath.IsEmpty) and (not CurrentPath.EndsWith('/')) then CurrentPath := CurrentPath + '/'; Status := stRetrieving; lista := fAzure.ListBlobs(RootFolder,CurrentPath,False,respinfo); try if Assigned(lista) then begin if Assigned(OnGetListItem) then begin DirItem := TCloudItem.Create; try DirItem.Name := '..'; DirItem.IsDir := True; DirItem.Date := 0; OnGetListItem(DirItem); finally DirItem.Free; end; end; end; if respinfo.StatusCode = 200 then begin for Blob in lista do begin DirItem := TCloudItem.Create; try if Blob.Name.StartsWith(CurrentPath) then Blob.Name := StringReplace(Blob.Name,CurrentPath,'',[]); if Blob.Name.Contains('/') then begin DirItem.IsDir := True; DirItem.Name := Copy(Blob.Name,1,Blob.Name.IndexOf('/')); end else begin DirItem.IsDir := False; DirItem.Name := Blob.Name; DirItem.Size := Blob.Size; DirItem.Date := Blob.LastModified; end; if Assigned(OnGetListItem) then OnGetListItem(DirItem); finally DirItem.Free; end; end; Status := stDone; end else Status := stFailed; finally lista.Free; ResponseInfo.Get(respinfo.StatusCode,respinfo.StatusMsg); end; end;} procedure TCloudStorageAzureProvider.SetSecure(aValue: Boolean); begin inherited; if aValue then fAzureConnection.Protocol := 'HTTPS' else fAzureConnection.Protocol := 'HTTP'; end; end.
Unit DT_Jour; { $Id: DT_Jour.pas,v 1.45 2010/04/05 06:31:04 voba Exp $ } // $Log: DT_Jour.pas,v $ // Revision 1.45 2010/04/05 06:31:04 voba // - remove debug checks // // Revision 1.44 2010/03/30 11:12:37 voba // - заменил trunk файла на прописывание метки // // Revision 1.42 2010/03/25 09:44:49 voba // K:197496324 // // Revision 1.41 2010/03/25 09:43:49 voba // K:197496324 // // Revision 1.40 2010/03/22 18:12:52 voba // no message // // Revision 1.39 2010/03/22 17:48:03 voba // K:197496324 // // Revision 1.38 2010/03/22 17:47:02 voba // K:197496324 // // Revision 1.37 2010/03/17 15:42:31 voba // K:197496324 // // Revision 1.35 2010/01/22 12:17:59 voba // - enh : вываливаем exeption если не удается захватить журнал // // Revision 1.34 2009/12/11 11:55:37 voba // no message // // Revision 1.33 2009/12/10 15:59:05 voba // - bug fiх забыл залочить файл перед обработкой // // Revision 1.32 2009/11/20 13:51:56 voba // - bug fix // // Revision 1.31 2009/11/20 13:43:21 voba // - bug fix: Tl3BuuferedFilter не корректно работает в режиме почитали, пописали, почитали. Пришлось сделать в DT_Jour собственную буфферизацию // // Revision 1.30 2009/11/18 10:14:12 voba // - opt. // // Revision 1.29 2009/11/17 16:15:16 voba // - ернул кеширование чтения журнала из-за скорости // // Revision 1.28 2009/10/14 11:07:27 voba // - избавляемся от библиотеки mg // // Revision 1.27 2008/02/20 11:41:02 lulin // - bug fix: не собирался Архивариус. // // Revision 1.26 2008/02/04 15:22:57 lulin // - bug fix: не запускался парень. // // Revision 1.25 2008/02/01 16:41:34 lulin // - используем кошерные потоки. // // Revision 1.24 2007/11/22 14:38:58 fireton // - приводим информацию о всех пользователей, захвативших документ // // Revision 1.23 2007/08/14 20:25:14 lulin // - bug fix: не собиралася Архивариус. // // Revision 1.22 2007/08/14 14:30:07 lulin // - оптимизируем перемещение блоков памяти. // // Revision 1.21 2007/03/26 09:34:03 fireton // - изменился формат l3System.FreeLocalMem // // Revision 1.20 2005/10/17 11:30:35 voba // no message // // Revision 1.19 2004/09/21 12:04:20 lulin // - Release заменил на Cleanup. // // Revision 1.18 2004/08/03 08:52:50 step // замена dt_def.pas на DtDefine.inc // // Revision 1.17 2004/03/05 16:54:43 step // чистка кода // // Revision 1.16 2004/02/16 10:54:54 step // add: TAbstractJournal.ClearDeadRecs // // Revision 1.15 2003/10/31 17:20:43 voba // - bug fix // // Revision 1.14 2003/10/18 12:43:39 voba // -bug fix // // Revision 1.13 2003/10/02 13:53:37 voba // -enhance: введено понятие типа залочек, добавлен новый тип dtlPrevent - предотвращает захват с другой станции, но прозраченый для захвата со своей // // Revision 1.12 2003/03/31 13:48:59 demon // - new: увеличен размер буферов, выделяемых по умолчанию с 64кб до 8Мб // // Revision 1.11 2002/12/24 13:02:00 law // - change: объединил Int64_Seek c основной веткой. // // Revision 1.10.4.1 2002/12/24 11:56:43 law // - new behavior: используем 64-битный Seek вместо 32-битного. // // Revision 1.10 2002/02/11 14:30:49 voba // -lib sincro : change some m0 modules to m2 // // Revision 1.9 2000/12/15 15:36:16 law // - вставлены директивы Log. // {$I DtDefine.inc} {.$Define LockDebug} Interface Uses Dt_Types, //MGExFStr,MGBufStr,mgLckStr, l3Base, l3Stream, l3DatLst, l3RecList; Const cHeaderSize = 12; cHeader : Array[1..cHeaderSize] of Char = 'Lock Journal'; cVersion : Char = #03; type TIDType = Longint; TSysData = Longint; TdtLockType = (dtlUsual,dtlExclusive,dtlPrevent); {* - dtlUsual - обычная, dtlExclusive - полная(не допускает наличия других захватов документа), dtlPrevent - предотвращает захват с другой станции, для текущей станции прозрачна} PJourRec = ^TJourRec; TJourRec = packed record rStationName : Int64; //TStationID; rDocID : TIDType; rLockType : TdtLockType; rSysData : TSysData; end; TdtJIAccessFunc = function(var aRec : TJourRec; aPos : Longint) : Boolean; register; TCompareSysDataFunc = function(Var OldSysData, NewSysData) : Boolean of object; TAbstractJournal = Class(Tl3Base) private fJourFl : Tl3FileStream; fJourName : TPathStr; fStName : Int64; fHeaderSize : LongInt; fCompareSysData : TCompareSysDataFunc; protected procedure ClearBadJourRec; procedure BeforeRelease; override; procedure Cleanup; override; procedure IterateRecF(aFunc : TdtJIAccessFunc); procedure JFLock; procedure JFUnlock; public Constructor Create(aStationName : TStationID; aJourFullName : TPathStr); Reintroduce; function Lock(aID : TIDType; var aSysData : TSysData; aLockType : TdtLockType = dtlUsual) : TJLHandle; procedure SetNewSysData(aLH : TJLHandle; var aSysData : TSysData); procedure UnLock(aLH : TJLHandle); function CheckLock(aID : TIDType; LockInfoList : Tl3RecList; aIgnoredLockHandle : TJLHandle = -1): Boolean; procedure ClearDeadRecs(aActiveStations: Tl3StringDataList); // удаление записей, оставшихся от мертвых станций (тех, которые не входят в aActiveStations) property CompareSysData : TCompareSysDataFunc read fCompareSysData write fCompareSysData; end; Implementation Uses SysUtils, Classes, l3Types, l3MinMax, m0Const, m2xltlib, Dt_Const; const sJourFileBroken = 'Возможно нарушена структура файла залочек!'#13+'Свяжитесь с разработчиками.'; sJourFileBrokenP = 'Нарушена структура файла залочек'#13+'Свяжитесь с разработчиками. P=%d'; cStopLockType : TdtLockType = TdtLockType($ff); // специальное значение, показывает что за данной записью "живых" (непустых) нет. {$IFDEF LOCKDEBUG} procedure Check(aHandle : TJLHandle); begin Assert(((aHandle - 13) mod 17) = 0, Format(sJourFileBrokenP, [aHandle])); end; {$ENDIF LOCKDEBUG} function L2JIAccessFunc(Action: Pointer): TdtJIAccessFunc; register; asm jmp l3LocalStub end;{asm} procedure FreeJIAccessFunc(var Stub: TdtJIAccessFunc); register; asm jmp l3FreeLocalStub end;{asm} Constructor TAbstractJournal.Create(aStationName : TStationID; aJourFullName : TPathStr); Var TmpVer : Char; begin Inherited Create(Nil); fHeaderSize := cHeaderSize + 1; m2XLTConvertBuff(@aStationName, SizeOf(TStationID), Cm2XLTANSI2UPPER); fStName := PInt64(@aStationName)^; fJourName:=aJourFullName; if not FileExists(fJourName) then begin fJourFl := Tl3FileStream.Create(fJourName, l3_fmFullShareCreateReadWrite); fJourFl.Write(cVersion, 1); fJourFl.Write(cHeader, cHeaderSize); end else begin fJourFl := Tl3FileStream.Create(fJourName, l3_fmFullShareReadWrite); fJourFl.ReadBuffer(TmpVer, 1); if TmpVer <> cVersion then begin l3Free(fJourFl); fJourFl := Tl3FileStream.Create(fJourName, l3_fmFullShareCreateReadWrite); fJourFl.Write(cVersion, 1); fJourFl.Write(cHeader, cHeaderSize); end; end; //fJourFl := Tl3FileStream.Create(fJourName,l3_fmFullShareReadWrite); ClearBadJourRec; end; procedure TAbstractJournal.BeforeRelease; begin try ClearBadJourRec; finally Inherited; end; end; procedure TAbstractJournal.Cleanup; begin l3Free(fJourFl); Inherited; end; procedure TAbstractJournal.JFLock; begin if not fJourFl.Lock(1, cHeaderSize, 3*60*1000 {3 мин}) then raise Exception.Create('Журнал захватов недоступен.'); end; procedure TAbstractJournal.JFUnlock; begin fJourFl.UnLock(1, cHeaderSize); end; procedure TAbstractJournal.IterateRecF(aFunc : TdtJIAccessFunc); var lBuff : array[0..1000] of TJourRec; lBuffCnt : Integer; lStreamPos : Int64; lRSize : Integer; I : Integer; begin try fJourFl.Seek(fHeaderSize, soBeginning); while true do begin lStreamPos := fJourFl.Position; lRSize := fJourFl.Read(lBuff, SizeOf(lBuff)); if lRSize = 0 then // файл кончился Exit; if (lRSize mod SizeOf(TJourRec)) <> 0 then raise Exception.Create(sJourFileBroken); lBuffCnt := lRSize div SizeOf(TJourRec); for I := 0 to pred(lBuffCnt) do if not aFunc(lBuff[I], lStreamPos + I * SizeOf(TJourRec)) then exit; // восстановим позицию, которую могли попортить в подитеративной функции fJourFl.Seek(lStreamPos + lRSize, soBeginning); end; finally FreeJIAccessFunc(aFunc); end; end; procedure TAbstractJournal.ClearBadJourRec; function lJIAccessProc(var aRec : TJourRec; aPos : Longint) : Boolean; begin Result := not ((aRec.rStationName = cDelStationID) and (aRec.rLockType = cStopLockType)); // метка окончания полезной части файла if not Result then Exit; if aRec.rStationName = fStName then begin aRec.rStationName := cDelStationID; fJourFl.Seek(aPos, soBeginning); try fJourFl.Write(aRec, SizeOf(TJourRec)); except raise Exception.Create(sJourFileBroken); end; end; end; begin JFLock; try {$IFDEF LOCKDEBUG} check(fJourFl.Size); {$ENDIF LOCKDEBUG} IterateRecF(L2JIAccessFunc(@lJIAccessProc)); {$IFDEF LOCKDEBUG} check(fJourFl.Size); {$ENDIF LOCKDEBUG} finally JFUnlock; end; end; procedure TAbstractJournal.ClearDeadRecs(aActiveStations: Tl3StringDataList); function lJIAccessProc(var aRec : TJourRec; aPos : Longint) : Boolean; var l_Tmp: Longint; begin Result := not ((aRec.rStationName = cDelStationID) and (aRec.rLockType = cStopLockType)); // метка окончания полезной части файла if not Result then Exit; if not aActiveStations.FindStr(@(aRec.rStationName), l_Tmp) then begin aRec.rStationName := cDelStationID; fJourFl.Seek(aPos, soBeginning); try fJourFl.Write(aRec, SizeOf(TJourRec)); except raise Exception.Create(sJourFileBroken); end; end; end; begin // это не работает потому что у rStationName нет нуля на конце, FindStr не найдет. // нужно aActiveStations переделать на Reclist Assert(false, 'TAbstractJournal.ClearDeadRecs'); JFLock; try {$IFDEF LOCKDEBUG} check(fJourFl.Size); {$ENDIF LOCKDEBUG} IterateRecF(L2JIAccessFunc(@lJIAccessProc)); {$IFDEF LOCKDEBUG} check(fJourFl.Size); {$ENDIF LOCKDEBUG} finally JFUnlock; end; end; function TAbstractJournal.Lock(aID : TIDType; var aSysData : TSysData; aLockType : TdtLockType = dtlUsual) : TJLHandle; var lCurFreePos : Longint; lLastFreeChunkPos : Longint; // указатель на хвост из пустых lLockFailure : boolean; function lJIAccessProc(var aRec : TJourRec; aPos : Longint) : Boolean; begin Result := True; if aRec.rStationName <> cDelStationID then begin lLastFreeChunkPos := -1; if aRec.rDocID = aID then begin if (aRec.rLockType = dtlPrevent) and (aRec.rStationName = fStName) then Exit; //своя Prevent залочка нам не мешает if (aRec.rLockType = dtlPrevent) //чужая Prevent залочка, т к свою мы уже проверили выше or (aLockType = dtlExclusive) //залочка не Prevent (иначе бы раньше выпали), а мы хотели в эксклюзиве or (aRec.rLockType = dtlExclusive) //Exclusive залочка or ((aLockType = dtlUsual) and //(aRec.LockType = dtlUsual) and //это и так понятно, т. к. остальные виды залочек обработаны выше (not Assigned(fCompareSysData) or fCompareSysData(aRec.rSysData, aSysData))) then //все права уже захвачены begin Result := False; lLockFailure := True; end; end; //if aRec.rDocID = aID then end else //aRec.rStationName <> cDelStationID if lCurFreePos = -1 then begin lCurFreePos := aPos; if (aRec.rLockType = cStopLockType) then // метка окончания полезной части файла begin lLastFreeChunkPos := aPos + SizeOf(TJourRec); // переставим метку на след. запись if lLastFreeChunkPos >= fJourFl.Size then //если она есть lLastFreeChunkPos := -1; Result := False; // конец итерирования end end else begin if (aRec.rLockType = cStopLockType) then // метка окончания полезной части файла Result := False // конец итерирования else if lLastFreeChunkPos = -1 then lLastFreeChunkPos := aPos; end; end; var lRec : TJourRec; {$IFDEF LOCKDEBUG} lSaveSize : Integer; {$ENDIF LOCKDEBUG} begin Result := -1; lLockFailure := False; lCurFreePos := -1; lLastFreeChunkPos := -1; JFLock; {$IFDEF LOCKDEBUG} check(fJourFl.Size); //l3System.Msg2Log('Lock Size = %d', [fJourFl.Size - 13 div 17]); lSaveSize := fJourFl.Size; {$ENDIF LOCKDEBUG} try try IterateRecF(L2JIAccessFunc(@lJIAccessProc)); if lLockFailure then Exit; With lRec do begin rStationName := fStName; rDocID := aID; rLockType := aLockType; rSysData := aSysData; end; if lCurFreePos <> -1 then begin fJourfl.Seek(lCurFreePos, soBeginning); {$IFDEF LOCKDEBUG} Check(fJourFl.Position); {$ENDIF LOCKDEBUG} end else begin fJourFl.Seek(0, soEnd); {$IFDEF LOCKDEBUG} Check(fJourFl.Position); {$ENDIF LOCKDEBUG} end; Result := fJourFl.Position; fJourFl.Write(lRec, SizeOf(TJourRec)); if lLastFreeChunkPos <> -1 then begin {$IFDEF LOCKDEBUG} Check(lLastFreeChunkPos); {$ENDIF LOCKDEBUG} with lRec do begin rStationName := cDelStationID; rDocID := 0; rLockType := cStopLockType; end; fJourfl.Seek(lLastFreeChunkPos, soBeginning); fJourFl.Write(lRec, SizeOf(TJourRec)); //fJourFl.Size := lLastFreeChunkPos; {$IFDEF LOCKDEBUG} l3System.Msg2Log('Lock Trunc'); {$ENDIF LOCKDEBUG} end; finally If Result = -1 then {$IFDEF LOCKDEBUG} try {$ENDIF LOCKDEBUG} l3FillChar(aSysData, SizeOf(aSysData)); {$IFDEF LOCKDEBUG} except l3System.Msg2Log('Lock проблемы с l3FillChar'); Raise; end; {$ENDIF LOCKDEBUG} end; {$IFDEF LOCKDEBUG} check(fJourFl.Size); try if lSaveSize = fJourFl.Size then l3System.Msg2Log('Lock Size = %d, LH = %d', [(fJourFl.Size - 13) div 17, (Result - 13) div 17]) else l3System.Msg2Log('Lock Size = %d > %d, LH = %d', [(lSaveSize - 13) div 17, (fJourFl.Size - 13) div 17, (Result - 13) div 17]); except l3System.Msg2Log('Lock проблемы с l3System.Msg2Log'); l3System.Msg2Log('Lock ss = %d', [lSaveSize]); l3System.Msg2Log('Lock lh = %d', [Result]); l3System.Msg2Log('Lock s = %d', [fJourFl.Size]); Raise; end; {$ENDIF LOCKDEBUG} finally JFUnlock; end; end; procedure TAbstractJournal.SetNewSysData(aLH : TJLHandle; var aSysData : TSysData); begin {$IFDEF LOCKDEBUG} check(aLH); check(fJourFl.Size); Assert(fJourFl.Size > aLH, 'NewSysData: aLH outside Size'); {$ENDIF LOCKDEBUG} JFLock; try fJourFl.Seek(aLH + Longint(@(PJourRec(nil)^.rSysData)) {SysDataOffset} ,soBeginning); fJourFl.Write(aSysData, SizeOf(TSysData)); {$IFDEF LOCKDEBUG} Check(fJourFl.Size); {$ENDIF LOCKDEBUG} finally JFUnlock; end; end; procedure TAbstractJournal.UnLock(aLH : TJLHandle); begin {$IFDEF LOCKDEBUG} check(aLH); check(fJourFl.Size); Assert(fJourFl.Size > aLH, 'UnLock: aLH outside Size'); l3System.Msg2Log('UnLock Size = %d, LH = %d', [(fJourFl.Size - 13) div 17, (aLH - 13) div 17]); {$ENDIF LOCKDEBUG} JFLock; try fJourFl.Seek(aLH, soBeginning); fJourFl.Write(cDelStationID, SizeOf(cDelStationID)); {$IFDEF LOCKDEBUG} Check(fJourFl.Size); {$ENDIF LOCKDEBUG} finally JFUnlock; end; end; function TAbstractJournal.CheckLock(aID : TIDType; LockInfoList : Tl3RecList; aIgnoredLockHandle : TJLHandle = -1) : Boolean; function lJIAccessProc(var aRec : TJourRec; aPos : Longint) : Boolean; begin Result := not ((aRec.rStationName = cDelStationID) and (aRec.rLockType = cStopLockType)); // метка окончания полезной части файла if not Result then Exit; if (aRec.rStationName <> cDelStationID) and (aPos <> aIgnoredLockHandle) and (aRec.rDocID = aID) then LockInfoList.Add(aRec); end; begin LockInfoList.Count := 0; JFLock; try IterateRecF(L2JIAccessFunc(@lJIAccessProc)); finally JFUnlock; end; Result := LockInfoList.Count > 0; end; end.
unit clCliente; interface uses clPessoaJ, clConexao; type TCliente = Class(TPessoaJ) private function getCodigo: Integer; procedure setCodigo(const Value: Integer); function getOperacao: String; procedure setOperacao(const Value: String); constructor Create; destructor Destroy; function getOS: Integer; procedure setOS(const Value: Integer); protected _codigo: Integer; _os : Integer; _operacao: String; _conexao: TConexao; public property Codigo: Integer read getCodigo write setCodigo; property Operacao: String read getOperacao write setOperacao; property OS: Integer read getOS write setOS; function Validar(): Boolean; function JaExiste(id: String): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function Insert(): Boolean; function Update(): Boolean; function getObjects(): Boolean; function getField(campo, coluna: String): String; end; const TABLENAME = 'TBCLIENTES'; implementation { TCliente } uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB, Math; constructor TCliente.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TCliente.Destroy; begin _conexao.Free; end; function TCliente.getCodigo: Integer; begin Result := _codigo; end; function TCliente.getOperacao: String; begin Result := _operacao; end; function TCliente.getOS: Integer; begin Result := _os; end; function TCliente.Validar(): Boolean; begin Result := False; if Self.Codigo = 0 then begin MessageDlg('Informe o código do cliente', mtWarning, [mbOK], 0); Exit end; if Self.Operacao = 'I' then begin if Self.JaExiste(IntToStr(Self.Codigo)) then begin MessageDlg('Código de Cliente já Cadastrado', mtWarning, [mbOK], 0); Exit; end; end; if TUtil.Empty(Self.Razao) then begin MessageDlg('Informe o nome do cliente!', mtWarning, [mbNo], 0); Exit; end; Result := True; end; function TCliente.JaExiste(id: String): Boolean; begin try Result := False; if TUtil.Empty(id) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); SQL.Add(' WHERE COD_CLIENTE =:CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(id); dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then begin Result := True; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TCliente.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_CLIENTE = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Codigo; end; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TCliente.getObject(id, filtro: String): Boolean; begin Try Result := False; if TUtil.Empty(id) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add(' WHERE COD_CLIENTE =:CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(id); end else if filtro = 'NOME' then begin SQL.Add(' WHERE NOM_CLIENTE = :NOME'); ParamByName('NOME').AsString := id; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then begin dm.QryGetObject.First; Self.Codigo := dm.QryGetObject.FieldByName('COD_CLIENTE').AsInteger; Self.Razao := dm.QryGetObject.FieldByName('NOM_CLIENTE').AsString; Self.OS := dm.QryGetObject.FieldByName('DOM_OS').AsInteger; Result := True; end else begin ShowMessage('Registro não encontrado!'); dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TCliente.Insert(): Boolean; begin Try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_CLIENTE, ' + 'NOM_CLIENTE, ' + 'DOM_OS) ' + 'VALUES (' + ':CODIGO, ' + ':NOME, ' + ':OS)'; ParamByName('CODIGO').AsInteger := Self.Codigo; ParamByName('NOME').AsString := Self.Razao; ParamByName('OS').AsInteger := Self.OS; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; MessageDlg('Os dados foram salvos com sucesso!', mtInformation, [mbOK], 0); Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TCliente.Update(): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'NOM_CLIENTE = :NOME, ' + 'DOM_OS = :OS ' + 'WHERE ' + 'COD_CLIENTE = :CODIGO '; ParamByName('CODIGO').AsInteger := Self.Codigo; ParamByName('NOME').AsString := Self.Razao; ParamByName('OS').AsInteger := Self.OS; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; MessageDlg('Os dados foram alterados com sucesso!', mtInformation, [mbOK], 0); Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TCliente.getObjects(): Boolean; begin try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TCliente.getField(campo, coluna: String): String; begin Try Result := ''; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'CODIGO' then begin SQL.Add(' WHERE COD_CLIENTE = :CODIGO '); ParamByName('CODIGO').AsInteger := Self.Codigo; end else if coluna = 'NOME' then begin SQL.Add(' WHERE NOM_CLIENTE =:NOME '); ParamByName('NOME').AsString := Self.Razao; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := dm.QryGetObject.FieldByName(campo).AsString; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TCliente.setCodigo(const Value: Integer); begin _codigo := Value; end; procedure TCliente.setOperacao(const Value: String); begin _operacao := Value; end; procedure TCliente.setOS(const Value: Integer); begin _os := Value; end; end.
/// Utility methods to format numbers as Excel does it. unit tmsUFlxNumberFormat; {$INCLUDE ..\FLXCOMPILER.INC} interface uses SysUtils, {$IFDEF FLX_NEEDSVARIANTS} variants,{$ENDIF} tmsUFlxMessages, Math; /// <summary> /// This method has been deprecated. Use <see cref="XlsFormatValue1904@variant@UTF16String@boolean@Integer@PFormatSettings" text="XlsFormatValue1904" /> /// instead. /// </summary> /// <remarks> /// Excel has two different date systems: one starts at 1900 and the other at 1904. While 1900 is the /// most common (it is the default in Windows), 1904 is used in Macs and also might be set in Excel for /// Windows too in the options dialog.<para></para> /// <para></para> /// This method assumes always 1900 dates, so it is not safe to use and you should use &quot;1904&quot; /// overloads instead. /// </remarks> /// <param name="V">Value to convert.</param> /// <param name="Format">Format to be applied to the value. This must be an standard Excel format /// string.</param> /// <param name="Color">\Returns the color the text should be in, if the format contains color /// information.</param> /// <returns> /// The value formatted as a string. /// </returns> function XlsFormatValue(const V: variant; const Format: UTF16String; var Color: Integer): UTF16String; deprecated {$IFDEF FLX_HAS_DEPRECATED_COMMENTS}'Use XlsFormatValue1904 instead.'{$ENDIF}; /// <summary> /// Formats a value as Excel would show it in a cell. /// </summary> /// <remarks> /// If you have for example the number &quot;1&quot; stored in cell A1, and the format for the cell is /// &quot;0.00&quot;, Excel will displa yin the cell the string &quot;1.00&quot;, not just &quot;1&quot;. /// This method allows you to get what should be displayed in a cell based on the value in it and the /// format of the cell. /// </remarks> /// <param name="V">Value to convert.</param> /// <param name="Format">Format to be applied to the value. This must be an standard Excel format /// string (like &quot;0.00&quot;). </param> /// <param name="Color">\Returns the color the text should be in, if the format contains color /// information.</param> /// <param name="Dates1904">A boolean indicating if the workbook uses 1904 or 1900 dates. <b>Note that /// the result will be different depending on this parameter.</b> You will /// normally get the value for this parameter from /// TFlexCelImport.Options1904Dates</param> /// <param name="FormatSettings">Locale used for the conversion. If nil (the default) this method will use the machine locale.</param> /// <returns> /// The value formatted as a string. /// </returns> function XlsFormatValue1904(const V: variant; const Format: UTF16String; const Dates1904: boolean; var Color: Integer; FormatSettings: PFormatSettings = nil): UTF16String; /// <summary> /// \Returns true if the given Format string contains a Date or Time. /// </summary> /// <remarks> /// You can also get the data returned by this method with XlsFormatValue, but if you are only interested /// in knowing if a format contains a date/time, this method is easier. /// </remarks> /// <param name="Format">Format string in Excel format, like &quot;0.00&quot; or &quot;dd/mm/yyy&quot;.</param> /// <param name="HasDate">\Returns true if the format contains a date.</param> /// <param name="HasTime">Return true if the format contains time.</param> /// <param name="FormatSettings">Locale used for the conversion. If nil (the default) this method will use the machine locale.</param> /// <returns> /// True if the format contains either a date, a time or both. /// </returns> function HasXlsDateTime(const Format: UTF16String; out HasDate, HasTime: boolean; FormatSettings: PFormatSettings = nil): boolean; //-----------------------------------------------------------------------------// implementation type TResultCondition = record SupressNeg: Boolean; SupressNegComp: Boolean; Complement: Boolean; Assigned: boolean; end; TResultConditionArray = Array of TResultCondition; var RegionalSet : TFormatSettings; //Must be global so it is not freed when we point to it. procedure CheckRegionalSettings(const Format: UTF16String; var RegionalCulture: PFormatSettings; var p: integer; var TextOut: UTF16String; const Quote: Boolean); var StartCurr: integer; v: UTF16String; StartStr: integer; EndStr: integer; Len: integer; Offset: integer; i: integer; digit: AnsiChar; Result: integer; FormatLength: integer; begin FormatLength := Length(Format); if p - 1 >= (FormatLength - 3) then exit; if copy(Format, p, 2) = '[$' then //format is [$Currency-Locale] begin p:= p + 2; StartCurr := p; //Currency while (Format[p] <> '-') and (Format[p] <> ']') do begin Inc(p); if p - 1 >= FormatLength then //no tag found. exit; end; if (p - StartCurr) > 0 then begin if Quote then TextOut := TextOut + '"'; v := copy(Format, StartCurr, p - StartCurr); if Quote then StringReplace(v, '"', '"\""', [rfReplaceAll]); TextOut := TextOut + v; if Quote then TextOut := TextOut + '"'; end; if Format[p] <> '-' then begin Inc(p); exit; //no culture info. end; Inc(p); StartStr := p; while (p <= FormatLength) and (Format[p] <> ']') do begin begin Inc(p); end; end; if p <= FormatLength then //We actually found a close tag begin EndStr := p; Inc(p); //add the ']' char. Len := Math.Min(4, EndStr - StartStr); Result := 0; //to avoid issues with non existing tryparse we will convert from hexa directly. Offset := 0; for i := EndStr - 1 downto EndStr - Len do begin if (Format[i]) >=#255 then exit; //cannot parse digit := UpCase(AnsiChar(Format[i])); if (digit >= '0') and (digit <= '9') then begin Result:= Result + ((integer(digit) - integer('0')) shl Offset); Offset:= Offset + 4; continue; end; if (digit >= 'A') and (digit <= 'F') then begin Result:= Result + (((10 + integer(digit)) - integer('A')) shl Offset); Offset:= Offset + 4; continue; end; exit; //Cannot parse. end; if Result < 0 then exit; try {$IFDEF DELPHIXEUP} {$warn SYMBOL_PLATFORM OFF} RegionalSet := TFormatSettings.Create(Result); {$warn SYMBOL_PLATFORM ON} {$ELSE} GetLocaleFormatSettings(Result, RegionalSet); RegionalCulture := @RegionalSet; {$ENDIF} except begin //We could not create the culture, so we will continue with the existing one. end; end; end; end; end; function GetResultCondition(const aSupressNeg: Boolean; const aSupressNegComp: Boolean; const aComplement: Boolean; const aAssigned: Boolean): TResultCondition; begin Result.SupressNeg := aSupressNeg; Result.SupressNegComp := aSupressNegComp; Result.Complement := aComplement; Result.Assigned := aAssigned; end; function FindFrom(const wc: UTF16Char; const w: UTF16String; const p: integer): integer; begin Result:=pos(wc, copy(w, p, Length(w))) end; function GetconditionNumber(const Format: UTF16String; const p: integer; out HasErrors: Boolean): Extended; var p2: integer; number: UTF16String; begin HasErrors := true; p2 := FindFrom(']', Format, p + 1) - 1; if p2 < 0 then begin Result := 0; exit; end; number := copy(Format, p + 1, p2); Result := 0; HasErrors := not TryStrToFloatInvariant(number, Result); end; function EvalCondition(const Format: UTF16String; const position: integer; const V: Double; out ResultValue: Boolean; out SupressNegativeSign: Boolean; out SupressNegativeSignComp: Boolean): Boolean; var HasErrors: Boolean; c: Double; begin SupressNegativeSign := false; SupressNegativeSignComp := false; ResultValue := false; if (position + 2) >= Length(Format) then //We need at least a sign and a bracket. begin Result := false; exit; end; case Format[1 + position] of '=': begin begin c := GetconditionNumber(Format, position + 1, HasErrors); if HasErrors then begin Result := false; exit; end; ResultValue := V = c; SupressNegativeSign := true; SupressNegativeSignComp := false; begin Result := true; exit; end; end; end; '<': begin begin if Format[1 + position + 1] = '=' then begin c := GetconditionNumber(Format, position + 2, HasErrors); if HasErrors then begin Result := false; exit; end; ResultValue := V <= c; if c <= 0 then SupressNegativeSign := true else SupressNegativeSign := false; SupressNegativeSignComp := true; begin Result := true; exit; end; end; if Format[1 + position + 1] = '>' then begin c := GetconditionNumber(Format, position + 2, HasErrors); if HasErrors then begin Result := false; exit; end; ResultValue := V <> c; SupressNegativeSign := false; SupressNegativeSignComp := true; begin Result := true; exit; end; end; begin c := GetconditionNumber(Format, position + 1, HasErrors); if HasErrors then begin Result := false; exit; end; ResultValue := V < c; if c <= 0 then SupressNegativeSign := true else SupressNegativeSign := false; SupressNegativeSignComp := true; begin Result := true; exit; end; end; end; end; '>': begin begin if Format[1 + position + 1] = '=' then begin c := GetconditionNumber(Format, position + 2, HasErrors); if HasErrors then begin Result := false; exit; end; ResultValue := V >= c; if c <= 0 then SupressNegativeSignComp := true else SupressNegativeSignComp := false; SupressNegativeSign := false; begin Result := true; exit; end; end; begin c := GetconditionNumber(Format, position + 1, HasErrors); if HasErrors then begin Result := false; exit; end; ResultValue := V > c; if c <= 0 then SupressNegativeSignComp := true else SupressNegativeSignComp := false; SupressNegativeSign := false; begin Result := true; exit; end; end; end; end; end; Result := false; end; function GetNegativeSign(const Conditions: TResultConditionArray; const SectionCount: integer; var TargetedSection: integer; const V: Double): Boolean; var NullCount: integer; CompCount: integer; Comp: TResultCondition; i: integer; begin if TargetedSection < 0 then begin if (not Conditions[0].Assigned) and (((V > 0) or (SectionCount <= 1)) or ((V = 0) and (SectionCount <= 2))) then begin TargetedSection := 0; begin Result := false; exit; end; //doesn't matter. end; if (not Conditions[1].Assigned) and ((V < 0) or (SectionCount <= 2)) then begin TargetedSection := 1; if (SectionCount = 2) and (Conditions[0].Assigned) then begin Result := Conditions[0].SupressNegComp; exit; end; begin Result := true; exit; end; end; if (not Conditions[2].Assigned) then TargetedSection := 2 else TargetedSection := 3; begin Result := false; exit; end; end; if Conditions[TargetedSection].Assigned then begin Result := Conditions[TargetedSection].SupressNeg; exit; end; NullCount := 0; //Find Complement, if any CompCount := 0; Comp := GetResultCondition(false, false, false, false); for i := 0 to SectionCount - 1 do begin if Conditions[i].Assigned then begin Assert(Conditions[i].Complement); Inc(CompCount); if CompCount > 1 then begin Result := false; exit; end; Comp := Conditions[i]; end else begin Inc(NullCount); if NullCount > 1 then begin Result := false; exit; end; end; end; if Comp.Assigned then begin Result := Comp.SupressNegComp; exit; end; Result := false; end; function GetSections(const Format: UTF16String; const V: Double; out TargetedSection: integer; out SectionCount: integer; out SupressNegativeSign: Boolean): WideStringArray; var InQuote: Boolean; Conditions: TResultConditionArray; CurrentSection: integer; StartSection: integer; i: integer; TargetsThis: Boolean; SupressNegs: Boolean; SupressNegsComp: Boolean; FormatLength: Integer; begin InQuote := false; SetLength (Result, 4); for i:= 0 to Length(Result) - 1 do Result[i] := ''; SetLength (Conditions, 4); for i:= 0 to Length(Conditions) - 1 do Conditions[i] := GetResultCondition(false, false, false, false); CurrentSection := 0; StartSection := 0; TargetedSection := -1; i := 0; FormatLength := Length(Format); while i < FormatLength do begin if Format[1 + i] = '"' then begin InQuote := not InQuote; end; if InQuote then begin Inc(i); continue; //escaped characters inside a quote like \" are not valid. end; if Format[1 + i] = '\' then begin i:= i + 2; continue; end; if Format[1 + i] = '[' then begin if (i + 2) < FormatLength then begin if EvalCondition(Format, i + 1, V, TargetsThis, SupressNegs, SupressNegsComp) then begin Conditions[CurrentSection] := GetResultCondition(SupressNegs, SupressNegsComp, not TargetsThis, true); if TargetedSection < 0 then begin if TargetsThis then begin TargetedSection := CurrentSection; end; end; end; end; //Quotes inside brackets are not quotes. So we need to process the full bracket. while (i < FormatLength) and (Format[1 + i] <> ']') do begin Inc(i) end; Inc(i); continue; end; if Format[1 + i] = ';' then begin if i > StartSection then Result[CurrentSection] := copy(Format, StartSection + 1, i - StartSection); Inc(CurrentSection); SectionCount := CurrentSection; if CurrentSection >= Length(Result) then begin SupressNegativeSign := GetNegativeSign(Conditions, SectionCount, TargetedSection, V); exit; end; StartSection := i + 1; end; Inc(i); end; if i > StartSection then Result[CurrentSection] := copy(Format, StartSection + 1, i - StartSection + 1); Inc(CurrentSection); SectionCount := CurrentSection; SupressNegativeSign := GetNegativeSign(Conditions, SectionCount, TargetedSection, V); end; function GetSection(const Format: UTF16String; const V: Double; out SectionMatches: Boolean; out SupressNegativeSign: Boolean): UTF16String; var TargetedSection: integer; SectionCount: integer; Sections: WideStringArray; begin SectionMatches := true; Sections := GetSections(Format, V, TargetedSection, SectionCount, SupressNegativeSign); if TargetedSection >= SectionCount then begin SectionMatches := false; //No section matches condition. This has changed in Excel 2007, older versions would show an empty cell here, and Excel 2007 displays "####". We will use Excel2007 formatting. begin Result := ''; exit; end; end; if Sections[TargetedSection] = null then Result := '' else Result := Sections[TargetedSection]; end; //we include this so we don't need to use graphics const clBlack = $000000; clGreen = $008000; clRed = $0000FF; clYellow = $00FFFF; clBlue = $FF0000; clFuchsia = $FF00FF; clAqua = $FFFF00; clWhite = $FFFFFF; procedure CheckColor(const Format: UTF16String; var Color: integer; out p: integer); var s: string; IgnoreIt: boolean; begin p:=1; if (Length(Format)>0) and (Format[1]='[') and (pos(']', Format)>0) then begin IgnoreIt:=false; s:=copy(Format,2,pos(']', Format)-2); if s = 'Black' then Color:=clBlack else if s = 'Cyan' then Color:=clAqua else if s = 'Blue' then Color:=clBlue else if s = 'Green' then Color:=clGreen else if s = 'Magenta'then Color:=clFuchsia else if s = 'Red' then Color:=clRed else if s = 'White' then Color:=clWhite else if s = 'Yellow' then Color:=clYellow else IgnoreIt:=true; if not IgnoreIt then p:= Pos(']', Format)+1; end; end; procedure CheckOptional(const V: Variant; const Format: UTF16String; var p: integer; var TextOut: UTF16String); var p2, p3: integer; begin if p>Length(Format) then exit; if Format[p]='[' then begin p2:=FindFrom(']', Format, p); if (p<Length(Format))and(Format[p+1]='$') then //currency begin p3:=FindFrom('-', Format+'-', p); TextOut:=TextOut + copy(Format, p+2, min(p2,p3)-3); end; Inc(p, p2); end; end; procedure CheckLiteral(const V: Variant; const Format: UTF16String; var p: integer; var TextOut: UTF16String); var FormatLength: integer; begin FormatLength := Length(Format); if p>FormatLength then exit; if (ord(Format[p])<255) and (AnsiChar(Format[p]) in[' ','$','(',')','!','^','&','''',#$B4,'~','{','}','=','<','>']) then begin TextOut:=TextOut+Format[p]; inc(p); exit; end; if (Format[p]='\') or (Format[p]='*')then begin if p<FormatLength then TextOut:=TextOut+Format[p+1]; inc(p,2); exit; end; if Format[p]='_' then begin if p<FormatLength then TextOut:=TextOut+' '; inc(p,2); exit; end; if Format[p]='"' then begin inc(p); while (p<=FormatLength) and (Format[p]<>'"') do begin TextOut:=TextOut+Format[p]; inc(p); end; if p<=FormatLength then inc(p); end; end; procedure CheckDate(var RegionalCulture: PFormatSettings; const V: Variant; const Format: UTF16String; const Dates1904: boolean; var p: integer; var TextOut: UTF16String; var LastHour: boolean;var HasDate, HasTime: boolean); const DateTimeChars=['C','D','W','M','Q','Y','H','N','S','T','A','P','/',':','.','\']; DChars=['C','D','Y']; TChars=['H','N','S']; var Fmt: string; FormatLength: integer; begin FormatLength := Length(Format); Fmt:=''; while (p<=FormatLength) and (ord(Format[p])<255) and (Upcase(AnsiChar(Format[p])) in DateTimeChars) do begin if (Format[p] = '\') then inc(p); if p > FormatLength then exit; if (p > 2) and (Format[p] = '/') and (p + 2 <= FormatLength) and ((Format[p-1] = 'M') or (Format[p-1] = 'm')) and ((Format[p-2] = 'A') or (Format[p-2] = 'a')) and ((Format[p+1] = 'P') or (Format[p+1] = 'p')) and ((Format[p+2] = 'M') or (Format[p+2] = 'm')) then begin //AM/PM, must be changed to AMPM HasTime := true; Fmt:=Fmt + 'PM'; inc (p, 3); continue; end; if (UpCase(AnsiChar(Format[p])) in DChars)or (not LastHour and (UpCase(AnsiChar(Format[p]))='M')) then HasDate:=true; if (UpCase(AnsiChar(Format[p])) in TChars)or (LastHour and (UpCase(AnsiChar(Format[p]))='M')) then HasTime:=true; if (UpCase(AnsiChar(Format[p]))='H') then LastHour:=true; if LastHour and (UpCase(AnsiChar(Format[p]))='M') then begin while (p<=FormatLength) and (UpCase(AnsiChar(Format[p]))='M') do begin Fmt:=Fmt+'n'; inc(p); end; LastHour:=false; end else begin Fmt:=Fmt+Format[p]; inc(p); end; end; EnsureAMPM(RegionalCulture); if Fmt<>'' then TextOut:=TextOut+TryFormatDateTime1904(Fmt,v, Dates1904, RegionalCulture^); end; procedure CheckNumber( V: Variant; const NegateValue: Boolean; const wFormat: UTF16String; var p: integer; var TextOut: UTF16String); const NumberChars=['0','#','.',',','e','E','+','-','%','\','?','*','"']; var Fmt: string; Format : string; FormatLength: integer; p0: integer; begin Format := wFormat; FormatLength := Length(Format); Fmt:=''; p0 := p; while (p<=FormatLength) and (ord(wFormat[p])<255) and (AnsiChar(Format[p]) in NumberChars) do begin if (Format[p]='"') and (p > p0) then begin inc(p); while (p <= FormatLength) and (wFormat[p] <> '"') do begin if (Format[p] <> '\') then Fmt := Fmt + Format[p]; inc(p); end; continue; end; if Format[p]='%' then V:=V*100; if (Format[p] = '\') then inc(p); if (p <= FormatLength) then begin if (Format[p] = '?') then Fmt:=Fmt+'#' else if (Format[p] = '*') then begin if (p<Length(Format)) then Fmt := Fmt + Format[p + 1]; inc(p); end else Fmt:=Fmt+Format[p]; inc(p); end; end; if (NegateValue) and (v < 0) then v := -v; if Fmt<>'' then TextOut:=TextOut+FormatFloat(Fmt,v); end; procedure CheckText(const V: Variant; const Format: UTF16String; var p: integer; var TextOut: UTF16String); begin if p>Length(Format) then exit; if Format[p]='@' then begin TextOut:=TextOut+v; inc(p); end; end; procedure CheckEllapsedTime(const value: variant; const UpFormat: UTF16String; var p: Int32; var TextOut: UTF16String; var HasDate: Boolean; var HasTime: Boolean; out HourPos: Int32); var endP: Int32; HCount: Int32; MCount: Int32; SCount: Int32; d: Double; Count: Int32; begin HourPos := -1; if (p >= Length(UpFormat)) or (UpFormat[p] <> '[') then exit; endP := p + 1; HCount := 0; MCount := 0; SCount := 0; while (endP < Length(UpFormat)) and (UpFormat[endP] <> ']') do begin begin if UpFormat[endP] = 'H' then Inc(HCount) else if UpFormat[endP] = 'M' then Inc(MCount) else if UpFormat[endP] = 'S' then Inc(SCount) else exit; //only h and m formats here. Inc(endP); end; end; if endP >= Length(UpFormat) then exit; if ((HCount <= 0) and (MCount <= 0)) and (SCount <= 0) then exit; if (((HCount * MCount) <> 0) or ((HCount * SCount) <> 0)) or ((MCount * SCount) <> 0) then exit; HasTime := true; d := value; Count := 0; if HCount > 0 then begin d := d * 24; Count := HCount; end else if MCount > 0 then begin d := (d * 24) * 60; Count := MCount; end else if SCount > 0 then begin d := (d * 24) * 3600; Count := SCount; end; d := Floor(Abs(d)) * Sign(d); TextOut := TextOut + FormatFloat(StringOfChar('0', Count), d); p := endP + 1; if HCount > 0 then HourPos := p; end; function FormatNumber(const V: Variant; const NegateValue: Boolean; const Format: UTF16String; const Dates1904: boolean; var Color: integer;var HasDate, HasTime: boolean): UTF16String; var p, p1: integer; LastHour: boolean; HourPos: integer; FormatLength: integer; RegionalCulture: PFormatSettings; UpFormat: UTF16String; begin FormatLength := Length(Format); UpFormat := UpperCase(Format); RegionalCulture := GetDefaultLocaleFormatSettings; CheckColor(Format, Color, p); Result:=''; LastHour:=false; while p<=FormatLength do begin p1:=p; CheckRegionalSettings(Format, RegionalCulture, p, Result, false); CheckEllapsedTime(v, UpFormat, p, Result, HasDate, HasTime, HourPos); LastHour := HourPos = p; CheckOptional(V, Format, p, Result); CheckLiteral (V, Format, p, Result); CheckDate (RegionalCulture, V, Format, Dates1904, p, Result, LastHour, HasDate, HasTime); CheckNumber (V, NegateValue, Format, p, Result); if p1=p then //not found begin if (NegateValue) and (V < 0) then Result := -V //Format number is always called with a numeric arg else Result:=V; exit; end; end; end; function FormatText(const V:Variant; Format: UTF16String; var Color: integer):UTF16String; var SectionCount: integer; ts: integer; SupressNegativeSign: Boolean; Sections: WideStringArray; p: integer; p1: integer; FormatLength: integer; NewColor: integer; begin FormatLength := Length(Format); //Numbers/dates and text formats can't be on the same format string. It is a number XOR a date XOR a text Sections := GetSections(Format, 0, ts, SectionCount, SupressNegativeSign); if SectionCount < 4 then begin Format := Sections[0]; if (Pos('@', Format) <= 0) then //everything is ignored here. begin NewColor:=Color; CheckColor(Format, NewColor, p); if (p > Length(Format)) or (UpperCase(copy(Format, p, length(Format))) = 'GENERAL') then Color := NewColor; //Excel only uses the color if the format is empty or has an "@". Result := v; exit; end; end else begin Format := Sections[3]; end; CheckColor(Format, Color, p); Result:=''; while p<=FormatLength do begin p1:=p; CheckOptional(V, Format, p, Result); CheckLiteral (V, Format, p, Result); CheckText (V, Format, p, Result); if p1=p then //not found begin Result:=V; exit; end; end; end; function XlsFormatValueEx(const V: variant; Format: UTF16String; const Dates1904: boolean; var Color: Integer; out HasDate, HasTime: boolean; const FormatSettings: PFormatSettings): UTF16String; var SectionMatches: Boolean; SupressNegativeSign: Boolean; FormatSection: UTF16String; FmSet: PFormatSettings; begin if (FormatSettings = nil) then FmSet := GetDefaultLocaleFormatSettings else FmSet := FormatSettings; HasDate:=false; HasTime:=false; if VarIsNull(v) or VarIsClear(v) then begin; Result := ''; exit; end; if Format='' then //General begin Result:= VariantToString(v); exit; end; //This is slow. We will do it in checkdate. //Format:=StringReplaceSkipQuotes(Format,'AM/PM','AMPM'); //Format AMPM is equivalent to AM/PM on delphi case VarType(V) of varByte, varSmallint, varInteger, varSingle, varDouble, {$IFDEF FLX_HASCUSTOMVARIANTS} varInt64,{$ENDIF} //Delphi 6 or above varCurrency : begin FormatSection := GetSection(Format, V, SectionMatches, SupressNegativeSign); if not SectionMatches then //This is Excel2007 way. Older version would show an empty cell. begin Result := '###################'; exit; end; if Pos('[$-F800]', UpperCase(FormatSection)) > 0 then //This means format with long date from regional settings. This is new on Excel 2002 begin Result := TryFormatDateTime1904(FmSet.LongDateFormat, V, Dates1904); HasDate := true; exit; end; if Pos('[$-F400]', UpperCase(FormatSection)) > 0 then //This means format with long hour from regional settings. This is new on Excel 2002 begin Result := TryFormatDateTime1904(FmSet.LongTimeFormat, V, Dates1904); HasTime := true; exit; end; Result := FormatNumber(V, SupressNegativeSign, FormatSection, Dates1904, Color, HasDate, HasTime); end; varDate : begin FormatSection := GetSection(Format, V, SectionMatches, SupressNegativeSign); if not SectionMatches then //This is Excel2007 way. Older version would show an empty cell. begin Result := '###################'; exit; end; if Pos('[$-F800]', UpperCase(FormatSection)) > 0 then //This means format with long date from regional settings. This is new on Excel 2002 begin Result := TryFormatDateTime1904(FmSet.LongDateFormat, V, Dates1904); HasDate := true; exit; end; if Pos('[$-F400]', UpperCase(FormatSection)) > 0 then //This means format with long hour from regional settings. This is new on Excel 2002 begin Result := TryFormatDateTime1904(FmSet.LongTimeFormat, V, Dates1904); HasTime := true; exit; end; if V<0 then Result:='###################' else //Negative dates are shown this way Result := FormatNumber(V, SupressNegativeSign, FormatSection, Dates1904, Color, HasDate, HasTime); end; varOleStr, varStrArg, {$IFDEF DELPHI2008UP} varUString, {$ENDIF} varString : Result:=FormatText(V,Format, Color); varBoolean : if V then Result:=TxtTrue else Result:=TxtFalse; else Result:= VariantToString(V); end; //case end; function XlsFormatValue(const V: variant; const Format: UTF16String; var Color: Integer): UTF16String; var HasDate, HasTime: boolean; begin Result:=XlsFormatValueEx(V, Format, false, Color, HasDate, HasTime, nil); end; function XlsFormatValue1904(const V: variant; const Format: UTF16String; const Dates1904: boolean; var Color: Integer; FormatSettings: PFormatSettings = nil): UTF16String; var HasDate, HasTime: boolean; begin Result:=XlsFormatValueEx(V, Format, Dates1904, Color, HasDate, HasTime, FormatSettings); end; function HasXlsDateTime(const Format: UTF16String; out HasDate, HasTime: boolean; FormatSettings: PFormatSettings = nil): boolean; var Color: integer; begin Color := -1; XlsFormatValueEx(10, Format, false, Color, HasDate, HasTime, FormatSettings); Result:=HasDate or HasTime; end; end.
unit MarikoTutorial; interface uses SysUtils, Tasks; const tidTask_ClusterMariko = 'MarikoTutorial'; tidTask_Mariko_MainHeadquarter = 'MarikoMainHq'; tidTask_Mariko_SelectProduct = 'MarikoSelProduct'; tidTask_Mariko_PharmaTutorial = 'MarikoPharmaTutorial'; procedure RegisterTasks; implementation uses Kernel, ClusterTask, HeadquarterTasks, FoodStore, Tutorial, CommonTasks, BasicAccounts, StdAccounts, StdFluids, FacIds; // Register Mariko Tutorial Tasks procedure RegisterTasks; begin with TMetaClusterTask.Create( tidTask_ClusterMariko, 'Mariko Cluster Tutorial', '', // No description tidTask_Tutorial, // None 10, TClusterTask) do begin Priority := tprHighest - 1; ClusterName := 'Mariko'; Register(tidClassFamily_Tasks); end; {// Main Headquarter with TMetaHeadquarterTask.Create( tidTask_MainHeadquarter, tidTask_Mariko_MainHeadquarter, tidTask_ClusterMariko) do begin Priority := tprNormal - 1; Register(tidClassFamily_Tasks); end;} // Select Product Task with TMetaTask.Create( tidTask_SelectProduct, tidTask_Mariko_SelectProduct, tidTask_ClusterMariko) do begin Priority := tprNormal - 2; Register(tidClassFamily_Tasks); end; CommonTasks.AssembleTutorialBranch( 'CDs', tidTask_Mariko_SelectProduct, 'Mariko', tidTask_BuildGenWarehouse, tidFluid_CDs, tidTask_BuildCDStore, 'CDInd', tidTask_BuildCDPlant, tidTask_Mariko_MainHeadquarter, tidTask_ClusterMariko, accIdx_CDStore, FID_CDStore, FID_CDPlant, 0.667); CommonTasks.AssembleTutorialBranch( 'HHA', tidTask_Mariko_SelectProduct, 'Mariko', tidTask_BuildGenWarehouse, tidFluid_HouseHoldingAppliances, tidTask_BuildHHAStore, 'HHALic', tidTask_BuildHHAInd, tidTask_Mariko_MainHeadquarter, tidTask_ClusterMariko, accIdx_HHAStore, FID_HHAStore, FID_Household, 0.1665); CommonTasks.AssembleTutorialBranch( 'Clothes', tidTask_Mariko_SelectProduct, 'Mariko', tidTask_BuildGenWarehouse, tidFluid_Clothes, tidTask_BuildClotheStore, 'ClothesLic', tidTask_BuildClotheInd, tidTask_Mariko_MainHeadquarter, tidTask_ClusterMariko, accIdx_ClothesStore, FID_ClotheStore, FID_Clothes, 0.1665); end; end.
{ This is a personal project that I give to community under this licence: Copyright 2016 Eric Buso (Alias Caine_dvp) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit UCustomDataEngine; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface Uses USQLite3; type TCustomDataEngine = class(TObject) public type TRows = Array of Array of TVarRec; constructor Create(Const DBName:String); destructor Destroy;override; function Exists(const Value : String; const Table: String; const Column: String ) : Boolean; protected Procedure CopyRows(Var Rows : TRows;Const R : Integer); Procedure AssignResult(Var Values : TRows;Const MaxRow : Integer); Procedure InsertARow; Procedure Select; Procedure Fetch (const ColFormat : Array of TVarRec); Procedure Update; private FRowCount , FColCount : Integer; FSql : TSql ; FColFormat: Array of TVarRec; // Format des colonnes de la recherche. FColumns , FTables , FValues , FWhere : String; FError : Integer; FRows : TRows ; // Valeurs résultant d'un select. function ColCount: Integer; Protected property Columns : string read FColumns write FColumns ; property Tables : string read FTables write FTables ; property Values : string read FValues write FValues ; property Where : string read FWhere write FWhere ; property Error : Integer read FError ; property RowCount: Integer read FRowCount ; property Rows : TRows read FRows ; end; implementation Uses Math,SysUtils,Windows; { TCustomDataEngine } procedure TCustomDataEngine.AssignResult(var Values: TRows; const MaxRow: Integer); Var M : Integer; begin M := Min(MaxRow,FRowCount); SetLength(Values,M); Dec(M); CopyRows(Values,M); end; function TCustomDataEngine.ColCount: Integer; Var I,L:Integer; begin Result := 0; L := Length(FColumns); If L = 0 Then Exit; Inc(Result); I := 1; Repeat If FColumns[I] = ',' Then Inc(Result); Inc(I); Until I>=L; end; procedure TCustomDataEngine.CopyRows(var Rows: TRows; const R: Integer); Var I,J: Integer; begin For I := 0 To R Do Begin SetLength(Rows[I],FColCount); FSql.Fetch(FColFormat); For J:=0 To FColCount-1 Do Begin Rows[I][J] := FColFormat[J]; End; // TODO CopyMemory( PVoid(@Rows[I]), PVoid(@FColFormat), Sizeof(FColFormat) ); End; FSql.Fetch(FColFormat);// Appel poubelle, on finalise le statement de FSql. end; constructor TCustomDataEngine.Create(Const DBName:String); var ErrorMSg : String; begin inherited Create; FSql := TSql.Create(DBName,FError,ErrorMSg); if (FSql = nil) or (FError <>0) then Raise Exception.Create('Impossible d''initialiser le SGBD '+DBName+' :' + ErrorMSg); end; destructor TCustomDataEngine.Destroy; begin If Assigned(FSql) Then FSql.Destroy; If Assigned(FColFormat) Then Finalize(FColFormat); If Assigned(FRows) Then Finalize(FRows); inherited; end; function TCustomDataEngine.Exists(const Value, Table, Column: String): Boolean; var Where : String; begin Result := False; Where := Format('%s="%s"' ,[Column,Value]); Result := FSql.CountSelect(Table,Where) > 0 ; end; procedure TCustomDataEngine.Fetch(const ColFormat : Array of TVarRec); Var I : Integer; begin FColCount := ColCount; If Length(ColFormat) <> FColCount Then Raise Exception.Create('Format de recherche incompatible. Le nombre de colonnes diffère.'); If FRowCOunt <=0 Then Exit; SetLength(FColFormat,FColCount); For I:= 0 To FColCount-1 Do FColFormat[I] := ColFormat[I]; SetLength(FRows,FRowCount); CopyRows(FRows,FRowCount-1); end; procedure TCustomDataEngine.InsertARow; begin If (FColumns=EmptyStr) or (FTables=EmptyStr) or (FValues=EmptyStr) Then Exit; FError := FSql.insert(FTables,FColumns,FValues); // Error = 0 si insertion correcte. end; procedure TCustomDataEngine.Select; begin If (FColumns=EmptyStr) or (FTables=EmptyStr) Then Exit; FError := FSql.Select(FTables,FColumns,FWhere,FRowCount); //Error = 0 si requête Sql correcte. end; procedure TCustomDataEngine.Update; begin end; end.
unit nec_v20_v30; { v1.1 Aņadidos muchos opcodes Aņadidos al reset todos los registros v1.2 Corregidos opcodes $f2 y $f3 } interface uses {$IFDEF WINDOWS}windows,{$ENDIF} main_engine,dialogs,sysutils,vars_hide,cpu_misc,timer_engine; const NEC_V20=0; NEC_V30=1; NEC_V33=2; type band_nec=record SignVal,AuxVal,OverVal,ZeroVal,CarryVal,ParityVal,T,I,D,M:boolean; end; reg_nec=record eo,ip,old_pc:word; aw,cw,dw,bw:parejas; sp,bp,ix,iy:parejas; f:band_nec; ds1_r,ps_r,ds0_r,ss_r:word; ea:dword; end; preg_nec=^reg_nec; cpu_nec=class(cpu_class) constructor create(clock:dword;frames_div:word;tipo:byte); destructor free; public vect_req:byte; procedure reset; procedure run(maximo:single); procedure change_ram_calls(getbyte:tgetbyte16;putbyte:tputbyte16); procedure change_io_calls(inbyte:tgetbyte;outbyte:tputbyte); procedure change_io_calls16(inword:tgetword;outword:tputword); private getbyte:tgetbyte16; putbyte:tputbyte16; r:preg_nec; vect,prefetch_size,prefetch_cycles,tipo_cpu:byte; prefix_base:dword; prefetch_count:integer; prefetch_reset,seg_prefix:boolean; ea_calculated,no_interrupt,irq_pending:boolean; inbyte:tgetbyte; outbyte:tputbyte; inword:tgetword; outword:tputword; //procedure init_nec(tipo:byte); procedure nec_nmi; procedure nec_interrupt(vect_num:word); procedure GetEA(ModRM:byte); procedure write_word(dir:dword;x:word); function read_word(dir:dword):word; function fetch:byte; function fetchword:word; procedure do_prefetch(previous_icount:integer); function DefaultBase(Seg:byte):dword; procedure CLKW(v20o,v30o,v33o,v20e,v30e,v33e:byte;addr:word); procedure CLKM(v20,v30,v33,v20m,v30m,v33m,ModRM:byte); procedure CLKR(v20o,v30o,v33o,v20e,v30e,v33e,vall:byte;ModRM:word); function RegByte(ModRM:byte):byte; function GetRMByte(ModRM:byte):byte; function RegWord(ModRM:byte):word; function GetRMWord(ModRM:byte):word; procedure PutRMWord(ModRM:byte;valor:word); procedure PutbackRMByte(ModRM,valor:byte); procedure PutBackRegByte(ModRM,valor:byte); procedure PutbackRMWord(ModRM:byte;valor:word); procedure PutBackRegWord(ModRM:byte;valor:word); procedure PutRMByte(ModRM,valor:byte); procedure PutImmRMByte(ModRM:byte); procedure PutImmRMWord(ModRM:byte); procedure SetSZPF_Byte(x:byte); procedure SetSZPF_Word(x:word); function GetMemB(Seg:byte;Off:word):byte; function GetMemW(Seg:byte;Off:word):word; procedure PutMemB(Seg:byte;Off:word;x:byte); procedure PutMemW(Seg:byte;Off,x:word); function IncWordReg(tmp:word):word; function DecWordReg(tmp:word):word; function ANDB(src,dst:byte):byte; function ANDW(src,dst:word):word; function ADDB(src,dst:byte):byte; function ADDW(src,dst:word):word; function ORB(src,dst:byte):byte; function ORW(src,dst:word):word; function SUBB(src,dst:byte):byte; function SUBW(src,dst:word):word; function XORB(src,dst:byte):byte; function XORW(src,dst:word):word; function SHR_BYTE(c,dst:byte):byte; function SHR_WORD(c:byte;dst:word):word; function SHL_BYTE(c,dst:byte):byte; function SHL_WORD(c:byte;dst:word):word; procedure SHRA_WORD(c:byte;dst:word;ModRM:byte); function ROR_BYTE(dst:byte):byte; function ROR_WORD(dst:word):word; function ROL_BYTE(dst:byte):byte; function ROL_WORD(dst:word):word; function ROLC_BYTE(dst:byte):byte; function ROLC_WORD(dst:word):word; function RORC_BYTE(dst:byte):byte; function RORC_WORD(dst:word):word; procedure ADD4S; procedure i_jmp(flag:boolean); procedure i_movsb; procedure i_movsw; procedure i_lodsb; procedure i_stosb; procedure i_lodsw; procedure i_stosw; procedure i_scasb; procedure i_scasw; procedure ADJ4(param1,param2:shortint); procedure ejecuta_instruccion(instruccion:byte); procedure PUSH(val:word); procedure i_pushf; function BITOP_WORD(ModRM:byte):word; function BITOP_BYTE(ModRM:byte):byte; end; var nec_0,nec_1:cpu_nec; implementation var prev_icount:integer; const parity_table:array[0..$ff] of boolean=( true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true, true, false, false, true, false, true, true, false, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, true); DS1=0; PS=1; SS=2; DS0=3; function inbyte_ff(direccion:word):byte; begin inbyte_ff:=$ff; MessageDlg('in byte sin funcion', mtInformation,[mbOk], 0); end; function inword_ff(direccion:dword):word; begin inword_ff:=$ffff; MessageDlg('in word sin funcion', mtInformation,[mbOk], 0); end; procedure outbyte_ff(direccion:word;valor:byte); begin MessageDlg('out byte sin funcion', mtInformation,[mbOk], 0); end; procedure outword_ff(direccion:dword;valor:word); begin MessageDlg('out word sin funcion', mtInformation,[mbOk], 0); end; constructor cpu_nec.create(clock:dword;frames_div:word;tipo:byte); begin getmem(self.r,sizeof(reg_nec)); fillchar(self.r^,sizeof(reg_nec),0); self.numero_cpu:=cpu_main_init(clock); self.clock:=clock; self.tframes:=(clock/frames_div)/llamadas_maquina.fps_max; case tipo of 0:; 1:begin self.prefetch_size:=6; // 3 words */ self.prefetch_cycles:= 2; // two cycles per byte / four per word */ self.tipo_cpu:=tipo; end; end; self.inbyte:=inbyte_ff; self.outbyte:=outbyte_ff; self.inword:=inword_ff; self.outword:=outword_ff; self.despues_instruccion:=nil; end; destructor cpu_nec.free; begin freemem(self.r); end; procedure cpu_nec.reset; begin r.ip:=0; r.f.T:=false; r.f.i:=false; r.f.D:=false; r.f.SignVal:=false; r.f.AuxVal:=false; r.f.OverVal:=false; r.f.ZeroVal:=true; r.f.CarryVal:=false; r.f.ParityVal:=true; r.f.M:=true; self.prefetch_reset:=true; self.change_irq(CLEAR_LINE); r.ps_r:=$ffff; r.ds1_r:=0; r.ds0_r:=0; r.ss_r:=0; r.aw.w:=0; r.cw.w:=0; r.dw.w:=0; r.bw.w:=0; r.sp.w:=0; r.bp.w:=0; r.ix.w:=0; r.iy.w:=0; r.ea:=0; r.eo:=0; end; procedure cpu_nec.change_ram_calls(getbyte:tgetbyte16;putbyte:tputbyte16); begin self.getbyte:=getbyte; self.putbyte:=putbyte; end; procedure cpu_nec.change_io_calls(inbyte:tgetbyte;outbyte:tputbyte); begin if @inbyte<>nil then self.inbyte:=inbyte; if @outbyte<>nil then self.outbyte:=outbyte; end; procedure cpu_nec.change_io_calls16(inword:tgetword;outword:tputword); begin if @inword<>nil then self.inword:=inword; if @outword<>nil then self.outword:=outword; end; procedure cpu_nec.GetEA(ModRM:byte); var EO:word; EA:dword; tempb:byte; E16:word; begin if self.ea_calculated then exit; case ModRM of $00,$08,$10,$18,$20,$28,$30,$38:begin EO:=r.bw.w+r.ix.w; EA:=self.DefaultBase(DS0)+EO; end; $01,$09,$11,$19,$21,$29,$31,$39:begin EO:=r.bw.w+r.iy.w; EA:=self.DefaultBase(DS0)+EO; end; $02,$0a,$12,$1a,$22,$2a,$32,$3a:begin //01_05 EO:=r.bp.w+r.ix.w; EA:=self.DefaultBase(SS)+EO; end; $04,$0c,$14,$1c,$24,$2c,$34,$3c:begin EO:=r.ix.w; EA:=self.DefaultBase(DS0)+EO; end; $05,$0d,$15,$1d,$25,$2d,$35,$3d:begin EO:=r.iy.w; EA:=self.DefaultBase(DS0)+EO; end; $06,$0e,$16,$1e,$26,$2e,$36,$3e:begin EO:=self.fetch; EO:=EO+(self.FETCH shl 8); EA:=self.DefaultBase(DS0)+EO; end; $07,$0f,$17,$1f,$27,$2f,$37,$3f:begin EO:=r.bw.w; EA:=self.DefaultBase(DS0)+EO; end; $40,$48,$50,$58,$60,$68,$70,$78:begin tempb:=self.fetch; EO:=r.bw.w+r.ix.w+shortint(tempb); EA:=self.DefaultBase(DS0)+EO; end; $41,$49,$51,$59,$61,$69,$71,$79:begin tempb:=self.fetch; EO:=r.bw.w+r.iy.w+shortint(tempb); EA:=self.DefaultBase(DS0)+EO; end; $42,$4a,$52,$5a,$62,$6a,$72,$7a:begin tempb:=self.fetch; EO:=r.bp.w+r.ix.w+shortint(tempb); EA:=self.DefaultBase(SS)+EO; end; $43,$4b,$53,$5b,$63,$6b,$73,$7b:begin tempb:=self.fetch; EO:=r.bp.w+r.iy.w+shortint(tempb); EA:=self.DefaultBase(SS)+EO; end; $44,$4c,$54,$5c,$64,$6c,$74,$7c:begin tempb:=self.fetch; EO:=r.ix.w+shortint(tempb); EA:=self.DefaultBase(DS0)+EO; end; $45,$4d,$55,$5d,$65,$6d,$75,$7d:begin tempb:=self.fetch; EO:=r.iy.w+shortint(tempb); EA:=self.DefaultBase(DS0)+EO; end; $46,$4e,$56,$5e,$66,$6e,$76,$7e:begin tempb:=self.fetch; EO:=r.bp.w+shortint(tempb); EA:=self.DefaultBase(SS)+EO; end; $47,$4f,$57,$5f,$67,$6f,$77,$7f:begin tempb:=self.fetch; EO:=r.bw.w+shortint(tempb); EA:=self.DefaultBase(DS0)+EO; end; $80,$88,$90,$98,$a0,$a8,$b0,$b8:begin E16:=self.FETCH; E16:=E16+(self.FETCH shl 8); EO:=r.bw.w+r.ix.w+smallint(E16); EA:=self.DefaultBase(DS0)+EO; end; $81,$89,$91,$99,$a1,$a9,$b1,$b9:begin E16:=self.FETCH; E16:=E16+(self.FETCH shl 8); EO:=r.bw.w+r.iy.w+smallint(E16); EA:=self.DefaultBase(DS0)+EO; end; $84,$8c,$94,$9c,$a4,$ac,$b4,$bc:begin E16:=self.FETCH; E16:=E16+(self.FETCH shl 8); EO:=r.ix.w+smallint(E16); EA:=self.DefaultBase(DS0)+EO; end; $85,$8d,$95,$9d,$a5,$ad,$b5,$bd:begin E16:=self.FETCH; E16:=E16+(self.FETCH shl 8); EO:=r.iy.w+smallint(E16); EA:=self.DefaultBase(DS0)+EO; end; $86,$8e,$96,$9e,$a6,$ae,$b6,$be:begin E16:=self.FETCH; E16:=E16+(self.FETCH shl 8); EO:=r.bp.w+smallint(E16); EA:=self.DefaultBase(SS)+EO; end; $87,$8f,$97,$9f,$a7,$af,$b7,$bf:begin E16:=self.FETCH; E16:=E16+(self.FETCH shl 8); EO:=r.bw.w+smallint(E16); EA:=self.DefaultBase(DS0)+EO; end; else MessageDlg('GetEA No Implementado ModRM '+inttohex(ModRM,10)+'. PC='+inttohex((r.ps_r shl 4)+r.ip,10), mtInformation,[mbOk], 0); end; self.ea_calculated:=true; r.eo:=EO; r.ea:=EA; end; procedure cpu_nec.write_word(dir:dword;x:word); begin self.putbyte(dir,x and $ff); self.putbyte(dir+1,x shr 8); end; function cpu_nec.read_word(dir:dword):word; var tmp:byte; begin tmp:=self.getbyte(dir); read_word:=tmp+(self.getbyte(dir+1) shl 8); end; function cpu_nec.fetch:byte; begin self.prefetch_count:=self.prefetch_count+1; fetch:=self.getbyte((r.ps_r shl 4)+r.ip); r.ip:=r.ip+1; end; function cpu_nec.fetchword:word; begin fetchword:=self.fetch+(self.fetch shl 8); end; procedure cpu_nec.do_prefetch(previous_icount:integer); var diff:integer; begin diff:=previous_ICount-self.contador; { The implementation is not accurate, but comes close. * It does not respect that the V30 will fetch two bytes * at once directly, but instead uses only 2 cycles instead * of 4. There are however only very few sources publicy * available and they are vague.} while (self.prefetch_count<0) do begin self.prefetch_count:=self.prefetch_count+1; if (diff>self.prefetch_cycles) then diff:=diff-self.prefetch_cycles else self.contador:=self.contador+self.prefetch_cycles; end; if self.prefetch_reset then begin self.prefetch_count:=0; self.prefetch_reset:=false; exit; end; while ((diff >=self.prefetch_cycles) and (self.prefetch_count<self.prefetch_size)) do begin diff:=diff-self.prefetch_cycles; self.prefetch_count:=self.prefetch_count+1; end; end; procedure CLKS(clk_v20,clk_v30,clk_v33:byte); begin case nec_0.tipo_cpu of 0:nec_0.contador:=nec_0.contador+clk_v20; 1:nec_0.contador:=nec_0.contador+clk_v30; 2:nec_0.contador:=nec_0.contador+clk_v33; end; end; procedure cpu_nec.CLKW(v20o,v30o,v33o,v20e,v30e,v33e:byte;addr:word); begin case self.tipo_cpu of 0:if (addr and 1)<>0 then self.contador:=self.contador+v20o else self.contador:=self.contador+v20e; 1:if (addr and 1)<>0 then self.contador:=self.contador+v30o else self.contador:=self.contador+v30e; 2:if (addr and 1)<>0 then self.contador:=self.contador+v33o else self.contador:=self.contador+v33e; end; end; procedure cpu_nec.CLKM(v20,v30,v33,v20m,v30m,v33m,ModRM:byte); begin case self.tipo_cpu of 0:if (ModRM>=$c0) then self.contador:=self.contador+v20 else self.contador:=self.contador+v20m; 1:if (ModRM>=$c0) then self.contador:=self.contador+v30 else self.contador:=self.contador+v30m; 2:if (ModRM>=$c0) then self.contador:=self.contador+v33 else self.contador:=self.contador+v33m; end; end; procedure cpu_nec.CLKR(v20o,v30o,v33o,v20e,v30e,v33e,vall:byte;ModRM:word); begin if (ModRM>=$c0) then begin self.contador:=self.contador+vall; end else begin if (r.ea and 1)<>0 then begin case self.tipo_cpu of 0:self.contador:=self.contador+v20o; 1:self.contador:=self.contador+v30o; 2:self.contador:=self.contador+v33o; end; end else begin case self.tipo_cpu of 0:self.contador:=self.contador+v20e; 1:self.contador:=self.contador+v30e; 2:self.contador:=self.contador+v33e; end; end; end; end; function cpu_nec.RegByte(ModRM:byte):byte; //AL, CL, DL, BL, AH, CH, DH, BH begin case ((ModRM and $38) shr 3) of 0:RegByte:=r.aw.l; 1:RegByte:=r.cw.l; 2:RegByte:=r.dw.l; 3:RegByte:=r.bw.l; 4:RegByte:=r.aw.h; 5:RegByte:=r.cw.h; 6:RegByte:=r.dw.h; 7:RegByte:=r.bw.h; end; end; function cpu_nec.GetRMByte(ModRM:byte):byte; //AL, CL, DL, BL, AH, CH, DH, BH begin if (ModRM>=$c0) then begin case (modRM and $7) of 0:GetRMByte:=r.aw.l; 1:GetRMByte:=r.cw.l; 2:GetRMByte:=r.dw.l; 3:GetRMByte:=r.bw.l; 4:GetRMByte:=r.aw.h; 5:GetRMByte:=r.cw.h; 6:GetRMByte:=r.dw.h; 7:GetRMByte:=r.bw.h; end; end else begin self.GetEA(ModRM); GetRMByte:=self.getbyte(r.ea); end; end; function cpu_nec.RegWord(ModRM:byte):word; //AW, CW, DW, BW, SP, BP, IX, IY begin case ((ModRM and $38) shr 3) of 0:RegWord:=r.aw.w; 1:RegWord:=r.cw.w; 2:RegWord:=r.dw.w; 3:RegWord:=r.bw.w; 4:RegWord:=r.sp.w; 5:RegWord:=r.bp.w; 6:RegWord:=r.ix.w; 7:RegWord:=r.iy.w; end; end; function cpu_nec.GetRMWord(ModRM:byte):word; //AW, CW, DW, BW, SP, BP, IX, IY begin if (ModRM>=$c0) then begin case (ModRM and 7) of 0:GetRMWord:=r.aw.w; 1:GetRMWord:=r.cw.w; 2:GetRMWord:=r.dw.w; 3:GetRMWord:=r.bw.w; 4:GetRMWord:=r.sp.w; 5:GetRMWord:=r.bp.w; 6:GetRMWord:=r.ix.w; 7:GetRMWord:=r.iy.w; end; end else begin self.GetEA(ModRM); GetRMWord:=self.read_word(r.ea); end; end; procedure cpu_nec.PutRMByte(ModRM,valor:byte); begin if (ModRM>=$c0) then begin case (modRM and $7) of 0:r.aw.l:=valor; 1:r.cw.l:=valor; 2:r.dw.l:=valor; 3:r.bw.l:=valor; 4:r.aw.h:=valor; 5:r.cw.h:=valor; 6:r.dw.h:=valor; 7:r.bw.h:=valor; end; end else begin self.GetEA(ModRM); self.putbyte(r.ea,valor); end; end; procedure cpu_nec.PutbackRMByte(ModRM,valor:byte); begin if (ModRM>=$c0) then begin case (modRM and $7) of 0:r.aw.l:=valor; 1:r.cw.l:=valor; 2:r.dw.l:=valor; 3:r.bw.l:=valor; 4:r.aw.h:=valor; 5:r.cw.h:=valor; 6:r.dw.h:=valor; 7:r.bw.h:=valor; end; end else self.putbyte(r.ea,valor); end; procedure cpu_nec.PutBackRegByte(ModRM,valor:byte); //AL, CL, DL, BL, AH, CH, DH, BH begin case ((ModRM and $38) shr 3) of 0:r.aw.l:=valor; 1:r.cw.l:=valor; 2:r.dw.l:=valor; 3:r.bw.l:=valor; 4:r.aw.h:=valor; 5:r.cw.h:=valor; 6:r.dw.h:=valor; 7:r.bw.h:=valor; end; end; procedure cpu_nec.PutRMWord(ModRM:byte;valor:word); //AW, CW, DW, BW, SP, BP, IX, IY begin if (ModRM>=$c0) then begin case (modRM and $7) of 0:r.aw.w:=valor; 1:r.cw.w:=valor; 2:r.dw.w:=valor; 3:r.bw.w:=valor; 4:r.sp.w:=valor; 5:r.bp.w:=valor; 6:r.ix.w:=valor; 7:r.iy.w:=valor; end; end else begin self.GetEA(ModRM); self.write_word(r.ea,valor); end; end; procedure cpu_nec.PutbackRMWord(ModRM:byte;valor:word); //AW, CW, DW, BW, SP, BP, IX, IY begin if (ModRM>=$c0) then begin case (modRM and $7) of 0:r.aw.w:=valor; 1:r.cw.w:=valor; 2:r.dw.w:=valor; 3:r.bw.w:=valor; 4:r.sp.w:=valor; 5:r.bp.w:=valor; 6:r.ix.w:=valor; 7:r.iy.w:=valor; end; end else self.write_word(r.ea,valor); end; procedure cpu_nec.PutBackRegWord(ModRM:byte;valor:word); //AW, CW, DW, BW, SP, BP, IX, IY begin case ((ModRM and $38) shr 3) of 0:r.aw.w:=valor; 1:r.cw.w:=valor; 2:r.dw.w:=valor; 3:r.bw.w:=valor; 4:r.sp.w:=valor; 5:r.bp.w:=valor; 6:r.ix.w:=valor; 7:r.iy.w:=valor; end; end; procedure cpu_nec.PutImmRMByte(ModRM:byte); var valor:byte; begin if (ModRM>=$c0) then begin valor:=self.fetch; case (modRM and $7) of 0:r.aw.l:=valor; 1:r.cw.l:=valor; 2:r.dw.l:=valor; 3:r.bw.l:=valor; 4:r.aw.h:=valor; 5:r.cw.h:=valor; 6:r.dw.h:=valor; 7:r.bw.h:=valor; end; end else begin self.GetEA(ModRM); self.putbyte(r.ea,self.fetch); end; end; procedure cpu_nec.PutImmRMWord(ModRM:byte); //AW, CW, DW, BW, SP, BP, IX, IY var valor:word; begin if (ModRM>=$c0) then begin valor:=self.FETCHWORD; case (modRM and $7) of 0:r.aw.w:=valor; 1:r.cw.w:=valor; 2:r.dw.w:=valor; 3:r.bw.w:=valor; 4:r.sp.w:=valor; 5:r.bp.w:=valor; 6:r.ix.w:=valor; 7:r.iy.w:=valor; end; end else begin self.GetEA(ModRM); valor:=self.FETCHWORD; self.write_word(r.ea,valor); end; end; procedure cpu_nec.SetSZPF_Byte(x:byte); begin r.f.SignVal:=(x and $80)<>0; r.f.ZeroVal:=(x=0); r.f.ParityVal:=parity_table[x]; end; procedure cpu_nec.SetSZPF_Word(x:word); begin r.f.SignVal:=(x and $8000)<>0; r.f.ZeroVal:=(x=0); r.f.ParityVal:=parity_table[x and $ff]; end; function cpu_nec.DefaultBase(Seg:byte):dword; begin if (self.seg_prefix and ((Seg=DS0) or (Seg=SS))) then begin DefaultBase:=self.prefix_base; end else begin case Seg of DS1:DefaultBase:=r.ds1_r shl 4; PS:DefaultBase:=r.ps_r shl 4; SS:DefaultBase:=r.ss_r shl 4; DS0:DefaultBase:=r.ds0_r shl 4; end; end; end; function cpu_nec.GetMemB(Seg:byte;Off:word):byte; begin GetMemB:=self.getbyte(DefaultBase(Seg)+Off); end; function cpu_nec.GetMemW(Seg:byte;Off:word):word; begin GetMemW:=self.read_word(self.DefaultBase(Seg)+Off); end; procedure cpu_nec.PutMemB(Seg:byte;Off:word;x:byte); begin self.putbyte(DefaultBase(Seg)+Off,x); end; procedure cpu_nec.PutMemW(Seg:byte;Off,x:word); begin self.write_word(self.DefaultBase(Seg)+Off,x); end; function cpu_nec.IncWordReg(tmp:word):word; var tmp1:word; begin tmp1:=tmp+1; r.f.OverVal:=(tmp=$7fff); r.f.AuxVal:=((tmp1 xor (tmp xor 1)) and $10)<>0; self.SetSZPF_Word(tmp1); IncWordReg:=tmp1; end; function cpu_nec.DecWordReg(tmp:word):word; var tmp1:word; begin tmp1:=tmp-1; r.f.OverVal:=(tmp=$8000); r.f.AuxVal:=((tmp1 xor (tmp xor 1)) and $10)<>0; self.SetSZPF_Word(tmp1); DecWordReg:=tmp1; end; //INSTRUCIONES function cpu_nec.ANDB(src,dst:byte):byte; begin dst:=dst and src; r.f.CarryVal:=false; r.f.OverVal:=false; r.f.AuxVal:=false; self.SetSZPF_Byte(dst); ANDB:=dst; end; function cpu_nec.ANDW(src,dst:word):word; begin dst:=dst and src; r.f.CarryVal:=false; r.f.OverVal:=false; r.f.AuxVal:=false; self.SetSZPF_Word(dst); andw:=dst; end; function cpu_nec.ADDB(src,dst:byte):byte; var res:word; begin res:=dst+src; r.f.CarryVal:=(res and $100)<>0; r.f.OverVal:=((res xor src) and (res xor dst) and $80)<>0; r.f.AuxVal:=((res xor (src xor dst)) and $10)<>0; self.SetSZPF_Byte(res); ADDB:=res; end; function cpu_nec.ADDW(src,dst:word):word; var res:dword; begin res:=dst+src; r.f.CarryVal:=(res and $10000)<>0; r.f.OverVal:=((res xor src) and (res xor dst) and $8000)<>0; r.f.AuxVal:=((res xor (src xor dst)) and $10)<>0; self.SetSZPF_Word(res); ADDW:=res; end; function cpu_nec.ORB(src,dst:byte):byte; begin dst:=dst or src; r.f.CarryVal:=false; r.f.OverVal:=false; r.f.AuxVal:=false; self.SetSZPF_Byte(dst); ORB:=dst; end; function cpu_nec.ORW(src,dst:word):word; begin dst:=dst or src; r.f.CarryVal:=false; r.f.OverVal:=false; r.f.AuxVal:=false; self.SetSZPF_word(dst); ORW:=dst; end; function cpu_nec.SUBB(src,dst:byte):byte; var res:word; begin res:=dst-src; r.f.CarryVal:=(res and $100)<>0; r.f.OverVal:=((dst xor src) and (dst xor res) and $80)<>0; r.f.AuxVal:=((res xor (src xor dst)) and $10)<>0; self.SetSZPF_Byte(res); SUBB:=res; end; function cpu_nec.SUBW(src,dst:word):word; var res:dword; begin res:=dst-src; r.f.CarryVal:=(res and $10000)<>0; r.f.OverVal:=((dst xor src) and (dst xor res) and $8000)<>0; r.f.AuxVal:=((res xor (src xor dst)) and $10)<>0; self.SetSZPF_Word(res); SUBW:=res; end; function cpu_nec.XORB(src,dst:byte):byte; begin dst:=dst xor src; r.f.CarryVal:=false; r.f.OverVal:=false; r.f.AuxVal:=false; self.SetSZPF_Byte(dst); XORB:=dst; end; function cpu_nec.XORW(src,dst:word):word; begin dst:=dst xor src; r.f.CarryVal:=false; r.f.OverVal:=false; r.f.AuxVal:=false; self.SetSZPF_Word(dst); XORW:=dst; end; function cpu_nec.SHR_BYTE(c,dst:byte):byte; begin self.contador:=self.contador+c; dst:=dst shr (c-1); r.f.CarryVal:=(dst and 1)<>0; dst:=dst shr 1; self.SetSZPF_Byte(dst); SHR_BYTE:=dst; end; function cpu_nec.SHR_WORD(c:byte;dst:word):word; begin self.contador:=self.contador+c; dst:=dst shr (c-1); r.f.CarryVal:=(dst and 1)<>0; dst:=dst shr 1; self.SetSZPF_Word(dst); SHR_WORD:=dst; end; function cpu_nec.SHL_BYTE(c,dst:byte):byte; var res:word; begin self.contador:=self.contador+c; res:=dst shl c; r.f.CarryVal:=(res and $100)<>0; self.SetSZPF_Byte(res); SHL_BYTE:=res; end; function cpu_nec.SHL_WORD(c:byte;dst:word):word; var res:dword; begin self.contador:=self.contador+c; res:=dst shl c; r.f.CarryVal:=(res and $10000)<>0; self.SetSZPF_Word(res); SHL_WORD:=res; end; function cpu_nec.ROL_BYTE(dst:byte):byte; begin r.f.CarryVal:=(dst and $80)<>0; ROL_BYTE:=(dst shl 1)+byte(r.f.CarryVal); end; function cpu_nec.ROL_WORD(dst:word):word; begin r.f.CarryVal:=(dst and $8000)<>0; ROL_WORD:=(dst shl 1)+byte(r.f.CarryVal); end; function cpu_nec.ROR_BYTE(dst:byte):byte; begin r.f.CarryVal:=(dst and $1)<>0; ROR_BYTE:=(dst shr 1)+(byte(r.f.CarryVal) shl 7); end; function cpu_nec.ROR_WORD(dst:word):word; begin r.f.CarryVal:=(dst and $1)<>0; ROR_WORD:=(dst shr 1)+(byte(r.f.CarryVal) shl 15); end; function cpu_nec.ROLC_BYTE(dst:byte):byte; var temp:word; begin temp:=(dst shl 1)+byte(r.f.CarryVal); r.f.CarryVal:=(temp and $100)<>0; ROLC_BYTE:=temp; end; function cpu_nec.ROLC_WORD(dst:word):word; var temp:dword; begin temp:=(dst shl 1)+byte(r.f.CarryVal); r.f.CarryVal:=(temp and $10000)<>0; ROLC_WORD:=temp; end; function cpu_nec.RORC_BYTE(dst:byte):byte; var temp:word; begin temp:=dst+(byte(r.f.CarryVal) shl 8); r.f.CarryVal:=(dst and $1)<>0; RORC_BYTE:=temp shr 1; end; function cpu_nec.RORC_WORD(dst:word):word; var temp:dword; begin temp:=dst+(byte(r.f.CarryVal) shl 16); r.f.CarryVal:=(dst and $1)<>0; RORC_WORD:=temp shr 1; end; procedure cpu_nec.SHRA_WORD(c:byte;dst:word;ModRM:byte); function sshr(num:integer;fac:byte):integer; begin if num<0 then sshr:=-(abs(num) shr fac) else sshr:=num shr fac; end; begin self.contador:=self.contador+c; dst:=sshr(smallint(dst),c-1); r.f.CarryVal:=(dst and $1)<>0; dst:=sshr(smallint(dst),1); self.SetSZPF_Word(dst); PutbackRMWord(ModRM,dst); end; procedure cpu_nec.ADD4S; const table:array [0..2] of byte=(18,19,19); var di,si,result:word; count,i,tmp,tmp2,v1,v2:byte; begin count:=(r.cw.l+1) div 2; di:=r.iy.w; si:=r.ix.w; if self.seg_prefix then MessageDlg('Warning: seg_prefix defined for add4s', mtInformation,[mbOk],0); r.f.ZeroVal:=false; r.f.CarryVal:=false; for i:=0 to (count-1) do begin self.contador:=self.contador+table[self.tipo_cpu]; tmp:=self.GetMemB(DS0,si); tmp2:=self.GetMemB(DS1,di); v1:=(tmp shr 4)*10+(tmp and $f); v2:=(tmp2 shr 4)*10+(tmp2 and $f); result:=v1+v2+byte(r.f.CarryVal); r.f.CarryVal:=(result>99); result:=result mod 100; v1:=((result div 10) shl 4) or (result mod 10); self.PutMemB(DS1,di,v1); r.f.ZeroVal:=(v1<>0); si:=si+1; di:=di+1; end; end; //MACROS INSTRUCCIONES procedure cpu_nec.i_jmp(flag:boolean); const table:array [0..2] of byte=(18,19,19); var tmp:byte; begin self.prefetch_reset:=true; tmp:=self.FETCH; if flag then begin r.ip:=r.ip+shortint(tmp); self.contador:=self.contador+table[self.tipo_cpu]; end; end; procedure cpu_nec.i_movsb; var tmp:byte; df:integer; begin tmp:=self.GetMemB(DS0,r.ix.w); self.PutMemB(DS1,r.iy.w,tmp); if r.f.d then df:=-1 else df:=1; r.ix.w:=r.ix.w+df; r.iy.w:=r.iy.w+df; CLKS(8,8,6); end; procedure cpu_nec.i_movsw; var tmp:word; df:integer; begin tmp:=self.GetMemW(DS0,r.ix.w); self.PutMemW(DS1,r.iy.w,tmp); if r.f.d then df:=-2 else df:=2; r.ix.w:=r.ix.w+df; r.iy.w:=r.iy.w+df; CLKS(16,16,10); end; procedure cpu_nec.i_lodsb; begin r.aw.l:=self.GetMemB(DS0,r.ix.w); if r.f.d then r.ix.w:=r.ix.w-1 else r.ix.w:=r.ix.w+1; CLKS(4,4,3); end; procedure cpu_nec.i_stosb; begin self.PutMemB(DS1,r.iy.w,r.aw.l); if r.f.d then r.iy.w:=r.iy.w-1 else r.iy.w:=r.iy.w+1; CLKS(4,4,3); end; procedure cpu_nec.i_lodsw; begin r.aw.w:=self.GetMemW(DS0,r.ix.w); if r.f.d then r.ix.w:=r.ix.w-2 else r.ix.w:=r.ix.w+2; self.CLKW(8,8,5,8,4,3,r.ix.w); end; procedure cpu_nec.i_stosw; begin self.PutMemW(DS1,r.iy.w,r.aw.w); if r.f.d then r.iy.w:=r.iy.w-2 else r.iy.w:=r.iy.w+2; self.CLKW(8,8,5,8,4,3,r.iy.w); end; procedure cpu_nec.i_scasb; var src,dst:byte; begin src:=self.GetMemB(DS1,r.iy.w); dst:=r.aw.l; self.SUBB(src,dst); if r.f.d then r.iy.w:=r.iy.w-1 else r.iy.w:=r.iy.w+1; CLKS(4,4,3); end; procedure cpu_nec.i_scasw; var src,dst:word; begin src:=self.GetMemW(DS1,r.iy.w); dst:=r.aw.w; self.SUBW(src,dst); if r.f.d then r.iy.w:=r.iy.w-2 else r.iy.w:=r.iy.w+2; self.CLKW(8,8,5,8,4,3,r.iy.w); end; procedure cpu_nec.ADJ4(param1,param2:shortint); var tmp:word; begin if (r.f.AuxVal or ((r.aw.l and $f)>9)) then begin tmp:=r.aw.l+param1; r.aw.l:=tmp; self.r.f.AuxVal:=true; self.r.f.CarryVal:=self.r.f.CarryVal or ((tmp and $100)<>0); end; if (r.f.CarryVal or (r.aw.l>$9f)) then begin r.aw.l:=r.aw.l+param2; r.f.CarryVal:=true; end; SetSZPF_Byte(r.aw.l) end; procedure cpu_nec.PUSH(val:word); begin self.r.sp.w:=self.r.sp.w-2; self.write_word((self.r.ss_r shl 4)+self.r.sp.w,val); end; procedure cpu_nec.i_pushf; var temp:word; begin temp:=$7002; if r.f.CarryVal then temp:=$1; if r.f.ParityVal then temp:=temp+4; if r.f.AuxVal then temp:=temp+$10; if r.f.ZeroVal then temp:=temp+$40; if r.f.SignVal then temp:=temp+$80; if r.f.t then temp:=temp+$100; if r.f.I then temp:=temp+$200; if r.f.D then temp:=temp+$400; if r.f.OverVal then temp:=temp+$800; if r.f.m then temp:=temp+$8000; PUSH(temp); CLKS(12,8,3); end; function cpu_nec.BITOP_BYTE(ModRM:byte):byte; begin if (ModRM>=$c0) then case (ModRM and 7) of 0:BITOP_BYTE:=r.aw.l; 1:BITOP_BYTE:=r.cw.l; 2:BITOP_BYTE:=r.dw.l; 3:BITOP_BYTE:=r.bw.l; 4:BITOP_BYTE:=r.sp.l; 5:BITOP_BYTE:=r.bp.l; 6:BITOP_BYTE:=r.ix.l; 7:BITOP_BYTE:=r.iy.l; end else begin self.GetEA(ModRM); BITOP_BYTE:=self.getbyte(r.ea); end; end; function cpu_nec.BITOP_WORD(ModRM:byte):word; begin if (ModRM>=$c0) then case (ModRM and 7) of 0:BITOP_WORD:=r.aw.w; 1:BITOP_WORD:=r.cw.w; 2:BITOP_WORD:=r.dw.w; 3:BITOP_WORD:=r.bw.w; 4:BITOP_WORD:=r.sp.w; 5:BITOP_WORD:=r.bp.w; 6:BITOP_WORD:=r.ix.w; 7:BITOP_WORD:=r.iy.w; end else begin self.GetEA(ModRM); BITOP_WORD:=self.read_word(r.ea); end; end; procedure cpu_nec.ejecuta_instruccion(instruccion:byte); var tmpw,tmpw1:word; ModRM,srcb,dstb,c:byte; srcw,dstw:word; tmpb,tmpb1:byte; tmpdw,tmpdw1:dword; tmpi:integer; function POP:word; begin pop:=read_word((r.ss_r shl 4)+r.sp.w); r.sp.w:=r.sp.w+2; end; procedure ExpandFlags(temp:word); begin r.f.CarryVal:=(temp and 1)<>0; r.f.ParityVal:=(temp and 4)<>0; r.f.AuxVal:=(temp and $10)<>0; r.f.ZeroVal:=(temp and $40)<>0; r.f.SignVal:=(temp and $80)<>0; r.f.t:=(temp and $100)<>0; r.f.I:=(temp and $200)<>0; r.f.D:=(temp and $400)<>0; r.f.OverVal:=(temp and $800)<>0; r.f.m:=(temp and $8000)<>$8000; end; procedure i_popf; var tmp:word; begin tmp:=POP; ExpandFlags(tmp); CLKS(12,8,5); if r.f.t then MessageDlg('trap despues o_popf', mtInformation,[mbOk],0); end; procedure DEF_br8; begin ModRM:=self.FETCH; srcb:=RegByte(ModRM); dstb:=GetRMByte(ModRM); end; procedure DEF_wr16; begin ModRM:=FETCH; srcw:=RegWord(ModRM); dstw:=GetRMWord(ModRM); end; procedure DEF_r8b; begin ModRM:=FETCH; dstb:=RegByte(ModRM); srcb:=GetRMByte(ModRM); end; procedure DEF_r16w; begin ModRM:=FETCH; dstw:=RegWord(ModRM); srcw:=GetRMWord(ModRM); end; procedure DEF_ald8; begin srcb:=fetch; dstb:=r.aw.l; end; procedure DEF_axd16; begin srcw:=FETCH+(FETCH shl 8); dstw:=r.aw.w; end; begin case instruccion of $00:begin //i_add_br8 DEF_br8; dstb:=ADDB(srcb,dstb); PutbackRMByte(ModRM,dstb); CLKM(2,2,2,16,16,7,ModRM); end; $01:begin //i_add_wr16 DEF_wr16; dstw:=ADDW(srcw,dstw); PutbackRMWord(ModRM,dstw); CLKR(24,24,11,24,16,7,2,ModRM); end; $02:begin //i_add_r8b DEF_r8b; dstb:=ADDB(srcb,dstb); PutBackRegByte(ModRM,dstb); CLKM(2,2,2,11,11,6,ModRM); end; $03:begin //add_r16w DEF_r16w; dstw:=ADDW(srcw,dstw); PutBackRegWord(ModRM,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $04:begin //i_add_ald8 DEF_ald8; r.aw.l:=ADDB(srcb,dstb); CLKS(4,4,2); end; $05:begin //i_add_axd16 DEF_axd16; r.aw.w:=ADDW(srcw,dstw); CLKS(4,4,2); end; $06:begin //i_push_ds1 PUSH(r.ds1_r); CLKS(12,8,3); end; $07:begin //i_pop_es r.ds1_r:=POP; CLKS(12,8,5); end; $08:begin //i_or_br8 01_05 DEF_br8; dstb:=ORB(srcb,dstb); PutbackRMByte(ModRM,dstb); CLKM(2,2,2,16,16,7,ModRM); end; $09:begin //i_or_wr16 01_05 DEF_wr16; dstw:=ORW(srcw,dstw); PutbackRMWord(ModRM,dstw); CLKR(24,24,11,24,16,7,2,ModRM); end; $0a:begin //i_or_r8b DEF_r8b; dstb:=ORB(srcb,dstb); PutBackRegByte(ModRM,dstb); CLKM(2,2,2,11,11,6,ModRM); end; $0b:begin //i_or_r16w 28_04 DEF_r16w; dstw:=ORW(srcw,dstw); PutbackRegWord(ModRM,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $0c:begin //i_or_ald8 DEF_ald8; r.aw.l:=ORB(srcb,dstb); CLKS(4,4,2); end; $0d:begin //i_or_axd16 DEF_axd16; r.aw.w:=ORW(srcw,dstw); CLKS(4,4,2); end; $0e:begin //i_push_ps PUSH(r.ps_r); CLKS(12,8,3); end; $0f:begin //i_pre_nec case self.FETCH of {case 0x10 : BITOP_BYTE; CLKS(3,3,4); tmp2 = nec_state->regs.b[CL] & 0x7; nec_state->ZeroVal = (tmp & (1<<tmp2)) ? 1 : 0; nec_state->CarryVal=nec_state->OverVal=0; break; /* Test */ case 0x11 : BITOP_WORD; CLKS(3,3,4); tmp2 = nec_state->regs.b[CL] & 0xf; nec_state->ZeroVal = (tmp & (1<<tmp2)) ? 1 : 0; nec_state->CarryVal=nec_state->OverVal=0; break; /* Test */ case 0x12 : BITOP_BYTE; CLKS(5,5,4); tmp2 = nec_state->regs.b[CL] & 0x7; tmp &= ~(1<<tmp2); PutbackRMByte(ModRM,tmp); break; /* Clr */ case 0x13 : BITOP_WORD; CLKS(5,5,4); tmp2 = nec_state->regs.b[CL] & 0xf; tmp &= ~(1<<tmp2); PutbackRMWord(ModRM,tmp); break; /* Clr */ case 0x14 : BITOP_BYTE; CLKS(4,4,4); tmp2 = nec_state->regs.b[CL] & 0x7; tmp |= (1<<tmp2); PutbackRMByte(ModRM,tmp); break; /* Set */ case 0x15 : BITOP_WORD; CLKS(4,4,4); tmp2 = nec_state->regs.b[CL] & 0xf; tmp |= (1<<tmp2); PutbackRMWord(ModRM,tmp); break; /* Set */ case 0x16 : BITOP_BYTE; CLKS(4,4,4); tmp2 = nec_state->regs.b[CL] & 0x7; BIT_NOT; PutbackRMByte(ModRM,tmp); break; /* Not */ case 0x17 : BITOP_WORD; CLKS(4,4,4); tmp2 = nec_state->regs.b[CL] & 0xf; BIT_NOT; PutbackRMWord(ModRM,tmp); break; /* Not */ case 0x1e : BITOP_BYTE; CLKS(5,5,4); tmp2 = (FETCH()) & 0x7; BIT_NOT; PutbackRMByte(ModRM,tmp); break; /* Not */ case 0x1f : BITOP_WORD; CLKS(5,5,4); tmp2 = (FETCH()) & 0xf; BIT_NOT; PutbackRMWord(ModRM,tmp); break; /* Not */} $18:begin //TEST BYTE ModRM:=fetch; tmpb:=BITOP_BYTE(ModRM); CLKS(4,4,4); tmpb1:=fetch and $7; r.f.ZeroVal:=(tmpb and (1 shl tmpb1))=0; r.f.CarryVal:=false; r.f.OverVal:=false; end; $19:begin //TEST WORD ModRM:=fetch; tmpw:=BITOP_WORD(ModRM); CLKS(4,4,4); tmpb:=fetch and $f; r.f.ZeroVal:=(tmpw and (1 shl tmpb))=0; r.f.CarryVal:=false; r.f.OverVal:=false; end; $1a:begin //CLR BYTE ModRM:=fetch; tmpb:=BITOP_BYTE(ModRM); CLKS(6,6,4); tmpb1:=fetch and $7; tmpb:=tmpb and not(1 shl tmpb1); PutbackRMByte(ModRM,tmpb); end; $1b:begin //CLR WORD ModRM:=fetch; tmpw:=BITOP_WORD(ModRM); CLKS(6,6,4); tmpb:=fetch and $f; tmpw:=tmpw and not(1 shl tmpb); PutbackRMWord(ModRM,tmpw); end; $1c:begin //SET BYTE ModRM:=fetch; tmpb:=self.BITOP_BYTE(ModRM); CLKS(5,5,4); tmpb1:=fetch and $7; tmpb:=tmpb or (1 shl tmpb1); PutbackRMByte(ModRM,tmpb); end; $1d:begin //SET WORD ModRM:=fetch; tmpw:=self.BITOP_WORD(ModRM); CLKS(5,5,4); tmpb:=fetch and $f; tmpw:=tmpw or (1 shl tmpb); PutbackRMWord(ModRM,tmpw); end; $20:begin self.ADD4S; CLKS(7,7,2); end; { case 0x22 : SUB4S; CLKS(7,7,2); break; case 0x26 : CMP4S; CLKS(7,7,2); break; case 0x28 : ModRM = FETCH(); tmp = GetRMByte(ModRM); tmp <<= 4; tmp |= nec_state->regs.b[AL] & 0xf; nec_state->regs.b[AL] = (nec_state->regs.b[AL] & 0xf0) | ((tmp>>8)&0xf); tmp &= 0xff; PutbackRMByte(ModRM,tmp); CLKM(13,13,9,28,28,15); break; case 0x2a : ModRM = FETCH(); tmp = GetRMByte(ModRM); tmp2 = (nec_state->regs.b[AL] & 0xf)<<4; nec_state->regs.b[AL] = (nec_state->regs.b[AL] & 0xf0) | (tmp&0xf); tmp = tmp2 | (tmp>>4); PutbackRMByte(ModRM,tmp); CLKM(17,17,13,32,32,19); break; case 0x31 : ModRM = FETCH(); ModRM=0; logerror("%06x: Unimplemented bitfield INS\n",PC(nec_state)); break; case 0x33 : ModRM = FETCH(); ModRM=0; logerror("%06x: Unimplemented bitfield EXT\n",PC(nec_state)); break; case 0x92 : CLK(2); break; /* V25/35 FINT */ case 0xe0 : ModRM = FETCH(); ModRM=0; logerror("%06x: V33 unimplemented BRKXA (break to expansion address)\n",PC(nec_state)); break; case 0xf0 : ModRM = FETCH(); ModRM=0; logerror("%06x: V33 unimplemented RETXA (return from expansion address)\n",PC(nec_state)); break; case 0xff : ModRM = FETCH(); ModRM=0; logerror("%06x: unimplemented BRKEM (break to 8080 emulation mode)\n",PC(nec_state)); break;} else MessageDlg('$F otro...'+inttohex(((r.ps_r shl 4)+r.ip)-1,10)+' INST: '+inttohex(instruccion,4)+' oldPC: '+inttohex(((r.ps_r shl 4)+r.old_pc)-1,10), mtInformation,[mbOk],0); end; end; $10:begin //i_adc_br8 DEF_br8; srcb:=srcb+byte(r.f.CarryVal); dstb:=ADDB(srcb,dstb); PutbackRMByte(ModRM,dstb); CLKM(2,2,2,16,16,7,ModRM); end; $11:begin //i_adc_wr16 29_04 DEF_wr16; srcw:=srcw+byte(r.f.CarryVal); dstw:=ADDW(srcw,dstw); PutbackRMWord(ModRM,dstw); CLKR(24,24,11,24,16,7,2,ModRM); end; $12:begin //i_adc_r8b 01_05 DEF_r8b; srcb:=srcb+byte(r.f.CarryVal); dstb:=ADDB(srcb,dstb); PutBackRegByte(ModRM,dstb); CLKM(2,2,2,11,11,6,ModRM); end; $13:begin //i_adc_r16w 01_05 DEF_r16w; srcw:=srcw+byte(r.f.CarryVal); dstw:=ADDW(srcw,dstw); PutBackRegWord(ModRM,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $1b:begin //i_sbb_r16w 01_05 DEF_r16w; srcw:=srcw+byte(r.f.CarryVal); dstw:=SUBW(srcw,dstw); PutBackRegWord(ModRM,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $1e:begin //i_push_ds PUSH(r.ds0_r); CLKS(12,8,3); end; $1f:begin //i_pop_ds r.ds0_r:=POP; CLKS(12,8,5); end; $20:begin //i_and_br8 01_05 DEF_br8; dstb:=ANDB(srcb,dstb); PutbackRMByte(ModRM,dstb); CLKM(2,2,2,16,16,7,ModRM); end; $21:begin //i_and_wr16 01_05 DEF_wr16; dstw:=ANDW(srcw,dstw); PutbackRMWord(ModRM,dstw); CLKR(24,24,11,24,16,7,2,ModRM); end; $22:begin //i_and_r8b DEF_r8b; dstb:=ANDB(srcb,dstb); PutBackRegByte(ModRM,dstb); CLKM(2,2,2,11,11,6,ModRM); end; $23:begin //i_and_r16w DEF_r16w; dstw:=ANDW(srcw,dstw); PutBackRegWord(ModRM,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $24:begin //and_ald8 DEF_ald8; r.aw.l:=ANDB(srcb,dstb); CLKS(4,4,2); end; $25:begin //i_and_axd16 DEF_axd16; r.aw.w:=ANDW(srcw,dstw); CLKS(4,4,2); end; $26:begin //i_es self.seg_prefix:=true; self.prefix_base:=r.ds1_r shl 4; self.contador:=self.contador+2; ejecuta_instruccion(self.fetch); self.seg_prefix:=false; end; $27:begin //i_daa ADJ4(6,$60); CLKS(3,3,2); end; $28:begin //i_sub_br8 DEF_br8; dstb:=SUBB(srcb,dstb); PutbackRMByte(ModRM,dstb); CLKM(2,2,2,16,16,7,ModRM); end; $29:begin //i_sub_wr16 DEF_wr16; dstw:=SUBW(srcw,dstw); PutbackRMWord(ModRM,dstw); CLKR(24,24,11,24,16,7,2,ModRM); end; $2a:begin //i_sub_r8b DEF_r8b; dstb:=SUBB(srcb,dstb); PutBackRegByte(ModRM,dstb); CLKM(2,2,2,11,11,6,ModRM); end; $2b:begin //sub_r16w DEF_r16w; dstw:=SUBW(srcw,dstw); PutBackRegWord(ModRM,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $2c:begin //i_sub_ald8 DEF_ald8; r.aw.l:=SUBB(srcb,dstb); CLKS(4,4,2); end; $2d:begin //i_sub_axd16 DEF_axd16; r.aw.w:=SUBW(srcw,dstw); CLKS(4,4,2); end; $2e:begin //i_cs 28_04 self.seg_prefix:=true; self.prefix_base:=r.ps_r shl 4; self.contador:=self.contador+2; ejecuta_instruccion(self.fetch); self.seg_prefix:=false; end; $2f:begin //i_das self.ADJ4(-6,-$60); CLKS(3,3,2); end; $30:begin //i_xor_br8 DEF_br8; dstb:=XORB(srcb,dstb); PutbackRMByte(ModRM,dstb); CLKM(2,2,2,16,16,7,ModRM); end; $31:begin //i_xor_wr16 DEF_wr16; dstw:=XORW(srcw,dstw); PutbackRMWord(ModRM,dstw); CLKR(24,24,11,24,16,7,2,r.ea); end; $32:begin //i_xor_r8b DEF_r8b; dstb:=XORB(srcb,dstb); PutBackRegByte(ModRM,dstb); CLKM(2,2,2,11,11,6,ModRM); end; $33:begin //xor_r16w DEF_r16w; dstw:=XORW(srcw,dstw); PutBackRegWord(ModRM,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $34:begin //i_xor_ald8 DEF_ald8; r.aw.l:=XORB(srcb,dstb); CLKS(4,4,2); end; $35:begin //i_xor_axd16 DEF_axd16; r.aw.w:=XORW(srcw,dstw); CLKS(4,4,2); end; $36:begin //i_ss self.seg_prefix:=true; self.prefix_base:=r.ss_r shl 4; self.contador:=self.contador+2; ejecuta_instruccion(fetch); self.seg_prefix:=false; end; $38:begin //i_cmp_br8 DEF_br8; SUBB(srcb,dstb); CLKM(2,2,2,11,11,6,ModRM); end; $39:begin //i_cmp_wr16 DEF_wr16; SUBW(srcw,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $3a:begin //i_cmp_r8b DEF_r8b; SUBB(srcb,dstb); CLKM(2,2,2,11,11,6,ModRM); end; $3b:begin //i_cmp_r16w DEF_r16w; SUBW(srcw,dstw); CLKR(15,15,8,15,11,6,2,ModRM); end; $3c:begin //i_cmp_ald8 DEF_ald8; SUBB(srcb,dstb); CLKS(4,4,2); end; $3d:begin //i_cmp_axd16 DEF_axd16; SUBW(srcw,dstw); CLKS(4,4,2); end; $3e:begin //i_ds 29_04 seg_prefix:=true; prefix_base:=r.ds0_r shl 4; self.contador:=self.contador+2; ejecuta_instruccion(self.fetch); seg_prefix:=false; end; $40:begin //inc_ax r.aw.w:=IncWordReg(r.aw.w); self.contador:=self.contador+2; end; $41:begin //inc_cx r.cw.w:=IncWordReg(r.cw.w); self.contador:=self.contador+2; end; $42:begin //inc_dx r.dw.w:=IncWordReg(r.dw.w); self.contador:=self.contador+2; end; $43:begin //inc_bx r.bw.w:=IncWordReg(r.bw.w); self.contador:=self.contador+2; end; $44:begin //inc_sp r.sp.w:=IncWordReg(r.sp.w); self.contador:=self.contador+2; end; $45:begin //inc_bp r.bp.w:=IncWordReg(r.bp.w); self.contador:=self.contador+2; end; $46:begin //inc_si r.ix.w:=IncWordReg(r.ix.w); self.contador:=self.contador+2; end; $47:begin //inc_di r.iy.w:=IncWordReg(r.iy.w); self.contador:=self.contador+2; end; $48:begin //dec_ax r.aw.w:=decWordReg(r.aw.w); self.contador:=self.contador+2; end; $49:begin //dec_cx r.cw.w:=DecWordReg(r.cw.w); self.contador:=self.contador+2; end; $4a:begin //dec_dx r.dw.w:=DecWordReg(r.dw.w); self.contador:=self.contador+2; end; $4b:begin //dec_bx r.bw.w:=DecWordReg(r.bw.w); self.contador:=self.contador+2; end; $4c:begin //dec_sp r.sp.w:=DecWordReg(r.sp.w); self.contador:=self.contador+2; end; $4d:begin //dec_bp r.bp.w:=DecWordReg(r.bp.w); self.contador:=self.contador+2; end; $4e:begin //dec_si r.ix.w:=DecWordReg(r.ix.w); self.contador:=self.contador+2; end; $4f:begin //dec_di r.iy.w:=DecWordReg(r.iy.w); self.contador:=self.contador+2; end; $50:begin //i_push_ax PUSH(r.aw.w); CLKS(12,8,3); end; $51:begin //i_push_cx PUSH(r.cw.w); CLKS(12,8,3); end; $52:begin //i_push_dx PUSH(r.dw.w); CLKS(12,8,3); end; $53:begin //i_push_bx PUSH(r.bw.w); CLKS(12,8,3); end; $54:begin //i_push_sp PUSH(r.sp.w); CLKS(12,8,3); end; $55:begin //i_push_bp PUSH(r.bp.w); CLKS(12,8,3); end; $56:begin //i_push_si PUSH(r.ix.w); CLKS(12,8,3); end; $57:begin //i_push_di PUSH(r.iy.w); CLKS(12,8,3); end; $58:begin //i_pop_ax r.aw.w:=POP; CLKS(12,8,5); end; $59:begin //i_pop_cx r.cw.w:=POP; CLKS(12,8,5); end; $5a:begin //i_pop_dx r.dw.w:=POP; CLKS(12,8,5); end; $5b:begin //i_pop_bx r.bw.w:=POP; CLKS(12,8,5); end; $5c:begin //i_pop_sp r.sp.w:=POP; CLKS(12,8,5); end; $5d:begin //i_pop_bp r.bp.w:=POP; CLKS(12,8,5); end; $5e:begin //i_pop_si r.ix.w:=POP; CLKS(12,8,5); end; $5f:begin //i_pop_di r.iy.w:=POP; CLKS(12,8,5); end; $60:begin //i_pusha tmpw:=r.sp.w; PUSH(r.aw.w); PUSH(r.cw.w); PUSH(r.dw.w); PUSH(r.bw.w); PUSH(tmpw); PUSH(r.bp.w); PUSH(r.ix.w); PUSH(r.iy.w); CLKS(67,35,20); end; $61:begin //i_popa r.iy.w:=POP; r.ix.w:=POP; r.bp.w:=POP; POP; r.bw.w:=POP; r.dw.w:=POP; r.cw.w:=POP; r.aw.w:=POP; CLKS(75,43,22); end; $68:begin //i_push_d16 tmpw:=fetchword; PUSH(tmpw); CLKW(12,12,5,12,8,5,r.sp.w); end; $6a:begin //i_push_d8 tmpw:=smallint(shortint(fetch)); self.PUSH(tmpw); CLKW(11,11,5,11,7,3,r.sp.w); end; $6b:begin //i_imul_d8 DEF_r16w; tmpw:=smallint(shortint(fetch)); tmpi:=integer(smallint(srcw))*integer(tmpw); r.f.CarryVal:=((tmpi div $8000)<>0) and ((tmpi div $8000)<>-1); r.f.OverVal:=r.f.CarryVal; PutBackRegWord(ModRM,word(tmpi)); if (ModRM>=$c0) then self.contador:=self.contador+31 else self.contador:=self.contador+39; end; $70:begin //jo i_JMP(r.f.OverVal); CLKS(4,4,3); end; $71:begin //jno i_JMP(not(r.f.OverVal)); CLKS(4,4,3); end; $72:begin //i_jc i_JMP(r.f.CarryVal); CLKS(4,4,3); end; $73:begin //i_jnc i_JMP(not(r.f.CarryVal)); CLKS(4,4,3); end; $74:begin i_JMP(r.f.ZeroVal); CLKS(4,4,3); end; $75:begin //jnz i_JMP(not(r.f.ZeroVal)); CLKS(4,4,3); end; $76:begin //i_jce i_JMP((r.f.CarryVal or r.f.ZeroVal)); CLKS(4,4,3); end; $77:begin //i_jnce i_JMP(not(r.f.CarryVal or r.f.ZeroVal)); CLKS(4,4,3); end; $78:begin //i_js i_JMP(r.f.SignVal); CLKS(4,4,3); end; $79:begin //i_jns i_JMP(not(r.f.SignVal)); CLKS(4,4,3); end; $7a:begin //i_jp i_JMP(r.f.ParityVal); CLKS(4,4,3); end; $7b:begin //i_jnp i_JMP(not(r.f.ParityVal)); CLKS(4,4,3); end; $7c:begin //i_jl i_JMP(((r.f.SignVal<>r.f.OverVal) and not(r.f.ZeroVal))); CLKS(4,4,3); end; $7d:begin //i_jnl i_JMP((r.f.ZeroVal or (r.f.SignVal=r.f.OverVal))); CLKS(4,4,3); end; $7e:begin //i_jle i_JMP((r.f.ZeroVal or (r.f.SignVal<>r.f.OverVal))); CLKS(4,4,3); end; $7f:begin //i_jnle i_JMP(((r.f.SignVal=r.f.OverVal) and not(r.f.ZeroVal))); CLKS(4,4,3); end; $80:begin //i_80pre ModRM:=fetch; dstb:=GetRMByte(ModRM); //dst srcb:=fetch; //src if (ModRM>=$c0) then CLKS(4,4,2) else if ((ModRM and $38)=$38) then CLKS(13,13,6) else CLKS(18,18,7); case (ModRM and $38) of $00:begin //ADDB dstb:=ADDB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $08:begin //ORB dstb:=ORB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $10:begin //ADDB CF 28/04 srcb:=srcb+byte(r.f.CarryVal); dstb:=ADDB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $18:MessageDlg('$80 SUBB CF', mtInformation,[mbOk],0);// src+=CF; SUBB; PutbackRMByte(ModRM,dst); $20:begin //ANDB dstb:=ANDB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $28:begin dstb:=SUBB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $30:begin //XORB dstb:=XORB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $38:SUBB(srcb,dstb); // CMPB end; end; $81:begin //i_81pre ModRM:=fetch; dstw:=GetRMWord(ModRM); srcw:=fetchword; if (ModRM>=$c0) then CLKS(4,4,2) else if ((ModRM and $38)=$38) then CLKW(17,17,8,17,13,6,r.ea) else CLKW(26,26,11,26,18,7,r.ea); case (ModRM and $38) of $00:begin //ADDW dstw:=ADDW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $08:begin dstw:=ORW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $10:MessageDlg('$81 ADDW CF', mtInformation,[mbOk],0);// src+=CF; ADDW; PutbackRMWord(ModRM,dst); break; $18:MessageDlg('$81 SUBW CF', mtInformation,[mbOk],0);// src+=CF; SUBW; PutbackRMWord(ModRM,dst); break; $20:begin //ANDW dstw:=ANDW(srcw,dstw); PutBackRMWord(ModRM,dstw); end; $28:begin dstw:=SUBW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $30:begin //XORW 01_05 dstw:=XORW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $38:SUBW(srcw,dstw); // CMP end; end; $82:begin //i_82pre ModRM:=fetch; dstb:=GetRMByte(ModRM); //dst srcb:=shortint(fetch); //src if (ModRM>=$c0) then CLKS(4,4,2) else if ((ModRM and $38)=$38) then CLKS(13,13,6) else CLKS(18,18,7); case (ModRM and $38) of $00:begin //ADDB dstb:=ADDB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $08:begin //ORB dstb:=ORB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $10:begin //ADDB CF 28/04 srcb:=srcb+byte(r.f.CarryVal); dstb:=ADDB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $18:MessageDlg('$80 SUBB CF', mtInformation,[mbOk],0);// src+=CF; SUBB; PutbackRMByte(ModRM,dst); $20:begin //ANDB dstb:=ANDB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $28:begin dstb:=SUBB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $30:begin //XORB dstb:=XORB(srcb,dstb); PutbackRMByte(ModRM,dstb); end; $38:SUBB(srcb,dstb); // CMPB end; end; $83:begin //i_83pre ModRM:=fetch; dstw:=GetRMWord(ModRM); //dst srcw:=fetch; //src srcw:=smallint(shortint(srcw)); if (ModRM>=$c0) then CLKS(4,4,2) else if ((ModRM and $38)=$38) then CLKW(17,17,8,17,13,6,r.ea) else CLKW(26,26,11,26,18,7,r.ea); case (ModRM and $38) of $00:begin //ADDW dstw:=ADDW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $08:begin dstw:=ORW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $10:begin // 01_05 srcw:=srcw+byte(r.f.CarryVal); dstw:=ADDW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $18:MessageDlg('$83 SUBW CF', mtInformation,[mbOk],0);// src+=CF; SUBW; PutbackRMWord(ModRM,dst); break; $20:begin dstw:=ANDW(srcw,dstw); PutBackRMWord(ModRM,dstw); end; $28:begin dstw:=SUBW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $30:begin dstw:=XORW(srcw,dstw); PutbackRMWord(ModRM,dstw); end; $38:SUBW(srcw,dstw); // CMP end; end; $84:begin //i_test_br8 28_04 DEF_br8; ANDB(srcb,dstb); CLKM(2,2,2,10,10,6,ModRM); end; $85:begin //i_test_wr16 DEF_wr16; ANDW(srcw,dstw); CLKR(14,14,8,14,10,6,2,ModRM); end; $86:begin //i_xchg_br8 DEF_br8; PutBackRegByte(ModRM,dstb); PutbackRMByte(ModRM,srcb); CLKM(3,3,3,16,18,8,ModRM); end; $87:begin //i_xchg_wr16 DEF_wr16; PutBackRegWord(ModRM,dstw); PutbackRMWord(ModRM,srcw); CLKR(24,24,12,24,16,8,3,ModRM); end; $88:begin //i_mov_br8 ModRM:=fetch; srcb:=RegByte(ModRM); PutRMByte(ModRM,srcb); CLKM(2,2,2,9,9,3,ModRM); end; $89:begin //i_mov_wr16 ModRM:=fetch; srcw:=RegWord(ModRM); PutRMWord(ModRM,srcw); CLKR(13,13,5,13,9,3,2,r.ea); end; $8a:begin //i_mov_r8b ModRM:=fetch; srcb:=GetRMByte(ModRM); //src PutBackRegByte(ModRM,srcb); CLKM(2,2,2,11,11,5,ModRM); end; $8b:begin //i_mov_r16w ModRM:=fetch; srcw:=GetRMWord(ModRM); //src PutBackRegWord(ModRM,srcw); CLKR(15,15,7,15,11,5,2,r.ea); end; $8c:begin //i_mov_wsreg ModRM:=fetch; CLKR(14,14,5,14,10,3,2,ModRM); case (ModRM and $38) of $00:PutRMWord(ModRM,r.DS1_r); $08:PutRMWord(ModRM,r.PS_r); $10:PutRMWord(ModRM,r.SS_r); $18:PutRMWord(ModRM,r.DS0_r); else MessageDlg('$8c MOV Sreg - Invalid', mtInformation,[mbOk],0); end; end; $8d:begin //i_lea ModRM:=fetch; if (ModRM>=$c0) then //logerror("LDEA invalid mode %Xh\n", ModRM) halt(0) else begin self.GetEA(ModRM); PutBackRegWord(ModRM,r.EO); end; CLKS(4,4,2); end; $8e:begin //mov_sregw ModRM:=fetch; srcw:=GetRMWord(ModRM); //src CLKR(15,15,7,15,11,5,2,ModRM); case (ModRM and $38) of $00:r.ds1_r:=srcw; // mov es,ew $08:r.ps_r:=srcw; // mov cs,ew $10:r.ss_r:=srcw; // mov ss,ew $18:r.ds0_r:=srcw;// mov ds,ew else MessageDlg('$8e Mov Sreg invalido', mtInformation,[mbOk],0); end; self.no_interrupt:=true; end; $8f:begin //i_popw ModRM:=fetch; dstw:=POP; PutRMWord(ModRM,dstw); self.contador:=self.contador+21; end; $90:self.contador:=self.contador+3; //nop $91:begin //i_xchg_axcx dstw:=r.cw.w; r.cw.w:=r.aw.w; r.aw.w:=dstw; self.contador:=self.contador+3; end; $92:begin //i_xchg_axdx dstw:=r.dw.w; r.dw.w:=r.aw.w; r.aw.w:=dstw; self.contador:=self.contador+3; end; $93:begin //i_xchg_axbx dstw:=r.bw.w; r.bw.w:=r.aw.w; r.aw.w:=dstw; self.contador:=self.contador+3; end; $94:begin //i_xchg_axsp dstw:=r.sp.w; r.sp.w:=r.aw.w; r.aw.w:=dstw; self.contador:=self.contador+3; end; $95:begin //i_xchg_axbp dstw:=r.bp.w; r.bp.w:=r.aw.w; r.aw.w:=dstw; self.contador:=self.contador+3; end; $96:begin //i_xchg_axsi dstw:=r.ix.w; r.ix.w:=r.aw.w; r.aw.w:=dstw; self.contador:=self.contador+3; end; $97:begin //i_xchg_axdi dstw:=r.iy.w; r.iy.w:=r.aw.w; r.aw.w:=dstw; self.contador:=self.contador+3; end; $98:begin //i_cbw if (r.aw.l and $80)<>0 then r.aw.h:=$ff else r.aw.h:=0; self.contador:=self.contador+2; end; $99:begin //i_cwd 29_04 if (r.aw.h and $80)<>0 then r.dw.w:=$ffff else r.dw.w:=0; self.contador:=self.contador+4; end; $9a:begin //i_call_far tmpw:=self.fetchword; //tmp tmpw1:=self.fetchword; //tmp2 PUSH(r.ps_r); PUSH(r.ip); r.ip:=tmpw; r.ps_r:=tmpw1; self.prefetch_reset:=true; CLKW(29,29,13,29,21,9,r.sp.w); end; $9c:i_pushf; $9d:i_popf; $a0:begin //mov_aldisp srcw:=self.fetchword; r.aw.l:=GetMemB(DS0,srcw); CLKS(10,10,5); end; $a1:begin //mov_axdisp srcw:=self.fetchword; r.aw.w:=GetMemW(DS0,srcw); CLKW(14,14,7,14,10,5,srcw); end; $a2:begin //i_mov_dispal srcw:=self.fetchword; //addr PutMemB(DS0,srcw,r.aw.l); CLKS(9,9,3); end; $a3:begin //i_mov_dispax srcw:=self.fetchword; PutMemW(DS0,srcw,r.aw.w); CLKW(13,13,5,13,9,3,srcw); end; $a4:self.i_movsb; $a5:self.i_movsw; $a8:begin //i_test_ald8 DEF_ald8; ANDB(srcb,dstb); CLKS(4,4,2); end; $a9:begin //i_test_axd16 DEF_axd16; ANDW(srcw,dstw); CLKS(4,4,2); end; $aa:self.i_stosb; $ab:self.i_stosw; $ac:self.i_lodsb; $ad:self.i_lodsw; $ae:self.i_scasb; $af:self.i_scasw; $b0:begin //mov_ald8 r.aw.l:=fetch; CLKS(4,4,2); end; $b1:begin //mov_cld8 r.cw.l:=fetch; CLKS(4,4,2); end; $b2:begin //mov_dld8 r.dw.l:=fetch; CLKS(4,4,2); end; $b3:begin //mov_bld8 r.bw.l:=fetch; CLKS(4,4,2); end; $b4:begin //mov_ahd8 r.aw.h:=fetch; CLKS(4,4,2); end; $b5:begin //mov_chd8 r.cw.h:=fetch; CLKS(4,4,2); end; $b6:begin //mov_dhd8 r.dw.h:=fetch; CLKS(4,4,2); end; $b7:begin //mov_bhd8 r.bw.h:=fetch; CLKS(4,4,2); end; $b8:begin //mov_axd16 r.aw.l:=fetch; r.aw.h:=fetch; CLKS(4,4,2); end; $b9:begin //mov_cxd16 r.cw.l:=fetch; r.cw.h:=fetch; CLKS(4,4,2); end; $ba:begin //mov_dxd16 r.dw.l:=fetch; r.dw.h:=fetch; CLKS(4,4,2); end; $bb:begin //mov_bxd16 r.bw.l:=fetch; r.bw.h:=fetch; CLKS(4,4,2); end; $bc:begin //mov_spd16 r.sp.w:=fetchword; CLKS(4,4,2); end; $bd:begin //mov_bpd16 r.bp.w:=fetchword; CLKS(4,4,2); end; $be:begin //mov_sid16 r.ix.w:=fetchword; CLKS(4,4,2); end; $bf:begin //mov_did16 r.iy.w:=fetchword; CLKS(4,4,2); end; $c0:begin //i_rotshft_bd8 ModRM:=fetch; srcb:=GetRMByte(ModRM); dstb:=srcb; c:=fetch; CLKM(7,7,2,19,19,6,ModRM); if (c<>0) then case (ModRM and $38) of $00:begin // 03_05 repeat dstb:=ROL_BYTE(dstb); c:=c-1; self.contador:=self.contador+1; until not(c>0); PutbackRMByte(ModRM,dstb); end; $08:begin repeat dstb:=ROR_BYTE(dstb); c:=c-1; self.contador:=self.contador+1; until not(c>0); PutbackRMByte(ModRM,dstb); end; $10:MessageDlg('$c0 ROLC_BYTE!', mtInformation,[mbOk],0); $18:MessageDlg('$c0 RORC_BYTE!', mtInformation,[mbOk],0); $20:begin dstb:=SHL_BYTE(c,dstb); self.PutbackRMByte(ModRM,dstb); end; $28:begin dstb:=SHR_BYTE(c,dstb); self.PutbackRMByte(ModRM,dstb); end; $30:MessageDlg('$c0 SHLA_BYTE indefinido!', mtInformation,[mbOk],0); $38:MessageDlg('$c0 SHRA_BYTE!', mtInformation,[mbOk],0);// SHRA_BYTE(c); break; end; end; $c1:begin //i_rotshft_wd8 ModRM:=fetch; srcw:=GetRMWord(ModRM); dstw:=srcw; c:=fetch; CLKM(7,7,2,27,19,6,ModRM); if (c<>0) then case (ModRM and $38) of $00:begin //03_05 repeat dstw:=ROL_WORD(dstw); c:=c-1; self.contador:=self.contador+1; until not(c>0); PutbackRMWord(ModRM,dstw); end; $08:begin //03_05 repeat dstw:=ROR_WORD(dstw); c:=c-1; self.contador:=self.contador+1; until not(c>0); PutbackRMWord(ModRM,dstw); end; $10:MessageDlg('$c1 ROLC_WORD!', mtInformation,[mbOk],0);// do { ROLC_WORD; c--; CLK(1); } {while (c>0); PutbackRMWord(ModRM,(WORD)dst); break; $18:MessageDlg('$c1 RORC_WORD!', mtInformation,[mbOk],0); // do { RORC_WORD; c--; CLK(1); }{ while (c>0); PutbackRMWord(ModRM,(WORD)dst); break; $20:begin dstw:=SHL_WORD(c,dstw); self.PutbackRMWord(ModRM,dstw); end; $28:begin dstw:=SHR_WORD(c,dstw); self.PutbackRMWord(ModRM,dstw); end; $30:MessageDlg('$c1 SHLA_WORD indefinido!', mtInformation,[mbOk],0); $38:SHRA_WORD(c,dstw,ModRM); //03_05 end; end; $c3:begin //i_ret r.ip:=POP; self.prefetch_reset:=true; CLKS(19,19,10); end; $c4:begin //i_les_dw 01_05 ModRM:=fetch; tmpw:=GetRMWord(ModRM); PutBackRegWord(ModRM,tmpw); r.ds1_r:=self.read_word((r.ea and $f0000) or ((r.ea+2) and $ffff)); CLKW(26,26,14,26,18,10,r.ea); end; $c5:begin //i_lds_dw 01_05 ModRM:=fetch; tmpw:=GetRMWord(ModRM); PutBackRegWord(ModRM,tmpw); r.ds0_r:=self.read_word((r.ea and $f0000) or ((r.ea+2) and $ffff)); CLKW(26,26,14,26,18,10,r.ea); end; $c6:begin //i_mov_bd8 ModRM:=fetch; PutImmRMByte(ModRM); if ModRM>=$c0 then self.contador:=self.contador+4 else self.contador:=self.contador+11; end; $c7:begin //i_mov_wd16 ModRM:=fetch; PutImmRMWord(ModRM); if ModRM>=$c0 then self.contador:=self.contador+4 else self.contador:=self.contador+15; end; $c8:begin //i_enter tmpw:=fetch; self.contador:=self.contador+23; tmpw:=tmpw+(fetch shl 8); tmpb:=fetch; self.PUSH(r.bp.w); r.bp.w:=r.sp.w; r.sp.w:=r.sp.w-tmpw; for tmpb1:=1 to tmpb do begin self.PUSH(self.GetMemW(SS,r.bp.w-tmpb1*2)); self.contador:=self.contador+16; end; if tmpb<>0 then self.PUSH(r.bp.w); end; $c9:begin //i_leave r.sp.w:=r.bp.w; r.bp.w:=POP; self.contador:=self.contador+8; end; $cb:begin //i_retf r.ip:=POP; r.ps_r:=POP; self.prefetch_reset:=true; CLKS(29,29,16); end; $cf:begin //i_iret r.ip:=POP; r.ps_r:=POP; i_popf; self.prefetch_reset:=true; CLKS(39,39,19); end; $d0:begin //i_rotshft_b ModRM:=fetch; srcb:=GetRMByte(ModRM); dstb:=srcb; CLKM(6,6,2,16,16,7,ModRM); case (ModRM and $38) of $00:begin // 01_05 dstb:=ROL_BYTE(dstb); PutbackRMByte(ModRM,dstb); r.f.OverVal:=((srcb xor dstb) and $80)<>0; end; $08:begin // 01_05 dstb:=ROR_BYTE(dstb); PutbackRMByte(ModRM,dstb); r.f.OverVal:=((srcb xor dstb) and $80)<>0; end; $10:begin dstb:=ROLC_BYTE(dstb); PutbackRMByte(ModRM,dstb); r.f.OverVal:=((srcb xor dstb) and $80)<>0; end; $18:begin dstb:=RORC_BYTE(dstb); PutbackRMByte(ModRM,dstb); r.f.OverVal:=((srcb xor dstb) and $80)<>0; end; $20:begin //SHL_BYTE dstb:=SHL_BYTE(1,dstb); self.PutbackRMByte(ModRM,dstb); r.f.OverVal:=((srcb xor dstb) and $80)<>0; end; $28:begin dstb:=SHR_BYTE(1,dstb); self.PutbackRMByte(ModRM,dstb); r.f.OverVal:=((srcb xor dstb) and $80)<>0; end; $30:MessageDlg('$d0 SHLA_BYTE Invalido!', mtInformation,[mbOk],0); $38:MessageDlg('$d0 SHRA_BYTE', mtInformation,[mbOk],0);// SHRA_BYTE(1); nec_state->OverVal = 0; break; end; end; $d1:begin //i_rotshft_w ModRM:=fetch; srcw:=GetRMWord(ModRM); dstw:=srcw; CLKM(6,6,2,24,16,7,ModRM); case (ModRM and $38) of $00:begin dstw:=ROL_WORD(dstw); PutbackRMWord(ModRM,dstw); r.f.OverVal:=((srcw xor dstw) and $8000)<>0; end; $08:begin dstw:=ROR_WORD(dstw); PutbackRMWord(ModRM,dstw); r.f.OverVal:=((srcw xor dstw) and $8000)<>0; end; $10:begin dstw:=ROLC_WORD(dstw); PutbackRMWord(ModRM,dstw); r.f.OverVal:=((srcw xor dstw) and $8000)<>0; end; $18:MessageDlg('$d1 RORC_WORD', mtInformation,[mbOk],0);//RORC_WORD; PutbackRMWord(ModRM,(WORD)dst); nec_state->OverVal = (src^dst)&0x8000; break; $20:begin //28_04 dstw:=SHL_WORD(1,dstw); self.PutbackRMWord(ModRM,dstw); r.f.OverVal:=((srcw xor dstw) and $8000)<>0; end; $28:begin dstw:=SHR_WORD(1,dstw); self.PutbackRMWord(ModRM,dstw); r.f.OverVal:=((srcw xor dstw) and $8000)<>0; end; $30:MessageDlg('$d1 SHLA_WORD Invalido!', mtInformation,[mbOk],0); $38:begin SHRA_WORD(1,dstw,ModRM); r.f.OverVal:=false; end; end; end; $d2:begin //i_rotshft_bcl ModRM:=fetch; srcb:=GetRMByte(ModRM); dstb:=srcb; c:=r.cw.l; CLKM(7,7,2,19,19,6,ModRM); if (c<>0) then case (ModRM and $38) of $00:begin repeat dstb:=ROL_BYTE(dstb); c:=c-1; self.contador:=self.contador+1; until not(c>0); PutbackRMByte(ModRM,dstb); end; $08:MessageDlg('$d2 ROR_BYTE', mtInformation,[mbOk],0); // do { ROR_BYTE; c--; CLK(1); }// while (c>0); PutbackRMByte(ModRM,(BYTE)dst); break; $10:begin repeat dstb:=ROLC_BYTE(dstb); c:=c-1; self.contador:=self.contador+1; until not(c>0); PutbackRMByte(ModRM,dstb); end; $18:begin repeat dstb:=RORC_BYTE(dstb); c:=c-1; self.contador:=self.contador+1; until not(c>0); PutbackRMByte(ModRM,dstb); end; $20:begin dstb:=SHL_BYTE(c,dstb); self.PutbackRMByte(ModRM,dstb); end; $28:begin dstb:=SHR_BYTE(c,dstb); self.PutbackRMByte(ModRM,dstb); end; $30:MessageDlg('$d2 SHLA_BYTE Invalido!', mtInformation,[mbOk],0); $38:MessageDlg('$d2 SHRA_BYTE', mtInformation,[mbOk],0); // SHRA_BYTE(c); break; end; end; $d3:begin //i_rotshft_wcl ModRM:=fetch; srcw:=GetRMWord(ModRM); dstw:=srcw; c:=r.cw.l; CLKM(7,7,2,19,19,6,ModRM); if (c<>0) then case (ModRM and $38) of $00:MessageDlg('$d3 ROL_WORD', mtInformation,[mbOk],0); // do { ROL_BYTE; c--; CLK(1); } //while (c>0); PutbackRMByte(ModRM,(BYTE)dst); break; $08:MessageDlg('$d3 ROR_WORD', mtInformation,[mbOk],0); // do { ROR_BYTE; c--; CLK(1); }// while (c>0); PutbackRMByte(ModRM,(BYTE)dst); break; $10:MessageDlg('$d3 ROLC_WORD', mtInformation,[mbOk],0); $18:MessageDlg('$d3 RORC_WORD', mtInformation,[mbOk],0); $20:begin dstw:=SHL_WORD(c,dstw); self.PutbackRMWord(ModRM,dstw); end; $28:begin dstw:=SHR_WORD(c,dstw); self.PutbackRMWord(ModRM,dstw); end; $30:MessageDlg('$d3 SHLA_WORD Invalido!', mtInformation,[mbOk],0); $38:SHRA_WORD(c,dstw,ModRM); end; end; $e1:begin //i_loope tmpb:=fetch; r.cw.w:=r.cw.w-1; if (r.f.ZeroVal and (r.cw.w<>0)) then begin r.ip:=r.ip+shortint(tmpb); CLKS(14,14,6); end else CLKS(5,5,3); end; $e2:begin //i_loop tmpb:=fetch; r.cw.w:=r.cw.w-1; if (r.cw.w<>0) then begin r.ip:=r.ip+shortint(tmpb); CLKS(13,13,6); end else CLKS(5,5,3); end; $e3:begin //i_jcxz tmpb:=fetch; if (r.cw.w=0) then begin r.ip:=r.ip+shortint(tmpb); CLKS(13,13,6); end else CLKS(5,5,3); end; $e4:begin //i_inal tmpb:=fetch; self.r.aw.l:=self.inbyte(tmpb); CLKS(9,9,5); end; $e5:begin //inax tmpb:=fetch; r.aw.w:=self.inword(tmpb); CLKW(13,13,7,13,9,5,tmpb); end; $e6:begin //outal tmpb:=fetch; self.outbyte(tmpb,r.aw.l); CLKS(8,8,3); end; $e7:begin //outax tmpb:=fetch; self.outword(tmpb,r.aw.w); CLKW(12,12,5,12,8,3,tmpb); end; $e8:begin //i_call_d16 tmpw:=self.fetchword; PUSH(r.ip); r.ip:=r.ip+smallint(tmpw); self.prefetch_reset:=true; self.contador:=self.contador+24; end; $e9:begin //jmp_d16 tmpw:=self.fetchword; r.ip:=r.ip+smallint(tmpw); self.prefetch_reset:=true; self.contador:=self.contador+15; end; $ea:begin //jump_far tmpw:=self.fetchword; tmpw1:=self.fetchword; r.ip:=tmpw; r.ps_r:=tmpw1; self.prefetch_reset:=true; self.contador:=self.contador+27; end; $eb:begin //i_jmp_d8 tmpb:=fetch; r.ip:=r.ip+shortint(tmpb); self.contador:=self.contador+12; end; $ec:begin //i_inaldx self.r.aw.l:=self.inbyte(self.r.dw.w); CLKS(8,8,5); end; $ee:begin //i_outdxal self.outbyte(self.r.dw.w,self.r.aw.l); CLKS(8,8,3); end; $ef:begin //i_outdxax self.outword(self.r.dw.w,self.r.aw.w); CLKW(12,12,5,12,8,3,r.dw.w) end; $f2:begin //i_repne 29_04 tmpb:=fetch; tmpw:=r.cw.w; case tmpb of $26:begin seg_prefix:=true; prefix_base:=r.ds1_r shl 4; tmpb:=fetch; inc(self.contador,2); end; $2e:begin seg_prefix:=true; prefix_base:=r.ps_r shl 4; tmpb:=fetch; inc(self.contador,2); end; $36:begin seg_prefix:=true; prefix_base:=r.ss_r shl 4; tmpb:=fetch; inc(self.contador,2); end; $3e:begin seg_prefix:=true; prefix_base:=r.ds0_r shl 4; tmpb:=fetch; inc(self.contador,2); end; end; self.contador:=self.contador+2; case tmpb of { $6c: CLK(2); if (c) do { i_insb(); c--; } //while (c>0); Wreg(CW)=c; break; { $6d: CLK(2); if (c) do { i_insw(); c--; } //while (c>0); Wreg(CW)=c; break; { $6e: CLK(2); if (c) do { i_outsb(); c--; } //while (c>0); Wreg(CW)=c; break; { $6f: CLK(2); if (c) do { i_outsw(); c--; } //while (c>0); Wreg(CW)=c; break; { $a4: CLK(2); if (c) do { i_movsb(); c--; } //while (c>0); Wreg(CW)=c; break; { $a6: CLK(2); if (c) do { i_cmpsb(); c--; } //while (c>0 && ZF==0); Wreg(CW)=c; break; { $a7: CLK(2); if (c) do { i_cmpsw(); c--; } //while (c>0 && ZF==0); Wreg(CW)=c; break; { $aa: CLK(2); if (c) do { i_stosb(); c--; } //while (c>0); Wreg(CW)=c; break; { $ab: CLK(2); if (c) do { i_stosw(); c--; } //while (c>0); Wreg(CW)=c; break; { $ac: CLK(2); if (c) do { i_lodsb(); c--; } //while (c>0); Wreg(CW)=c; break; { $ad: CLK(2); if (c) do { i_lodsw(); c--; } //while (c>0); Wreg(CW)=c; break; $a4:if (tmpw<>0) then begin repeat self.i_movsb; tmpw:=tmpw-1; until not((tmpw>0)); r.cw.w:=tmpw; end; $a5:if (tmpw<>0) then begin repeat self.i_movsw; tmpw:=tmpw-1; until not((tmpw>0)); r.cw.w:=tmpw; end; $ae:if (tmpw<>0) then begin repeat self.i_scasb; tmpw:=tmpw-1; until not((tmpw>0) and not(r.f.ZeroVal)); r.cw.w:=tmpw; end; $af:if (tmpw<>0) then begin repeat self.i_scasw; tmpw:=tmpw-1; until not((tmpw>0) and not(r.f.ZeroVal)); r.cw.w:=tmpw; end; else MessageDlg('$f2 Mal! '+inttohex(tmpb,10), mtInformation,[mbOk],0); end; seg_prefix:=false; end; $f3:begin //repe tmpb:=fetch; //next tmpw:=r.cw.w; //c case tmpb of // Puede que coja esto o NO!!! $26:begin self.seg_prefix:=true; self.prefix_base:=r.ds1_r shl 4; tmpb:=self.fetch; self.contador:=self.contador+2; end; $2e:begin self.seg_prefix:=true; self.prefix_base:=r.ps_r shl 4; tmpb:=self.fetch; self.contador:=self.contador+2; end; $36:begin self.seg_prefix:=true; self.prefix_base:=r.ss_r shl 4; tmpb:=self.fetch; self.contador:=self.contador+2; end; $3e:begin self.seg_prefix:=true; self.prefix_base:=r.ds0_r shl 4; tmpb:=self.fetch; self.contador:=self.contador+2; end; end; self.contador:=self.contador+2; case tmpb of $6c:MessageDlg('$f3 i_insb', mtInformation,[mbOk],0); $6d:MessageDlg('$f3 i_insw', mtInformation,[mbOk],0); $6e:MessageDlg('$f3 i_outsb', mtInformation,[mbOk],0); $6f:MessageDlg('$f3 i_outsw', mtInformation,[mbOk],0); $a4:if (tmpw<>0) then begin //i_movsb repeat self.i_movsb; tmpw:=tmpw-1; until not(tmpw>0); r.cw.w:=tmpw; end; $a5:if (tmpw<>0) then begin //i_movsw repeat self.i_movsw; tmpw:=tmpw-1; until not(tmpw>0); r.cw.w:=tmpw; end; $a6:MessageDlg('$f3 i_cmpsb', mtInformation,[mbOk],0); $a7:MessageDlg('$f3 i_cmpsw', mtInformation,[mbOk],0); $aa:if (tmpw<>0) then begin repeat self.i_stosb; tmpw:=tmpw-1; until not(tmpw>0); r.cw.w:=tmpw; end; $ab:if (tmpw<>0) then begin repeat self.i_stosw; tmpw:=tmpw-1; until not(tmpw>0); r.cw.w:=tmpw; end; $ac:if (tmpw<>0) then begin repeat self.i_lodsb; tmpw:=tmpw-1; until not(tmpw>0); r.cw.w:=tmpw; end; $ad:if (tmpw<>0) then begin repeat self.i_lodsw; tmpw:=tmpw-1; until not(tmpw>0); r.cw.w:=tmpw; end; $ae:if (tmpw<>0) then begin repeat self.i_scasb; tmpw:=tmpw-1; until not(((tmpw>0) and r.f.ZeroVal)); r.cw.w:=tmpw; end; $af:if (tmpw<>0) then begin repeat self.i_scasw; tmpw:=tmpw-1; until not(((tmpw>0) and r.f.ZeroVal)); r.cw.w:=tmpw; end; else MessageDlg('$f3 REPE invalido', mtInformation,[mbOk],0); end; self.seg_prefix:=false; end; $f6:begin //i_f6pre ModRM:=self.fetch; tmpb:=GetRMByte(ModRM); //tmp case (ModRM and $38) of $00:begin //TEST tmpb:=tmpb and fetch; r.f.CarryVal:=false; r.f.OverVal:=false; SetSZPF_Byte(tmpb); if (ModRM>=$c0) then self.contador:=self.contador+4 else self.contador:=self.contador+11; end; $08:MessageDlg('Opcode indefinido $f6 08', mtInformation,[mbOk], 0); $10:begin //29_04 PutbackRMByte(ModRM,not(tmpb)); if (ModRM>=$c0) then self.contador:=self.contador+2 else self.contador:=self.contador+16; end; $18:begin r.f.CarryVal:=(tmpb<>0); tmpb:=not(tmpb)+1; SetSZPF_Byte(tmpb); PutbackRMByte(ModRM,tmpb); if (ModRM>=$c0) then self.contador:=self.contador+2 else self.contador:=self.contador+16; end; $20:begin //MULU tmpw:=r.aw.l*tmpb; r.aw.w:=tmpw; r.f.OverVal:=(r.aw.h<>0); r.f.CarryVal:=r.f.OverVal; if (ModRM>=$c0) then self.contador:=self.contador+30 else self.contador:=self.contador+36; end; $28:MessageDlg('$f6 MUL', mtInformation,[mbOk], 0); // result = (INT16)((INT8)nec_state->regs.b[AL])*(INT16)((INT8)tmp); nec_state->regs.w[AW]=(WORD)result; nec_state->CarryVal=nec_state->OverVal=(nec_state->regs.b[AH]!=0); nec_state->icount-=(ModRM >=0xc0 )?30:36; break; /* MUL */ $30:if (tmpb<>0) then begin tmpw:=r.aw.w; tmpb1:=tmpw mod tmpb; tmpw:=tmpw div tmpb; if (tmpw>$ff) then MessageDlg('$f6 DIVUB mod>$ff', mtInformation,[mbOk], 0) else begin r.aw.l:=tmpw; r.aw.h:=tmpb1; end; if (ModRM>=$c0) then self.contador:=self.contador+43 else self.contador:=self.contador+53; end else MessageDlg('$f6 DIVUB div por 0', mtInformation,[mbOk], 0); $38:MessageDlg('$f6 DIVB', mtInformation,[mbOk], 0); // if (tmp) { DIVB; } else nec_interrupt(nec_state, 0,0); nec_state->icount-=(ModRM >=0xc0 )?43:53; break; end; end; $f7:begin //i_f7pre ModRM:=fetch; tmpw:=GetRMWord(ModRM); //tmp case (ModRM and $38) of $00:begin // TEST tmpw1:=self.fetchword; tmpw:=tmpw and tmpw1; r.f.CarryVal:=false; r.f.OverVal:=false; SetSZPF_Word(tmpw); if (ModRM>=$c0) then self.contador:=self.contador+4 else self.contador:=self.contador+11; end; $08:MessageDlg('Opcode indefinido $f7 08', mtInformation,[mbOk], 0); $10:begin // NOT PutbackRMWord(ModRM,not(tmpw)); if (ModRM>=$c0) then self.contador:=self.contador+2 else self.contador:=self.contador+16; end; $18:begin //NEG r.f.CarryVal:=(tmpw<>0); tmpw:=not(tmpw)+1; SetSZPF_Word(tmpw); PutbackRMWord(ModRM,tmpw); if (ModRM>=$c0) then self.contador:=self.contador+2 else self.contador:=self.contador+16; end; $20:begin //MULU tmpdw:=r.aw.w*tmpw; r.aw.w:=tmpdw and $ffff; r.dw.w:=tmpdw shr 16; r.f.CarryVal:=(r.dw.w<>0); r.f.OverVal:=r.f.CarryVal; if (ModRM>=$c0) then self.contador:=self.contador+30 else self.contador:=self.contador+36; end; $28:begin // MUL tmpi:=integer(smallint(r.aw.w))*integer(smallint(tmpw)); r.aw.w:=tmpi and $ffff; r.dw.w:=tmpi div $10000; r.f.CarryVal:=(r.dw.w<>0); r.f.OverVal:=r.f.CarryVal; if (ModRM>=$c0) then self.contador:=self.contador+30 else self.contador:=self.contador+36; end; $30: if (tmpw<>0) then begin tmpdw:=(r.dw.w shl 16) or r.aw.w; tmpw1:=tmpdw mod tmpw; tmpdw:=tmpdw div tmpw; if (tmpdw>$ffff) then MessageDlg('$f7 DIVUW mod>$ffff', mtInformation,[mbOk], 0) else begin r.aw.w:=tmpdw; r.dw.w:=tmpw1; end; if (ModRM>=$c0) then self.contador:=self.contador+43 else self.contador:=self.contador+53; end else MessageDlg('$f7 DIVUW div por 0', mtInformation,[mbOk], 0); $38:if (tmpw<>0) then begin tmpi:=(smallint(r.dw.w) shl 16) or smallint(r.aw.w); tmpw1:=tmpi mod smallint(tmpw); tmpi:=tmpi div smallint(tmpw); if (tmpi>$ffff) then MessageDlg('$f7 DIVU mod>$ffff', mtInformation,[mbOk], 0) else begin r.aw.w:=tmpi; r.dw.w:=tmpw1; end; if (ModRM>=$c0) then self.contador:=self.contador+43 else self.contador:=self.contador+53; end else MessageDlg('$f7 DIVU div por 0', mtInformation,[mbOk], 0); end; end; $f8:begin //i_clc r.f.CarryVal:=false; self.contador:=self.contador+2; end; $f9:begin //i_stc r.f.CarryVal:=true; self.contador:=self.contador+2; end; $fa:begin //di r.f.I:=false; self.contador:=self.contador+2; end; $fb:begin //ei r.f.I:=true; self.contador:=self.contador+2; end; $fc:begin //cld r.f.d:=false; self.contador:=self.contador+2; end; $fd:begin //std r.f.d:=true; self.contador:=self.contador+2; end; $fe:begin //fepre ModRM:=fetch; //modmr tmpb:=GetRMByte(ModRM); //tmp case (ModRM and $38) of $00:begin // INC tmpb1:=tmpb+1; r.f.OverVal:=(tmpb=$7f); r.f.AuxVal:=((tmpb1 xor (tmpb xor 1)) and $10)<>0; SetSZPF_Byte(tmpb1); PutbackRMByte(ModRM,tmpb1); CLKM(2,2,2,16,16,7,ModRM); end; $08:begin // DEC tmpb1:=tmpb-1; r.f.OverVal:=(tmpb=$80); r.f.AuxVal:=((tmpb1 xor (tmpb xor 1)) and $10)<>0; SetSZPF_Byte(tmpb1); PutbackRMByte(ModRM,tmpb1); CLKM(2,2,2,16,16,7,ModRM); end; else MessageDlg('Instruccion $fe no implementada', mtInformation,[mbOk], 0); end; end; $ff:begin //i_ffpre ModRM:=fetch; tmpw:=GetRMWord(ModRM); //tmp case (ModRM and $38) of $00:begin //INC tmpw1:=tmpw+1; //tmp1 r.f.OverVal:=(tmpw=$7fff); r.f.AuxVal:=((tmpw1 xor (tmpw xor 1)) and $10)<>0; SetSZPF_Word(tmpw1); PutbackRMWord(ModRM,tmpw1); CLKM(2,2,2,24,16,7,ModRM); end; $08:begin //DEC tmpw1:=tmpw-1; //tmp1 r.f.OverVal:=(tmpw=$8000); r.f.AuxVal:=((tmpw1 xor (tmpw xor 1)) and $10)<>0; SetSZPF_Word(tmpw1); PutbackRMWord(ModRM,tmpw1); CLKM(2,2,2,24,16,7,ModRM); end; $10:begin // CALL PUSH(r.ip); r.ip:=tmpw; self.prefetch_reset:=true; if (ModRM>=$c0) then self.contador:=self.contador+16 else self.contador:=self.contador+20; end; $18:MessageDlg('FF CALL_FAR', mtInformation,[mbOk], 0); // tmp1 = nec_state->sregs[PS]; nec_state->sregs[PS] = GetnextRMWord; PUSH(tmp1); PUSH(nec_state->ip); nec_state->ip = tmp; CHANGE_PC; nec_state->icount-=(ModRM >=0xc0 )?16:26; break; /* CALL FAR */ $20:begin r.ip:=tmpw; self.prefetch_reset:=true; self.contador:=self.contador+13; end; $28:MessageDlg('FF JMP_FAR', mtInformation,[mbOk], 0); //nec_state->ip = tmp; nec_state->sregs[PS] = GetnextRMWord; CHANGE_PC; nec_state->icount-=15; break; /* JMP FAR */ $30:begin PUSH(tmpw); self.contador:=self.contador+4; end; else MessageDlg('Instruccion $ff no implementada', mtInformation,[mbOk], 0); end; end; else MessageDlg('Intruccion desconocida NEC PC: '+inttohex(((r.ps_r shl 4)+r.ip)-1,10)+' INST: '+inttohex(instruccion,4)+' oldPC: '+inttohex(((r.ps_r shl 4)+r.old_pc)-1,10), mtInformation,[mbOk], 0); end; //del case end; procedure cpu_nec.nec_nmi; begin self.change_nmi(CLEAR_LINE); i_pushf; r.f.T:=false; r.f.I:=false; PUSH(r.ps_r); PUSH(r.ip); r.ip:=read_word(2*4); r.ps_r:=read_word(2*4+2); self.contador:=self.contador+9; self.prefetch_reset:=true; end; procedure cpu_nec.nec_interrupt(vect_num:word); begin if self.no_interrupt then begin if not(self.irq_pending) then self.vect:=vect_num; self.irq_pending:=true; self.no_interrupt:=false; exit; end; if not(r.f.I) then begin if not(self.irq_pending) then self.vect:=vect_num; self.irq_pending:=true; exit; end; if vect_num=$100 then vect_num:=self.vect; self.change_irq(CLEAR_LINE); self.irq_pending:=false; self.contador:=self.contador+14; i_pushf; r.f.T:=false; r.f.I:=false; PUSH(r.ps_r); PUSH(r.ip); r.ip:=read_word(vect_num*4); r.ps_r:=read_word(vect_num*4+2); self.prefetch_reset:=true; end; procedure cpu_nec.run(maximo:single); var instruccion:byte; begin self.contador:=0; while self.contador<maximo do begin //IRQ's prev_icount:=self.contador; if self.irq_pending then nec_interrupt($100) else if self.pedir_nmi<>CLEAR_LINE then nec_nmi else if self.pedir_irq<>CLEAR_LINE then nec_interrupt(self.vect_req); self.opcode:=true; {if ((((r.ps_r shl 4)+r.ip)=$304d0) and (self.numero_cpu=0)) then begin r.ip:=0; r.ip:=$4d0; end;} self.r.old_pc:=self.r.ip; instruccion:=self.fetch; self.opcode:=false; self.ea_calculated:=false; self.ejecuta_instruccion(instruccion); self.do_prefetch(prev_ICount); self.no_interrupt:=false; timers.update(self.contador-prev_icount,self.numero_cpu); if @self.despues_instruccion<>nil then self.despues_instruccion(self.contador-prev_icount); end; //del while end; end.
unit uHaiku; interface type IHaiku = interface(IInvokable) ['{72BA7A1E-4B4F-44C5-AD73-AB484E7894E6}'] function GetResultStr: string; property ResultStr: string read GetResultStr; end; function HaikuReview(inStr: string): IHaiku; implementation uses System.SysUtils, System.StrUtils; type THaiku = class(TInterfacedObject, IHaiku) private const fVowels: TSysCharSet = ['a','e','i','o','u','y']; fExpectedSyllableCount: array[0..2] of integer = (5,7,5); var fResultStr: string; function isVowel(inChar: char):boolean; function NumberOfLines(inStr: string): integer; function getLines(inStr: string):TArray<String>; function TheWordsIn(line: string):TArray<String>; function CountSyllables(Words: TArray<String>): integer; function GetResultStr: string; public constructor Review(inStr : string); property ResultStr: string read GetResultStr; end; function HaikuReview(inStr: string): IHaiku; begin result := THaiku.Review(inStr); end; function THaiku.isVowel(inChar : char):boolean; begin result := CharInSet(inChar,fVowels); end; function THaiku.NumberOfLines(inStr : string): integer; var wrkStr : string; begin wrkStr := inStr.Trim; wrkStr := ifthen(wrkstr.EndsWith('/'),wrkStr.PadRight(1,' '),wrkStr); result := wrkStr.CountChar('/') + 1; end; function THaiku.getLines(inStr : string):TArray<String>; begin result := instr.Split(['/']); if length(result) < 3 then SetLength(result,3); end; function THaiku.TheWordsIn(line: string):TArray<String>; var NumWords : integer; wrkStr : string; begin wrkStr := line.Trim; if wrkStr.IsEmpty then wrkStr := ' '; NumWords := wrkStr.CountChar(' ') + 1; result := wrkStr.Split([' '],NumWords); end; function THaiku.CountSyllables(Words : TArray<String>): integer; var word : string; letter : char; CountThisVowel : boolean; begin result := 0; for word in Words do begin CountThisVowel := true; for letter in word do begin if isVowel(letter) then begin if CountThisVowel then inc(result); CountThisVowel := false; end else CountThisVowel := true; end; end; end; constructor THaiku.Review(inStr : string); var isProperHaiku : boolean; procedure CheckEachLine; var Lines : TArray<string>; line : string; LineNum : integer; Syllables : integer; begin isProperHaiku := true; Lines := getLines(inStr.ToLower); LineNum := 0; for line in Lines do begin Syllables := CountSyllables(TheWordsIn(line)); isProperHaiku := isProperHaiku and (Syllables = fExpectedSyllableCount[LineNum]); fResultStr := fResultStr + format('%d, ',[Syllables]); inc(LineNum); end; end; begin fResultStr := inStr + ', '; if NumberOfLines(inStr) = 3 then begin CheckEachLine; fResultStr := fResultStr + ifthen(isProperHaiku,'Yes','No'); end else fResultStr := fResultStr + 'No, incorrect line count'; end; function THaiku.GetResultStr: string; begin result := fResultStr; end; end.
unit HtmlParserTestMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, HTMLParser, Vcl.Grids, Vcl.ComCtrls; type TForm16 = class(TForm) btn1: TButton; lv1: TListView; procedure btn1Click(Sender: TObject); private { Private declarations } HtmlParser: THtmlParser; function LoadHtmlFile: String; public { Public declarations } end; var Form16: TForm16; implementation uses DomCore, Formatter; {$R *.dfm} procedure TForm16.btn1Click(Sender: TObject); var HtmlDoc: TDocument; Formatter: TBaseFormatter; list: TNodeList; I: Integer; span: TNode; classAttr: TNode; href: TNode; Item: TListItem; begin HtmlParser := THtmlParser.Create; try HtmlDoc := HtmlParser.parseString(LoadHtmlFile); list := HtmlDoc.getElementsByTagName('span'); for I := 0 to list.length-1 do begin span := list.item(i); classAttr := span.attributes.getNamedItem('class'); if Assigned(classAttr) then begin if classAttr.childNodes.item(0).NodeValue = 'ina_zh' then begin href := span.childNodes.item(0); if href.nodeName = 'a' then begin Item := lv1.Items.Add; Item.Caption := href.attributes.getNamedItem('href').childNodes.item(0).nodeValue; Item.SubItems.Add(href.childNodes.item(0).NodeValue); Item.SubItems.Add(span.parentNode.childNodes.item(2).childNodes.item(0).NodeValue); end; end; end; end; list.Free; finally HtmlParser.Free end; HtmlDoc.Free; end; function TForm16.LoadHtmlFile: String; var F: TFileStream; Reader: TStreamReader; begin F := TFileStream.Create('Test.html', fmOpenRead); try Reader := TStreamReader.Create(F); try Result := Reader.ReadToEnd; finally Reader.Free; end; finally F.Free end; end; end.
unit App; { Based on Hello_Triangle.c from Book: OpenGL(R) ES 2.0 Programming Guide Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner ISBN-10: 0321502795 ISBN-13: 9780321502797 Publisher: Addison-Wesley Professional URLs: http://safari.informit.com/9780321563835 http://www.opengles-book.com } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App; type TTriangleApp = class(TApplication) private FProgram: TGLProgram; FAttrPosition: TGLVertexAttrib; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes; { TTriangleApp } procedure TTriangleApp.Initialize; var VertexShader, FragmentShader: TGLShader; begin { Compile vertex and fragment shaders } VertexShader.New(TGLShaderType.Vertex, 'attribute vec4 vPosition;'#10+ 'void main(void)'#10+ '{'#10+ ' gl_Position = vPosition;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'void main(void)'#10+ '{'#10+ ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);'#10+ '}'); FragmentShader.Compile; { Link shaders into program } FProgram.New(VertexShader, FragmentShader); FProgram.Link; { We don't need the shaders anymore. Note that the shaders won't actually be deleted until the program is deleted. } VertexShader.Delete; FragmentShader.Delete; { Initialize vertex attribute } FAttrPosition.Init(FProgram, 'vPosition'); { Set clear color to black } gl.ClearColor(0, 0, 0, 0); end; procedure TTriangleApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TTriangleApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); const VERTICES: array [0..2] of TVector3 = ( (X: 0.0; Y: 0.5; Z: 0.0), (X: -0.5; Y: -0.5; Z: 0.0), (X: 0.5; Y: -0.5; Z: 0.0)); begin { Clear the color buffer } gl.Clear([TGLClear.Color]); { Use the program } FProgram.Use; { Set the data for the vertex attribute } FAttrPosition.SetData(VERTICES); FAttrPosition.Enable; { Draw the triangle } gl.DrawArrays(TGLPrimitiveType.Triangles, 3); end; procedure TTriangleApp.Shutdown; begin { Release resources } FProgram.Delete; end; end.
unit EULAKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы EULA } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Common\EULAKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "EULAKeywordsPack" MUID: (145DA8D181DD) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtLabel , vtButton , eeMemoWithEditOperations ; {$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 , EULA_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_EULA = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы EULA ---- *Пример использования*: [code] 'aControl' форма::EULA TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_EULA Tkw_EULA_Control_ShellCaptionLabel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ShellCaptionLabel ---- *Пример использования*: [code] контрол::ShellCaptionLabel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EULA_Control_ShellCaptionLabel Tkw_EULA_Control_ShellCaptionLabel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ShellCaptionLabel ---- *Пример использования*: [code] контрол::ShellCaptionLabel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EULA_Control_ShellCaptionLabel_Push Tkw_EULA_Control_OkButton = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола OkButton ---- *Пример использования*: [code] контрол::OkButton TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EULA_Control_OkButton Tkw_EULA_Control_OkButton_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола OkButton ---- *Пример использования*: [code] контрол::OkButton:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EULA_Control_OkButton_Push Tkw_EULA_Control_eeMemoWithEditOperations1 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола eeMemoWithEditOperations1 ---- *Пример использования*: [code] контрол::eeMemoWithEditOperations1 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EULA_Control_eeMemoWithEditOperations1 Tkw_EULA_Control_eeMemoWithEditOperations1_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола eeMemoWithEditOperations1 ---- *Пример использования*: [code] контрол::eeMemoWithEditOperations1:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_EULA_Control_eeMemoWithEditOperations1_Push TkwEfEULAShellCaptionLabel = {final} class(TtfwPropertyLike) {* Слово скрипта .TefEULA.ShellCaptionLabel } private function ShellCaptionLabel(const aCtx: TtfwContext; aefEULA: TefEULA): TvtLabel; {* Реализация слова скрипта .TefEULA.ShellCaptionLabel } 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;//TkwEfEULAShellCaptionLabel TkwEfEULAOkButton = {final} class(TtfwPropertyLike) {* Слово скрипта .TefEULA.OkButton } private function OkButton(const aCtx: TtfwContext; aefEULA: TefEULA): TvtButton; {* Реализация слова скрипта .TefEULA.OkButton } 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;//TkwEfEULAOkButton TkwEfEULAEeMemoWithEditOperations1 = {final} class(TtfwPropertyLike) {* Слово скрипта .TefEULA.eeMemoWithEditOperations1 } private function eeMemoWithEditOperations1(const aCtx: TtfwContext; aefEULA: TefEULA): TeeMemoWithEditOperations; {* Реализация слова скрипта .TefEULA.eeMemoWithEditOperations1 } 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;//TkwEfEULAEeMemoWithEditOperations1 function Tkw_Form_EULA.GetString: AnsiString; begin Result := 'efEULA'; end;//Tkw_Form_EULA.GetString class function Tkw_Form_EULA.GetWordNameForRegister: AnsiString; begin Result := 'форма::EULA'; end;//Tkw_Form_EULA.GetWordNameForRegister function Tkw_EULA_Control_ShellCaptionLabel.GetString: AnsiString; begin Result := 'ShellCaptionLabel'; end;//Tkw_EULA_Control_ShellCaptionLabel.GetString class procedure Tkw_EULA_Control_ShellCaptionLabel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_EULA_Control_ShellCaptionLabel.RegisterInEngine class function Tkw_EULA_Control_ShellCaptionLabel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ShellCaptionLabel'; end;//Tkw_EULA_Control_ShellCaptionLabel.GetWordNameForRegister procedure Tkw_EULA_Control_ShellCaptionLabel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ShellCaptionLabel'); inherited; end;//Tkw_EULA_Control_ShellCaptionLabel_Push.DoDoIt class function Tkw_EULA_Control_ShellCaptionLabel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ShellCaptionLabel:push'; end;//Tkw_EULA_Control_ShellCaptionLabel_Push.GetWordNameForRegister function Tkw_EULA_Control_OkButton.GetString: AnsiString; begin Result := 'OkButton'; end;//Tkw_EULA_Control_OkButton.GetString class procedure Tkw_EULA_Control_OkButton.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtButton); end;//Tkw_EULA_Control_OkButton.RegisterInEngine class function Tkw_EULA_Control_OkButton.GetWordNameForRegister: AnsiString; begin Result := 'контрол::OkButton'; end;//Tkw_EULA_Control_OkButton.GetWordNameForRegister procedure Tkw_EULA_Control_OkButton_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('OkButton'); inherited; end;//Tkw_EULA_Control_OkButton_Push.DoDoIt class function Tkw_EULA_Control_OkButton_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::OkButton:push'; end;//Tkw_EULA_Control_OkButton_Push.GetWordNameForRegister function Tkw_EULA_Control_eeMemoWithEditOperations1.GetString: AnsiString; begin Result := 'eeMemoWithEditOperations1'; end;//Tkw_EULA_Control_eeMemoWithEditOperations1.GetString class procedure Tkw_EULA_Control_eeMemoWithEditOperations1.RegisterInEngine; begin inherited; TtfwClassRef.Register(TeeMemoWithEditOperations); end;//Tkw_EULA_Control_eeMemoWithEditOperations1.RegisterInEngine class function Tkw_EULA_Control_eeMemoWithEditOperations1.GetWordNameForRegister: AnsiString; begin Result := 'контрол::eeMemoWithEditOperations1'; end;//Tkw_EULA_Control_eeMemoWithEditOperations1.GetWordNameForRegister procedure Tkw_EULA_Control_eeMemoWithEditOperations1_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('eeMemoWithEditOperations1'); inherited; end;//Tkw_EULA_Control_eeMemoWithEditOperations1_Push.DoDoIt class function Tkw_EULA_Control_eeMemoWithEditOperations1_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::eeMemoWithEditOperations1:push'; end;//Tkw_EULA_Control_eeMemoWithEditOperations1_Push.GetWordNameForRegister function TkwEfEULAShellCaptionLabel.ShellCaptionLabel(const aCtx: TtfwContext; aefEULA: TefEULA): TvtLabel; {* Реализация слова скрипта .TefEULA.ShellCaptionLabel } begin Result := aefEULA.ShellCaptionLabel; end;//TkwEfEULAShellCaptionLabel.ShellCaptionLabel class function TkwEfEULAShellCaptionLabel.GetWordNameForRegister: AnsiString; begin Result := '.TefEULA.ShellCaptionLabel'; end;//TkwEfEULAShellCaptionLabel.GetWordNameForRegister function TkwEfEULAShellCaptionLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEfEULAShellCaptionLabel.GetResultTypeInfo function TkwEfEULAShellCaptionLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfEULAShellCaptionLabel.GetAllParamsCount function TkwEfEULAShellCaptionLabel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefEULA)]); end;//TkwEfEULAShellCaptionLabel.ParamsTypes procedure TkwEfEULAShellCaptionLabel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ShellCaptionLabel', aCtx); end;//TkwEfEULAShellCaptionLabel.SetValuePrim procedure TkwEfEULAShellCaptionLabel.DoDoIt(const aCtx: TtfwContext); var l_aefEULA: TefEULA; begin try l_aefEULA := TefEULA(aCtx.rEngine.PopObjAs(TefEULA)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefEULA: TefEULA : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ShellCaptionLabel(aCtx, l_aefEULA)); end;//TkwEfEULAShellCaptionLabel.DoDoIt function TkwEfEULAOkButton.OkButton(const aCtx: TtfwContext; aefEULA: TefEULA): TvtButton; {* Реализация слова скрипта .TefEULA.OkButton } begin Result := aefEULA.OkButton; end;//TkwEfEULAOkButton.OkButton class function TkwEfEULAOkButton.GetWordNameForRegister: AnsiString; begin Result := '.TefEULA.OkButton'; end;//TkwEfEULAOkButton.GetWordNameForRegister function TkwEfEULAOkButton.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtButton); end;//TkwEfEULAOkButton.GetResultTypeInfo function TkwEfEULAOkButton.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfEULAOkButton.GetAllParamsCount function TkwEfEULAOkButton.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefEULA)]); end;//TkwEfEULAOkButton.ParamsTypes procedure TkwEfEULAOkButton.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству OkButton', aCtx); end;//TkwEfEULAOkButton.SetValuePrim procedure TkwEfEULAOkButton.DoDoIt(const aCtx: TtfwContext); var l_aefEULA: TefEULA; begin try l_aefEULA := TefEULA(aCtx.rEngine.PopObjAs(TefEULA)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefEULA: TefEULA : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(OkButton(aCtx, l_aefEULA)); end;//TkwEfEULAOkButton.DoDoIt function TkwEfEULAEeMemoWithEditOperations1.eeMemoWithEditOperations1(const aCtx: TtfwContext; aefEULA: TefEULA): TeeMemoWithEditOperations; {* Реализация слова скрипта .TefEULA.eeMemoWithEditOperations1 } begin Result := aefEULA.eeMemoWithEditOperations1; end;//TkwEfEULAEeMemoWithEditOperations1.eeMemoWithEditOperations1 class function TkwEfEULAEeMemoWithEditOperations1.GetWordNameForRegister: AnsiString; begin Result := '.TefEULA.eeMemoWithEditOperations1'; end;//TkwEfEULAEeMemoWithEditOperations1.GetWordNameForRegister function TkwEfEULAEeMemoWithEditOperations1.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TeeMemoWithEditOperations); end;//TkwEfEULAEeMemoWithEditOperations1.GetResultTypeInfo function TkwEfEULAEeMemoWithEditOperations1.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfEULAEeMemoWithEditOperations1.GetAllParamsCount function TkwEfEULAEeMemoWithEditOperations1.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefEULA)]); end;//TkwEfEULAEeMemoWithEditOperations1.ParamsTypes procedure TkwEfEULAEeMemoWithEditOperations1.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству eeMemoWithEditOperations1', aCtx); end;//TkwEfEULAEeMemoWithEditOperations1.SetValuePrim procedure TkwEfEULAEeMemoWithEditOperations1.DoDoIt(const aCtx: TtfwContext); var l_aefEULA: TefEULA; begin try l_aefEULA := TefEULA(aCtx.rEngine.PopObjAs(TefEULA)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefEULA: TefEULA : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(eeMemoWithEditOperations1(aCtx, l_aefEULA)); end;//TkwEfEULAEeMemoWithEditOperations1.DoDoIt initialization Tkw_Form_EULA.RegisterInEngine; {* Регистрация Tkw_Form_EULA } Tkw_EULA_Control_ShellCaptionLabel.RegisterInEngine; {* Регистрация Tkw_EULA_Control_ShellCaptionLabel } Tkw_EULA_Control_ShellCaptionLabel_Push.RegisterInEngine; {* Регистрация Tkw_EULA_Control_ShellCaptionLabel_Push } Tkw_EULA_Control_OkButton.RegisterInEngine; {* Регистрация Tkw_EULA_Control_OkButton } Tkw_EULA_Control_OkButton_Push.RegisterInEngine; {* Регистрация Tkw_EULA_Control_OkButton_Push } Tkw_EULA_Control_eeMemoWithEditOperations1.RegisterInEngine; {* Регистрация Tkw_EULA_Control_eeMemoWithEditOperations1 } Tkw_EULA_Control_eeMemoWithEditOperations1_Push.RegisterInEngine; {* Регистрация Tkw_EULA_Control_eeMemoWithEditOperations1_Push } TkwEfEULAShellCaptionLabel.RegisterInEngine; {* Регистрация efEULA_ShellCaptionLabel } TkwEfEULAOkButton.RegisterInEngine; {* Регистрация efEULA_OkButton } TkwEfEULAEeMemoWithEditOperations1.RegisterInEngine; {* Регистрация efEULA_eeMemoWithEditOperations1 } TtfwTypeRegistrator.RegisterType(TypeInfo(TefEULA)); {* Регистрация типа TefEULA } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtButton)); {* Регистрация типа TvtButton } TtfwTypeRegistrator.RegisterType(TypeInfo(TeeMemoWithEditOperations)); {* Регистрация типа TeeMemoWithEditOperations } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
unit RILogger; interface uses pi, pi_int, orbtypes, code_int; const REQUEST_CONTEXT_ID: ServiceId = 100; REPLY_CONTEXT_ID: ServiceId = 101; type {TRILogger = class() end;} TRIORBInitializerImpl = class(TORBInitializer) protected procedure pre_init(const info: IORBInitInfo); override; procedure post_init(const info: IORBInitInfo); override; public class procedure Init; end; TCORBAOut = class public class procedure ShowAny(const a: IAny); class procedure DisplayAny(const a: IAny); class procedure DisplayIDLTypeCode(const tc: ITypeCode); class procedure ShowAnyWithoutType(const a: IAny); class procedure ShowNameTypeCode(const tc: ITypeCode); end; procedure DisplayRequestInfo(const info: IRequestInfo; logLevel: short; ASlotId: TSlotId); procedure Down(); procedure Up(); procedure Skip(); function GetOctet(o: octet): string; implementation uses SysUtils, PIImpl, SRILoggerImpl, CRILoggerImpl, LoggerPolicy_int, pi_impl, exceptions, orb_int; const NameTypeIDL: array [TCKind] of string = ( 'null', 'void', 'short', 'long', 'unsigned short', 'unsigned long', 'float', 'double', 'boolean', 'char', 'octet', 'any', 'TypeCode', 'Principal', 'objref', 'struct', 'union', 'enum', 'string', 'sequence', 'array', 'alias', 'exception', 'long long', 'unsigned long long', 'long double', 'wchar', 'wstring', 'fixed', 'value', 'valuebox', 'native', 'abstract_interface' ); var level: Integer = 0; procedure Down(); begin Inc(level); end; procedure Up(); begin Dec(level); end; procedure Skip(); var i: Integer; begin for i := 0 to level do Write(' '); end; function GetOctet(o: octet): string; begin end; procedure DisplayRequestInfo(const info: IRequestInfo; logLevel: short; ASlotId: TSlotId); var i: Integer; args: TParameterList; excepts: TExceptionList; response_expected: Boolean; status: TReplyStatus; context: ServiceContext; res: IAny; begin args := nil; excepts := nil; // // Display request id // Skip(); WriteLn('request id = ', info.request_id); // // Display operation // Skip(); WriteLn('operation = ', info.operation); // // Display arguments // try args := info.arguments; Skip(); Write('arguments = '); if Length(args) = 0 then Write('(no arguments)') else begin Down(); for i := 0 to Length(args) - 1 do begin WriteLn; case args[i].mode of PARAM_IN: begin Skip(); Write('in '); end; PARAM_OUT: begin Skip(); Write('out '); end; else begin Skip(); Write('inout '); end; end; TCORBAOut.ShowAny(args[i].argument); end; Up(); end; WriteLn; except on E: BAD_INV_ORDER do ; // Operation not supported in this context on E: NO_RESOURCES do ; // Operation not supported in this environment end; // // Display exceptions // try excepts := info.exceptions; Skip(); Write('exceptions = '); if Length(excepts) = 0 then WriteLn('(no exceptions)') else begin WriteLn; Down(); for i := 0 to Length(excepts) - 1 do TCORBAOut.DisplayIDLTypeCode(excepts[i]); Up(); end; except on E: BAD_INV_ORDER do ; // Operation not supported in this context on E: NO_RESOURCES do ; // Operation not supported in this environment end; // // Display result // try res := info._result; Skip(); Write('result = '); TCORBAOut.ShowAny(res); WriteLn; except on E: BAD_INV_ORDER do ; // Operation not supported in this context on E: NO_RESOURCES do ; // Operation not supported in this environment end; // // Display response expected // response_expected := info.response_expected; Skip(); Write('response expected = '); if response_expected then Write('true') else Write('false'); WriteLn; // // Display reply status // try status := info.reply_status; Skip(); Write('reply status = '); case status of pi_int.SUCCESSFUL: Write('SUCCESSFUL'); pi_int.SYSTEM_EXCEPTION: Write('SYSTEM_EXCEPTION'); pi_int.USER_EXCEPTION: Write('USER_EXCEPTION'); pi_int.LOCATION_FORWARD: Write('LOCATION_FORWARD'); pi_int.LOCATION_FORWARD_PERMANENT: Write('LOCATION_FORWARD_PERMANENT'); pi_int.TRANSPORT_RETRY: Write('TRANSPORT_RETRY'); else Write('UNKNOWN_REPLY_STATUS'); end; WriteLn; except on E: BAD_INV_ORDER do ; // Operation not supported in this context end; if logLevel > 1 then begin // // Display slot data // try Skip(); WriteLn('slot data ', ASlotId, ' = '); Down(); TCORBAOut.DisplayAny(info.get_slot(ASlotId)); Up(); except on E: TInvalidSlot do ; end; // // Display request service context // try context := info.get_request_service_context(REQUEST_CONTEXT_ID); Skip(); Write('request service context ', REQUEST_CONTEXT_ID, ' = '); for i := 0 to Length(context.context_data) - 1 do Write(GetOctet(context.context_data[i])); WriteLn; except on E: BAD_INV_ORDER do ; // Operation not supported in this context on E: BAD_PARAM do ; // No entry found end; // // Display reply service context // try context := info.get_reply_service_context(REPLY_CONTEXT_ID); Skip(); Write('reply service context ', REPLY_CONTEXT_ID, ' = '); for i := 0 to Length(context.context_data) - 1 do Write(GetOctet(context.context_data[i])); WriteLn; except on E: BAD_INV_ORDER do ; // Operation not supported in this context on E: BAD_PARAM do ; // No entry found end; end; end; { TRIORBInitializerImpl } // Note: the interceptors are registered in post_init() // because the TCRILoggerImpl and TSRILoggerImpl // constructors require // ORBInitInfo::resolve_initial_reference(), which // cannot be called in pre_init(). class procedure TRIORBInitializerImpl.Init; begin // // Register the ORB initializer // TPIManager.RegisterOrbInitializer(TRIORBInitializerImpl.Create()); end; procedure TRIORBInitializerImpl.post_init(const info: IORBInitInfo); var slotId: TSlotId; begin // // Register the policy factory // info.register_policy_factory(LOGGER_POLICY_ID, TLoggerPolicyFactory.Create()); // // Allocate state slot for call stack tracing // slotId := info.allocate_slot_id(); // // Create the interceptors // // // Register the interceptors // try info.add_client_request_interceptor(TCRILoggerImpl.Create(info, slotId)); info.add_server_request_interceptor(TSRILoggerImpl.Create(info, slotId)); except on E: TDuplicateName do Assert(false); end; end; procedure TRIORBInitializerImpl.pre_init(const info: IORBInitInfo); begin end; { TCORBAOut } class procedure TCORBAOut.DisplayAny(const a: IAny); begin Skip(); ShowAny(a); WriteLn; end; class procedure TCORBAOut.DisplayIDLTypeCode(const tc: ITypeCode); var kind: TCKind; i: Integer; member_type: ITypeCode; begin kind := tc.kind; case kind of tk_objref: begin Skip(); Write('interface ', tc.name(), ';'); end; tk_struct, tk_except: begin Skip(); WriteLn(NameTypeIDL[kind], ' ', tc.name(), ' {'); Down(); for i := 0 to tc.member_count() - 1 do begin Skip(); member_type := tc.member_type(i); ShowNameTypeCode(member_type); WriteLn(' ', tc.member_name(i), ';'); end; Up(); Skip(); Write('};'); end; end; WriteLn; end; class procedure TCORBAOut.ShowAny(const a: IAny); begin ShowNameTypeCode(a.__tc); Write('('); ShowAnyWithoutType(a); Write(')'); end; class procedure TCORBAOut.ShowAnyWithoutType(const a: IAny); var //i: _ulong; tc: ITypeCode; kind: TCKind; v_short: short; v_long: long; v_ushort: _ushort; v_ulong: _ulong; v_float: float; v_double: double; v_boolean: Boolean; v_char: AnsiChar; v_octet: octet; v_any: IAny; v_tc: ITypeCode; v_obj: IInterface; v_string: AnsiString; v_longlong: longlong; v_ulonglong: _ulonglong; v_wchar: WideChar; v_wstring: WideString; // Get original type, i.e. remove aliases function GetOrigType(const ATC: ITypeCode): ITypeCode; begin result := ATC; while result.kind = tk_alias do result := result.content_type; end; begin a.rewind; tc := a.__tc(); tc := GetOrigType(tc); kind := tc.kind(); case kind of tk_null, tk_void: ; tk_short: begin a.to_short(v_short); Write(v_short); end; tk_long: begin a.to_long(v_long); Write(v_long); end; tk_ushort: begin a.to_ushort(v_ushort); Write(v_ushort); end; tk_ulong: begin a.to_ulong(v_ulong); Write(v_ulong); end; tk_float: begin a.to_float(v_float); Write(v_float); end; tk_double: begin a.to_double(v_double); Write(v_double); end; tk_boolean: begin a.to_boolean(v_boolean); if v_boolean then Write('TRUE') else Write('FALSE'); end; tk_char: begin a.to_char(v_char); Write('''(char)'', v_char, '''); end; tk_octet: begin a.to_octet(v_octet); Write(v_octet); end; tk_any: begin a.to_any(v_any); ShowAny(v_any); end; tk_TypeCode: begin a.to_typecode(v_tc); ShowNameTypeCode(v_tc); end; tk_Principal: Write('<Principal>'); tk_objref: begin Write(tc.id()); a.to_object(v_obj); if v_obj = nil then Write('<NULL>'); end; tk_struct: begin (*DynStruct_var dyn_struct = DynStruct::_narrow(dyn_any); ostr_ << OB_ENDL; down(); ULong member_count = tc -> member_count(); for(i = 0 ; i < member_count ; i++) { String_var member_name = dyn_struct -> current_member_name(); skip() << member_name << " = "; DynAny_var component = dyn_struct -> current_component(); show_DynAny(component); ostr_ << OB_ENDL; dyn_struct -> next(); } up(); skip();*) end; tk_union: begin (*DynUnion_var dyn_union = DynUnion::_narrow(dyn_any); ostr_ << OB_ENDL; down(); DynAny_var component = dyn_union -> current_component(); skip() << "discriminator = "; show_DynAny(component); ostr_ << OB_ENDL; if(dyn_union -> component_count() == 2) { dyn_union -> next(); component = dyn_union -> current_component(); String_var member_name = dyn_union -> member_name(); skip() << member_name << " = "; show_DynAny(component); ostr_ << OB_ENDL; } up(); skip();*) end; tk_enum: begin (*DynEnum_var dyn_enum = DynEnum::_narrow(dyn_any); String_var v_string = dyn_enum -> get_as_string(); ostr_ << v_string;*) end; tk_string: begin a.to_string(v_string); Write('"', v_string, '"'); end; tk_sequence: begin (*DynSequence_var dyn_sequence = DynSequence::_narrow(dyn_any); for(i = 0 ; i < dyn_sequence -> get_length() ; i++) { if(i != 0) ostr_ << ", "; DynAny_var component = dyn_sequence -> current_component(); show_DynAny(component); dyn_sequence -> next(); }*) end; tk_array: begin (*DynArray_var dyn_array = DynArray::_narrow(dyn_any); for(i = 0 ; i < tc -> length() ; i++) { if(i != 0) ostr_ << ", "; DynAny_var component = dyn_array -> current_component(); show_DynAny(component); dyn_array -> next(); }*) end; tk_alias: Write('<alias>'); tk_except: Write('<except>'); tk_longlong: begin a.to_longlong(v_longlong); Write(v_longlong); end; tk_ulonglong: begin a.to_ulonglong(v_ulonglong); Write(v_ulonglong); end; (*#if SIZEOF_LONG_DOUBLE >= 12 case tk_longdouble: { LongDouble v_longdouble = dyn_any -> get_longdouble(); // // Not all platforms support this // //ostr_ << v_longdouble; char str[25]; sprintf(str, "%31Lg", v_longdouble); ostr_ << str; break; } #endif*) tk_wchar: begin a.to_wchar(v_wchar); Write('"', v_wchar, '"'); end; tk_wstring: begin a.to_wstring(v_wstring); Write('"', v_wstring, '"'); end; tk_fixed: begin (*DynFixed_var dyn_fixed = DynFixed::_narrow(dyn_any); ostr_ << OB_ENDL; down(); // XXX String_var str = dyn_fixed -> get_value(); skip() << str; ostr_ << OB_ENDL; up(); skip();*) end; tk_value: Write('<value>'); tk_value_box: Write('<value_box>'); tk_native: Write('<native>'); tk_abstract_interface: Write('<abstract_interface>'); else Write('Unknown DynAny: ', Integer(kind)); end; a.rewind; end; class procedure TCORBAOut.ShowNameTypeCode(const tc: ITypeCode); var kind: TCKind; len: _ulong; content_type: ITypeCode; begin kind := tc.kind(); case kind of tk_objref, tk_enum, tk_union, tk_struct, tk_except, tk_alias: Write(tc.name()); tk_string: begin Write('string'); len := tc._length(); if (len <> 0) then Write('<', len, '>'); end; tk_sequence: begin Write('sequence<'); content_type := tc.content_type(); ShowNameTypeCode(content_type); len := tc._length(); if (len <> 0) then Write(', ', len, '>'); end; tk_array: begin content_type := tc.content_type(); ShowNameTypeCode(content_type); Write('[', tc._length(), ']'); end; else Write(NameTypeIDL[kind]); end; end; end.
unit UBSExplorer.Tab; interface uses System.SysUtils, System.IOUtils, System.Classes, System.UITypes, System.Types, Vcl.Forms, Vcl.Dialogs, Vcl.Controls, Vcl.ComCtrls, Pengine.EventHandling, Pengine.ICollections, Unbound.Game.Serialization, UBSExplorer.DataModule; type TUBSTreeNode = class(TTreeNode) private FUBSParent: TUBSParent; FUBSValue: TUBSValue; FName: string; FIndex: Integer; procedure SetName(const Value: string); public procedure Initialize(AParentMap: TUBSMap; AName: string); overload; procedure Initialize(AParentList: TUBSList; AIndex: Integer); overload; property UBSParent: TUBSParent read FUBSParent; property UBSValue: TUBSValue read FUBSValue; property Name: string read FName write SetName; property Index: Integer read FIndex; function CanRename: Boolean; procedure UpdateDisplay; procedure UpdateChildren; class procedure GenerateChildren(ATreeView: TTreeView; AUBSValue: TUBSValue; AParent: TUBSTreeNode = nil); end; TfrmTab = class(TFrame) tvExplorer: TTreeView; procedure tvExplorerCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); procedure tvExplorerEditing(Sender: TObject; Node: TTreeNode; var AllowEdit: Boolean); private FFilename: string; FFileTimestamp: TDateTime; FUBSValue: TUBSValue; FModified: Boolean; FSaved: Boolean; FOnFilenameChange: TEvent<TfrmTab>; FOnModifiedChange: TEvent<TfrmTab>; function FindNewName(AMap: TUBSMap): string; function GetOnFilenameChange: TEvent<TfrmTab>.TAccess; procedure Modify; function GetOnModifiedChange: TEvent<TfrmTab>.TAccess; function GetSelectedUBSValue: TUBSValue; function GetSelectedUBSParent: TUBSParent; function GetSelectedValueNode: TUBSTreeNode; function GetSelectedParentNode: TUBSTreeNode; public constructor Create(AOwner: TComponent; AUBSTag: TUBSTag); reintroduce; overload; constructor Create(AOwner: TComponent; AFilename: string); reintroduce; overload; destructor Destroy; override; property Filename: string read FFilename; property UBSValue: TUBSValue read FUBSValue; property Modified: Boolean read FModified; property Saved: Boolean read FSaved; function FindNode(AValue: TUBSValue): TUBSTreeNode; property SelectedValueNode: TUBSTreeNode read GetSelectedValueNode; property SelectedParentNode: TUBSTreeNode read GetSelectedParentNode; property SelectedUBSValue: TUBSValue read GetSelectedUBSValue; property SelectedUBSParent: TUBSParent read GetSelectedUBSParent; procedure UpdateTreeView; function Save: Boolean; function SaveAs: Boolean; function FileChanged: Boolean; procedure CheckFileChanged; function TryClose: Boolean; function CanAddValue: Boolean; procedure AddValue; overload; procedure AddValue(ATag: TUBSTag); overload; property OnFilenameChange: TEvent<TfrmTab>.TAccess read GetOnFilenameChange; property OnModifiedChange: TEvent<TfrmTab>.TAccess read GetOnModifiedChange; end; implementation {$R *.dfm} { TUBSTreeNode } procedure TUBSTreeNode.Initialize(AParentMap: TUBSMap; AName: string); begin FUBSParent := AParentMap; FUBSValue := AParentMap[AName]; FName := AName; UpdateDisplay; UpdateChildren; end; procedure TUBSTreeNode.Initialize(AParentList: TUBSList; AIndex: Integer); begin FUBSParent := AParentList; FUBSValue := AParentList[AIndex]; FIndex := AIndex; UpdateDisplay; UpdateChildren; end; procedure TUBSTreeNode.SetName(const Value: string); var Map: TUBSMap; begin if Name = Value then Exit; Map := FUBSParent as TUBSMap; Map[Value] := Map.Extract(Name); FName := Value; end; procedure TUBSTreeNode.UpdateDisplay; begin if (UBSValue = nil) or (UBSParent = nil) then begin ImageIndex := -1; Text := '<ERROR>'; Exit; end; ImageIndex := Ord(UBSValue.GetTag); SelectedIndex := ImageIndex; Text := UBSValue.Format(ufInline); case UBSParent.GetTag of utList: Text := Format('[%d]: %s', [Index, Text]); utMap: Text := Format('%s: %s', [Name, Text]); else Text := Format('???: %s', [Text]); end; end; procedure TUBSTreeNode.UpdateChildren; begin GenerateChildren(TTreeView(TreeView), UBSValue, Self); end; function TUBSTreeNode.CanRename: Boolean; begin Result := UBSParent is TUBSMap; end; class procedure TUBSTreeNode.GenerateChildren(ATreeView: TTreeView; AUBSValue: TUBSValue; AParent: TUBSTreeNode); var NewNode: TUBSTreeNode; Pair: TPair<string, TUBSValue>; I: Integer; begin case AUBSValue.GetTag of utMap: for Pair in TUBSMap(AUBSValue).Order do begin NewNode := TTreeView(ATreeView).Items.AddChild(AParent, '') as TUBSTreeNode; NewNode.Initialize(TUBSMap(AUBSValue), Pair.Key); end; utList: for I := 0 to TUBSList(AUBSValue).Items.MaxIndex do begin NewNode := TTreeView(ATreeView).Items.AddChild(AParent, '') as TUBSTreeNode; NewNode.Initialize(TUBSList(AUBSValue), I); end; end; end; { TfrmTab } procedure TfrmTab.tvExplorerCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); begin NodeClass := TUBSTreeNode; end; function TfrmTab.GetOnFilenameChange: TEvent<TfrmTab>.TAccess; begin Result := FOnFilenameChange.Access; end; procedure TfrmTab.Modify; begin FModified := True; FOnModifiedChange.Execute(Self); end; function TfrmTab.GetOnModifiedChange: TEvent<TfrmTab>.TAccess; begin Result := FOnModifiedChange.Access; end; function TfrmTab.GetSelectedUBSValue: TUBSValue; var SelectedNode: TUBSTreeNode; begin SelectedNode := tvExplorer.Selected as TUBSTreeNode; if SelectedNode = nil then Exit(nil); Result := SelectedNode.UBSValue; end; function TfrmTab.GetSelectedUBSParent: TUBSParent; var Node: TUBSTreeNode; begin Node := SelectedParentNode; if Node = nil then begin if UBSValue is TUBSParent then Exit(TUBSParent(UBSValue)); Exit(nil); end; Exit(TUBSParent(Node.UBSValue)); end; function TfrmTab.GetSelectedValueNode: TUBSTreeNode; begin Result := tvExplorer.Selected as TUBSTreeNode; end; function TfrmTab.GetSelectedParentNode: TUBSTreeNode; begin Result := SelectedValueNode; if Result = nil then Exit; if Result.UBSValue is TUBSParent then Exit; if Result.Parent <> nil then Result := Result.Parent as TUBSTreeNode; if Result.UBSValue is TUBSParent then Exit; Result := nil; end; constructor TfrmTab.Create(AOwner: TComponent; AUBSTag: TUBSTag); begin inherited Create(AOwner); FUBSValue := UBSClasses[AUBSTag].Create; UpdateTreeView; end; constructor TfrmTab.Create(AOwner: TComponent; AFilename: string); begin inherited Create(AOwner); if not TFile.Exists(AFilename) then raise Exception.Create('File not found.'); FSaved := True; FFilename := AFilename; FFileTimestamp := TFile.GetLastWriteTime(AFilename); FUBSValue := TUBSValue.LoadFromFile(AFilename); UpdateTreeView; end; destructor TfrmTab.Destroy; begin FUBSValue.Free; inherited; end; function TfrmTab.FindNewName(AMap: TUBSMap): string; const DefaultName = 'Unnamed'; var I: Integer; begin Result := DefaultName; I := 0; while AMap.Map.ContainsKey(Result) do begin Inc(I); Result := Format('%s%d', [DefaultName, I]); end; end; function TfrmTab.FindNode(AValue: TUBSValue): TUBSTreeNode; var Node: TTreeNode; begin for Node in tvExplorer.Items do if (Node as TUBSTreeNode).UBSValue = AValue then Exit(TUBSTreeNode(Node)); Result := nil; end; procedure TfrmTab.UpdateTreeView; begin tvExplorer.Items.BeginUpdate; try tvExplorer.Items.Clear; TUBSTreeNode.GenerateChildren(tvExplorer, UBSValue); finally tvExplorer.Items.EndUpdate; end; end; function TfrmTab.Save: Boolean; begin if Filename.IsEmpty then if not SaveAs then Exit(False); Result := True; UBSValue.SaveToFile(Filename); FFileTimestamp := TFile.GetLastWriteTime(Filename); FModified := False; FOnModifiedChange.Execute(Self); end; function TfrmTab.SaveAs: Boolean; begin (Parent as TTabSheet).PageControl.ActivePage := (Parent as TTabSheet); dmData.dlgSave.Filename := Filename; Result := dmData.dlgSave.Execute; if not Result then Exit; FFilename := dmData.dlgSave.Filename; FOnFilenameChange.Execute(Self); Result := Save; end; function TfrmTab.FileChanged: Boolean; begin Result := not Filename.IsEmpty and (TFile.GetLastWriteTime(Filename) <> FFileTimestamp); end; procedure TfrmTab.CheckFileChanged; begin if FileChanged and (MessageDlg('File contents changed. Do you want to reload?', mtConfirmation, mbYesNo, 0) = mrYes) then begin FUBSValue.Free; FUBSValue := TUBSValue.LoadFromFile(Filename); end; end; function TfrmTab.TryClose: Boolean; begin Result := True; if Modified then begin case MessageDlg('Do you want to save your changes?', mtInformation, mbYesNoCancel, 0) of mrYes: Result := Save; mrCancel: Result := False; end; end; if Result then Parent.Free; end; function TfrmTab.CanAddValue: Boolean; begin Result := SelectedUBSParent <> nil; end; procedure TfrmTab.AddValue; begin end; procedure TfrmTab.AddValue(ATag: TUBSTag); var Node, NewNode: TUBSTreeNode; UBSParent: TUBSParent; NewName: string; NewValue: TUBSValue; begin Node := SelectedParentNode; UBSParent := SelectedUBSParent; if UBSParent is TUBSList then begin NewValue := TUBSValue.CreateTyped(ATag); TUBSList(UBSParent).Add(NewValue); NewNode := tvExplorer.Items.AddChild(Node, '...') as TUBSTreeNode; NewNode.Initialize(TUBSList(UBSParent), TUBSList(UBSParent).Items.MaxIndex); end else if UBSParent is TUBSMap then begin NewName := FindNewName(TUBSMap(UBSParent)); NewValue := TUBSValue.CreateTyped(ATag); TUBSMap(UBSParent)[NewName] := NewValue; NewNode := tvExplorer.Items.AddChild(Node, NewName) as TUBSTreeNode; NewNode.Initialize(TUBSMap(Node.UBSValue), NewName); end; end; procedure TfrmTab.tvExplorerEditing(Sender: TObject; Node: TTreeNode; var AllowEdit: Boolean); begin AllowEdit := (Node as TUBSTreeNode).CanRename; end; end.
unit oki6295; interface uses {$IFDEF WINDOWS}windows,{$else}main_engine,{$ENDIF} math,dialogs,timer_engine,sysutils,sound_engine; const OKIM6295_VOICES=4; OKIM6295_PIN7_LOW=0; OKIM6295_PIN7_HIGH=1; type adpcm_state=record signal:integer; step:integer; end; // struct describing a single playing ADPCM voice */ ADPCMVoice=record playing:boolean; //if we are actively playing */ base_offset:dword; // pointer to the base memory location */ sample:dword; // current sample number */ count:dword; // total samples to play */ adpcm:adpcm_state; // current ADPCM state */ volume:dword; // output volume end; snd_okim6295=class(snd_chip_class) constructor Create(clock:dword;pin7:byte;amp:single=1); destructor free; public procedure reset; function read:byte; procedure write(valor:byte); procedure change_pin7(pin7:byte); function get_rom_addr:pbyte; procedure update; function load_snapshot(data:pbyte):word; function save_snapshot(data:pbyte):word; private voice:array[0..OKIM6295_VOICES-1] of ADPCMVoice; command,bank_offs,out_:integer; bank_installed:boolean; rom:pbyte; ntimer:byte; amp:single; procedure reset_adpcm(num_voice:byte); function clock_adpcm(num_voice,nibble:byte):integer; function generate_adpcm(num_voice:byte):integer; procedure stream_update; end; procedure internal_update_oki6295(index:byte); var oki_6295_0,oki_6295_1:snd_okim6295; implementation const // step size index shift table */ index_shift:array[0..7] of integer =(-1, -1, -1, -1, 2, 4, 6, 8 ); // volume lookup table. The manual lists only 9 steps, ~3dB per step. Given the dB values, // that seems to map to a 5-bit volume control. Any volume parameter beyond the 9th index // results in silent playback. volume_table:array[0..15] of integer =( $20, // 0 dB $16, // -3.2 dB $10, // -6.0 dB $0b, // -9.2 dB $08, // -12.0 dB $06, // -14.5 dB $04, // -18.0 dB $03, // -20.5 dB $02, // -24.0 dB $00, $00, $00, $00, $00, $00, $00); var //lookup table for the precomputed difference */ diff_lookup:array[0..(49*16)-1] of single; chips_total:integer=-1; procedure compute_tables; const // nibble to bit map */ nbl2bit:array[0..15,0..3] of integer=( ( 1, 0, 0, 0), ( 1, 0, 0, 1), ( 1, 0, 1, 0), ( 1, 0, 1, 1), ( 1, 1, 0, 0), ( 1, 1, 0, 1), ( 1, 1, 1, 0), ( 1, 1, 1, 1), (-1, 0, 0, 0), (-1, 0, 0, 1), (-1, 0, 1, 0), (-1, 0, 1, 1), (-1, 1, 0, 0), (-1, 1, 0, 1), (-1, 1, 1, 0), (-1, 1, 1, 1)); var step,nib,stepval:integer; begin // loop over all possible steps */ for step:=0 to 48 do begin // compute the step value */ stepval:= floor(16.0*power(11.0/10.0,step)); // loop over all nibbles and compute the difference */ for nib:=0 to 15 do begin diff_lookup[step*16 + nib]:=nbl2bit[nib][0]*(stepval*nbl2bit[nib][1]+ stepval/2*nbl2bit[nib][2]+ stepval/4*nbl2bit[nib][3]+ stepval/8); end; end; end; constructor snd_okim6295.create(clock:dword;pin7:byte;amp:single=1); begin chips_total:=chips_total+1; getmem(self.rom,$40000); compute_tables; self.bank_installed:=false; self.tsample_num:=init_channel; self.amp:=amp; self.clock:=clock; self.ntimer:=timers.init(sound_status.cpu_num,1,nil,internal_update_oki6295,true,chips_total); self.change_pin7(pin7); // initialize the voices */ self.reset; end; destructor snd_okim6295.free; begin freemem(self.rom); chips_total:=chips_total-1; end; function snd_okim6295.load_snapshot(data:pbyte):word; var temp:pbyte; f:byte; begin temp:=data; copymemory(@self.command,temp,4);inc(temp,4); copymemory(@self.bank_offs,temp,4);inc(temp,4); copymemory(@self.out_,temp,4);inc(temp,4); copymemory(@self.bank_installed,temp,sizeof(boolean));inc(temp,sizeof(boolean)); copymemory(@self.ntimer,temp,1);inc(temp,1); copymemory(@self.amp,temp,sizeof(single));inc(temp,sizeof(single)); for f :=0 to (OKIM6295_VOICES-1) do copymemory(@self.voice[f],temp,sizeof(ADPCMVoice));inc(temp,sizeof(ADPCMVoice)); end; function snd_okim6295.save_snapshot(data:pbyte):word; var temp:pbyte; size:word; f:byte; begin temp:=data; copymemory(temp,@self.command,4);inc(temp,4);size:=4; copymemory(temp,@self.bank_offs,4);inc(temp,4);size:=size+4; copymemory(temp,@self.out_,4);inc(temp,4);size:=size+4; copymemory(temp,@self.bank_installed,sizeof(boolean));inc(temp,sizeof(boolean));size:=size+sizeof(boolean); copymemory(temp,@self.ntimer,1);inc(temp,1);size:=size+1; copymemory(temp,@self.amp,sizeof(single));inc(temp,sizeof(single));size:=size+sizeof(single); for f:=0 to (OKIM6295_VOICES-1) do copymemory(temp,@self.voice[f],sizeof(ADPCMVoice));inc(temp,sizeof(ADPCMVoice));size:=size+sizeof(ADPCMVoice); save_snapshot:=size; end; function snd_okim6295.get_rom_addr:pbyte; begin get_rom_addr:=self.rom; end; procedure snd_okim6295.reset_adpcm(num_voice:byte); begin // reset the signal/step */ self.voice[num_voice].adpcm.signal:=-2; self.voice[num_voice].adpcm.step:=0; end; function snd_okim6295.clock_adpcm(num_voice,nibble:byte):integer; begin self.voice[num_voice].adpcm.signal:=self.voice[num_voice].adpcm.signal+trunc(diff_lookup[self.voice[num_voice].adpcm.step*16+(nibble and 15)]); // clamp to the maximum */ if (self.voice[num_voice].adpcm.signal>2047) then self.voice[num_voice].adpcm.signal:=2047 else if (self.voice[num_voice].adpcm.signal<-2048) then self.voice[num_voice].adpcm.signal:=-2048; // adjust the step size and clamp */ self.voice[num_voice].adpcm.step:=self.voice[num_voice].adpcm.step+index_shift[nibble and 7]; if (self.voice[num_voice].adpcm.step>48) then self.voice[num_voice].adpcm.step:=48 else if (self.voice[num_voice].adpcm.step<0) then self.voice[num_voice].adpcm.step:=0; // return the signal */ clock_adpcm:=self.voice[num_voice].adpcm.signal; end; function snd_okim6295.generate_adpcm(num_voice:byte):integer; var nibble:byte; base,sample,count:dword; ptemp:pbyte; begin base:=self.voice[num_voice].base_offset; sample:=self.voice[num_voice].sample; count:=self.voice[num_voice].count; // compute the new amplitude and update the current step */ ptemp:=self.rom; inc(ptemp,base+(sample shr 1)); nibble:=ptemp^; if (sample and 1)=0 then nibble:=nibble shr 4 else nibble:=nibble and $f;//(((sample and 1) shl 2) xor 4); // next! */ sample:=sample+1; if (sample>=count) then self.voice[num_voice].playing:=false; // update the parameters */ self.voice[num_voice].sample:=sample; // output to the buffer, scaling by the volume */ //signal in range -2048..2047, volume in range 2..32 => signal * volume / 2 in range -32768..32767 */ generate_adpcm:=round(((self.clock_adpcm(num_voice,nibble)*(self.voice[num_voice].volume shr 1)))*self.amp); end; procedure snd_okim6295.reset; var f:byte; begin // initialize the voices */ self.command:=-1; self.out_:=0; self.bank_offs:=0; for f:=0 to (OKIM6295_VOICES-1) do begin self.reset_adpcm(f); self.voice[f].playing:=false; self.voice[f].count:=0; self.voice[f].base_offset:=0; self.voice[f].sample:=0; self.voice[f].volume:=0; end; end; procedure snd_okim6295.change_pin7(pin7:byte); var divisor:byte; begin if pin7=OKIM6295_PIN7_HIGH then divisor:=132 else divisor:=165; timers.timer[self.ntimer].time_final:=sound_status.cpu_clock/(self.clock/divisor); end; function snd_okim6295.read:byte; var f,res:byte; begin res:=$f0; // naname expects bits 4-7 to be 1 */ // set the bit to 1 if something is playing on a given channel */ for f:=0 to (OKIM6295_VOICES-1) do if self.voice[f].playing then res:=res or (1 shl f); read:=res; end; procedure snd_okim6295.write(valor:byte); var base:word; start,stop:dword; ptemp:pbyte; temp,i:byte; begin // if a command is pending, process the second half */ if (self.command<>-1) then begin temp:=valor shr 4; // the manual explicitly says that it's not possible to start multiple voices at the same time */ //if ((temp<>0) and (temp<>1) and (temp<>2) and (temp<>4) and (temp<>8)) then // MessageDlg('OKI 6295 - Oppps! Inicia mas de un canal a la vez!', mtInformation,[mbOk], 0); // determine which voice(s) (voice is set by a 1 bit in the upper 4 bits of the second byte) */ for i:=0 to (OKIM6295_VOICES-1) do begin if (temp and 1)<>0 then begin // determine the start/stop positions */ base:=self.command*8; ptemp:=self.rom; inc(ptemp,base); start:=ptemp^ shl 16; inc(ptemp); start:=start+(ptemp^ shl 8); inc(ptemp); start:=(start+ptemp^) and $3ffff; inc(ptemp); stop:=ptemp^ shl 16; inc(ptemp); stop:=stop+(ptemp^ shl 8); inc(ptemp); stop:=(stop+ptemp^) and $3ffff; // set up the voice to play this sample */ if (start<stop) then begin if not(self.voice[i].playing) then begin // fixes Got-cha and Steel Force */ self.voice[i].playing:=true; self.voice[i].base_offset:=start; self.voice[i].sample:=0; self.voice[i].count:=2*(stop-start+1); // also reset the ADPCM parameters */ self.reset_adpcm(i); self.voice[i].volume:=volume_table[valor and $0f]; end else begin //logerror("OKIM6295:'%s' requested to play sample %02x on non-stopped voice\n",device->tag(),info->command); end; end else begin // invalid samples go here */ //logerror("OKIM6295:'%s' requested to play invalid sample %02x\n",device->tag(),info->command); self.voice[i].playing:=false; end; end; temp:=temp shr 1; end; //del for // reset the command */ self.command:=-1; end else begin // if this is the start of a command, remember the sample number for next time */ if (valor and $80)<>0 then begin self.command:=valor and $7f; end else begin // otherwise, see if this is a silence command */ temp:=valor shr 3; //determine which voice(s) (voice is set by a 1 bit in bits 3-6 of the command */ for i:=0 to (OKIM6295_VOICES-1) do begin if (temp and 1)<>0 then self.voice[i].playing:=false; temp:=temp shr 1; end; end; end; end; procedure snd_okim6295.stream_update; var f:byte; begin self.out_:=0; for f:=0 to (OKIM6295_VOICES-1) do if self.voice[f].playing then self.out_:=self.out_+self.generate_adpcm(f); if self.out_<-32767 then self.out_:=-32767 else if self.out_>32767 then self.out_:=32767; end; procedure internal_update_oki6295(index:byte); begin case index of 0:oki_6295_0.stream_update; 1:oki_6295_1.stream_update; end; end; procedure snd_okim6295.update; begin tsample[self.tsample_num,sound_status.posicion_sonido]:=self.out_; if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=self.out_; end; end.
unit uBitmaps; interface uses Winapi.Windows, Vcl.Graphics, Vcl.Forms, Vcl.Controls, System.Classes, System.Math; type IBitmapCompareResult = interface ['{BC211798-7B90-4DF7-A0CB-E5344CD23EF7}'] function BitmapGet: TBitmap; property Bitmap: TBitmap read BitmapGet; function CountGet: Integer; property Count: Integer read CountGet; end; TBitmapCompareResult = class(TInterfacedObject, IBitmapCompareResult) protected fBitmap: TBitmap; fCount: Integer; public constructor Create; destructor Destroy; override; function BitmapGet: TBitmap; property Bitmap: TBitmap read BitmapGet; function CountGet: Integer; property Count: Integer read CountGet; end; function BitmapCrop(aBitmap: TBitmap; const aRect: TRect): TBitmap; function BitmapControl(aForm: TForm; const aControl: TControl): TBitmap; overload; function BitmapControl(aForm: TForm; const aControl: TControl; aBorder: TRect): TBitmap; overload; function BitmapCompare(aBitmap1, aBitmap2: TBitmap; aThreshold: Integer): IBitmapCompareResult; procedure BitmapGrayscale(aBitmap: TBitmap); implementation type PRGB32Record = ^TRGB32Record; TRGB32Record = packed record Blue: Byte; Green: Byte; Red: Byte; Alpha: Byte; end; PRGB32Array = ^TRGB32Array; TRGB32Array = packed array [0 .. MaxInt div SizeOf(TRGB32Record) - 1] of TRGB32Record; function BitmapCrop(aBitmap: TBitmap; const aRect: TRect): TBitmap; begin Result := TBitmap.Create; Result.Width := aRect.Right - aRect.Left; Result.Height := aRect.Bottom - aRect.Top; Result.PixelFormat := pf32bit; Result.Canvas.CopyRect(Rect(0, 0, Result.Width, Result.Height), aBitmap.Canvas, aRect); end; function BitmapControl(aForm: TForm; const aControl: TControl): TBitmap; var b: TBitmap; r: TRect; begin b := aForm.GetFormImage; b.PixelFormat := pf32bit; try r.Top := aControl.Top; r.Left := aControl.Left; r.Width := aControl.Width; r.Height := aControl.Height; Result := BitmapCrop(b, r); finally b.free; end; end; function BitmapControl(aForm: TForm; const aControl: TControl; aBorder: TRect): TBitmap; overload; var zz: TBitmap; rr: TRect; begin zz := BitmapControl(aForm, aControl); try rr.Top := aBorder.Top; rr.Left := aBorder.Left; rr.Right := zz.Width - aBorder.Right; rr.Bottom := zz.Height - aBorder.Bottom; Result := BitmapCrop(zz, rr); Result.PixelFormat := pf32bit; finally zz.free; end; end; procedure BitmapGrayscale(aBitmap: TBitmap); var X: Integer; Y: Integer; P: PRGB32Record; G: Byte; begin Assert(aBitmap.PixelFormat = pf32bit); for Y := 0 to (aBitmap.Height - 1) do begin P := aBitmap.ScanLine[Y]; for X := 0 to (aBitmap.Width - 1) do begin G := Round(0.30 * P.Red + 0.59 * P.Green + 0.11 * P.Blue); P.Red := G; P.Green := G; P.Blue := G; Inc(P); end; end; end; function BitmapCompare(aBitmap1, aBitmap2: TBitmap; aThreshold: Integer): IBitmapCompareResult; var l1: PRGB32Array; l2: PRGB32Array; X: Integer; Y: Integer; r: TBitmapCompareResult; begin r := TBitmapCompareResult.Create; Result := r; r.fCount := 0; r.fBitmap := TBitmap.Create; r.fBitmap.Width := Max(aBitmap1.Width, aBitmap2.Width); r.fBitmap.Height := Max(aBitmap1.Height, aBitmap2.Height); r.fBitmap.PixelFormat := pf32bit; // Unione delle bitmap clLime r.fBitmap.Canvas.Pen.Color := clLime; r.fBitmap.Canvas.Brush.Color := clLime; r.fBitmap.Canvas.Rectangle(0, 0, Max(aBitmap1.Width, aBitmap2.Width), Max(aBitmap1.Height, aBitmap2.Height)); // Intersezione delle bitmap clWhite r.fBitmap.Canvas.Pen.Color := clWhite; r.fBitmap.Canvas.Brush.Color := clWhite; r.fBitmap.Canvas.Rectangle(0, 0, Min(aBitmap1.Width, aBitmap2.Width), Min(aBitmap1.Height, aBitmap2.Height)); // differenze clRed for Y := 0 to Min(aBitmap1.Height, aBitmap2.Height) - 1 do begin l1 := aBitmap1.ScanLine[Y]; l2 := aBitmap2.ScanLine[Y]; for X := 0 to Min(aBitmap1.Width, aBitmap2.Width) - 1 do if (abs(l1[X].Red - l2[X].Red) > aThreshold) or (abs(l1[X].Blue - l2[X].Blue) > aThreshold) or (abs(l1[X].Green - l2[X].Green) > aThreshold) then begin r.fCount := r.fCount + 1; r.fBitmap.Canvas.Pixels[X, Y] := clRed end; end; end; { TBitmapCompareResult } function TBitmapCompareResult.BitmapGet: TBitmap; begin Result := fBitmap end; function TBitmapCompareResult.CountGet: Integer; begin Result := fCount end; constructor TBitmapCompareResult.Create; begin fBitmap := nil; end; destructor TBitmapCompareResult.Destroy; begin fBitmap.free; inherited; end; end.
unit DataValidators.TestSuite; interface uses TestFramework, System.SysUtils, System.Variants, Framework.Interfaces, DataValidators.TBooleanDataValidator, DataValidators.TCurrencyDataValidator, DataValidators.TDateTimeDataValidator, DataValidators.TIntegerDataValidator, DataValidators.TNumericDataValidator, DataValidators.TStringDataValidator; type TTBooleanDataValidatorTest = class(TTestCase) strict private FBooleanDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_Boolean_True; procedure TestParse_Boolean_False; procedure TestParse_StringBoolean_Invalid; procedure TestParse_StringBoolean_Valid; end; TTCurrencyDataValidatorTest = class(TTestCase) strict private FCurrencyDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_Currency; procedure TestParse_StringCurrency_Invalid; procedure TestParse_StringCurrency_Valid; end; TTDateTimeDataValidatorTest = class(TTestCase) strict private FDateTimeDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_DateTime; procedure TestParse_StringDateTime_Invalid; procedure TestParse_StringDateTime_Valid; end; TTIntegerDataValidatorTest = class(TTestCase) strict private FIntegerDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_Integer; procedure TestParse_StringInteger_Invalid; procedure TestParse_StringInteger_Valid; end; TTNumericDataValidatorTest = class(TTestCase) strict private FNumericDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_Numeric; procedure TestParse_StringNumeric_Invalid; procedure TestParse_StringNumeric_Valid; end; TTStringDataValidatorTest = class(TTestCase) strict private FStringDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_String_Invalid; procedure TestParse_String_Valid; end; implementation procedure TTBooleanDataValidatorTest.SetUp; begin inherited; FBooleanDataValidator := TBooleanDataValidator.Create; end; procedure TTBooleanDataValidatorTest.TearDown; begin inherited; end; procedure TTBooleanDataValidatorTest.TestParse_StringBoolean_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := 'True'; ReturnValue := FBooleanDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TTBooleanDataValidatorTest.TestParse_Boolean_False; var ReturnValue: Boolean; AValue: Variant; begin AValue := False; ReturnValue := FBooleanDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TTBooleanDataValidatorTest.TestParse_Boolean_True; var ReturnValue: Boolean; AValue: Variant; begin AValue := True; ReturnValue := FBooleanDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TTBooleanDataValidatorTest.TestParse_StringBoolean_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := 'Tru'; ReturnValue := FBooleanDataValidator.Parse(AValue); Check(ReturnValue = False); end; { TTCurrencyDataValidatorTest } procedure TTCurrencyDataValidatorTest.SetUp; begin inherited; FCurrencyDataValidator := TCurrencyDataValidator.Create; end; procedure TTCurrencyDataValidatorTest.TearDown; begin inherited; end; procedure TTCurrencyDataValidatorTest.TestParse_Currency; var ReturnValue: Boolean; AValue: Variant; begin AValue := 2450.70; ReturnValue := FCurrencyDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TTCurrencyDataValidatorTest.TestParse_StringCurrency_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '12,50.44'; ReturnValue := FCurrencyDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TTCurrencyDataValidatorTest.TestParse_StringCurrency_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '1250.44'; ReturnValue := FCurrencyDataValidator.Parse(AValue); Check(ReturnValue = True); end; { TTDateTimeDataValidatorTest } procedure TTDateTimeDataValidatorTest.SetUp; begin inherited; FDateTimeDataValidator := TDateTimeDataValidator.Create('yyyy/mm/dd', '/'); end; procedure TTDateTimeDataValidatorTest.TearDown; begin inherited; end; procedure TTDateTimeDataValidatorTest.TestParse_DateTime; var ReturnValue: Boolean; AValue: Variant; begin AValue := Now; ReturnValue := FDateTimeDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TTDateTimeDataValidatorTest.TestParse_StringDateTime_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '1973/13/28'; ReturnValue := FDateTimeDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TTDateTimeDataValidatorTest.TestParse_StringDateTime_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '1973/11/28'; ReturnValue := FDateTimeDataValidator.Parse(AValue); Check(ReturnValue = True); end; { TTIntegerDataValidatorTest } procedure TTIntegerDataValidatorTest.SetUp; begin inherited; FIntegerDataValidator := TIntegerDataValidator.Create; end; procedure TTIntegerDataValidatorTest.TearDown; begin inherited; end; procedure TTIntegerDataValidatorTest.TestParse_Integer; var ReturnValue: Boolean; AValue: Variant; begin AValue := 12; ReturnValue := FIntegerDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TTIntegerDataValidatorTest.TestParse_StringInteger_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := 'invalid integer'; ReturnValue := FIntegerDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TTIntegerDataValidatorTest.TestParse_StringInteger_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '1234'; ReturnValue := FIntegerDataValidator.Parse(AValue); Check(ReturnValue = True); end; { TTNumericDataValidatorTest } procedure TTNumericDataValidatorTest.SetUp; begin inherited; FNumericDataValidator := TNumericDataValidator.Create; end; procedure TTNumericDataValidatorTest.TearDown; begin inherited; end; procedure TTNumericDataValidatorTest.TestParse_Numeric; var ReturnValue: Boolean; AValue: Variant; begin AValue := 1232132.43232; ReturnValue := FNumericDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TTNumericDataValidatorTest.TestParse_StringNumeric_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '12,32,1,32.43232'; ReturnValue := FNumericDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TTNumericDataValidatorTest.TestParse_StringNumeric_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '1232132.43232'; ReturnValue := FNumericDataValidator.Parse(AValue); Check(ReturnValue = True); end; { TTStringDataValidatorTest } procedure TTStringDataValidatorTest.SetUp; begin inherited; FStringDataValidator := TStringDataValidator.Create; end; procedure TTStringDataValidatorTest.TearDown; begin inherited; end; procedure TTStringDataValidatorTest.TestParse_String_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := 1234; ReturnValue := FStringDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TTStringDataValidatorTest.TestParse_String_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := 'my string for testing'; ReturnValue := FStringDataValidator.Parse(AValue); Check(ReturnValue = True); end; initialization ReportMemoryLeaksOnShutdown := True; RegisterTest(TTBooleanDataValidatorTest.Suite); RegisterTest(TTCurrencyDataValidatorTest.Suite); RegisterTest(TTDateTimeDataValidatorTest.Suite); RegisterTest(TTIntegerDataValidatorTest.Suite); RegisterTest(TTNumericDataValidatorTest.Suite); RegisterTest(TTStringDataValidatorTest.Suite); end.
unit TestAddressNotesSamplesUnit; interface uses TestFramework, Classes, SysUtils, BaseTestOnlineExamplesUnit; type TTestAddressNotesSamples = class(TTestOnlineExamples) private procedure GetAddress; published procedure MarkAsDetectedAsVisited; procedure MarkAsDetectedAsDeparted; end; implementation uses AddressParametersUnit, AddressUnit, NullableBasicTypesUnit; var FRouteId: NullableString; FRouteDestinationId: NullableInteger; procedure TTestAddressNotesSamples.GetAddress; {var ErrorString: String; Parameters: TAddressParameters; Address: TAddress;} begin FRouteId := '241466F15515D67D3F951E2DA38DE76D'; FRouteDestinationId := 167899269; { Parameters := TAddressParameters.Create; Address := FRoute4MeManager.Address.Get(Parameters, ErrorString); CheckEquals(EmptyStr, ErrorString); FRouteId := Address.RouteId; FRouteDestinationId := Address.RouteDestinationId;} end; procedure TTestAddressNotesSamples.MarkAsDetectedAsDeparted; var ErrorString: String; IsDeparted: boolean; begin CheckTrue(FRouteId.IsNotNull); CheckTrue(FRouteDestinationId.IsNotNull); IsDeparted := True; FRoute4MeManager.Address.MarkAsDetectedAsDeparted( FRouteId, FRouteDestinationId, IsDeparted, ErrorString); CheckEquals(EmptyStr, ErrorString); FRoute4MeManager.Address.MarkAsDetectedAsVisited( 'qwe', FRouteDestinationId, IsDeparted, ErrorString); CheckNotEquals(EmptyStr, ErrorString); FRoute4MeManager.Address.MarkAsDetectedAsVisited( FRouteId, -123, IsDeparted, ErrorString); CheckNotEquals(EmptyStr, ErrorString); IsDeparted := False; FRoute4MeManager.Address.MarkAsDetectedAsVisited( FRouteId, FRouteDestinationId, IsDeparted, ErrorString); CheckEquals(EmptyStr, ErrorString); end; procedure TTestAddressNotesSamples.MarkAsDetectedAsVisited; var ErrorString: String; IsVisited: boolean; begin GetAddress; CheckTrue(FRouteId.IsNotNull); CheckTrue(FRouteDestinationId.IsNotNull); IsVisited := True; FRoute4MeManager.Address.MarkAsDetectedAsVisited( FRouteId, FRouteDestinationId, IsVisited, ErrorString); CheckEquals(EmptyStr, ErrorString); FRoute4MeManager.Address.MarkAsDetectedAsVisited( 'qwe', FRouteDestinationId, IsVisited, ErrorString); CheckNotEquals(EmptyStr, ErrorString); FRoute4MeManager.Address.MarkAsDetectedAsVisited( FRouteId, -123, IsVisited, ErrorString); CheckNotEquals(EmptyStr, ErrorString); IsVisited := False; FRoute4MeManager.Address.MarkAsDetectedAsVisited( FRouteId, FRouteDestinationId, IsVisited, ErrorString); CheckEquals(EmptyStr, ErrorString); end; initialization RegisterTest('Examples\Online\AddressNotes\', TTestAddressNotesSamples.Suite); FRouteId := NullableString.Null; FRouteDestinationId := NullableInteger.Null; end.
unit SoundHandler; interface uses VoyagerInterfaces, Classes, Controls, MPlayer; type TSoundHandler = class( TInterfacedObject, IMetaURLHandler, IURLHandler ) public constructor Create; destructor Destroy; override; private fPlayers : TStringList; // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( const URLHandler : IMasterURLHandler ); private fMasterURLHandler : IMasterURLHandler; private procedure OnNotify( Sender : TObject ); end; const tidMetaHandler_Sound = 'SoundHandler'; const htmlAction_Play = 'PLAY'; htmlAction_Stop = 'STOP'; htmlAction_Pause = 'PAUSE'; htmlAction_Resume = 'RESUME'; htmlAction_SetVolume = 'SETVOLUME'; htmlParmName_MediaId = 'MediaId'; htmlParmName_MediaURL = 'MediaURL'; htmlParmName_UseCache = 'UseCache'; htmlParmName_Rewind = 'Rewind'; htmlParmName_Volume = 'Volume'; htmlParmName_Loop = 'Loop'; const evnAnswerMediaStatus = 6000; evnMediaStatusChanged = 6001; type TMediaStatusInfo = record MediaId : string; Status : TMPNotifyValues; end; implementation uses URLParser, SysUtils, Events; // TSoundHandler constructor TSoundHandler.Create; begin inherited Create; fPlayers := TStringList.Create; end; destructor TSoundHandler.Destroy; var i : integer; begin for i := 0 to pred(fPlayers.Count) do TMediaPlayer(fPlayers.Objects[i]).Free; fPlayers.Free; inherited; end; function TSoundHandler.getName : string; begin result := tidMetaHandler_Sound; end; function TSoundHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable, hopNonVisual]; end; function TSoundHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TSoundHandler.Instantiate : IURLHandler; begin result := self; end; function TSoundHandler.HandleURL( URL : TURL ) : TURLHandlingResult; function GetCachePath : string; begin fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, result ); end; function Play( URL : string ) : TURLHandlingResult; var MediaId : string; MediaURL : string; idx : integer; Player : TMediaPlayer; begin MediaId := uppercase(URLParser.GetParmValue( URL, htmlParmName_MediaId )); MediaURL := uppercase(URLParser.GetParmValue( URL, htmlParmName_MediaURL )); if (MediaId <> '') and (MediaURL <> '') then begin idx := fPlayers.IndexOf( MediaId ); if idx >= 0 then Player := TMediaPlayer(fPlayers.Objects[idx]) else begin Player := TMediaPlayer.Create( nil ); Player.OnNotify := OnNotify; Player.Visible := false; Player.Parent := TWinControl(fMasterURLHandler.getControl); fPlayers.AddObject( MediaId, Player ); end; Player.FileName := GetCachePath + '/Sound/' + MediaURL; Player.Tag := integer(uppercase(URLParser.GetParmValue( URL, htmlParmName_Loop )) = 'YES'); Player.Open; Player.Notify := true; Player.Play; result := urlHandled; end else result := urlError; end; function Stop( URL : string ) : TURLHandlingResult; var MediaId : string; // Rewind : boolean; idx : integer; begin MediaId := uppercase(URLParser.GetParmValue( URL, htmlParmName_MediaId )); // Rewind := StrToBoolean(URLParser.GetParmValue( URL, htmlParmName_Rewind )); idx := fPlayers.IndexOf( MediaId ); if idx >= 0 then TMediaPlayer(fPlayers.Objects[idx]).Stop; { if Rewind then TMediaPlayer(fPlayers.Objects[idx]).Stop else TMediaPlayer(fPlayers.Objects[idx]).PauseOnly; } result := urlHandled; end; function Pause : TURLHandlingResult; var MediaId : string; idx : integer; begin MediaId := uppercase(URLParser.GetParmValue( URL, htmlParmName_MediaId )); idx := fPlayers.IndexOf( MediaId ); if idx >= 0 then TMediaPlayer(fPlayers.Objects[idx]).Pause; result := urlHandled; end; function Resume : TURLHandlingResult; var MediaId : string; idx : integer; begin MediaId := uppercase(URLParser.GetParmValue( URL, htmlParmName_MediaId )); idx := fPlayers.IndexOf( MediaId ); if idx >= 0 then TMediaPlayer(fPlayers.Objects[idx]).Resume; result := urlHandled; end; var Action : string; begin Action := URLParser.GetURLAction( URL ); if Action = htmlAction_Play then result := Play( URL ) else if Action = htmlAction_Stop then result := Stop( URL ) else if Action = htmlAction_Pause then result := Pause else if Action = htmlAction_Resume then result := Resume else result := urlNotHandled; end; function TSoundHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; begin result := evnHandled; end; function TSoundHandler.getControl : TControl; begin result := nil; end; procedure TSoundHandler.setMasterURLHandler( const URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; end; procedure TSoundHandler.OnNotify( Sender : TObject ); function GetMediaIdOf( Player : TObject ) : string; var i : integer; begin i := 0; while (i < fPlayers.Count) and (fPlayers.Objects[i] <> Player) do inc( i ); if i < fPlayers.Count then result := fPlayers[i] else result := ''; end; var Info : TMediaStatusInfo; begin Info.MediaId := GetMediaIdOf( Sender ); if Info.MediaId <> '' then begin Info.Status := (Sender as TMediaPlayer).NotifyValue; if (Sender as TMediaPlayer).Tag = 1 then begin (Sender as TMediaPlayer).Rewind; (Sender as TMediaPlayer).Play; end; fMasterURLHandler.HandleEvent( evnMediaStatusChanged, Info ); end; end; end.
unit uUtilis; interface type TUtilis = class private public class function SubstituirString(pString,pOld,pNew: String): String; class function FormatReal(pValor: Currency): String; end; implementation uses System.SysUtils; { TuSmartPro99 } class function TUtilis.FormatReal(pValor: Currency): String; begin Result := Formatfloat('##,###,##0.00', pValor); end; class function TUtilis.SubstituirString(pString, pOld, pNew: String): String; begin Result := StringReplace(pString,pOld,pNew,[rfReplaceAll, rfIgnoreCase]); end; end.
unit add_order_window; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, data_module, data_module_add, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons,Vcl.WinXPickers,DateUtils, add_customer_window; type TForm_add_order = class(TForm) DataSource_Goods: TDataSource; DBGrid_from_address: TDBGrid; DBGrid_to_address: TDBGrid; Label5: TLabel; Label6: TLabel; lbClientName: TLabel; BitBtn1: TBitBtn; DataSource_to_address: TDataSource; cbTimeOfDelivery: TCheckBox; tpTimeOfDelivery: TTimePicker; edClientName: TEdit; lbPhone: TLabel; edPhone: TEdit; Label1: TLabel; BitBtn2: TBitBtn; btnShowMenu: TButton; lbSearch: TLabel; edSearch: TEdit; btnAddAddress: TButton; btnRefresh: TButton; procedure FormActivate(Sender: TObject); procedure cbTimeOfDeliveryClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure btnAddAddressClick(Sender: TObject); procedure btnShowMenuClick(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure edSearchChange(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure edClientNameChange(Sender: TObject); procedure DataSource_GoodsDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var Form_add_order: TForm_add_order; //orderNum: integer; addrID :integer; addressString, time: string; implementation {$R *.dfm} uses add_address_window, show_menu, login_window, operator_window_inh; procedure TForm_add_order.BitBtn1Click(Sender: TObject); begin addrID := DataSource_to_address.DataSet.Fields[0].Value; time := TimeToStr(tpTimeOfDelivery.Time); Delete(time, length(TimeToStr(tpTimeOfDelivery.Time))-2,length(TimeToStr(tpTimeOfDelivery.Time))); try dm_add.add_Order(orderNum, 1, edClientName.Text, edPhone.Text, addrID, 0, dm.spLogin.ParamByName('OUT_EMP_ID').value, Now, time, 0); except MessageDlg('Ошибка при добавлении заказа', mtError, [mbOk], 0) end; end; procedure TForm_add_order.BitBtn2Click(Sender: TObject); begin //удалякм врЕменный заказ из БД при отмене dm.smDeleteOrder(orderNum); end; procedure TForm_add_order.btnAddAddressClick(Sender: TObject); var tmp: integer; begin dm.TAddress_Out.Open; form_Add_Address := Tform_Add_Address.Create(Application); form_Add_Address.ShowModal; if form_Add_Address.ModalResult = mrOk then begin if form_add_address.label_flat.text = '' then tmp := 0 else tmp := StrToInt(form_add_address.label_flat.text); dm_add.add_address(form_Add_Address.label_street.Text, form_Add_Address.label_building.Text, tmp); // dm.TAddress_Out.Close; end; update; dm.TAddress_Out.Refresh; Form_add_order.btnRefreshClick(Self) // dm.qOrderInfo.Open; // dm.qOrderInfo.Close; // dm.open_all; end; procedure TForm_add_order.btnRefreshClick(Sender: TObject); var SQL_Line: string; begin //Form_add_order.DataSource_Goods.DataSet.Open; SQL_Line := 'select menu.name, categories.name, order_info.quantity, order_info.price, order_info.order_id' + ' from order_info join menu ON order_info.product_id = menu.product_id' + ' join categories ON menu.category_id= categories.category_id where order_id = ' + orderNum.ToString; if dm.qOrderInfo.Transaction.InTransaction then dm.qOrderInfo.Transaction.Commit; dm.qOrderInfo.Close; dm.qOrderInfo.SQL.Clear; dm.qOrderInfo.SQL.Add(SQL_Line); dm.qOrderInfo.Open; if dm.qOrderInfo.Transaction.InTransaction then dm.qOrderInfo.Transaction.Commit; DataSource_Goods.DataSet := dm.qOrderInfo; DataSource_Goods.DataSet.Open; //Настройка dbgrid Form_add_order.DBGrid_from_address.Fields[0].DisplayLabel := 'Наименование'; Form_add_order.DBGrid_from_address.Fields[0].DisplayWidth := 17; Form_add_order.DBGrid_from_address.Fields[1].DisplayLabel := 'Категория'; Form_add_order.DBGrid_from_address.Fields[1].DisplayWidth := 10; Form_add_order.DBGrid_from_address.Fields[2].DisplayLabel := 'Количество'; Form_add_order.DBGrid_from_address.Fields[2].DisplayWidth := 5; Form_add_order.DBGrid_from_address.Fields[3].DisplayLabel := 'Цена'; Form_add_order.DBGrid_from_address.Fields[3].DisplayWidth := 6; Form_add_order.DBGrid_from_address.Fields[4].Visible := false; Form_add_order.DBGrid_from_address.Refresh; end; procedure TForm_add_order.btnShowMenuClick(Sender: TObject); begin fmMenu := TFmMenu.Create(Application); fmMenu.ShowModal; edSearchChange(self); end; procedure TForm_add_order.cbTimeOfDeliveryClick(Sender: TObject); begin tpTimeOfDelivery.Enabled := not(cbTimeOfDelivery.Checked); tpTimeOfDelivery.Time := IncHour(Now); end; procedure TForm_add_order.DataSource_GoodsDataChange(Sender: TObject; Field: TField); begin BitBtn1.Enabled := (edClientName.Text <> '') and (edPhone.Text <> '') and (DBGrid_from_address.DataSource.DataSet <> nil); end; procedure TForm_add_order.edClientNameChange(Sender: TObject); begin BitBtn1.Enabled := (edClientName.Text <> '') and (edPhone.Text <> '') and (DBGrid_from_address.DataSource.DataSet.RecordCount <> 0); end; procedure TForm_add_order.edSearchChange(Sender: TObject); var SQL_Line: string; begin SQL_Line := 'select * from addresses ' + 'where addresses.street containing ''' + edSearch.Text + ''';'; dm.smSQLClear; dm.smSQLAddString(SQL_Line); dm.smSQLExecute; DataSource_to_address.DataSet := dm.IBQuery1; DataSource_to_address.DataSet.Open; DBGrid_to_address.Fields[0].Visible := false; DBGrid_to_address.Fields[0].DisplayLabel := 'Улица'; DBGrid_to_address.Fields[0].DisplayWidth := 55; DBGrid_to_address.Fields[1].DisplayLabel := 'Дом'; DBGrid_to_address.Fields[1].DisplayWidth := 5; DBGrid_to_address.Fields[2].DisplayLabel := 'Квартира'; DBGrid_to_address.Fields[2].DisplayWidth := 10; DBGrid_to_address.Refresh; end; procedure TForm_add_order.FormActivate(Sender: TObject); var i : integer; SQL_Line: string; begin time := TimeToStr(tpTimeOfDelivery.Time); Delete(time, length(TimeToStr(tpTimeOfDelivery.Time))-2,length(TimeToStr(tpTimeOfDelivery.Time))); orderNum := dm_add.Add_Order(0, 0, '', '', 0, 0, dm.spLogin.ParamByName('OUT_EMP_ID').value, Now, time, 0); Caption := Caption + ' №' + orderNum.ToString; if cbTimeOfDelivery.Checked = true then begin tpTimeOfDelivery.Time := IncHour(Now); tpTimeOfDelivery.Enabled := false; end else begin tpTimeOfDelivery.Enabled := true; end; DataSource_to_address.DataSet := dm.TAddress_Out; DataSource_to_address.DataSet.Open; DBGrid_to_address.Fields[0].Visible := False; DBGrid_to_address.Fields[0].DisplayLabel := 'Улица'; DBGrid_to_address.Fields[0].DisplayWidth := 55; DBGrid_to_address.Fields[1].DisplayLabel := 'Дом'; DBGrid_to_address.Fields[1].DisplayWidth := 5; DBGrid_to_address.Fields[2].DisplayLabel := 'Квартира'; DBGrid_to_address.Fields[2].DisplayWidth := 10; DBGrid_to_address.Refresh; // for I := 0 to ComponentCount - 1 do begin // if Components[i] is TEdit then begin // (Components[i] as TEdit).Text := ''; // BitBtn1.Enabled := false; // end; // end; {===================================================} SQL_Line := 'select menu.name, categories.name, order_info.quantity, order_info.price, order_info.order_id' + ' from order_info join menu ON order_info.product_id = menu.product_id' + ' join categories ON menu.category_id= categories.category_id where order_id = ' + orderNum.ToString; if dm.qOrderInfo.Transaction.InTransaction then dm.qOrderInfo.Transaction.Commit; dm.qOrderInfo.Close; dm.qOrderInfo.SQL.Clear; dm.qOrderInfo.SQL.Add(SQL_Line); dm.qOrderInfo.Open; if dm.qOrderInfo.Transaction.InTransaction then dm.qOrderInfo.Transaction.Commit; DataSource_Goods.DataSet := dm.qOrderInfo; DataSource_Goods.DataSet.Open; //Настройка dbgrid Form_add_order.DBGrid_from_address.Fields[0].DisplayLabel := 'Наименование'; Form_add_order.DBGrid_from_address.Fields[0].DisplayWidth := 17; Form_add_order.DBGrid_from_address.Fields[1].DisplayLabel := 'Категория'; Form_add_order.DBGrid_from_address.Fields[1].DisplayWidth := 10; Form_add_order.DBGrid_from_address.Fields[2].DisplayLabel := 'Количество'; Form_add_order.DBGrid_from_address.Fields[2].DisplayWidth := 5; Form_add_order.DBGrid_from_address.Fields[3].DisplayLabel := 'Цена'; Form_add_order.DBGrid_from_address.Fields[3].DisplayWidth := 6; Form_add_order.DBGrid_from_address.Fields[4].Visible := false; Form_add_order.DBGrid_from_address.Refresh; end; procedure TForm_add_order.FormClose(Sender: TObject; var Action: TCloseAction); begin // dm.smDeleteOrder(orderNum); end; end.
unit UFaceBookDemo; interface uses FMX.Forms, SysUtils, FMX.TMSCloudBase, FMX.TMSCloudFacebook, FMX.Controls, FMX.Dialogs, FMX.TabControl, FMX.Grid, FMX.TMSCloudListView, FMX.Edit, FMX.StdCtrls, FMX.Objects, FMX.TMSCloudImage, FMX.Layouts, FMX.ListBox, System.Classes, FMX.Types, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomFacebook, System.Rtti, FMX.Controls.Presentation, IOUtils; type TForm1 = class(TForm) StyleBook1: TStyleBook; TMSFMXCloudFacebook1: TTMSFMXCloudFacebook; OpenDialog1: TOpenDialog; Panel1: TPanel; Button1: TButton; GroupBox2: TGroupBox; ListBox1: TListBox; SpeedButton1: TSpeedButton; GroupBox3: TGroupBox; Edit2: TEdit; Edit1: TEdit; Label3: TLabel; Label1: TLabel; Edit3: TEdit; Button3: TButton; Button2: TButton; Label2: TLabel; SpeedButton2: TSpeedButton; GroupBox1: TGroupBox; TMSFMXCloudImage1: TTMSFMXCloudImage; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label4: TLabel; Label9: TLabel; Label10: TLabel; lbGender: TLabel; lbWebsite: TLabel; lbUpdated: TLabel; Label11: TLabel; lbName: TLabel; CloudListView1: TTMSFMXCloudListView; Button4: TButton; Image1: TImage; btRemove: TButton; PageControl1: TTabControl; Likes: TTabItem; Comments: TTabItem; Label13: TLabel; edComment: TEdit; btPostComment: TButton; btShowLikes: TButton; lvLikes: TTMSFMXCloudListView; lvComments: TTMSFMXCloudListView; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure ListBox1Click(Sender: TObject); procedure ToggleControls; procedure LoadFeed; procedure LoadComments; procedure LoadLikes; procedure ShowProfile(Profile: TFacebookProfile); procedure TMSFMXCloudFacebook1ReceivedAccessToken(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure btRemoveClick(Sender: TObject); procedure btPostCommentClick(Sender: TObject); procedure btShowLikesClick(Sender: TObject); procedure CloudListView1Change(Sender: TObject); private { Private declarations } public { Public declarations } Connected: boolean; InitLV: boolean; InitLVC: boolean; FeedOffset: integer; end; var Form1: TForm1; implementation {$R *.FMX} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // FacebookAppkey = 'xxxxxxxxx'; // FacebookAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm1.btPostCommentClick(Sender: TObject); var FeedItem: TFacebookFeedItem; begin if (CloudListView1.ItemIndex >= 0) and (edComment.Text <> '') then begin FeedItem := CloudListView1.Items[CloudListView1.ItemIndex].Data; TMSFMXCloudFacebook1.PostComment(FeedItem.ID, edComment.Text); LoadFeed; end else begin ShowMessage('Please make sure a feed item is selected and a Comment text has been entered.'); end; end; procedure TForm1.btRemoveClick(Sender: TObject); //var // dr: string; begin TMSFMXCloudFacebook1.Logout; TMSFMXCloudFacebook1.ClearTokens; Connected := false; ToggleControls; // dr := ExtractFileDir(ParamStr(0)) + '\cache'; // if TDirectory.Exists(dr) then // TDirectory.Delete(dr, True); end; procedure TForm1.btShowLikesClick(Sender: TObject); var i, j, k: integer; strlikes: string; begin if InitLVC then Exit; if (CloudListView1.ItemIndex >= 0) and (lvComments.ItemIndex >= 0) then begin i := CloudListView1.ItemIndex; j := lvComments.ItemIndex; TMSFMXCloudFacebook1.GetLikes(TMSFMXCloudFacebook1.Profile.Feed[i].Comments[j]); if TMSFMXCloudFacebook1.Profile.Feed[i].Comments[j].Likes.Count > 0 then begin strlikes := 'Likes:' + #13; for k := 0 to TMSFMXCloudFacebook1.Profile.Feed[i].Comments[j].Likes.Count - 1 do strlikes := strlikes + TMSFMXCloudFacebook1.Profile.Feed[i].Comments[j].Likes[k].FullName + #13; end else strlikes := 'No Likes found for this Comment.'; ShowMessage(strlikes); end; end; procedure TForm1.Button1Click(Sender: TObject); var acc: boolean; begin TMSFMXCloudFacebook1.App.Key := FacebookAppkey; TMSFMXCloudFacebook1.App.Secret := FacebookAppSecret; if TMSFMXCloudFacebook1.App.Key <> '' then begin TMSFMXCloudFacebook1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'facebook.ini'; TMSFMXCloudFacebook1.PersistTokens.Section := 'tokens'; TMSFMXCloudFacebook1.LoadTokens; acc := TMSFMXCloudFacebook1.TestTokens; if not acc then begin TMSFMXCloudFacebook1.RefreshAccess; acc := TMSFMXCloudFacebook1.TestTokens; if not acc then TMSFMXCloudFacebook1.DoAuth; end else begin Connected := true; ToggleControls; TMSFMXCloudFacebook1.GetUserInfo; end; end else ShowMessage('Please provide a valid application ID for the client component'); end; procedure TForm1.Button2Click(Sender: TObject); var ImageID: string; begin if OpenDialog1.Execute then begin ImageID := TMSFMXCloudFacebook1.PostImage(Edit2.Text, OpenDialog1.FileName); Edit3.Text := TMSFMXCloudFacebook1.GetImageURL(ImageID); end; end; procedure TForm1.Button3Click(Sender: TObject); begin TMSFMXCloudFacebook1.Post(Edit2.Text, Edit1.Text, Edit3.Text); LoadFeed; end; procedure TForm1.Button4Click(Sender: TObject); begin FeedOffset := FeedOffset + 10; LoadFeed; end; procedure TForm1.TMSFMXCloudFacebook1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudFacebook1.SaveTokens; Connected := true; ToggleControls; TMSFMXCloudFacebook1.GetUserInfo; end; procedure TForm1.FormCreate(Sender: TObject); begin Connected := false; FeedOffset := 0; ToggleControls; end; procedure TForm1.ShowProfile(Profile: TFacebookProfile); begin lbName.Text := Profile.FirstName + ' ' + Profile.LastName; Label5.Text := Profile.BirthDay; Label6.Text := Profile.Location.Name; if Profile.Gender = fbMale then lbGender.Text := 'Male' else lbGender.Text := 'Female'; lbWebsite.Text := Profile.Website; lbUpdated.Text := DateTimeToStr(Profile.UpdatedTime); TMSFMXCloudImage1.URL := Profile.ImageURL; end; procedure TForm1.SpeedButton1Click(Sender: TObject); var I: Integer; begin TMSFMXCloudFacebook1.GetFriends; for I := 0 to TMSFMXCloudFacebook1.FriendList.Count - 1 do ListBox1.Items.AddObject(TMSFMXCloudFacebook1.FriendList.Items[I].FullName, TMSFMXCloudFacebook1.FriendList.Items[I]); end; procedure TForm1.SpeedButton2Click(Sender: TObject); begin FeedOffset := 0; LoadFeed; end; procedure TForm1.ListBox1Click(Sender: TObject); var Profile: TFacebookProfile; begin Profile := ListBox1.Items.Objects[ListBox1.ItemIndex] as TFacebookProfile; Profile := TMSFMXCloudFacebook1.FriendList.Find(Profile.ID); TMSFMXCloudFacebook1.GetProfileInfo(Profile.ID, Profile); ShowProfile(Profile); end; procedure TForm1.LoadComments; var cm: TFacebookComment; li: TListItem; i, j: integer; begin if CloudListView1.ItemIndex >= 0 then begin InitLV := true; lvComments.Items.Clear; i := CloudListView1.ItemIndex; TMSFMXCloudFacebook1.GetComments(TMSFMXCloudFacebook1.Profile.Feed[i]); for j := 0 to TMSFMXCloudFacebook1.Profile.Feed[i].Comments.Count - 1 do begin li := lvComments.Items.Add; cm := TMSFMXCloudFacebook1.Profile.Feed[i].Comments[j]; li.Text := IntToStr(j + 1); li.SubItems.Add(cm.Text); li.SubItems.Add(cm.User.FullName); li.SubItems.Add(FormatDateTime('dd/mm/yyyy hh:nn',cm.CreatedTime)); li.Data := cm; end; InitLV := false; end; end; procedure TForm1.LoadLikes; var li: TListItem; i, j: integer; begin if CloudListView1.ItemIndex >= 0 then begin lvLikes.Items.Clear; i := CloudListView1.ItemIndex; for j := 0 to TMSFMXCloudFacebook1.Profile.Feed[i].Likes.Count - 1 do begin li := lvLikes.Items.Add; li.Text := TMSFMXCloudFacebook1.Profile.Feed[i].Likes[j].FullName; li.Data := TMSFMXCloudFacebook1.Profile.Feed[i].Likes[j]; end; end; end; procedure TForm1.CloudListView1Change(Sender: TObject); begin if InitLV then Exit; LoadComments; LoadLikes; end; procedure TForm1.LoadFeed; var I: integer; Profile: TFacebookProfile; li: TListItem; begin if FeedOffset = 0 then CloudListView1.Items.Clear; Profile := TMSFMXCloudFacebook1.Profile; TMSFMXCloudFacebook1.GetFeed(Profile,10,FeedOffset); // TMSFMXCloudFacebook1.GetFeed(Profile,100); InitLV := true; for I := FeedOffset to profile.Feed.Count - 1 do begin // TMSFMXCloudFacebook1.GetLikes(Profile.Feed[i]); li := CloudListView1.Items.Add; li.Text := IntToStr(i + 1); // if (Profile.Feed[i].Likes.Find(Profile.ID) <> nil) then // li.IsChecked := true; li.SubItems.Add(profile.Feed[i].User.FullName); if profile.Feed[i].Text <> '' then li.SubItems.Add(profile.Feed[i].Text) else li.SubItems.Add(profile.Feed[i].Story); li.SubItems.Add(FormatDateTime('dd/mm/yyyy hh:nn',profile.Feed[i].CreatedTime)); li.Data := profile.Feed[i]; end; InitLV := false; end; procedure TForm1.ToggleControls; begin GroupBox1.Enabled := Connected; GroupBox3.Enabled := Connected; SpeedButton1.Enabled := Connected; SpeedButton2.Enabled := Connected; ListBox1.Enabled := Connected; Button2.Enabled := Connected; Button3.Enabled := Connected; Edit1.Enabled := Connected; Edit2.Enabled := Connected; Edit3.Enabled := Connected; btRemove.Enabled := Connected; lvLikes.Enabled := Connected; PageControl1.Enabled := Connected; Button1.Enabled := not Connected; end; end.
{ Subroutine SST_SYMBOL_LOOKUP (NAME_H, SYM_P, STAT) * * Look up an existing symbol in the currently active name spaces. * NAME_H is the string handle returned by one of the SYO_GET_TAG routines. * SYM_P is returned pointing to the symbol data block. * STAT is returned with an error if the symbol was not found. } module sst_symbol_lookup; define sst_symbol_lookup; %include 'sst2.ins.pas'; procedure sst_symbol_lookup ( {get data about an existing symbol} in name_h: syo_string_t; {handle to name string from tag} out sym_p: sst_symbol_p_t; {returned pointer to symbol descriptor} out stat: sys_err_t); {completion status code} var name: string_var132_t; {symbol name string} begin name.max := sizeof(name.str); {init local var string} syo_get_tag_string (name_h, name); {get raw symbol name} sst_symbol_lookup_name (name, sym_p, stat); {lookup explicit name} end;
{ **** UBPFD *********** by delphibase.endimus.com **** >> Разбивка строки на отдельные слова function StringToWords(const DelimitedText: string; ResultList: TStrings; Delimiters: TDelimiter = []): boolean - разбивает отдельную строку на состовляющие ее слова и результат помещает в TStringList function StringsToWords(const DelimitedStrings: TStrings; ResultList: TStrings; Delimiters: TDelimiter = []): boolean - разбивает любое количество строк на состовляющие их слова и все помещяет в один TStringList Delimiters - список символов являющихся разделителями слов, например такие как пробел, !, ? и т.д. Зависимости: Classes Автор: Separator, separator@mail.kz, Алматы Copyright: Separator Дата: 13 ноября 2002 г. ***************************************************** } unit spUtilsUnit; interface uses Classes; type TDelimiter = set of #0..'я' ; const StandartDelimiters: TDelimiter = [' ', '!', '@', '(', ')', '-', '|', '\', ';', ':', '"', '/', '?', '.', '>', ',', '<']; //Преобразование в набор слов function StringToWords(const DelimitedText: string; ResultList: TStrings; Delimiters: TDelimiter = []; ListClear: boolean = true): boolean; function StringsToWords(const DelimitedStrings: TStrings; ResultList: TStrings; Delimiters: TDelimiter = []; ListClear: boolean = true): boolean; implementation function StringToWords(const DelimitedText: string; ResultList: TStrings; Delimiters: TDelimiter = []; ListClear: boolean = true): boolean; var i, Len, Prev: word; TempList: TStringList; begin Result := false; if (ResultList <> nil) and (DelimitedText <> '') then try TempList := TStringList.Create; if Delimiters = [] then Delimiters := StandartDelimiters; Len := 1; Prev := 0; for i := 1 to Length(DelimitedText) do begin if Prev <> 0 then begin if DelimitedText[i] in Delimiters then begin if Len = 0 then Prev := i + 1 else begin TempList.Add(copy(DelimitedText, Prev, Len)); Len := 0; Prev := i + 1 end end else Inc(Len) end else if not (DelimitedText[i] in Delimiters) then Prev := i end; if Len > 0 then TempList.Add(copy(DelimitedText, Prev, Len)); if TempList.Count > 0 then begin if ListClear then ResultList.Assign(TempList) else ResultList.AddStrings(TempList); Result := true end; finally TempList.Free end end; function StringsToWords(const DelimitedStrings: TStrings; ResultList: TStrings; Delimiters: TDelimiter = []; ListClear: boolean = true): boolean; begin if Delimiters = [] then Delimiters := StandartDelimiters + [#13, #10] else Delimiters := Delimiters + [#13, #10]; Result := StringToWords(DelimitedStrings.Text, ResultList, Delimiters, ListClear) end; end.
unit uAbout; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MGR32_Image, ExtCtrls; type TFrmAbout = class(TForm) View: TMPaintBox32; Timer: TTimer; procedure FormHide(Sender: TObject); procedure FormShow(Sender: TObject); procedure TimerTimer(Sender: TObject); private { Private declarations } public { Public declarations } end; TStar=record X,Y,Z:single; Color:Cardinal; Spec:integer; end; const MaxStars=128; var FrmAbout: TFrmAbout; Stars:array[0..MaxStars-1] of TStar; implementation {$R *.dfm} procedure InitStar(var Star:TStar); var Alpha:Cardinal; begin with Star do begin x:=random(512); y:=random(256); z:=random(10)+0.5; case random(100) of 0..70:Color:= $00FFFFFF; 71..80:Color:=$00FF6010; 81..85:Color:=$00FF0000; 86..90:Color:=$0000FF00; 91..95:Color:=$000000FF; 96..99:Color:=$00FF00FF; end; Alpha:=round(256-z*12.7); Color:=Color or (Alpha and $ff)shl 24; end; end; Procedure InitAllStars; var i:longint; begin for i:=0 to MaxStars-1 do InitStar(Stars[i]); end; Procedure MoveAndDrawStars; var i:longint; begin for i:=0 to MaxStars-1 do begin with Stars[i] do begin x:=x-1/z; if x<=0 then x:=511; FrmAbout.View.Buffer.SetPixelT(round(x),Round(y),Color); end; end; end; procedure TFrmAbout.FormHide(Sender: TObject); begin Timer.Enabled:=false; end; procedure TFrmAbout.FormShow(Sender: TObject); begin Timer.Enabled:=true; InitAllStars; end; procedure TFrmAbout.TimerTimer(Sender: TObject); begin View.Buffer.Clear(0); MoveAndDrawStars; //View.Buffer.PenColor:=$ff806010; View.Buffer.RenderText(8,8,'Chaotikmind - 2009',1,$ffC06010); View.Buffer.RenderText(8,24,'Dda Editor',1,$ffC06010); //View.Buffer.Textout(8,8,'Chaotikmind - 2009'); //View.Buffer.Textout(8,16,'Dda Editor'); View.Invalidate; end; end.
Dispose (* BinTree DA, 19.12.2018 --- Implementation of a binary search tree and several algorithms on it. ------------------------------------------------ *) PROGRAM BinTree; (*=====================================================*) (* 1. declarations *) (*=====================================================*) TYPE NodePtr = ^Node; Node = RECORD value: INTEGER; left, right: NodePtr; END; TreePtr = NodePtr; PROCEDURE ASSERT(cond: BOOLEAN; msg: STRING); BEGIN IF NOT cond THEN BEGIN WriteLn('ASSERTION FAILED: ', msg); HALT; END; (*IF*) END; (*ASSERT*) (*=====================================================*) (* 2. stack for iterative tree traversals *) (*=====================================================*) CONST maxSize = 100; VAR stack: ARRAY [1..maxSize] OF NodePtr; sp: INTEGER; PROCEDURE Init; BEGIN sp := 0; END; (*InitStack*) FUNCTION Empty: BOOLEAN; BEGIN Empty := (sp = 0); END; (*Empty*) FUNCTION Full: BOOLEAN; BEGIN Full := (sp = maxSize); END; (*Empty*) PROCEDURE Push(n: NodePtr); BEGIN ASSERT(NOT Full, '(in Push) stack is already full'); sp := sp + 1; stack[sp] := n; END; (*Push*) PROCEDURE Pop(VAR n: NodePtr); BEGIN ASSERT(NOT Empty, '(in Pop) stack is already empty'); n := stack[sp]; sp := sp - 1; END; (*Pop*) (*=====================================================*) (* 3. algorithms *) (*=====================================================*) (* New Tree - creates new tree *) FUNCTION NewTree: TreePtr; BEGIN NewTree := NIL; END; (* NewNode - creates new node for tree *) FUNCTION NewNode(value: INTEGER): NodePtr; VAR n: NodePtr; BEGIN New(n); n^.value := value; n^.left := NIL; n^.right := NIL; NewNode := n; END; (* TreeOf - creates a tree based on a node and two subtrees *) FUNCTION Treeof(n: NodePtr; lt, rt: TreePtr): TreePtr; BEGIN ASSERT(((n <> NIL) AND (n <> lt) AND (n <> rt) AND (lt <> rt)), 'invalid node or subtrees'); n^.left := lt; n^.right := rt; Treeof := n; END; (* WriteTreePreorder: write tree in preorder, i.e. parent - left child - right child *) (* recursive implementation *) PROCEDURE WriteTreePreorder(t: TreePtr); BEGIN IF t = NIL THEN (* do nothing *) ELSE BEGIN Write(t^.value, ' '); WriteTreePreorder(t^.left); WriteTreePreorder(t^.right); END; END; (* WriteTreeInorder: write tree in inorder, i.e. left - parent - right *) (* recursive implementation *) PROCEDURE WriteTreeInorder(t: TreePtr); BEGIN IF t = NIL THEN (* do nothing *) ELSE BEGIN WriteTreeInorder(t^.left); Write(t^.value, ' '); WriteTreeInorder(t^.right); END; END; (* WriteTreePostorder: write tree in inorder, i.e. left - right - parent *) (* recursive implementation *) PROCEDURE WriteTreePostorder(t: TreePtr); BEGIN IF t = NIL THEN (* do nothing *) ELSE BEGIN WriteTreePostorder(t^.left); WriteTreePostorder(t^.right); Write(t^.value, ' '); END; END; (* WriteTreePreorderIter: preorder strategy in iterative implementation *) PROCEDURE WriteTreePreorderIter(t: TreePtr); VAR nodesToPassBy: BOOLEAN; BEGIN Init; nodesToPassBy := TRUE; WHILE (t <> NIL) AND nodesToPassBy DO BEGIN Write(t^.value, ' '); IF t^.right <> NIL THEN (* keep right child *) Push(t^.right); IF t^.left <> NIL THEN t := t^.left ELSE IF not(empty) THEN Pop(t) ELSE nodesToPassBy := FALSE; END; END; (* Count Nodes of Tree *) FUNCTION CountNodes(t: TreePtr): INTEGER; BEGIN IF t = NIL THEN CountNodes := 0 ELSE CountNodes := 1 + CountNodes(t^.left) + CountNodes(t^.right); END; (* Insert: insert Node into binary search tree *) PROCEDURE Insert(VAR t: TreePtr; n: NodePtr); BEGIN IF t = NIL THEN t := n ELSE IF n^.value < t^.value THEN Insert(t^.left, n) ELSE Insert(t^.right,n); END; (* RemoveNode: removes node from tree *) PROCEDURE RemoveNode(VAR t: TreePtr; value: INTEGER; VAR n: NodePtr); VAR par: NodePtr; (* parent node of n *) subtree: TreePtr; (* subTree *) succ, succPar: NodePtr; BEGIN (* 1. Finde n: iterative search in binary tree *) n := t; par := NIL; WHILE (n <> NIL) AND (n^.value <> value) DO BEGIN par := n; IF value < n^.value THEN n := n^.left ELSE n := n^.right; END; (* 2. no node with value *) IF n <> NIL THEN Exit; (* 3. remove n *) (* 3.1. create new subtree *) IF n^.right = NIL THEN (* no right child *) subtree := n^.left ELSE BEGIN (* has right child *) IF n^.right^.left = NIL THEN BEGIN subtree := n^.right; subtree^.left := n^.left; END ELSE BEGIN (* search for left-most node in right subtree --> min. value *) succPar := NIL; succ := n^.right; WHILE succ^.left <> NIL DO BEGIN succPar := succ; succ := succ^.left; END; succPar^.left := succ^.right; succ^.left := n^.left; succ^.right := n^.right; subtree := succ; END; END; (*Insert subtree overall tree*) IF par = NIL THEN t := subtree ELSE IF n^.value < par^.value THEN par^.left := subtree ELSE par^.right := subtree; n^.left := NIL; n^.right := NIL; END; (* Dispose tree left - right - parent *) PROCEDURE DisposeTree(VAR t: TreePtr); BEGIN IF t <> NIL THEN BEGIN DisposeTree(t^.left); DisposeTree(t^.right); Dispose(t); t := NIL; END; END; VAR t: TreePtr; test: NodePtr; BEGIN (*BinTree*) t := TreeOf(NewNode(45), TreeOf(NewNode(27), NewNode(11), TreeOf(NewNode(31), NewNode(27), NIL)), TreeOf(NewNode(99), NewNode(54), NIL)); WriteTreePreorder(t); WriteLn; WriteTreeInorder(t); WriteLn; WriteTreePostorder(t); WriteLn; WriteTreePreorderIter(t); WriteLn; Insert(t,NewNode(44)); Insert(t,NewNode(103)); WriteTreeInorder(t); WriteLn; RemoveNode(t,44, test); WriteTreeInorder(t); WriteLn('Number: ', CountNodes(t)); DisposeTree(t); END. (*BinTree*)
unit atSyncedStringFileReader; // Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atSyncedStringFileReader.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatSyncedStringFileReader" MUID: (502A4763011B) interface uses l3IntfUses , atStringFileReader , atLockFile ; type TatSyncedStringFileReader = class(TatStringFileReader) private f_LockFile: TatLockFile; f_SyncFile: AnsiString; public constructor Create(const aStringFile: AnsiString; const aSyncFile: AnsiString); reintroduce; virtual; destructor Destroy; override; function AcquireNext(out theString: AnsiString): Boolean; override; procedure Reset; override; end;//TatSyncedStringFileReader implementation uses l3ImplUses , SysUtils //#UC START# *502A4763011Bimpl_uses* //#UC END# *502A4763011Bimpl_uses* ; constructor TatSyncedStringFileReader.Create(const aStringFile: AnsiString; const aSyncFile: AnsiString); //#UC START# *502A49CD0158_502A4763011B_var* //#UC END# *502A49CD0158_502A4763011B_var* begin //#UC START# *502A49CD0158_502A4763011B_impl* inherited Create(aStringFile); // f_SyncFile := aSyncFile; f_LockFile := TatLockFile.Create(f_SyncFile + '.lock_file'); if f_LockFile.Acquire then try if FileExists(f_SyncFile) then begin f_StringsUsage.LoadFromFile(f_SyncFile); if f_StringsUsage.Size <> f_Strings.Count then // если файл со строками поменялся между запусками f_StringsUsage.Size := f_Strings.Count; end; f_StringsUsage.SaveToFile(f_SyncFile); finally f_LockFile.Release; end; //#UC END# *502A49CD0158_502A4763011B_impl* end;//TatSyncedStringFileReader.Create destructor TatSyncedStringFileReader.Destroy; //#UC START# *48077504027E_502A4763011B_var* //#UC END# *48077504027E_502A4763011B_var* begin //#UC START# *48077504027E_502A4763011B_impl* FreeAndNil(f_LockFile); // inherited; //#UC END# *48077504027E_502A4763011B_impl* end;//TatSyncedStringFileReader.Destroy function TatSyncedStringFileReader.AcquireNext(out theString: AnsiString): Boolean; //#UC START# *502A459F005A_502A4763011B_var* //#UC END# *502A459F005A_502A4763011B_var* begin //#UC START# *502A459F005A_502A4763011B_impl* Result := false; // if f_LockFile.Acquire then try f_StringsUsage.LoadFromFile(f_SyncFile); Result := inherited AcquireNext(theString); if Result then f_StringsUsage.SaveToFile(f_SyncFile); finally f_LockFile.Release; end; //#UC END# *502A459F005A_502A4763011B_impl* end;//TatSyncedStringFileReader.AcquireNext procedure TatSyncedStringFileReader.Reset; //#UC START# *502AACD103A6_502A4763011B_var* //#UC END# *502AACD103A6_502A4763011B_var* begin //#UC START# *502AACD103A6_502A4763011B_impl* if f_LockFile.Acquire then try f_StringsUsage.LoadFromFile(f_SyncFile); inherited Reset; f_StringsUsage.SaveToFile(f_SyncFile); finally f_LockFile.Release; end; //#UC END# *502AACD103A6_502A4763011B_impl* end;//TatSyncedStringFileReader.Reset end.
unit l3PureMixIns; {* Абстрактные примеси. } // Модуль: "w:\common\components\rtl\Garant\L3\l3PureMixIns.pas" // Стереотип: "Interfaces" // Элемент модели: "l3PureMixIns" MUID: (47D810610398) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses ; // _ItemType_ (* Ml3CountHolder = interface function pm_GetCount: Integer; property Count: Integer read pm_GetCount; {* Число элементов. } end;//Ml3CountHolder *) (* Ml3List = interface(Ml3CountHolder) {* Список. } function pm_GetEmpty: Boolean; function pm_GetFirst: _ItemType_; function pm_GetLast: _ItemType_; function pm_GetItems(anIndex: Integer): _ItemType_; property Empty: Boolean read pm_GetEmpty; property First: _ItemType_ read pm_GetFirst; {* Первый элемент. } property Last: _ItemType_ read pm_GetLast; {* Последний элемент. } property Items[anIndex: Integer]: _ItemType_ read pm_GetItems; default; end;//Ml3List *) (* Ml3ListEx = interface(Ml3List) function IndexOf(const anItem: _ItemType_): Integer; function Add(const anItem: _ItemType_): Integer; end;//Ml3ListEx *) (* Ml3CheckStamp = interface function CheckStamp(const aGUID: TGUID): Boolean; {* Проверяет метку реализации интерфейса. Например для того, чтобы узнать, что реализация наша "родная". } end;//Ml3CheckStamp *) (* Ml3ChangingChanged = interface procedure Changed; {* нотификация о завершении изменения состояния объекта. Для перекрытия и использования в потомках. } procedure Changing; {* нотификация о начале изменения состояния объекта. Для перекрытия и использования в потомках. } end;//Ml3ChangingChanged *) implementation uses l3ImplUses ; end.
{ Subroutine SST_W_C_VAR (V, ADDR_CNT) * * Write the variable reference from the variable descriptor V. * ADDR_CNT is the number of times the resulting expression should be * the address of the variable descriptor. A value of 0 causes the * variable reference to be written as is. Values above 0 cause * "*"s to be removed or "&"s added. Values below 0 have the reverse * affect. } module sst_w_c_var; define sst_w_c_var; %include 'sst_w_c.ins.pas'; procedure sst_w_c_var ( {write variable reference} in v: sst_var_t; {variable reference descriptor block} in addr_cnt: sys_int_machine_t); {number of times to take address of} const max_msg_parms = 1; {max parameters we can pass to a message} max_insert = 2; {max modifiers can be inserted after top} var mod_p: sst_var_mod_p_t; {points to current variable modifier} quit_p: sst_var_mod_p_t; {pointer to start of mod chain to ignore} dtype_p: sst_dtype_p_t; {pointer to data type at current modifier} dt_p: sst_dtype_p_t; {scratch data type pointer} dt_nc_p: sst_dtype_p_t; {data type before resolve copies} sym_p: sst_symbol_p_t; {scratch pointer to symbol descriptor} ordval: sys_int_max_t; {ordinal value for array subscript range} addr_cnt_adj: sys_int_machine_t; {adjusted internal address-of count} since_arrow: sys_int_machine_t; {number of modifiers since last "->"} since_deref: sys_int_machine_t; {num of modifiers since last derefernce mod} mod_insert: {modifiers may be inserted after top ref} array[1..max_insert] of sst_var_mod_t; insert_cnt: sys_int_machine_t; {number of modifiers currently inserted} old_next_p: sst_var_mod_p_t; {saved copy of V.MOD1.NEXT_P} pnt_cnt: sys_int_machine_t; {levels of pointers before base data type} i: sys_int_machine_t; {scratch integer and loop counter} token: string_var16_t; {scratch string for number conversion} paren: boolean; {leading paren written, need close paren} enclose: boolean; {enclose everything when start with spec char} spchar_first: boolean; {next special leading char is the first} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; {error status code} label resolve_dtype; { **************************************** * * Local subroutine DEREF_TOP * * Edit modifier chain so that the top modifier is dereferenced one level * more than it otherwise would be. INSERT_CNT is updated to indicate the * total number of modifiers inserted after the top modifier. } procedure deref_top; var mod_p: sst_var_mod_p_t; {scratch modifier pointer} begin insert_cnt := insert_cnt + 1; {make MOD_INSERT index for new modifier} if insert_cnt > max_insert then begin sys_message_bomb ('sst_write_c', 'var_mode_too_many', nil, 0); end; mod_insert[insert_cnt].next_p := v.mod1.next_p; {fill in new modifier} mod_insert[insert_cnt].modtyp := sst_var_modtyp_unpnt_k; mod_p := addr(v.mod1); {subvert IN declaration for V argument} mod_p^.next_p := addr(mod_insert[insert_cnt]); {insert new modifier after top sym} end; { **************************************** * * Local function DEREF_FIELD (M) * * Return true if the modifier M is a pointer dereference of a record * pointer followed by a field in that record. It is assumed that MOD * is a pointer dereference modifier. } function deref_field ( in m: sst_var_mod_t) {modifier to check out} :boolean; {TRUE if rec pointer deref followed by field} val_param; begin deref_field := false; {init to not dereference before field name} if m.next_p = nil then return; {no modifier follows ?} if m.next_p^.modtyp <> sst_var_modtyp_field_k {next modifier is not a field ?} then return; deref_field := true; end; { **************************************** * * Local subroutine LEADING_DEREF (M) * * Handle all pointer dereferences that are not from record pointers followed * by fields. Each such pointer dereference requires a "*" be written at the * start of the variable reference expression. The modifier chain starting * at M is followed. QUIT_P will be updated to point to the first modifier * of a continuous block of dereference modifiers at the end of the variable * descriptor chain. This allows the main routine to stop when that modifier * is reached. A leading parenthesis will be written before the "*"s for * all but the outermost group. } procedure leading_deref ( in m: sst_var_mod_t); {modifier at start of chain to check out} val_param; var m_p: sst_var_mod_p_t; {pointer to current modifier} deref_cnt: sys_int_machine_t; {number of dereferences at end of mod chain} label write_deref; begin deref_cnt := 0; {init number of dereferences found} quit_p := nil; {indicate no dereference block found at end} m_p := addr(m); {init current modifier to first in chain} while m_p <> nil do begin {loop thru all the modifiers} if (m_p^.modtyp = sst_var_modtyp_unpnt_k) and {dereference modifier ?} (not deref_field(m_p^)) {not deref from rec pointer to field ?} then begin {this is dereference modifier we care about} if quit_p = nil then begin {first consecutive dereference ?} quit_p := m_p; {save start of consecutive dereference chain} end; deref_cnt := deref_cnt + 1; {count one more consecutive dereference} end else begin {not deref modifier we are looking for} if deref_cnt <> 0 then begin {first mod after block of dereferences ?} leading_deref (m_p^); {process rest of modifier chain recursively} sst_w.appendn^ ('(', 1); spchar_first := false; {next special char will not be at var start} goto write_deref; {write the dereferences} end; end ; m_p := m_p^.next_p; {advance to next modifier in chain} end; {back and process this new modifier} { * DEREF_CNT is set to the number of consecutive dereferences found at the end * of the modifier chain that was not handled recursively. This routine calls * itself recursively in such a way that the first invocation to come thru here * represents the end of the modifier chain. Therefore ADDR_CNT_ADJ will be * used only by the first invocation. } write_deref: {jump here if derefs not at end of chain} deref_cnt := deref_cnt - addr_cnt_adj; {add in caller's dereferences} addr_cnt_adj := 0; {insure caller's dereferences used only once} if {need leading parenthesis ?} (deref_cnt <> 0) and {will write some special character ?} spchar_first and {this will be start of everything written} enclose {need to enclose on leading special char ?} then begin sst_w.appendn^ ('(', 1); {write leading parenthesis} paren := true; {we will need close parenthesis later} end; spchar_first := false; {no longer at start of whole var} while deref_cnt > 0 do begin {once for each dereference to write} sst_w.appendn^ ('*', 1); deref_cnt := deref_cnt - 1; {one less dereference to write} end; while deref_cnt < 0 do begin {once for each "address of" to write} sst_w.appendn^ ('&', 1); deref_cnt := deref_cnt + 1; {one less dereference to write} end; end; { **************************************** * * Start of main routine. } begin token.max := sizeof(token.str); {init local var string} enclose := false; {init to don't enclose everything in ()} paren := false; {init to no close paren needed} spchar_first := true; {next char will be first in var reference} { * Init DTYPE_P to point to the data type of the top symbol. It will be * kept up to date as each modifier is processed. DTYPE_P is set to NIL * to indicate no data type exists. } dtype_p := nil; {init to no current data type exists} case v.mod1.top_sym_p^.symtype of {what kind of symbol do we have ?} sst_symtype_const_k: dtype_p := v.mod1.top_sym_p^.const_exp_p^.dtype_p; sst_symtype_enum_k: ; sst_symtype_dtype_k: dtype_p := v.mod1.top_sym_p^.dtype_dtype_p; sst_symtype_field_k: dtype_p := v.mod1.top_sym_p^.field_dtype_p; sst_symtype_var_k: dtype_p := v.mod1.top_sym_p^.var_dtype_p; sst_symtype_abbrev_k: dtype_p := v.mod1.top_sym_p^.abbrev_var_p^.dtype_p; sst_symtype_proc_k: ; sst_symtype_com_k: ; otherwise sys_msg_parm_int (msg_parm[1], ord(v.mod1.top_sym_p^.symtype)); sys_message_bomb ('sst', 'symbol_type_unknown', msg_parm, 1); end; if dtype_p <> nil then begin {there is a data type to resovle ?} while dtype_p^.dtype = sst_dtype_copy_k do dtype_p := dtype_p^.copy_dtype_p; end; { * Set ADDR_CNT_ADJ. This indicates the number of pointer derefernces to ignore * at the end of the modifier string. Some types of variables are implicitly * pointers instead of representing the thing they are pointing to. } addr_cnt_adj := addr_cnt; {init to number of address-ofs caller wants} if v.dtype_p <> nil then begin {this variable reference has a data type ?} dt_p := v.dtype_p; {resolve base pointed-to data type} dt_nc_p := dt_p; {save pointer to dtype before resolve copy} pnt_cnt := 0; {init pointed-to count for base data type} resolve_dtype: case dt_p^.dtype of sst_dtype_pnt_k: begin if dt_p^.pnt_dtype_p <> nil then begin {not NIL pointer ?} dt_p := dt_p^.pnt_dtype_p; {get pointed-to data type} dt_nc_p := dt_p; {save dtype pointer before resolve copies} pnt_cnt := pnt_cnt + 1; {count one more level of pointer data type} goto resolve_dtype; end; end; sst_dtype_copy_k: begin dt_p := dt_p^.copy_dtype_p; goto resolve_dtype; end; sst_dtype_array_k: begin {ultimate pointed-to data type is an array} if {array/pointer special case ?} (pnt_cnt = 0) or {var descriptor represents array directly ?} (pnt_cnt + addr_cnt_adj = 0) {caller want direct array ?} then begin pnt_cnt := pnt_cnt + addr_cnt_adj; {num of final "address of"s array dtype} addr_cnt_adj := {add in possible implicit pointer dereference} addr_cnt_adj + addr_cnt_ar; token.len := 0; {init to no "pointer to" operators} case array_mode of {how will this array name be interpreted} array_whole_k: ; {identifier is exactly what we assume it is} array_pnt_whole_k: ; {array symbol is pointer to whole array} array_pnt_first_k: begin {pointer to first ele, need to re-cast} for i := 1 to pnt_cnt do begin {once for each "pointer to" final array dtype} string_append1 (token, '*'); end; sst_w.appendn^ ('(', 1); {start of type-casting operator} sst_w_c_dtype_simple (dt_nc_p^, token, false); {write final desired data type} sst_w.appendn^ (')', 1); {end the type-casting operator} end; otherwise sys_msg_parm_int (msg_parm[1], ord(array_mode)); syo_error ( v.mod1.top_str_h, 'sst_c_write', 'array_mode_unexpeted', msg_parm, 1); end; end; end; {done with pointed to data type is ARRAY} sst_dtype_proc_k: begin {ultimate pointed-to data type is ROUTINE} if (pnt_cnt + addr_cnt_adj) = 0 then begin {actually calling the routine ?} enclose := true; {enclose in parens if using special chars} end; end; end; {end of data type cases} end; {end of var descriptor has a data type} { * Determine whether the top modifier must be dereferenced before use. This * can happen sometimes when it is a dummy argument passed by reference, * or an abbreviation symbol reference. * In that case, an extra dereference modifier is temporarily inserted in the * chain. The original NEXT_P in the top modifier is saved in OLD_NEXT_P. } old_next_p := v.mod1.next_p; {save original NEXT_P of top modifier} insert_cnt := 0; {init to no modifiers inserted after top sym} sym_p := v.mod1.top_sym_p; {init pointer to top symbol} case sym_p^.symtype of {what is top symbol type ?} sst_symtype_var_k: begin {top symbol is a variable} if (sym_p^.var_arg_p <> nil) and then {variable is a dummy arg ?} (sym_p^.var_arg_p^.pass = sst_pass_ref_k) {passed by ref ?} then begin dt_p := sym_p^.var_dtype_p; {resolve base data type of variable} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; if dt_p^.dtype <> sst_dtype_array_k then begin {dummy arg is not an array ?} deref_top; {edit chain to dereference top symbol} end; end; end; sst_symtype_abbrev_k: begin {top symbol is an abbreviation} deref_top; end; end; {end of top symbol type cases} { * Initialize for looping thru all the modifiers. } quit_p := nil; {init MOD_P value at which to quit} since_arrow := 1; {init to not right after writing "->"} since_deref := 1; {init num of modifiers since last deref mod} mod_p := addr(v.mod1); {make current modifier the first} while mod_p <> quit_p do begin {once for each modifier} if dtype_p <> nil then begin {resolve base data type, if there is one} while dtype_p^.dtype = sst_dtype_copy_k do dtype_p := dtype_p^.copy_dtype_p; end; since_arrow := since_arrow + 1; {one more modifier since writing "->"} since_deref := since_deref + 1; {one more mod since last defef modifier} case mod_p^.modtyp of { * Modifier indicates top name token of variable. } sst_var_modtyp_top_k: begin leading_deref (mod_p^); {write leading dereference operators} spchar_first := false; {next special char won't be the first} if {symbol is variable in a common block ?} (mod_p^.top_sym_p^.symtype = sst_symtype_var_k) and (mod_p^.top_sym_p^.var_com_p <> nil) then begin sst_w.append_sym_name^ (mod_p^.top_sym_p^.var_com_p^); {write common block name} sst_w.appendn^ ('.', 1); {var name is really a field in a STRUCT} end; sst_w.append_sym_name^ (mod_p^.top_sym_p^); {write this top name} end; { * Modifier indicates pointer dereference. All the dereference operators * except those on a record pointer followed by a field have been written. * These will be written here using the "->" operator. A close parenthesis * must be written for each continuous group of the other pointer dereferences. } sst_var_modtyp_unpnt_k: begin if deref_field(mod_p^) then begin {this dereference is for record pnt to field} sst_w.appendn^ ('->', 2); since_arrow := 0; {number of modifiers since writing last "->"} end else begin {this dereference written before} if since_deref > 1 then begin {this is start of new block of dereferences ?} sst_w.appendn^ (')', 1); end; since_deref := 0; {number of modifiers since last deref mod} end ; if {not temp deref inserted after top modifier ?} (insert_cnt = 0) or {no temporary deref was inserted ?} (v.mod1.next_p <> mod_p) {not deref immediately after top mod ?} then begin dtype_p := dtype_p^.pnt_dtype_p; {update current data type} end; end; { * Modifier indicates next array subscript. } sst_var_modtyp_subscr_k: begin sst_w.appendn^ ('[', 1); sst_ordval ( {get ordinal value of subscript range start} dtype_p^.ar_ind_first_p^.val, ordval, stat); if ordval = 0 then begin {subscript range starts at 0} sst_w_c_exp {write complete expression for subscript} (mod_p^.subscr_exp_p^, 0, nil, enclose_no_k); end else begin {range doesn't start where C assumed} sst_w_c_exp {write raw expression value} (mod_p^.subscr_exp_p^, 0, nil, enclose_yes_k); sst_w.delimit^; if ordval >= 0 then begin {need to subtract off ORDVAL} sst_w.appendn^ ('-', 1); end else begin {need to add on -ORDVAL} sst_w.appendn^ ('+', 1); ordval := -ordval; {make unsigned value to add/subtract} end ; sst_w.delimit^; string_f_int_max_base ( {convert ORDVAL to string} token, {output string} ordval, {input integer} 10, {number base} 0, {use free format} [string_fi_unsig_k], {input number is unsigned} stat); {returned error status code} sys_error_abort (stat, '', '', nil, 0); sst_w.append^ (token); {write offset for this array subscript} end ; sst_w.appendn^ (']', 1); if dtype_p^.ar_dtype_rem_p = nil then begin {this was last possible subscript} dtype_p := dtype_p^.ar_dtype_ele_p; end else begin {there may be more subscripts} dtype_p := dtype_p^.ar_dtype_rem_p; end ; end; { * Modifier indicates field in a record. } sst_var_modtyp_field_k: begin if since_arrow > 1 then begin {last modifier wasn't "->" ?} sst_w.appendn^ ('.', 1); end; sst_w.append_sym_name^ (mod_p^.field_sym_p^); {write this field name} dtype_p := mod_p^.field_sym_p^.field_dtype_p; {update current data type} end; { * Unexpected modifier type. } otherwise sys_msg_parm_int (msg_parm[1], ord(mod_p^.modtyp)); sys_message_bomb ('sst', 'var_modifier_unknown', msg_parm, 1); end; {end of modifier type cases} sst_w.allow_break^; {allow a line break after each modifier} mod_p := mod_p^.next_p; {advance to next modifier in chain} end; {back and process this new modifier} mod_p := addr(v.mod1); {allow writing to IN argument} mod_p^.next_p := old_next_p; {restore original NEXT_P of top modifier} if paren then begin {need to write close parenthesis ?} sst_w.appendn^ (')', 1); end; end;
unit ResequenceAllRouteDestinationsUnit; interface uses SysUtils, BaseOptimizationExampleUnit, DataObjectUnit; type TResequenceAllRouteDestinations = class(TBaseOptimizationExample) public procedure Execute(RouteId: String); end; implementation uses EnumsUnit; procedure TResequenceAllRouteDestinations.Execute(RouteId: String); var DisableOptimization: boolean; Optimize: TOptimize; ErrorString: String; begin DisableOptimization := False; Optimize := TOptimize.Distance; Route4MeManager.Route.ResequenceAll( RouteId, DisableOptimization, Optimize, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn('ResequenceAllRouteDestinations executed successfully'); WriteLn(''); end else WriteLn(Format('ResequenceAllRouteDestinations error "%s"', [ErrorString])); end; end.
unit aeLoaderAionH32; (* This class loads an aion h32 heightmap. *) (* A few test vectors : X/Y/Z Z = height -- > calculated height 1138.820435 1082.670288 135.8525238 --> 135,699005126953 1208.368896 1033.267212 140.8175659 --> 140,753875732422 1067.761353 1009.945679 136.7644653 --> 136,75 905.4499512 1174.427002 99.25 --> 99,25 //perfect 838.3372192 1204.778687 121.8994293 --> 121,809242248535 *) interface uses aeHeightmapLoaderBase, windows, types, classes, sysutils; type TaeLoaderAionH32 = class(TaeHeightmapLoaderBase) public Constructor Create(file_s: string); overload; Constructor Create(h32: Pointer; d_size: cardinal; remove_flag_byte: boolean = true); overload; function GetWord(x, y: cardinal): word; overload; function GetWord(indx: cardinal): word; overload; function GetData: PWord; function GetDataLength: cardinal; function GetSideLength: cardinal; // check if a point is below actual height; adjust it if it happens to be. procedure AdjustPointToHeight(var p: TPoint3D); function GetHeight(x, y: single): single; overload; function GetHeight(p: TPoint3D): single; overload; private // Remove the strange 3. byte in the file, we only need the height words. _sideLen: cardinal; _dataLen: cardinal; procedure ConvertData(h32: Pointer; d_size: cardinal); end; implementation { TaeLoaderAionH32 } procedure TaeLoaderAionH32.AdjustPointToHeight(var p: TPoint3D); var h: single; begin h := self.GetHeight(p); if (p.y < h) then p.y := h; end; procedure TaeLoaderAionH32.ConvertData(h32: Pointer; d_size: cardinal); var nPoints, nRealPoints, sidelen: integer; realHeightMapData: PWord; i: integer; begin Assert(((d_size mod 3) = 0), 'TaeLoaderAionH32.ConvertData() : h32 len not valid.'); nPoints := d_size div 3; nRealPoints := nPoints * 2; GetMem(realHeightMapData, nRealPoints); for i := 0 to nPoints - 1 do PWord(cardinal(realHeightMapData) + (i * 2))^ := PWord(cardinal(h32) + (i * 3))^; self.AllocateMem(nRealPoints); self.SetHeightData(realHeightMapData, nRealPoints); FreeMem(realHeightMapData, nRealPoints); // calculate square root of length. Asm for speed. // this reults in the side. asm fild nPoints // convert int to real, push to fpu stack fsqrt // square root of ST0 fistp sidelen // convert back, pop from fpu stack end; self._sideLen := round(sqrt(nPoints)); self._dataLen := nRealPoints; end; constructor TaeLoaderAionH32.Create(h32: Pointer; d_size: cardinal; remove_flag_byte: boolean = true); begin self._loaderType := AE_LOADER_AION_H32; if (remove_flag_byte) then self.ConvertData(h32, d_size) else begin self.AllocateMem(d_size); self.SetHeightData(h32, d_size); self._sideLen := round(sqrt(d_size div 2)); self._dataLen := d_size; end; end; constructor TaeLoaderAionH32.Create(file_s: string); var ms: TMemoryStream; begin Assert(FileExists(file_s), 'TaeLoaderAionH32.Create() : File doesn''t exist!'); ms := TMemoryStream.Create; ms.LoadFromFile(file_s); self.ConvertData(ms.Memory, ms.Size); ms.Free; end; function TaeLoaderAionH32.GetData: PWord; begin Result := PWord(self.GetHeightData()); end; function TaeLoaderAionH32.GetDataLength: cardinal; begin Result := self._dataLen; end; function TaeLoaderAionH32.GetHeight(x, y: single): single; var xInt, yInt: cardinal; p1, p2, p3, p4, p13, p24, p1234: single; begin x := x / 2.0; y := y / 2.0; xInt := round(x); yInt := round(y); p1 := self.GetWord(yInt + xInt * self._sideLen); p2 := self.GetWord(yInt + 1 + xInt * self._sideLen); p3 := self.GetWord(yInt + (xInt + 1) * self._sideLen); p4 := self.GetWord(yInt + 1 + (xInt + 1) * self._sideLen); p13 := p1 + (p1 - p3) * Frac(x); // frac(x) == (x mod 1.0) p24 := p2 + (p4 - p2) * Frac(x); p1234 := p13 + (p24 - p13) * Frac(y); Result := p1234 / 32.0; end; function TaeLoaderAionH32.GetHeight(p: TPoint3D): single; begin if (p.x < self._sideLen * 2) and (p.x > 0) and (p.Z < self._sideLen * 2) and (p.Z > 0) then Result := self.GetHeight(p.x, p.Z); end; function TaeLoaderAionH32.GetSideLength: cardinal; begin Result := self._sideLen; end; function TaeLoaderAionH32.GetWord(indx: cardinal): word; begin if (indx < (self._dataLen div 2)) then Result := PWord(cardinal(self.GetData()) + indx * 2)^; end; function TaeLoaderAionH32.GetWord(x, y: cardinal): word; begin Result := PWord(cardinal(self.GetData()) + (y + x * self._sideLen) * 2)^; end; end.
unit PE.RTTI; interface uses System.Classes; type TRecordFieldDesc = record Flags: uint32; FieldName: PChar; end; PRecordFieldDesc = ^TRecordFieldDesc; // TRttiReadFunc must return: // - OutFieldSize: size of field. // - OutReadSize size to read into field. TRttiFieldResolveProc = procedure(Desc: PRecordFieldDesc; OutFieldSize, OutReadWriteSize: PInteger; ud: pointer); TRttiOperation = (RttiRead, RttiWrite, RttiCalcSize); // MaxSize: -1 means no limit. function RTTI_Process(Stream: TStream; Op: TRttiOperation; Buf: PByte; FieldDesc: PRecordFieldDesc; FieldDescCnt: integer; MaxSize: integer; ResolveProc: TRttiFieldResolveProc; ud: pointer): uint32; implementation {$IFDEF DIAG} uses System.SysUtils; procedure DbgLogData(Desc: PRecordFieldDesc; Stream: TStream; FieldSize: integer; IOSize: integer); begin writeln(Format('"%s" @ %x FieldSize: %x IOSize: %x', [Desc.FieldName, Stream.Position, FieldSize, IOSize])); end; {$ENDIF} function RTTI_Process; var i: integer; FieldSize, ReadWriteSize, tmp: integer; begin Result := 0; if (Buf = nil) or (FieldDesc = nil) or (FieldDescCnt = 0) or (MaxSize = 0) then exit; for i := 0 to FieldDescCnt - 1 do begin ResolveProc(FieldDesc, @FieldSize, @ReadWriteSize, ud); {$IFDEF DIAG} DbgLogData(FieldDesc, Stream, FieldSize, ReadWriteSize); {$ENDIF} if ReadWriteSize <> 0 then begin case Op of RttiRead: begin if ReadWriteSize < FieldSize then FillChar(Buf^, FieldSize, 0); tmp := Stream.Read(Buf^, ReadWriteSize); end; RttiWrite: tmp := Stream.Write(Buf^, ReadWriteSize); RttiCalcSize: tmp := ReadWriteSize; else tmp := ReadWriteSize; end; if tmp <> ReadWriteSize then break; // read error {$IFDEF DIAG} case tmp of 1: writeln(Format('= %x', [PByte(Buf)^])); 2: writeln(Format('= %x', [PWord(Buf)^])); 4: writeln(Format('= %x', [PCardinal(Buf)^])); 8: writeln(Format('= %x', [PUint64(Buf)^])); end; {$ENDIF} end; inc(Result, ReadWriteSize); inc(Buf, FieldSize); inc(FieldDesc); {$WARN COMPARING_SIGNED_UNSIGNED OFF} if (MaxSize <> -1) and (Result >= MaxSize) then break; {$WARN COMPARING_SIGNED_UNSIGNED ON} end; end; end.
unit MainForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FileScanner, ExtCtrls, ComCtrls; type TForm1 = class(TForm) ListView1: TListView; Panel1: TPanel; BtnStart: TButton; Edit1: TEdit; BtnStop: TButton; StatusBar1: TStatusBar; Label1: TLabel; CboRecursive: TCheckBox; EdtSearched: TEdit; Label2: TLabel; RgpFilter: TRadioGroup; procedure BtnStartClick(Sender: TObject); procedure BtnStopClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private-Deklarationen } FStopped : Boolean; FSearchedDirs : Integer; FFoundFiles : Integer; function Filter(const FileInformation:TFileInformation):Boolean; procedure FoundHandler(Sender:TObject; const FileInformation:TFileInformation); procedure UpdateButtons; public { Public-Deklarationen } end; var Form1: TForm1; implementation uses JclStrings; {$R *.DFM} function IsDelphiApplication(const fn : string):Boolean; var modul : HMODULE; begin modul := LoadLibraryEx(PChar(fn), 0, LOAD_LIBRARY_AS_DATAFILE); if modul <> 0 then begin Result := (FindResourceEx(modul, RT_RCDATA, 'DVCLAL', 0) <> 0); FreeLibrary(modul); end else Result := False; end; function IsLoadable(const fn : string):Boolean; var t:string; begin t := UpperCase(ExtractFileExt(fn)); Result := StrIsOneOf(t, ['.EXE', '.DLL', '.OCX']); //Result := True; end; procedure TForm1.BtnStartClick(Sender: TObject); var x :TFileScanner; begin ListView1.Items.Clear; FStopped := False; FSearchedDirs := 0; FFoundFiles := 0; UpdateButtons; x := TFileScanner.Create; try x.Recursive := CboRecursive.Checked; x.OnFound := FoundHandler; x.ScanDir(Edit1.Text); finally x.Free; end; FStopped := True; UpdateButtons; StatusBar1.SimpleText := ''; end; function TForm1.Filter(const FileInformation: TFileInformation): Boolean; begin if RgpFilter.ItemIndex = 1 then Result := IsLoadable(FileInformation.Name) and IsDelphiApplication(FileInformation.Path+FileInformation.Name) else Result := True; end; procedure TForm1.FoundHandler(Sender: TObject; const FileInformation: TFileInformation); var li : TListItem; flags : string; begin if FileInformation.IsDir then begin // Verzeichnis if Pos('System32', FileInformation.Path) <> 0 then (Sender as TFileScanner).Stop; StatusBar1.SimpleText := 'Scanning '+ FileInformation.Path+ ' ...'; Inc(FSearchedDirs); EdtSearched.Text := IntToStr(FSearchedDirs)+' / ' +IntToStr(FFoundFiles); end else begin if Filter(FileInformation) then begin // Datei li := ListView1.Items.Add; li.Caption := FileInformation.Name; li.SubItems.Add(IntToStr(FileInformation.Size)); li.SubItems.Add(IntToStr(FileInformation.Depth)); li.SubItems.Add(DateTimeToStr(FileInformation.LastWrite)); li.SubItems.Add(DateTimeToStr(FileInformation.Created)); flags := ''; if FileInformation.ArchiveFlag then flags := flags + 'A'; if FileInformation.ReadOnlyFlag then flags := flags + 'R'; li.SubItems.Add(flags); li.SubItems.Add(FileInformation.Path); Inc(FFoundFiles); EdtSearched.Text := IntToStr(FSearchedDirs)+' / ' +IntToStr(FFoundFiles); end; end; Application.ProcessMessages; if FStopped then begin TFileScanner(Sender).Stop; StatusBar1.SimpleText := 'Stopped'; end; end; procedure TForm1.BtnStopClick(Sender: TObject); begin FStopped := True; end; // Start/Stop Button aktivieren/deaktivieren procedure TForm1.UpdateButtons; begin BtnStart.Enabled := FStopped; BtnStop.Enabled := not FStopped; end; procedure TForm1.FormShow(Sender: TObject); begin FStopped := True; UpdateButtons; end; procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin // Beim Schliesen muss die Suche unterbrochen werden können FStopped := True; CanClose := True; end; end.
unit UDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSBaseControl, FMX.TMSMemo, StrUtils, FMX.ListBox, FMX.Objects, FMX.Menus, FMX.TMSMemoStyles, FMX.StdCtrls, FMX.TMSXUtil; const crlf: string = #13 + #10; type TForm832 = class(TForm) PopupMenu1: TPopupMenu; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; MenuItem9: TMenuItem; Panel1: TPanel; Button1: TButton; TMSFMXMemo2: TTMSFMXMemo; TMSFMXMemoPascalStyler1: TTMSFMXMemoPascalStyler; Label1: TLabel; procedure TMSFMXMemo1GetAutoCompletionList(Sender: TObject; AToken: string; AList: TStringList); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } SLFormProperties, SLButtonProperties, SLEditProperties: TStringList; SLFormMethods, SLButtonMethods, SLEditMethods: TStringList; SLFormEvents, SLButtonEvents, SLEditEvents: TStringList; SLFormHintEvents, SLButtonHintEvents, SLEditHintEvents: TStringList; public { Public declarations } end; var Form832: TForm832; implementation {$R *.fmx} procedure TForm832.Button1Click(Sender: TObject); var I,CNT: Integer; begin CNT := TMSFMXMemo2.Lines.Count - 10; for I := 0 to 10 do TMSFMXMemo2.BookmarkIndex[Random(CNT) + 10] := Random(CNT); for I := 0 to 10 do TMSFMXMemo2.BreakPoint[Random(CNT) + 10] := True; end; procedure TForm832.FormCreate(Sender: TObject); begin TMSFMXMemo2.Lines.LoadFromFile(XGetRootDirectory + 'ueditor.pas'); ReportMemoryLeaksOnShutdown := True; SLFormProperties := TStringList.Create; SLFormProperties.Add('MDIChildren: [I : Integer]: TForm;'); SLFormProperties.Add('Action: TActionManager;'); SLFormProperties.Add('ActiveControl: TWinControl;'); SLFormProperties.Add('Align: TAlign;'); SLFormProperties.Add('AlphaBlend: Boolean;'); SLFormProperties.Add('AlphaBlendValue: Integer;'); SLFormProperties.Add('Anchors: TAnchorKind;'); SLFormProperties.Add('AutoScroll: Boolean;'); SLFormProperties.Add('AutoSize: Boolean;'); SLFormProperties.Add('BiDiMode: TBiDiMode;'); SLFormProperties.Add('BorderIcons: TBorderIcon;'); SLFormProperties.Add('BorderStyle: TFormBorderStyle;'); SLFormProperties.Add('BorderWidth: Integer;'); SLFormProperties.Add('Caption: String;'); SLFormProperties.Add('ClientHeight: Integer;'); SLFormProperties.Add('ClientWidth: Integer;'); SLFormProperties.Add('Color: TColor;'); SLFormProperties.Add('TransparentColor: Boolean;'); SLFormProperties.Add('TransparentColorValue: TColor;'); SLFormProperties.Add('Constraints: TSizeConstraints;'); SLFormProperties.Add('Ctl3D: Boolean;'); SLFormProperties.Add('UseDockManager: Boolean;'); SLFormProperties.Add('DefaultMonitor: TDefaultMonitor;'); SLFormProperties.Add('DockSite: Boolean;'); SLFormProperties.Add('DoubleBuffered: Boolean;'); SLFormProperties.Add('DragKind: TDragKind;'); SLFormProperties.Add('DragMode: TDragMode;'); SLFormProperties.Add('Enabled: Boolean;'); SLFormProperties.Add('ParentFont: Boolean;'); SLFormProperties.Add('Font: TFont;'); SLFormProperties.Add('FormStyle: TFormStyle;'); SLFormProperties.Add('GlassFrame: TGlassFrame;'); SLFormProperties.Add('Height: Integer;'); SLFormProperties.Add('HelpFile: String;'); SLFormProperties.Add('HorzScrollBar: TScrollBar;'); SLFormProperties.Add('Icon: TPicture;'); SLFormProperties.Add('KeyPreview: Boolean;'); SLFormProperties.Add('Padding: TPadding;'); SLFormProperties.Add('Menu: TMainMenu;'); SLFormProperties.Add('ObjectMenuItem: TObjectMenuItem;'); SLFormProperties.Add('ParentBiDiMode: Boolean;'); SLFormProperties.Add('PixelsPerInch: Integer;'); SLFormProperties.Add('PopupMenu: TPopupMenu;'); SLFormProperties.Add('PopupMode: TPopupMode;'); SLFormProperties.Add('PopupParent: TPopupParent;'); SLFormProperties.Add('Position: TPosition;'); SLFormProperties.Add('PrintScale: TPrintScale;'); SLFormProperties.Add('Scaled: Boolean;'); SLFormProperties.Add('ScreenSnap: Boolean;'); SLFormProperties.Add('ShowHint: Boolean;'); SLFormProperties.Add('SnapBuffer: Integer;'); SLFormProperties.Add('Touch: TTouchManager;'); SLFormProperties.Add('VertScrollBar: TControlScrollBar;'); SLFormProperties.Add('Visible: Boolean;'); SLFormProperties.Add('Width: Integer;'); SLFormProperties.Add('WindowState: TWindowState;'); SLFormProperties.Add('WindowMenu: TMenuItem;'); SLButtonProperties := TStringList.Create; SLEditProperties := TStringList.Create; SLFormMethods := TStringList.Create; SLFormMethods.Add('constructor Create(AOwner: TComponent);'); SLFormMethods.Add('constructor CreateNew(AOwner: TComponent; Dummy:Integer = 0);'); SLFormMethods.Add('destructor Destroy;'); SLFormMethods.Add('procedure Close;'); SLFormMethods.Add('function CloseQuery: Boolean;'); SLFormMethods.Add('procedure DefaultHandler(var Message);'); SLFormMethods.Add('procedure DefocusControl(Control: TWinControl; Removing: Boolean);'); SLFormMethods.Add('procedure Dock(NewDockSite: TWinControl; ARect: TRect);'); SLFormMethods.Add('procedure FocusControl(Control: TWinControl);'); SLFormMethods.Add('procedure GetChildren(Proc: TGetChildProc; Root: TComponent);'); SLFormMethods.Add('function GetFormImage: TBitmap;'); SLFormMethods.Add('procedure Hide;'); SLFormMethods.Add('function IsShortCut(var Message: TWMKey): Boolean; dynamic;'); SLFormMethods.Add('procedure MakeFullyVisible(AMonitor: TMonitor = nil);'); SLFormMethods.Add('procedure MouseWheelHandler(var Message: TMessage);'); SLFormMethods.Add('procedure Print;'); SLFormMethods.Add('procedure RecreateAsPopup(AWindowHandle: HWND);'); SLFormMethods.Add('procedure Release;'); SLFormMethods.Add('procedure SendCancelMode(Sender: TControl);'); SLFormMethods.Add('procedure SetFocus; override;'); SLFormMethods.Add('function SetFocusedControl(Control: TWinControl): Boolean;'); SLFormMethods.Add('procedure Show;'); SLFormMethods.Add('function ShowModal: Integer;'); SLFormMethods.Add('procedure WantChildKey(Child: TControl; var Message: TMessage): Boolean;'); SLFormMethods.Add('procedure set_PopupParent(Value: TCustomForm);'); SLFormMethods.Add('procedure AfterConstruction;'); SLFormMethods.Add('procedure BeforeDestruction;'); SLButtonMethods := TStringList.Create; SLEditMethods := TStringList.Create; SLFormEvents := TStringList.Create; SLFormEvents.Add('OnActivate: TNotifyEvent;'); SLFormEvents.Add('OnAlignInsertBefore: TAlignInsertBeforeEvent;'); SLFormEvents.Add('OnAlignPosition: TAlignPositionEvent;'); SLFormEvents.Add('OnCanResize: TCanResizeEvent;'); SLFormEvents.Add('OnClick: TNotifyEvent;'); SLFormEvents.Add('OnClose: TCloseEvent;'); SLFormEvents.Add('OnCloseQuery: TCloseQueryEvent;'); SLFormEvents.Add('OnConstrainedResize: TConstrainedResizeEvent;'); SLFormEvents.Add('OnContextPopup: TContextPopupEvent;'); SLFormEvents.Add('OnCreate: TNotifyEvent;'); SLFormEvents.Add('OnDblClick: TNotifyEvent;'); SLFormEvents.Add('OnDeactivate: TNotifyEvent;'); SLFormEvents.Add('OnDestroy: TNotifyEvent;'); SLFormEvents.Add('OnDockDrop: TDockDropEvent;'); SLFormEvents.Add('OnDockOver: TDockOverEvent;'); SLFormEvents.Add('OnDragDrop: TDragDropEvent;'); SLFormEvents.Add('OnDragOver: TDragOverEvent;'); SLFormEvents.Add('OnEndDock: TEndDragEvent;'); SLFormEvents.Add('OnGesture: TGestureEvent;'); SLFormEvents.Add('OnGetSiteInfo: TGetSiteInfoEvent;'); SLFormEvents.Add('OnHelp: THelpEvent;'); SLFormEvents.Add('OnHide: TNotifyEvent;'); SLFormEvents.Add('OnKeyDown: TKeyEvent;'); SLFormEvents.Add('OnKeyPress: TKeyPressEvent;'); SLFormEvents.Add('OnKeyUp: TKEyEvent;'); SLFormEvents.Add('OnMouseActivate: TMouseActivateEvent;'); SLFormEvents.Add('OnMouseDown: TMouseEvent;'); SLFormEvents.Add('OnMouseEnter: TNotifyEvent:'); SLFormEvents.Add('OnMouseLeave: TNotifyEvent;'); SLFormEvents.Add('OnMouseMove: TMouseMoveEvent;'); SLFormEvents.Add('OnMouseUp: TMouseEvent;'); SLFormEvents.Add('OnMouseWheel: TMouseWheelEvent;'); SLFormEvents.Add('OnMouseWheelDown: TMouseWheelUpDownEvent;'); SLFormEvents.Add('OnMouseWheelUp: TMouseWheelUpDownEvent;'); SLFormEvents.Add('OnPaint: TNotifyEvent;'); SLFormEvents.Add('OnResize: TNotifyEvent;'); SLFormEvents.Add('OnShortCut: TShortCutEvent;'); SLFormEvents.Add('OnShow: TNotifyEvent;'); SLFormEvents.Add('OnStartDock: TStartDockEvent;'); SLFormEvents.Add('OnUnDock: TUnDockEvent:'); SLFormHintEvents := TStringList.Create; SLFormHintEvents.Add('OnActivate(Sender: TObject);'); SLFormHintEvents.Add('OnAlignInsertBefore(Sender: TWinControl; C1, C2: TControl): Boolean;'); SLFormHintEvents.Add('OnAlignPosition(Sender: TWinControl; Control: TControl; var NewLeft, NewTop, NewWidth, NewHeight: Integer; var AlignRect: TRect; AlignInfo: TAlignInfo);'); SLFormHintEvents.Add('OnCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean);'); SLFormHintEvents.Add('OnClick(Sender: TObject);'); SLFormHintEvents.Add('OnClose(Sender: TObject; var Action: TCloseAction);'); SLFormHintEvents.Add('OnCloseQuery(Sender: TObject; var CanClose: Boolean);'); SLFormHintEvents.Add('OnConstrainedResize(Sender: TObject; var MinWidth, MinHeight, MaxWidth, MaxHeight: Integer);'); SLFormHintEvents.Add('OnContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);'); SLFormHintEvents.Add('OnCreate(Sender: TObject);'); SLFormHintEvents.Add('OnDblClick(Sender: TObject);'); SLFormHintEvents.Add('OnDeactivate(Sender: TObject);'); SLFormHintEvents.Add('OnDestroy(Sender: TObject);'); SLFormHintEvents.Add('OnDockDrop(Sender: TObject; Source: TDragDockObject; X, Y: Integer);'); SLFormHintEvents.Add('OnDockOver(Sender: TObject; Source: TDragDockObject; X, Y: Integer; State: TDragState; var Accept: Boolean);'); SLFormHintEvents.Add('OnDragDrop(Sender, Source: TObject; X, Y: Integer);'); SLFormHintEvents.Add('OnDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);'); SLFormHintEvents.Add('OnEndDock(Sender, Target: TObject; X, Y: Integer);'); SLFormHintEvents.Add('OnGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean);'); SLFormHintEvents.Add('OnGetSiteInfo(Sender: TObject; DockClient: TControl; var InfluenceRect: TRect; MousePos: TPoint; var CanDock: Boolean);'); SLFormHintEvents.Add('OnHelp(Command: Word; Data: Integer; var CallHelp: Boolean): Boolean;'); SLFormHintEvents.Add('OnHide(Sender: TObject);'); SLFormHintEvents.Add('OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);'); SLFormHintEvents.Add('OnKeyPress(Sender: TObject; var Key: Char);'); SLFormHintEvents.Add('OnKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);'); SLFormHintEvents.Add('OnMouseActivate(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y, HitTest: Integer; var MouseActivate: TMouseActivate);'); SLFormHintEvents.Add('OnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);'); SLFormHintEvents.Add('OnMouseEnter(Sender: TObject);'); SLFormHintEvents.Add('OnMouseLeave(Sender: TObject);'); SLFormHintEvents.Add('OnMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);'); SLFormHintEvents.Add('OnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);'); SLFormHintEvents.Add('OnMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);'); SLFormHintEvents.Add('OnMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);'); SLFormHintEvents.Add('OnMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);'); SLFormHintEvents.Add('OnPaint(Sender: TObject);'); SLFormHintEvents.Add('OnResize(Sender: TObject);'); SLFormHintEvents.Add('OnShortCut(var Msg: TWMKey; var Handled: Boolean);'); SLFormHintEvents.Add('OnShow(Sender: TObject);'); SLFormHintEvents.Add('OnStartDock(Sender: TObject; var DragObject: TDragDockObject);'); SLFormHintEvents.Add('OnUnDock(Sender: TObject; Client: TControl; NewTarget: TWinControl; var Allow: Boolean);'); SLButtonEvents := TStringList.Create; SLButtonHintEvents := TStringList.Create; SLButtonEvents.Add('OnClick(Sender: TObject);'); SLButtonEvents.Add('OnContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);'); SLButtonEvents.Add('OnDragDrop(Sender, Source: TObject; X, Y: Integer);'); SLButtonEvents.Add('OnDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);'); SLButtonEvents.Add('OnDropDownClick(Sender: TObject);'); SLButtonEvents.Add('OnEndDock(Sender, Target: TObject; X, Y: Integer);'); SLButtonEvents.Add('OnEndDrag(Sender, Target: TObject; X, Y: Integer);'); SLButtonEvents.Add('OnEnter(Sender: TObject);'); SLButtonEvents.Add('OnExit(Sender: TObject);'); SLButtonEvents.Add('OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);'); SLButtonEvents.Add('OnKeyPress(Sender: TObject; var Key: Char);'); SLButtonEvents.Add('OnKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);'); SLButtonEvents.Add('OnMouseActivate(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y, HitTest: Integer; var MouseActivate: TMouseActivate);'); SLButtonEvents.Add('OnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);'); SLButtonEvents.Add('OnMouseEnter(Sender: TObject);'); SLButtonEvents.Add('OnMouseLeave(Sender: TObject);'); SLButtonEvents.Add('OnMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);'); SLButtonEvents.Add('OnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);'); SLButtonEvents.Add('OnStartDock(Sender: TObject; var DragObject: TDragDockObject);'); SLButtonEvents.Add('OnStartDrag(Sender: TObject; var DragObject: TDragObject);'); SLEditEvents := TStringList.Create; SLEditHintEvents := TStringList.Create; SLEditEvents.Add('OnChange(Sender: TObject);'); SLEditEvents.Add('OnClick(Sender: TObject);'); SLEditEvents.Add('OnContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);'); SLEditEvents.Add('OnDblClick(Sender: TObject);'); SLEditEvents.Add('OnDragDrop(Sender, Source: TObject; X, Y: Integer);'); SLEditEvents.Add('OnDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);'); SLEditEvents.Add('OnEndDock(Sender, Target: TObject; X, Y: Integer);'); SLEditEvents.Add('OnEndDrag(Sender, Target: TObject; X, Y: Integer);'); SLEditEvents.Add('OnEnter(Sender: TObject);'); SLEditEvents.Add('OnExit(Sender: TObject);'); SLEditEvents.Add('OnGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean);'); SLEditEvents.Add('OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);'); SLEditEvents.Add('OnKeyPress(Sender: TObject; var Key: Char);'); SLEditEvents.Add('OnKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);'); SLEditEvents.Add('OnMouseActivate(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y, HitTest: Integer; var MouseActivate: TMouseActivate);'); SLEditEvents.Add('OnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);'); SLEditEvents.Add('OnMouseEnter(Sender: TObject);'); SLEditEvents.Add('OnMouseLeave(Sender: TObject);'); SLEditEvents.Add('OnMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);'); SLEditEvents.Add('OnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);'); SLEditEvents.Add('OnStartDock(Sender: TObject; var DragObject: TDragDockObject);'); SLEditEvents.Add('OnStartDrag(Sender: TObject; var DragObject: TDragObject);'); end; procedure TForm832.FormDestroy(Sender: TObject); begin FreeAndNil(SLFormProperties); FreeAndNil(SLButtonProperties); FreeAndNil(SLEditProperties); FreeAndNil(SLFormMethods); FreeAndNil(SLButtonMethods); FreeAndNil(SLEditMethods); FreeAndNil(SLFormEvents); FreeAndNil(SLButtonEvents); FreeAndNil(SLEditEvents); FreeAndNil(SLFormHintEvents); FreeAndNil(SLButtonHintEvents); FreeAndNil(SLEditHintEvents); end; procedure TForm832.FormShow(Sender: TObject); begin TMSFMXMemo2.SetFocus; end; procedure TForm832.TMSFMXMemo1GetAutoCompletionList(Sender: TObject; AToken: string; AList: TStringList); var ridx, spos: integer; subs: string; begin if pos('FORM',UpperCase(AToken)) > 0 then begin for ridx := 0 to SLFormMethods.Count - 1 do AList.AddObject(SLFormMethods.Strings[ridx], TObject(ttMethod)); for ridx := 0 to SLFormProperties.Count - 1 do begin spos := pos(': ', SLFormProperties.Strings[ridx]) + 1 ; subs := RightStr(SLFormProperties.Strings[ridx], length(SLFormProperties.Strings[ridx]) - spos); AList.AddObject('Property ' + LeftStr(SLFormProperties.Strings[ridx], spos-2) + ': ' + subs, TObject(ttProp)); end; for ridx := 0 to SLFormEvents.Count-1 do begin spos := pos(': ', SLFormEvents.Strings[ridx]) + 1 ; subs := RightStr(SLFormEvents.Strings[ridx], length(SLFormEvents.Strings[ridx]) - spos); AList.AddObject('Event ' + LeftSTr(SLFormEvents.Strings[ridx], spos) + ' ' + Subs, TObject(ttEvent)); end; for ridx := 0 to SLFormMethods.Count-1 do begin spos := pos('(', SLFormMethods.Strings[ridx]); if spos > 0 then begin spos := pos(' ', SLFormMethods.Strings[ridx]); subs := RightStr(SLFormMethods.Strings[ridx],length(SLFormMethods.Strings[ridx]) - spos); TMSFMXMemoPascalStyler1.HintParameter.Parameters.Add(subs); end; end; end; if pos('EDIT',UpperCase(AToken)) > 0 then begin ALIst.AddObject('procedure Show;', TObject(ttMethod)); ALIst.AddObject('procedure SetFocus;', TObject(ttMethod)); ALIst.AddObject('property Text string', TObject(ttProp)); ALIst.AddObject('property Name string', TObject(ttProp)); ALIst.AddObject('property Top integer', TObject(ttProp)); ALIst.AddObject('property Left integer', TObject(ttProp)); ALIst.AddObject('property Enabled boolean', TObject(ttProp)); ALIst.AddObject('event OnCreate TNotifyEvent', TObject(ttEvent)); end; if pos('BUTTON',UpperCase(AToken)) > 0 then begin ALIst.AddObject('procedure Show;', TObject(ttMethod)); ALIst.AddObject('procedure SetFocus;', TObject(ttMethod)); ALIst.AddObject('property Caption string', TObject(ttProp)); ALIst.AddObject('property Name string', TObject(ttProp)); ALIst.AddObject('property Top integer', TObject(ttProp)); ALIst.AddObject('property Left integer', TObject(ttProp)); ALIst.AddObject('property Enabled boolean', TObject(ttProp)); ALIst.AddObject('event OnCreate TNotifyEvent', TObject(ttEvent)); end; end; end.
unit WaveOut; interface uses Windows, MMSystem, Classes; type TOnDataProc = function (var Data; Size : integer) : integer of object; TWavePlayer = class public constructor Create; destructor Destroy; override; public procedure Play; virtual; procedure Stop; virtual; procedure Wait; private fDevice : integer; fSamplingRate : integer; fChannels : integer; fBitsPerSample : integer; fBufferSize : integer; private function GetBlockAlign : integer; public property Device : integer read fDevice write fDevice; property SamplingRate : integer read fSamplingRate write fSamplingRate; property Channels : integer read fChannels write fChannels; property BitsPerSample : integer read fBitsPerSample write fBitsPerSample; property BlockAlign : integer read GetBlockAlign; property BufferSize : integer read fBufferSize write fBufferSize; public soPlayFinished : THandle; csFillingData : TRTLCriticalSection; fAutoStop : boolean; fManualStop : boolean; private fOutHandle : hWaveOut; fFirstBuffer : TWaveHdr; fSecondBuffer : TWaveHdr; private procedure StopIt; procedure CloseHandles; protected function MsToSamples(aMs : integer) : integer; procedure FeedData(var aHeader : TWaveHdr; ForceIt : boolean); function DataArrived(var Data; Size : integer) : integer; virtual; private fOnData : TOnDataProc; fOnStop : TNotifyEvent; public property OnData : TOnDataProc read fOnData write fOnData; property OnStop : TNotifyEvent read fOnStop write fOnStop; end; implementation uses WaveHdrs, MMCheck, SysUtils; const DefaultSamplingRate = 8000; DefaultChannels = 1; DefaultBitsPerSample = 16; DefaultBufferSize = 250; // 250 ms constructor TWavePlayer.Create; begin inherited; fDevice := word(WAVE_MAPPER); fSamplingRate := DefaultSamplingRate; fChannels := DefaultChannels; fBitsPerSample := DefaultBitsPerSample; BufferSize := DefaultBufferSize; soPlayFinished := CreateEvent(nil, false, true, nil); InitializeCriticalSection(csFillingData); end; destructor TWavePlayer.Destroy; begin Stop; fOnStop := nil; CloseHandle(soPlayFinished); DeleteCriticalSection(csFillingData); DeallocateBuffer(fFirstBuffer); DeallocateBuffer(fSecondBuffer); inherited; end; procedure DataArrivedProc(hdrvr : HDRVR; uMsg : UINT; dwUser : DWORD; dw1, dw2 : DWORD) stdcall; begin if (uMsg = WOM_DONE) and (dwUser <> 0) then with TWavePlayer(dwUser) do begin EnterCriticalSection(csFillingData); try FeedData(PWaveHdr(dw1)^, false); finally LeaveCriticalSection(csFillingData); end; end; end; procedure TWavePlayer.Play; var Format : TWaveFormatEx; BufferBytes : integer; begin Stop; DeallocateBuffer(fFirstBuffer); DeallocateBuffer(fSecondBuffer); BufferBytes := MsToSamples(fBufferSize) * BlockAlign; AllocateBuffer(fFirstBuffer, BufferBytes); AllocateBuffer(fSecondBuffer, BufferBytes); with Format do begin wFormatTag := WAVE_FORMAT_PCM; nChannels := fChannels; wBitsPerSample := fBitsPerSample; nSamplesPerSec := fSamplingRate; nBlockAlign := (wBitsPerSample div 8) * nChannels; nAvgBytesPerSec := nSamplesPerSec * nBlockAlign; cbSize := 0; end; try TryMM(waveOutOpen(@fOutHandle, fDevice, @Format, DWORD(@DataArrivedProc), DWORD(Self), CALLBACK_FUNCTION)); try TryMM(waveOutPrepareHeader(fOutHandle, @fFirstBuffer, sizeof(fFirstBuffer))); try TryMM(waveOutPrepareHeader(fOutHandle, @fSecondBuffer, sizeof(fSecondBuffer))); try ResetEvent(soPlayFinished); fManualStop := false; fAutoStop := false; FeedData(fFirstBuffer, true); if not fAutoStop then FeedData(fSecondBuffer, false); except SetEvent(soPlayFinished); waveOutUnprepareHeader(fOutHandle, @fSecondBuffer, sizeof(fSecondBuffer)); raise; end; except waveOutUnprepareHeader(fOutHandle, @fFirstBuffer, sizeof(fFirstBuffer)); raise; end; except waveOutClose(fOutHandle); fOutHandle := 0; raise; end; except raise; end; end; procedure TWavePlayer.Stop; begin fManualStop := true; Wait; end; procedure TWavePlayer.Wait; begin WaitForSingleObject(soPlayFinished, INFINITE); SetEvent(soPlayFinished); end; function TWavePlayer.GetBlockAlign : integer; begin Result := (fBitsPerSample div 8) * fChannels; end; procedure TWavePlayer.StopIt; begin EnterCriticalSection(csFillingData); try CloseHandles; SetEvent(soPlayFinished); if assigned(fOnStop) then fOnStop(Self); finally LeaveCriticalSection(csFillingData); end; end; procedure TWavePlayer.CloseHandles; begin if fOutHandle <> 0 then begin WaveOutReset(fOutHandle); waveOutUnprepareHeader(fOutHandle, @fSecondBuffer, sizeof(fSecondBuffer)); waveOutUnprepareHeader(fOutHandle, @fFirstBuffer, sizeof(fFirstBuffer)); waveOutClose(fOutHandle); fOutHandle := 0; end; end; function TWavePlayer.MsToSamples(aMs : integer) : integer; begin Result := MulDiv(aMs, fSamplingRate, 1000); end; procedure TWavePlayer.FeedData(var aHeader : TWaveHdr; ForceIt : boolean); var Fed : dword; Fill : byte; begin EnterCriticalSection(csFillingData); try if not fAutoStop then with aHeader do begin Fed := DataArrived(lpData^, dwBufferLength); if fBitsPerSample = 8 then Fill := 128 else Fill := 0; fillchar(PByteArray(lpData)[Fed], dwBufferLength - Fed, Fill); if ForceIt or ((Fed > 0) and not fManualStop) then waveOutWrite(fOutHandle, @aHeader, sizeof(aHeader)) else fAutoStop := true; end else StopIt; finally LeaveCriticalSection(csFillingData); end; end; function TWavePlayer.DataArrived(var Data; Size : integer) : integer; begin if assigned(fOnData) then try Result := fOnData(Data, Size) except Result := 0; end else Result := 0; end; end.
unit G2Mobile.Model.Produtos; interface uses FMX.ListView, uDmDados, uRESTDWPoolerDB, System.SysUtils, IdSSLOpenSSLHeaders, FireDAC.Comp.Client, FMX.Dialogs, FMX.ListView.Appearances, FMX.ListView.Types, System.Classes, Datasnap.DBClient, FireDAC.Comp.DataSet, Data.DB, FMX.Objects, FMX.Graphics, G2Mobile.Controller.Produtos; const CONST_DELETASQLITE = 'DELETE FROM PRODUTO'; CONST_BUSCAPRODSERVIDOR = ' SELECT P.COD_PROD, (DESC_REL) AS DESC_IND, P.UNID_MED, isnull(TP.PRECO1, 0) AS VALOR_MIN, isnull(TP.PRECO_VENDA, 0) AS VALOR_PROD, ' + ' CAST(P.GRUPO_COM AS varchar(10)) + '' - '' + tg.descricao_grupo as GRUPO_COM, ' + ' case when p.validadetempo = 0 then CAST(P.VALIDADE AS varchar(10))+'' MESES'' ' + ' when p.validadetempo = 1 then CAST(P.VALIDADE AS varchar(10))+'' DIAS'' ' + ' END AS VALIDADE , P.TIPO_CALC, P.QUANT_CX, P.PESO_PADRAO ' + ' from t_PRODUTO P ' + ' LEFT OUTER JOIN T_PRECOS_PROD TP ON (P.COD_PROD = TP.COD_PROD AND TP.DATA = (SELECT mAX(DATA) FROM T_PRECOS_PROD WHERE COD_PROD = TP.COD_PROD)) ' + ' LEFT OUTER JOIN t_gruposcomerciais tg on(p.grupo_com = tg.cod_grupo) ' + ' WHERE P.VENDAS = 1 AND TP.PRECO_VENDA <> 0 '; CONST_INSERTSQLITE = ' INSERT INTO PRODUTO ( COD_PROD, DESC_IND, UNID_MED, VALOR_MIN, VALOR_PROD, GRUPO_COM, VALIDADE, TIPO_CALC, QUANT_CX, PESO_PADRAO)' + ' VALUES ( :COD_PROD, :DESC_IND, :UNID_MED, :VALOR_MIN, :VALOR_PROD, :GRUPO_COM, :VALIDADE, :TIPO_CALC, :QUANT_CX, :PESO_PADRAO)'; CONST_DELETASQLITEFOTOS = 'DELETE FROM PRODUTO_FOTO'; CONST_BUSCAFOTOPRODSERVIDOR = ' SELECT TF.COD_PROD, TF.NOME_ARQ, TF.FOTO_ARQ AS FOTO FROM T_PRODUTO_FOTO TF ' + ' LEFT OUTER JOIN T_PRODUTO T ON (T.COD_PROD = TF.COD_PROD) ' + ' LEFT OUTER JOIN T_PRECOS_PROD TP ON (T.COD_PROD = TP.COD_PROD AND TP.DATA = (SELECT mAX(DATA) FROM T_PRECOS_PROD WHERE COD_PROD = TP.COD_PROD)) ' + ' WHERE T.VENDAS = 1 AND TP.PRECO_VENDA <> 0 '; CONST_INSERTSQLITEFOTO = ' INSERT INTO PRODUTO_FOTO ( COD_PROD, FOTO, NOME_ARQ) VALUES ( :COD_PROD, :FOTO, :NOME_ARQ)'; CONST_POPULALISTVIEW = ' select p.cod_prod, p.desc_ind, p.unid_med,p.valor_prod, pf.foto from produto p ' + ' left join produto_foto pf on (p.cod_prod = pf.cod_prod) '; CONST_POPULACAMPOS = 'select cod_prod, desc_ind as produto, validade, grupo_com, unid_med, valor_prod, quant_cx, peso_padrao from produto where cod_prod = :id'; CONST_RETORNAFOTO = 'SELECT FOTO FROM PRODUTO_FOTO WHERE COD_PROD = :ID'; type TModelProdutos = class(TInterfacedObject, iModelProdutos) private FQry : TFDQuery; FRdwSQL: TRESTDWClientSQL; public constructor create; destructor destroy; override; class function new: iModelProdutos; function BuscaProdServidor(ADataSet: TFDMemTable): iModelProdutos; function BuscaFotoProdServidor(ADataSet: TFDMemTable): iModelProdutos; function PopulaProdSqLite(ADataSet: TFDMemTable): iModelProdutos; function PopulaFotosProdSqLite(ADataSet: TFDMemTable): iModelProdutos; function PopulaListView(value: TListView; SemFoto: Timage; Pesq: String): iModelProdutos; function LimpaTabelaProd: iModelProdutos; function LimpaTabelaProdFoto: iModelProdutos; function PopulaCampos(value: integer; AList: TStringList): iModelProdutos; function RetornaFoto(value: integer; SemFoto, AImage: Timage): iModelProdutos; end; implementation { TModelProdutos } uses Form_Mensagem, uFrmUtilFormate; class function TModelProdutos.new: iModelProdutos; begin result := self.create; end; constructor TModelProdutos.create; begin FQry := TFDQuery.create(nil); FQry.Connection := DmDados.ConexaoInterna; FQry.FetchOptions.RowsetSize := 50000; FQry.Active := false; FQry.SQL.Clear; FRdwSQL := TRESTDWClientSQL.create(nil); FRdwSQL.DataBase := DmDados.RESTDWDataBase1; FRdwSQL.BinaryRequest := True; FRdwSQL.FormatOptions.MaxStringSize := 10000; FRdwSQL.Active := false; FRdwSQL.SQL.Clear; end; destructor TModelProdutos.destroy; begin FreeAndNil(FQry); FreeAndNil(FRdwSQL); inherited; end; function TModelProdutos.LimpaTabelaProd: iModelProdutos; begin result := self; FQry.ExecSQL(CONST_DELETASQLITE) end; function TModelProdutos.BuscaProdServidor(ADataSet: TFDMemTable): iModelProdutos; begin result := self; FRdwSQL.SQL.Text := CONST_BUSCAPRODSERVIDOR; FRdwSQL.Active := True; ADataSet.CopyDataSet(FRdwSQL, [coStructure, coRestart, coAppend]); end; function TModelProdutos.PopulaProdSqLite(ADataSet: TFDMemTable): iModelProdutos; var i: integer; begin result := self; ADataSet.First; for i := 0 to ADataSet.RecordCount - 1 do begin FQry.SQL.Text := CONST_INSERTSQLITE; FQry.ParamByName('COD_PROD').AsInteger := ADataSet.FieldByName('COD_PROD').AsInteger; FQry.ParamByName('DESC_IND').AsString := ADataSet.FieldByName('DESC_IND').AsString; FQry.ParamByName('UNID_MED').AsString := ADataSet.FieldByName('UNID_MED').AsString; FQry.ParamByName('VALOR_MIN').AsFloat := ADataSet.FieldByName('VALOR_MIN').AsFloat; FQry.ParamByName('VALOR_PROD').AsFloat := ADataSet.FieldByName('VALOR_PROD').AsFloat; FQry.ParamByName('GRUPO_COM').AsString := ADataSet.FieldByName('GRUPO_COM').AsString; FQry.ParamByName('VALIDADE').AsString := ADataSet.FieldByName('VALIDADE').AsString; FQry.ParamByName('TIPO_CALC').AsInteger := ADataSet.FieldByName('TIPO_CALC').AsInteger; FQry.ParamByName('QUANT_CX').AsFloat := ADataSet.FieldByName('QUANT_CX').AsFloat; FQry.ParamByName('PESO_PADRAO').AsFloat := ADataSet.FieldByName('PESO_PADRAO').AsFloat; FQry.ExecSQL; ADataSet.Next; end; end; function TModelProdutos.LimpaTabelaProdFoto: iModelProdutos; begin result := self; FQry.ExecSQL(CONST_DELETASQLITEFOTOS) end; function TModelProdutos.BuscaFotoProdServidor(ADataSet: TFDMemTable): iModelProdutos; begin result := self; FRdwSQL.SQL.Text := CONST_BUSCAFOTOPRODSERVIDOR; FRdwSQL.Active := True; ADataSet.CopyDataSet(FRdwSQL, [coStructure, coRestart, coAppend]); end; function TModelProdutos.PopulaFotosProdSqLite(ADataSet: TFDMemTable): iModelProdutos; var i : integer; foto : TStream; img_foto: Timage; begin result := self; img_foto := Timage.create(nil); ADataSet.First; try for i := 0 to ADataSet.RecordCount - 1 do begin FQry.SQL.Text := CONST_INSERTSQLITEFOTO; foto := TStream.create; foto := ADataSet.CreateBlobStream(ADataSet.FieldByName('FOTO'), TBlobStreamMode.bmRead); img_foto.Bitmap.LoadFromStream(foto); FQry.ParamByName('COD_PROD').AsInteger := ADataSet.FieldByName('COD_PROD').AsInteger; FQry.ParamByName('FOTO').Assign(img_foto.Bitmap); FQry.ParamByName('NOME_ARQ').AsString := ADataSet.FieldByName('NOME_ARQ').AsString; FQry.ExecSQL; ADataSet.Next; end; finally FreeAndNil(img_foto); end; end; function TModelProdutos.PopulaListView(value: TListView; SemFoto: Timage; Pesq: String): iModelProdutos; var x : integer; item: TListViewItem; txt : TListItemText; img : TListItemImage; bmp : TBitmap; foto: TStream; begin result := self; try FQry.SQL.Text := CONST_POPULALISTVIEW + ' where p.cod_prod = ' + QuotedStr(Pesq) + ' or p.desc_ind like ''%' + Pesq + '%'''; FQry.Open; FQry.First; value.Items.Clear; value.BeginUpdate; for x := 0 to FQry.RecordCount - 1 do begin item := value.Items.Add; with item do begin txt := TListItemText(Objects.FindDrawable('cod_prod')); txt.Text := formatfloat('0000', FQry.FieldByName('cod_prod').AsFloat); txt.TagString := FQry.FieldByName('cod_prod').AsString; txt := TListItemText(Objects.FindDrawable('desc_ind')); txt.Text := FQry.FieldByName('desc_ind').AsString; txt := TListItemText(Objects.FindDrawable('unid_med')); txt.Text := FQry.FieldByName('unid_med').AsString; txt := TListItemText(Objects.FindDrawable('valor_prod')); txt.Text := formatfloat('R$#,##0.00', FQry.FieldByName('valor_prod').AsFloat); img := TListItemImage(Objects.FindDrawable('Image')); if not(FQry.FieldByName('FOTO').isNull) then begin foto := FQry.CreateBlobStream(FQry.FieldByName('FOTO'), TBlobStreamMode.bmRead); bmp := TBitmap.create; bmp.LoadFromStream(foto); img.OwnsBitmap := True; img.Bitmap := bmp; end else begin img.Bitmap := SemFoto.Bitmap; end; end; FQry.Next end; finally value.EndUpdate; end; end; function TModelProdutos.PopulaCampos(value: integer; AList: TStringList): iModelProdutos; var i: integer; begin result := self; FQry.SQL.Text := CONST_POPULACAMPOS; FQry.ParamByName('ID').AsInteger := value; FQry.Open; if FQry.RecordCount = 0 then begin Exibir_Mensagem('ERRO', 'ALERTA', 'Erro', 'Registro não encontrado!', 'OK', '', $FFDF5447, $FFDF5447); Frm_Mensagem.Show; abort; end; for i := 0 to FQry.FieldCount - 1 do begin AList.Add(FQry.Fields[i].AsString); FQry.Next; end; end; function TModelProdutos.RetornaFoto(value: integer; SemFoto, AImage: Timage): iModelProdutos; var vStream: TMemoryStream; begin result := self; FQry.SQL.Text := CONST_RETORNAFOTO; FQry.ParamByName('ID').AsInteger := value; FQry.Open; if FQry.RecordCount <> 0 then begin vStream := TMemoryStream.create; TBlobField(FQry.FieldByName('FOTO')).SaveToStream(vStream); vStream.Position := 0; AImage.MultiResBitmap.LoadItemFromStream(vStream, 1); vStream.Free; end else begin AImage.Bitmap := SemFoto.Bitmap; end; end; end.
unit TTSCOLLTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSCOLLRecord = record PLenderNum: String[4]; PCollCode: String[8]; PAutoApplyItems: Boolean; PDescription: String[30]; PRate: Currency; End; TTTSCOLLBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSCOLLRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSCOLL = (TTSCOLLPrimaryKey); TTTSCOLLTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCollCode: TStringField; FDFAutoApplyItems: TBooleanField; FDFDescription: TStringField; FDFRate: TCurrencyField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCollCode(const Value: String); function GetPCollCode:String; procedure SetPAutoApplyItems(const Value: Boolean); function GetPAutoApplyItems:Boolean; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPRate(const Value: Currency); function GetPRate:Currency; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSCOLL); function GetEnumIndex: TEITTSCOLL; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSCOLLRecord; procedure StoreDataBuffer(ABuffer:TTTSCOLLRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCollCode: TStringField read FDFCollCode; property DFAutoApplyItems: TBooleanField read FDFAutoApplyItems; property DFDescription: TStringField read FDFDescription; property DFRate: TCurrencyField read FDFRate; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCollCode: String read GetPCollCode write SetPCollCode; property PAutoApplyItems: Boolean read GetPAutoApplyItems write SetPAutoApplyItems; property PDescription: String read GetPDescription write SetPDescription; property PRate: Currency read GetPRate write SetPRate; published property Active write SetActive; property EnumIndex: TEITTSCOLL read GetEnumIndex write SetEnumIndex; end; { TTTSCOLLTable } procedure Register; implementation function TTTSCOLLTable.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 { TTTSCOLLTable.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; { TTTSCOLLTable.GenerateNewFieldName } function TTTSCOLLTable.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; { TTTSCOLLTable.CreateField } procedure TTTSCOLLTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCollCode := CreateField( 'CollCode' ) as TStringField; FDFAutoApplyItems := CreateField( 'AutoApplyItems' ) as TBooleanField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFRate := CreateField( 'Rate' ) as TCurrencyField; end; { TTTSCOLLTable.CreateFields } procedure TTTSCOLLTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSCOLLTable.SetActive } procedure TTTSCOLLTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSCOLLTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSCOLLTable.SetPCollCode(const Value: String); begin DFCollCode.Value := Value; end; function TTTSCOLLTable.GetPCollCode:String; begin result := DFCollCode.Value; end; procedure TTTSCOLLTable.SetPAutoApplyItems(const Value: Boolean); begin DFAutoApplyItems.Value := Value; end; function TTTSCOLLTable.GetPAutoApplyItems:Boolean; begin result := DFAutoApplyItems.Value; end; procedure TTTSCOLLTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSCOLLTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSCOLLTable.SetPRate(const Value: Currency); begin DFRate.Value := Value; end; function TTTSCOLLTable.GetPRate:Currency; begin result := DFRate.Value; end; procedure TTTSCOLLTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('CollCode, String, 8, N'); Add('AutoApplyItems, Boolean, 0, N'); Add('Description, String, 30, N'); Add('Rate, Currency, 0, N'); end; end; procedure TTTSCOLLTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;CollCode, Y, Y, N, N'); end; end; procedure TTTSCOLLTable.SetEnumIndex(Value: TEITTSCOLL); begin case Value of TTSCOLLPrimaryKey : IndexName := ''; end; end; function TTTSCOLLTable.GetDataBuffer:TTTSCOLLRecord; var buf: TTTSCOLLRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCollCode := DFCollCode.Value; buf.PAutoApplyItems := DFAutoApplyItems.Value; buf.PDescription := DFDescription.Value; buf.PRate := DFRate.Value; result := buf; end; procedure TTTSCOLLTable.StoreDataBuffer(ABuffer:TTTSCOLLRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCollCode.Value := ABuffer.PCollCode; DFAutoApplyItems.Value := ABuffer.PAutoApplyItems; DFDescription.Value := ABuffer.PDescription; DFRate.Value := ABuffer.PRate; end; function TTTSCOLLTable.GetEnumIndex: TEITTSCOLL; var iname : string; begin result := TTSCOLLPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSCOLLPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSCOLLTable, TTTSCOLLBuffer ] ); end; { Register } function TTTSCOLLBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('LENDERNUM','COLLCODE','AUTOAPPLYITEMS','DESCRIPTION','RATE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TTTSCOLLBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftBoolean; 4 : result := ftString; 5 : result := ftCurrency; end; end; function TTTSCOLLBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCollCode; 3 : result := @Data.PAutoApplyItems; 4 : result := @Data.PDescription; 5 : result := @Data.PRate; end; end; end.
unit MFichas.Model.Produto.Metodos.Editar; interface uses System.SysUtils, System.Generics.Collections, MFichas.Model.Produto.Interfaces, MFichas.Model.Entidade.PRODUTO; type TModelProdutoMetodosEditar = class(TInterfacedObject, iModelProdutoMetodosEditar) private [weak] FParent : iModelProduto; FEntidade : TPRODUTO; FGUUID : String; FDescricao : String; FValor : Currency; FGrupo : String; FAtivoInativo: Integer; FListaProduto: TObjectList<TPRODUTO>; constructor Create(AParent: iModelProduto); procedure RecuperarObjetoDoBancoDeDados; procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelProduto): iModelProdutoMetodosEditar; function GUUID(AGUUID: String) : iModelProdutoMetodosEditar; function Descricao(ADescricao: String): iModelProdutoMetodosEditar; function Valor(AValor: Currency) : iModelProdutoMetodosEditar; function Grupo(AGrupo: String) : iModelProdutoMetodosEditar; function AtivoInativo(AValue: Integer): iModelProdutoMetodosEditar; function &End : iModelProdutoMetodos; end; implementation { TModelProdutoMetodosEditar } function TModelProdutoMetodosEditar.AtivoInativo( AValue: Integer): iModelProdutoMetodosEditar; begin Result := Self; FAtivoInativo := AValue; end; function TModelProdutoMetodosEditar.&End: iModelProdutoMetodos; begin Result := FParent.Metodos; RecuperarObjetoDoBancoDeDados; Gravar; end; constructor TModelProdutoMetodosEditar.Create(AParent: iModelProduto); begin FParent := AParent; FEntidade := TPRODUTO.Create; end; function TModelProdutoMetodosEditar.Descricao( ADescricao: String): iModelProdutoMetodosEditar; begin Result := Self; if ADescricao.IsNullOrWhiteSpace(ADescricao) then raise Exception.Create( 'Não é possível alterar este produto se não tiver um Nome/Descrição.' ); FDescricao := ADescricao.ToUpper; end; destructor TModelProdutoMetodosEditar.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); if Assigned(FListaProduto) then FreeAndNil(FListaProduto); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; if Assigned(FListaProduto) then begin FListaProduto.Free; FListaProduto.DisposeOf; end; {$ENDIF} inherited; end; procedure TModelProdutoMetodosEditar.Gravar; begin FParent.DAO.Modify(FEntidade); FEntidade.DESCRICAO := FDescricao; FEntidade.GRUPO := FGrupo; FEntidade.PRECO := FValor; FEntidade.STATUS := FAtivoInativo; FParent.DAO.Update(FEntidade); end; function TModelProdutoMetodosEditar.Grupo( AGrupo: String): iModelProdutoMetodosEditar; begin Result := Self; FGrupo := AGrupo; end; function TModelProdutoMetodosEditar.GUUID( AGUUID: String): iModelProdutoMetodosEditar; begin Result := Self; FGUUID := AGUUID; end; class function TModelProdutoMetodosEditar.New(AParent: iModelProduto): iModelProdutoMetodosEditar; begin Result := Self.Create(AParent); end; procedure TModelProdutoMetodosEditar.RecuperarObjetoDoBancoDeDados; begin FListaProduto := FParent.DAO.FindWhere('GUUID = ' + QuotedStr(FGUUID)); FEntidade.GUUID := FListaProduto[0].GUUID; FEntidade.GRUPO := FListaProduto[0].GRUPO; FEntidade.CODIGO := FListaProduto[0].CODIGO; FEntidade.DESCRICAO := FListaProduto[0].DESCRICAO; FEntidade.PRECO := FListaProduto[0].PRECO; FEntidade.STATUS := FListaProduto[0].STATUS; FEntidade.DATACADASTRO := FListaProduto[0].DATACADASTRO; FEntidade.DATAALTERACAO := FListaProduto[0].DATAALTERACAO; end; function TModelProdutoMetodosEditar.Valor( AValor: Currency): iModelProdutoMetodosEditar; begin Result := Self; if AValor <= 0 then raise Exception.Create( 'Não é possível alterar este produto com o valor de venda igual a 0.' ); FValor := AValor; 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_Widgets * Implements all common engine widgets (buttons, windows, images, etc) *********************************************************************************************************************** } Unit TERRA_Widgets; {$I terra.inc} {$IFNDEF MOBILE} {$DEFINE HASMOUSEOVER} {$ENDIF} {$IFDEF WINDOWS}{$UNDEF MOBILE}{$ENDIF} Interface Uses TERRA_String, TERRA_Utils, TERRA_UI, TERRA_Tween, TERRA_Vector2D, TERRA_Math, TERRA_Color, TERRA_Renderer, TERRA_FileManager, TERRA_SpriteManager, TERRA_Texture, TERRA_Font, TERRA_ClipRect, TERRA_Collections; Const layoutHorizontal = 0; layoutVertical = 1; ExtendedPressDuration = 2000; System_Name_Wnd = '@UI_Window'; System_Name_Text = '@UI_Text'; System_Name_Btn = '@UI_BTN'; System_Name_BG = '@UI_BG'; Type UICaption = Class(Widget) Protected _Caption:TERRAString; _TextRect:Vector2D; _PreviousFont:Font; _OriginalValue:TERRAString; Function GetLocalizationKey: TERRAString; Public Procedure SetCaption(Value:TERRAString); Procedure UpdateRects; Override; Function GetSize:Vector2D; Override; Procedure OnLanguageChange(); Override; Property Caption:TERRAString Read _Caption Write SetCaption; Property LocalizationKey:TERRAString Read GetLocalizationKey; End; UITabEntry = Record Visible:Boolean; Caption:TERRAString; Name:TERRAString; Index:Integer; End; UITabList = Class(Widget) Protected _Tabs:Array Of UITabEntry; _TabCount:Integer; _TabHighlight:Integer; _TabWidthOn:Integer; _TabWidthOff:Integer; _TabHeightOn:Integer; _TabHeightOff:Integer; _SelectedIndex:Integer; Function GetTabAt(X,Y:Integer):Integer; Function GetSelectedCaption: TERRAString; Procedure SetSelectedCaption(const Value: TERRAString); Procedure GetTabProperties(Const Selected:Boolean; Out TabColor:Color; Out TabFont:TERRA_Font.Font); Virtual; Procedure SetSelectedIndex(const Value: Integer); Function IsSelectable():Boolean; Override; Public Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; ComponentBG:TERRAString=''); Overload; Procedure Render; Override; Procedure UpdateRects; Override; Procedure AddTab(Name:TERRAString; Index:Integer); Procedure SetTabVisibility(Index:Integer; Visibility:Boolean); Procedure ClearTabs(); Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseMove(X,Y:Integer):Boolean; Override; Function OnSelectRight():Boolean; Override; Function OnSelectLeft():Boolean; Override; Procedure OnLanguageChange(); Override; Property SelectedIndex:Integer Read _SelectedIndex Write SetSelectedIndex; Property Caption:TERRAString Read GetSelectedCaption Write SetSelectedCaption; End; UIWindow = Class(Widget) Protected _Width: Integer; _Height: Integer; _WndLayout:UISkinLayout; _Caption:TERRAString; _IX:Integer; _IY:Integer; Function IsSelectable():Boolean; Override; Public Selectable:Boolean; Frameless:Boolean; CloseButton:Widget; Procedure Render; Override; Procedure UpdateRects; Override; // Procedure EnableHighlights(); Procedure SetCaption(Const Value:TERRAString); Procedure SetHeight(Const Value: Integer); Procedure SetWidth(Const Value: Integer); Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseWheel(X,Y:Integer; Delta:Integer):Boolean; Override; Constructor Create(Name:TERRAString; UI:UI; X,Y,Z:Single; Width, Height:Integer; ComponentBG:TERRAString=''); Overload; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Width, Height:Integer; ComponentBG:TERRAString=''); Overload; Procedure Release; Override; Property Layout:UISkinLayout Read _WndLayout; Property Width: Integer Read _Width Write SetWidth; Property Height: Integer Read _Height Write SetHeight; Property Caption:TERRAString Read _Caption Write SetCaption; End; UILabel = Class(UICaption) Protected _Width:Single; _Height:Single; Public OnReveal:WidgetEventHandler; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Caption:TERRAString; TabIndex:Integer=-1); Procedure Render; Override; Procedure UpdateRects; Override; Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override; End; UIButton = Class(UICaption) Protected _Width:Integer; _Height:Integer; _Dual:Boolean; Public Disabled:Boolean; TextColor:Color; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Caption:TERRAString; Skin:TERRAString=''; TabIndex:Integer=-1); Procedure Render; Override; Procedure UpdateRects; Override; Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; End; UISpriteButton = Class(UIButton) Protected _Texture:Texture; Public Filter:TextureFilterMode; Offset:Single; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Skin:TERRAString=''; TabIndex:Integer=-1); Procedure SetTexture(Tex:Texture); Procedure Render; Override; End; UIIcon = Class(Widget) Protected _Icon:TERRAString; _Width:Integer; _Height:Integer; _Dual:Boolean; _Down:Boolean; _Base:Integer; Public Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Icon:TERRAString; TabIndex:Integer=-1); Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Procedure Render; Override; Procedure UpdateRects; Override; Property Width:Integer Read _Width; Property Height:Integer Read _Height; Property Icon:TERRAString Read _Icon; End; UISprite = Class(Widget) Protected _Texture:Texture; Public Rect:TextureRect; Anchor:Vector2D; Flip, Mirror:Boolean; Filter:TextureFilterMode; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Picture:TERRAString = ''; TabIndex:Integer=-1); Procedure SetTexture(Tex:Texture); Procedure Render; Override; Procedure UpdateRects; Override; Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override; Property Texture:TERRA_Texture.Texture Read _Texture Write _Texture; End; UICheckBox = Class(UICaption) Protected _Checked:Boolean; _Variable:PBoolean; _Width:Integer; _Height:Integer; Procedure SetChecked(Value:Boolean); Virtual; Function HasMouseOver():Boolean; Override; Function IsSelectable():Boolean; Override; Public Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Caption:TERRAString; Skin:TERRAString = ''; TabIndex:Integer=-1); Procedure Render; Override; Procedure UpdateRects; Override; Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Procedure SetCheckedWithoutPropagation(Value:Boolean); Property Checked:Boolean Read _Checked Write SetChecked; Property Variable:PBoolean Read _Variable Write _Variable; End; UIRadioButton = Class(UICheckBox) Protected Procedure SetChecked(Value:Boolean); Override; Public Group:Integer; Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Caption:TERRAString; TabIndex:Integer=-1); End; UISlider = Class(Widget) Protected _Value:Single; _Max:Single; _Width:Integer; _Height:Integer; _PickWidth:Integer; _PickHeight:Integer; _Changed:Boolean; Procedure SetValue(X:Single); Public OnChange:WidgetEventHandler; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; TabIndex:Integer=-1); Procedure Render; Override; Procedure UpdateRects; Override; Function OnRegion(X,Y:Integer): Boolean; Override; Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseMove(X,Y:Integer):Boolean; Override; Property Value:Single Read _Value Write SetValue; Property Max:Single Read _Max Write _Max; End; UIScrollBarHandle = Class(UIIcon) Public Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseMove(X,Y:Integer):Boolean; Override; End; UIScrollBar = Class(Widget) Protected _Value:Single; _Max:Single; _Length:Integer; _BgWidth:Integer; _BgHeight:Integer; _PickWidth:Integer; _PickHeight:Integer; _Changed:Boolean; _Horizontal:Boolean; _Handle:UIScrollBarHandle; _HandlePos:Single; _HandleOffset:Vector2D; Procedure SetLength(Const Value:Integer); Procedure SetValue(Const Value: Single); Function GetLengthInPixels():Single; Procedure HandleMove(X,Y:Integer); Public OnChange:WidgetEventHandler; //Function OnHandleRegion(X,Y:Integer):Boolean; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Size:Integer; Horizontal:Boolean; TabIndex:Integer=-1); Procedure Render; Override; Procedure UpdateRects; Override; Procedure Slide(Ammount:Single); Property Value:Single Read _Value Write SetValue; Property Max:Single Read _Max Write _Max; Property Horizontal:Boolean Read _Horizontal; Property ScrollSize:Integer Read _Length Write SetLength; End; UIProgressBar = Class(Widget) Protected _Percent:Single; _Width:Integer; _Height:Integer; Function CreateCustomTween(TweenType:Integer; TargetValue:Single):Tween; Override; Public Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Skin:TERRAString = ''; TabIndex:Integer=-1); Procedure Render; Override; Procedure UpdateRects; Override; Property Percent:Single Read _Percent Write _Percent; End; UIComboBox = Class(Widget) Protected _ItemIndex:Integer; _ItemHighlight:Integer; _ShowList:Boolean; _Width:Integer; _BarWidth:Integer; _BarSlices:Integer; _HandlePos:Integer; _HandleWidth:Integer; _HandleHeight:Integer; _ListWidth:Integer; _ListHeight:Integer; _ListSlicesX:Integer; _ListSlicesY:Integer; _Content:List; _Selected:CollectionObject; Function GetItem(Index:Integer):CollectionObject; Function GetItemAtIndex(X,Y:Integer):Integer; Procedure SetItemIndex(Const Value:Integer); Public ShowLabelOnly:Boolean; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Width:Integer; TabIndex:Integer=-1); Procedure Render; Override; Procedure UpdateRects; Override; Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseMove(X,Y:Integer):Boolean; Override; Procedure SetContent(Content:List); Procedure Select(Const Value:TERRAString); Property ItemIndex:Integer Read _ItemIndex Write SetItemIndex; Property Items[Index:Integer]:CollectionObject Read GetItem; Property Selected:CollectionObject Read _Selected; End; UIEditText = Class(UICaption) Protected _Width:Integer; _Height:Single; _LineCount:Integer; _Lines:Array Of TERRAString; _LineIndex:Integer; _MaxLines:Integer; _SelectedColor:Color; _ScrollIndex:Single; _Clip:ClipRect; {_HorScroll:UIScrollBar; _VertScroll:UIScrollBar;} _KoreanBaseJamo:Integer; _KoreanInitialJamo:Integer; _KoreanMedialJamo:Integer; _KoreanFinalJamo:Integer; _InsideEvent:Boolean; Procedure UpdateJamos(); Function UpdateTransform():Boolean; Override; Procedure StartHighlight(); Override; Procedure StopHighlight(); Override; Function IsSelectable():Boolean; Override; Public OnEnter:WidgetEventHandler; OnChange:WidgetEventHandler; PasswordField:Boolean; TextColor:Color; Centered:Boolean; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Width:Integer; Skin:TERRAString=''; TabIndex:Integer=-1); Procedure Render; Override; Procedure UpdateRects; Override; Procedure SetFocus(ShowKeyboard:Boolean); Procedure SetText(Const Value:TERRAString); Function GetText:TERRAString; Procedure SetLineCount(const Value: Integer); Function GetCurrentLine:TERRAString; Procedure SetCurrentLine(const Value:TERRAString); Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override; Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override; Function OnKeyPress(Key:Word):Boolean; Override; Property Text:TERRAString Read GetText Write SetText; Property Line:TERRAString Read GetCurrentLine Write SetCurrentLine; Property LineCount:Integer Read _LineCount Write SetLineCount; End; UITooltip = Class(UICaption) Protected _Width:Single; _Height:Single; _Sections:Integer; Public Procedure Render; Override; Procedure UpdateRects; Override; Constructor Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Caption:TERRAString=''; Skin:TERRAString=''); End; UILayout = Class(Widget) Protected _Width:Integer; _Height:Integer; Public Position:Vector2D; HorizontalSpacing:Integer; VerticalSpacing:Integer; LayoutMode:Integer; Constructor Create(Name:TERRAString; UI:UI; X,Y,Z:Single; Width, Height, LayoutMode:Integer; TabIndex:Integer=-1); Procedure Render; Override; Property Width:Integer Read _Width; Property Height:Integer Read _Height; End; Var UseNativeKeyboard:Boolean = False; Implementation Uses TERRA_OS, TERRA_Application, TERRA_GraphicsManager, TERRA_Vector3D, TERRA_Log, TERRA_FileUtils, TERRA_Localization {$IFDEF VIRTUALKEYBOARD},TERRA_UIVirtualKeyboard{$ENDIF}; Function GetLocalizedString(Value:TERRAString):TERRAString; Begin If (Value<>'') And (Value[1]='#') Then Begin Value := Copy(Value, 2, MaxInt); Result := LocalizationManager.Instance.GetString(Value); End Else Result := Value; End; Function UICaption.GetLocalizationKey: TERRAString; Begin If StringFirstChar(_OriginalValue) = Ord('#') Then Begin Result := StringCopy(_OriginalValue, 2, MaxInt); End Else Result := ''; End; Function UICaption.GetSize: Vector2D; Begin If (_NeedsUpdate) Then Self.UpdateRects(); Result := Inherited GetSize; End; Procedure UICaption.OnLanguageChange; Begin Self.SetCaption(Self._OriginalValue); End; Procedure UICaption.SetCaption(Value:TERRAString); Begin _OriginalValue := Value; _NeedsUpdate := True; _Caption := GetLocalizedString(Value); _Caption := ConvertFontCodes(_Caption); End; Procedure UICaption.UpdateRects; Var Fnt:TERRA_Font.Font; Begin Fnt := Self.GetFont(); If ((_NeedsUpdate) Or (Fnt<>_PreviousFont)) And (Assigned(FontRenderer)) Then Begin _TextRect := FontRenderer.GetTextRect(_Caption, 1.0); _PreviousFont := Fnt; _NeedsUpdate := False; End; End; { UIWindow } Constructor UIWindow.Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Width, Height:Integer; ComponentBG:TERRAString); Begin Inherited Create(Name, UI, Parent); Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self._Width := Width; Self._Height := Height; Self._Dragging := False; If (ComponentBG='') Then ComponentBG := 'ui_window'; Self.LoadComponent(ComponentBG); Self.Selectable := True; If (Length(_ComponentList)>0) Then Begin _IX := Self._ComponentList[0].Buffer.Width; _IY := Self._ComponentList[0].Buffer.Height; _WndLayout := UISkinLayout.Create(_ComponentList[0]); End Else _WndLayout := UISkinLayout.Create(Nil); Self.UpdateRects(); End; Constructor UIWindow.Create(Name:TERRAString; UI:UI; X,Y,Z:Single; Width, Height:Integer; ComponentBG:TERRAString); Begin Create(Name, UI, Nil, X,Y,Z, Width, Height, ComponentBG); End; Procedure UIWindow.Release(); Begin ReleaseObject(_WndLayout); Inherited; End; Function UIWindow.OnMouseDown(X,Y:Integer;Button:Word):Boolean; Var Temp:WidgetEventHandler; Begin If (Not Visible) Or (Not Selectable) Then Begin Result := False; Exit; End; Temp := Self.OnMouseClick; Self.OnMouseClick := Nil; Result := Inherited OnMouseDown(X,Y,Button); Self.OnMouseClick := Temp; If Result Then Exit; If (Not FrameLess) And (OnRegion(X,Y)) Then Begin Result := True; If (Assigned(OnMouseClick)) And (Not Self.HasTweens()) Then Begin Self._HitTime := Application.GetTime(); Self._Hitting := True; End; End Else Result := False; End; Function UIWindow.OnMouseUp(X,Y:Integer;Button:Word):Boolean; Begin Result := Inherited OnMouseUp(X,Y, Button); If (_Hitting) Then Begin Result := True; _Hitting := False; If (Application.GetTime - _HitTime > ExtendedPressDuration) And (Assigned(OnExtendedClick)) Then OnExtendedClick(Self) Else OnMouseClick(Self); Self.OnHit(); End; End; {Procedure UIWindow.EnableHighlights; Var I:Integer; W:Widget; Begin For I:=0 To Pred(ChildrenCount) Do Begin W := GetChild(I); If (Assigned(W)) And (W.CanHighlight) Then Begin While (W.UpControl<>Nil) And (W.UpControl.Position.Y<W.Position.Y) Do W := W.UpControl; UI.Highlight := W; Exit; End; End; End;} Procedure UIWindow.UpdateRects(); Begin _Size.X := _WndLayout.GetWidth(_Width); _Size.Y := _WndLayout.GetHeight(_Height); End; Procedure UIWindow.Render; Var MyColor:TERRA_Color.Color; //Pos, Size:Vector2D; Begin Self.UpdateRects(); Self.UpdateTransform(); Self.UpdateHighlight(); {If (Not Self.HasTweens) And (Self.Parent = Nil) Then Begin Pos := Self.GetAbsolutePosition(); Size := Self.Size; If (Pos.X + Size.X<=0) Or (Pos.Y + Size.Y<=0) Or (Pos.X + Size.X>=UIManager.Instance.Width) Or (Pos.Y + Size.Y>=UIManager.Instance.Height) Then Begin Self.Visible := False; Exit; End; End;} MyColor := Self.Color; If (Not Frameless) Then Begin Self.DrawWindow(0, VectorZero, _Width, _Height, _WndLayout, MyColor); { Self.DrawComponent(0, VectorZero, 0.0, 0.0, 1/3, 1/3); Self.DrawComponent(0, VectorCreate(32.0*Pred(_Width), 0.0, 0.0), 2/3, 0.0, 1.0, 1/3); Self.DrawComponent(0, VectorCreate(0.0, 32.0 * Pred(_Height), 0.0), 0.0, 2/3, 1/3, 1.0); Self.DrawComponent(0, VectorCreate(32.0 * Pred(_Width), 32.0 * Pred(_Height), 0.0), 2/3, 2/3, 1.0, 1.0); For I:=1 To _Width Do Begin If (_TabCount=0) Then Self.DrawComponent(0, VectorCreate(32.0 * Pred(I), 0.0, 0.0), 1/3, 0.0, 2/3, 1/3); Self.DrawComponent(0, VectorCreate(32.0 * Pred(I), Pred(_Height) * 32.0, 0.0), 1/3, 2/3, 2/3, 1.0); End; For I:=1 To _Height Do Begin Self.DrawComponent(0, VectorCreate(0.0, 32.0 * Pred(I), 0.0), 0.0, 1/3, 1/3, 2/3); Self.DrawComponent(0, VectorCreate(Pred(_Width) * 32.0, 32.0 * Pred(I), 0.0), 2/3, 1/3, 1.0, 2/3); End; For J:=1 To _Height Do For I:=1 To _Width Do Begin Self.DrawComponent(0, VectorCreate(32*Pred(I), 32*Pred(J), 0.0), 1/3, 1/3, 2/3, 2/3); End; } End; Inherited Render(); End; Constructor UIButton.Create(Name:TERRAString; UI:UI;Parent:Widget; X,Y,Z:Single; Caption:TERRAString; Skin:TERRAString; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent); Self._TabIndex := TabIndex; Self.SetCaption(Caption); Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self.TextColor := ColorWhite; If Skin = '' Then Skin := 'ui_button'; Skin := GetFileName(Skin, True); _Dual := FileManager.Instance.SearchResourceFile(Skin+'_down.png')<>''; If _Dual Then Begin Self.LoadComponent(Skin+'_up'); Self.LoadComponent(Skin+'_down'); Self.LoadComponent(Skin+'_over'); End Else Self.LoadComponent(Skin); If (Length(_ComponentList)>0) Then Begin _Width := Self._ComponentList[0].Buffer.Width; _Height := Self._ComponentList[0].Buffer.Height; End; _NeedsUpdate := True; End; Procedure UIButton.UpdateRects(); Begin Inherited; _Size.X := _Width; _Size.Y := _Height; End; Procedure UIButton.Render; Var MyColor:TERRA_Color.Color; ID:Integer; TX, TY:Single; TempSat:Single; Begin Self.UpdateRects(); Self.UpdateTransform(); Self.UpdateHighlight(); MyColor := Self.Color; TextColor.A := MyColor.A; TempSat := Self._Saturation; If Disabled Then Self._Saturation := 0.0; If (_Dual) And (Self.IsHighlighted()) Then Begin If (Self._ComponentCount>=3) Then ID := 2 Else ID := 1 End Else ID := 0; Self.DrawComponent(ID, VectorZero, 0.0, 0.0, 1.0, 1.0, MyColor, True); If (Assigned(Self.Font)) And (Caption<>'') Then Begin {If (Self.IsHighlighted()) Then S := '\w'+S;} {If Pos('\p',S)>0 Then IntToString(2);} TX := (Self._Width - _TextRect.X) * 0.5; TY := (Self._Height - _TextRect.Y) * 0.5; Self.DrawText(_Caption, VectorCreate(TX, TY, 0.25), Self.TextColor, 1.0); End; Inherited; Self._Saturation := TempSat; End; Function UIButton.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Begin If (OnRegion(X,Y)) And (Self.Visible) And (Not Self.HasTweens) And (Not Disabled) Then Begin If (Assigned(OnMouseClick)) Then Result := OnMouseClick(Self) Else Result := True; Self.OnHit(); End Else Result := Inherited OnMouseDown(X,Y, Button); End; Procedure UIWindow.SetCaption(const Value:TERRAString); Begin _Caption := Value; End; Procedure UIWindow.SetWidth(const Value: Integer); Begin _Width := Value; Self.UpdateRects(); End; Procedure UIWindow.SetHeight(const Value: Integer); Begin _Height := Value; Self.UpdateRects(); End; Function UIWindow.OnMouseWheel(X,Y:Integer; Delta: Integer): Boolean; Var I:Integer; Add:Single; S:UIScrollbar; Begin Result := False; RemoveHint(X+Y); //TODO - check this stupid hint For I:=0 To Pred(Self._ChildrenCount) Do If (_ChildrenList[I] Is UIScrollbar) Then Begin S := UIScrollbar(_ChildrenList[I]); Add := (Delta/Abs(Delta)) * -0.1; If (Not S.Horizontal) Then S.Slide(Add * S.Max); Result := True; End; End; Function UIWindow.IsSelectable: Boolean; Begin Result := False; End; { UISpriteButton } Constructor UISpriteButton.Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Skin:TERRAString; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent, X,Y,Z, '', Skin, TabIndex); Self.Filter := filterLinear; End; Procedure UISpriteButton.Render; Var Pos:Vector2D; W, H:Single; Begin Inherited; If _Texture = Nil Then Exit; W := _Texture.Width; H := (_Size.Y - _Texture.Height) * 0.5; Pos := Self.GetAbsolutePosition(); SpriteManager.Instance.DrawSprite(Pos.X + (_Width-W) * 0.5, H + Offset + Pos.Y, Layer+0.5, _Texture, Nil, BlendBlend, Saturation, Filter); End; Procedure UISpriteButton.SetTexture(Tex: Texture); Begin Self._Texture := Tex; End; Constructor UIIcon.Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Icon:TERRAString; TabIndex:Integer); Var Base:TERRAString; Begin Inherited Create(Name, UI, Parent); Self._Icon := Icon; Self._TabIndex := TabIndex; Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; If Pos('|',Icon)>0 Then Base := StringGetNextSplit(Icon, Ord('|')) Else Base := ''; Log(logDebug, 'Game', 'Seaching icons'); _Dual := FileManager.Instance.SearchResourceFile(Icon+'_down.png')<>''; Log(logDebug, 'Game', 'Loading components'); If _Dual Then Begin Self.LoadComponent(Icon+'_up'); Self.LoadComponent(Icon+'_down'); Self.LoadComponent(Icon+'_over'); End Else Self.LoadComponent(Icon); Log(logDebug, 'Game', 'Getting length'); If Length(Self._ComponentList)>0 Then Begin _Width := _ComponentList[0].Buffer.Width; _Height := _ComponentList[0].Buffer.Height; End; If Base<>'' Then Begin _Base := Self.LoadComponent(Base); End Else _Base := -1; End; Procedure UIIcon.UpdateRects(); Begin _Size.X := _Width; _Size.Y := _Height; End; Procedure UIIcon.Render; Var ID:Integer; MyColor:TERRA_Color.Color; Begin Self.UpdateRects(); Self.UpdateTransform(); If (Not DisableHighlights) Then Self.UpdateHighlight(); MyColor := Self.Color; {$IFDEF OUYA} {If (UI.Highlight<>Nil) And (Not Self.IsHighlighted) And (Assigned(Self.OnMouseClick)) Then MyColor := ColorGrey(64);} {$ENDIF} If (_Down) And (Not Self.IsHighlighted()) Then _Down := False; If (_Dual) And (_Down) Then ID := 1 Else If (_Dual) And (Self._ComponentCount>=3) And (Self.IsHighlighted()) Then ID := 2 Else ID := 0; If (_Base>=0) Then Self.DrawComponent(_Base, VectorZero, 0.0, 0.0, 1.0, 1.0, MyColor, True); Self.DrawComponent(ID, VectorCreate(0.0, 0.0, 0.1), 0.0, 0.0, 1.0, 1.0, MyColor, True); Inherited; End; Function UIIcon.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Var Touched:Boolean; Begin Touched := OnRegion(X,Y); If (Touched) And (Self.Visible) And (Assigned(OnMouseClick)) And (Not Self.HasTweens) Then Begin Self.OnHit(); Result := OnMouseClick(Self); End Else Result := Inherited OnMouseDown(X,Y, Button); _Down := Result; End; Constructor UILabel.Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Caption:TERRAString; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent); Self._TabIndex := TabIndex; Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self._Width := 0; Self._Height := 0; Self.SetCaption(Caption); _NeedsUpdate := True; End; Function UILabel.OnMouseDown(X,Y:Integer;Button:Word):Boolean; Begin If (Assigned(OnMouseClick)) And (OnRegion(X,Y)) And (Not Self.HasTweens) Then Begin Self._HitTime := Application.GetTime(); Self._Hitting := True; Result := True; End Else Result := Inherited OnMouseDown(X,Y, Button); End; Function UILabel.OnMouseUp(X,Y:Integer;Button:Word):Boolean; Begin Result := False; If (_Hitting) Then Begin Result := True; _Hitting := False; If (Application.GetTime - _HitTime > ExtendedPressDuration) And (Assigned(OnExtendedClick)) Then OnExtendedClick(Self) Else OnMouseClick(Self); Self.OnHit(); End; End; (*Function UILabel.OnMouseMove(X,Y:Integer):Boolean; Var Pos:Vector2D; AO, OH:Boolean; Begin Pos := Self.GetPosition; OH := _HighLight; AO := (Assigned(OnMouseClick)); _HighLight := (AO) And (OnRegion(X,Y)) And (Not Self.HasTweens); Result := False; If _HighLight Then Result := True; {$IFDEF IPHONE} If (_Highlight) And (Not OH) And (Not DisableSlideTouch) Then Self.OnMouseDown(X, Y, 99); {$ENDIF} End;*) {Procedure UILabel.Reveal(DurationPerLetter, Delay:Cardinal); Begin Self._RevealTime := Delay + GetTime; If Not Assigned(Self.Font) Then Exit; Self._RevealDuration := Self.Font.GetLength(Caption); Self._RevealDuration := DurationPerLetter * Self._RevealDuration; End;} Procedure UILabel.UpdateRects(); Begin Inherited; _Size := _TextRect; End; Procedure UILabel.Render(); Var S:TERRAString; Time:Cardinal; Delta:Single; Color:TERRA_Color.Color; P:Vector2D; Begin Self.UpdateRects; If (_Caption = '') Then Exit; Self.UpdateTransform(); _Width := Self._TextRect.X; _Height := Self._TextRect.Y; (* {$IFDEF MOBILE} Color := Self.GetColor; {$ELSE} If (Not Assigned(OnMouseClick)) Or (_HighLight) Then Color := Self.GetColor Else Color := ColorGrey(200, Self.Color.A); {$ENDIF}*) If (Not DisableHighlights) Then Self.UpdateHighlight(); Color := Self.GetColor; {Color.R := Self._Color.R; Color.G := Self._Color.G; Color.B := Self._Color.B ;} { If (_RevealTime = 0) Or (Self.Font = Nil) Then RevealCount := 9999 Else Begin Time := GetTime; If (Time<_RevealTime) Then Delta := 0 Else Begin Time := (Time - _RevealTime); Delta := Time / _RevealDuration; If Delta<0 Then Delta := 0.0; End; If (Delta>=1.0) Then Begin _RevealTime := 0; RevealCount := 9999; If Assigned(OnReveal) Then OnReveal(Self); End Else RevealCount := Trunc(Self.Font.GetLength(Caption) * Delta); End;} //RevealCount, {TODO}!!! Self.DrawText(_Caption, VectorZero, Color, Scale); Inherited; End; { UICheckBox } Constructor UICheckBox.Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Caption:TERRAString; Skin:TERRAString; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent); Self._TabIndex := TabIndex; Self.SetCaption(Caption); Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self._Checked := False; If Skin = '' Then Skin := 'ui_checkbox'; Self.LoadComponent(Skin+'_on'); Self.LoadComponent(Skin+'_off'); If (Length(_ComponentList)>0) Then Begin _Width := Self._ComponentList[0].Buffer.Width; _Height := Self._ComponentList[0].Buffer.Height; End; _NeedsUpdate := True; End; Function UICheckBox.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Begin If (OnRegion(X,Y)) And (Not Self.HasTweens) Then Begin SetChecked(Not _Checked); Result := True; End Else Result := Inherited OnMouseDown(X,Y, Button); End; Function UICheckBox.HasMouseOver: Boolean; Begin Result := True; End; Procedure UICheckBox.SetCheckedWithoutPropagation(Value: Boolean); Begin _Checked := Value; End; Procedure UICheckBox.SetChecked(Value:Boolean); Begin If (Value = _Checked) Then Exit; _Checked := Value; If Assigned(_Variable) Then _Variable^ := _Checked; If (Self.Visible) And (Assigned(OnMouseClick)) Then Begin Self.OnHit(); OnMouseClick(Self); End; End; Const CheckBoxPixelOfs = 5; Procedure UICheckBox.UpdateRects(); Begin Inherited; _Size.X := CheckBoxPixelOfs + _Width + _TextRect.X; _Size.Y := FloatMax(_TextRect.Y, _Height); End; Procedure UICheckBox.Render; Var ID:Integer; MyColor:TERRA_Color.Color; Begin Self.UpdateRects(); Self.UpdateTransform(); If (Not DisableHighlights) Then Self.UpdateHighlight(); If Assigned(_Variable) Then _Checked := _Variable^; If (_Checked) Then ID := 0 Else ID := 1; MyColor := Self.Color; Self.DrawComponent(ID, VectorCreate(0.0, 0.0, 0.0), 0.0, 0.0, 1.0, 1.0, MyColor, True); {If (Self.IsHighlighted()) Then S := '\w'+S;} Self.DrawText(_Caption, VectorCreate(_Width + CheckBoxPixelOfs, (_Size.Y - _TextRect.Y) * 0.5, 5.0), GetColor, Scale); Inherited; End; Constructor UIRadioButton.Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Caption:TERRAString; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent, X, Y, Z, Caption); Self.LoadComponent('ui_radiobox_on'); Self.LoadComponent('ui_radiobox_off'); If (Length(_ComponentList)>0) Then Begin _Width := Self._ComponentList[0].Buffer.Width; _Height := Self._ComponentList[0].Buffer.Height; End; _NeedsUpdate := True; End; Function UIRadioButton.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Begin If (OnRegion(X,Y)) And (Not Self.HasTweens) And (Not _Checked) Then Begin SetChecked(True); Result := True; End Else Result := Inherited OnMouseDown(X,Y, Button); End; Procedure UIRadioButton.SetChecked(Value:Boolean); Var I:Integer; W:Widget; RB:UIRadioButton; Begin If (_Checked = Value) Or (Not Value) Then Exit; _Checked := Value; If Assigned(_Variable) Then _Variable^ := _Checked; If (Not Value) Then Exit; If Assigned(OnMouseClick) Then OnMouseClick(Self); If Parent = Nil Then Exit; For I:=0 To Pred(Parent.ChildrenCount) Do Begin W := Widget(Parent.GetChild(I)); If W = Self Then Continue; If (W Is UIRadioButton) Then Begin RB := UIRadioButton(W); If (RB.Group = Self.Group) Then RB._Checked := False; End; End; End; Constructor UISlider.Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent); Self._TabIndex := TabIndex; Self._Value := 0.0; Self._Max := 100; Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self.LoadComponent('ui_slider1'); Self.LoadComponent('ui_slider2'); If (Length(_ComponentList)>0) And (Assigned(_ComponentList[0])) And (Assigned(Self._ComponentList[0].Buffer)) Then Begin _Width := Self._ComponentList[0].Buffer.Width; _Height := Self._ComponentList[0].Buffer.Height; End; If (Length(_ComponentList)>1) And (Assigned(_ComponentList[1])) And (Assigned(Self._ComponentList[1].Buffer)) Then Begin _PickWidth := Self._ComponentList[1].Buffer.Width; _PickHeight := Self._ComponentList[1].Buffer.Height; End; End; Procedure UISlider.UpdateRects(); Begin _Size.X := _Width; _Size.Y := _Height; End; Procedure UISlider.Render(); Var Ofs:Single; MyColor:TERRA_Color.Color; Begin Self.UpdateRects(); Self.UpdateTransform(); If (_Changed) Then Begin _Changed := False; If Assigned(OnChange) Then OnChange(Self); End; MyColor := Self.GetColor(); Self.DrawComponent(0, VectorZero, 0.0, 0.0, 1.0, 1.0, MyColor); Ofs := 1.0 + (_Value/_Max)*(_Width-_PickWidth); Self.DrawComponent(1, VectorCreate(Ofs, -(_PickHeight Shr 1), 1.0), 0.0, 0.0, 1.0 , 1.0, MyColor); Inherited; End; Function UISlider.OnRegion(X,Y:Integer):Boolean; Var Pos:Vector2D; Begin Pos := Self.GetAbsolutePosition(); Result := (_Enabled) And (X>=Pos.X) And (X<=Pos.X+_Width) And (Y>=Pos.Y-16) And (Y<=Pos.Y+16); End; Function UISlider.OnMouseDown(X,Y:Integer;Button:Word):Boolean; Begin If Not Visible Then Begin Result := False; Exit; End; If (Button<>0) And (OnRegion(X,Y)) Then Begin _Dragging := True; Result := True; End Else Result := False; End; Function UISlider.OnMouseUp(X,Y:Integer;Button:Word):Boolean; Begin RemoveHint(X+Y+Button); //TODO - check this stupid hint _Dragging := False; Result := False; End; Function UISlider.OnMouseMove(X,Y:Integer):Boolean; Var Pos:Vector2D; Begin Pos := Self.GetAbsolutePosition(); If (_Dragging) And (X>=Pos.X) And (X<=Pos.X+_Width) And (Y>=Pos.Y-_PickHeight) And (Y<=Pos.Y+_PickHeight) Then Begin _Changed := True; _Value := (((X - Pos.X)/_Width)*_Max); End Else _Dragging := False; Result := False; End; Function UICheckBox.IsSelectable: Boolean; Begin Result := True; End; {UIScrollBar} Constructor UIScrollBar.Create(Name:TERRAString; UI:UI; Parent:Widget; X,Y,Z:Single; Size:Integer; Horizontal:Boolean;TabIndex:Integer); Var S, HandleTex:TERRAString; Begin Inherited Create(Name, UI, Parent); Self._TabIndex := TabIndex; Self._Value := 0.0; Self._Max := 100; Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self._Horizontal := Horizontal; Self._Length := Size; If Horizontal Then S := 'horizontal' Else S := 'vertical'; HandleTex := 'ui_slider_handle_'+S; Self.LoadComponent(HandleTex); Self.LoadComponent('ui_slider_bg_'+S); _Handle := UIScrollBarHandle.Create(Name+'_handle', UI, Self, 0, 0, 1, HandleTex); Self.AddChild(_Handle); If (Length(_ComponentList)>0) And (Assigned(_ComponentList[0])) And (Assigned(Self._ComponentList[0].Buffer)) Then Begin _PickWidth := Self._ComponentList[0].Buffer.Width; _PickHeight := Self._ComponentList[0].Buffer.Height; End; If (Length(_ComponentList)>1) And (Assigned(_ComponentList[1])) And (Assigned(Self._ComponentList[1].Buffer)) Then Begin _BgWidth := Self._ComponentList[1].Buffer.Width; _BgHeight := Self._ComponentList[1].Buffer.Height; End; End; Procedure UIScrollBar.Render; Var Size:Vector2D; I, Height:Integer; Count:Integer; HH:Single; MyColor:TERRA_Color.Color; Begin Self.UpdateRects(); Self.UpdateTransform(); MyColor := Self.GetColor(); If (_Changed) Then _Changed := False; //If (UI.Instance.Dragger = Self) Then MyColor := ColorBlue; If (_Horizontal) Then Begin HH := _BgWidth * 0.25; _HandleOffset.X := -(_PickWidth * 0.5); _HandleOffset.Y := (_BgHeight - _PickHeight) * 0.5; Self.DrawComponent(1, VectorCreate(0, 0, 0), 0.0, 0.0, 0.25, 1.0, MyColor); For I:=0 To Pred(_Length) Do Self.DrawComponent(1, VectorCreate(HH*I, 0, 0), 0.25, 0.0, 0.75, 1.0, MyColor); Self.DrawComponent(1, VectorCreate(Pred(_Length)*HH, 0, 0), 0.75, 0.0, 1.0, 1.0, MyColor); //Self.DrawComponent(0, VectorCreate(_HandleOffset.X + _HandlePos, _HandleOffset.Y, 0.2), 0.0, 0, 1.0, 1.0, MyColor); _Handle._Position.X := _HandleOffset.X + _HandlePos; _Handle._Position.Y := _HandleOffset.Y; End Else Begin HH := _BgHeight * 0.25; _HandleOffset.X := (_BgWidth - _PickWidth) * 0.5; _HandleOffset.Y := -(_PickHeight * 0.5); Self.DrawComponent(1, VectorCreate(0, 0, 0), 0.0, 0.0, 1.0, 0.25, MyColor); For I:=0 To Pred(_Length) Do Self.DrawComponent(1, VectorCreate(0, HH*I, 0), 0.0, 0.25, 1.0, 0.75, MyColor); Self.DrawComponent(1, VectorCreate(0, Pred(_Length)*HH, 0), 0.0, 0.75, 1.0, 1.0, MyColor); //Self.DrawComponent(0, VectorCreate(_HandleOffset.X, _HandleOffset.Y + _HandlePos, 0.2), 0.0, 0, 1.0, 1.0, MyColor); _Handle._Position.X := _HandleOffset.X; _Handle._Position.Y := _HandleOffset.Y + _HandlePos; End; // Ofs := 1.0 + (_Value/_Max)*(_Width-_PickWidth); // Self.DrawComponent(1, VectorCreate(Ofs, -(_PickHeight Shr 1), 1.0), 0.0, 0.0, 1.0 , 1.0); Inherited; End; Procedure UIScrollBar.UpdateRects(); Begin If _Horizontal Then Begin _Size.X := GetLengthInPixels(); _Size.Y := _BgHeight; End Else Begin _Size.X := _BgWidth; _Size.Y := GetLengthInPixels(); End; End; Procedure UIScrollBar.SetLength(const Value: Integer); Begin Self._Length := Value; Self.UpdateRects(); End; {Function UIScrollBar.OnHandleRegion(X, Y: Integer): Boolean; Var Pos:Vector2D; X1,X2,Y1,Y2:Single; Begin Pos := Self.GetAbsolutePosition(); If _Horizontal Then Begin X1 := Pos.X + _HandleOffset.X + _HandlePos; X2 := Pos.X + _HandleOffset.X + _HandlePos + _PickWidth; Y1 := Pos.Y + _HandleOffset.Y; Y2 := Pos.Y + _HandleOffset.Y + _PickHeight; End Else Begin X1 := Pos.X + _HandleOffset.X; X2 := Pos.X + _HandleOffset.X + _PickWidth; Y1 := Pos.Y + _HandleOffset.Y + _HandlePos; Y2 := Pos.Y + _HandleOffset.Y + _HandlePos + _PickHeight; End; Result := (X>=X1) And (X<=X2) And (Y>=Y1) And (Y<=Y2); End;} Function UIScrollBar.GetLengthInPixels: Single; Begin If (_Horizontal) Then Result := _BgWidth * 0.25 * (_Length+2) Else Result := _BgHeight * 0.25 * (_Length+2); End; Procedure UIScrollBar.SetValue(const Value: Single); Begin _Value := Value; If Assigned(OnChange) Then OnChange(Self); End; Procedure UIScrollBar.Slide(Ammount: Single); Begin Value := Value + Ammount; If Value<0 Then Value := 0 Else If (Value>Max) Then Value := Max; If Assigned(OnChange) Then OnChange(Self); End; Procedure UIScrollBar.HandleMove(X, Y: Integer); Var Pos:Vector2D; Begin Pos := Self.GetAbsolutePosition(); If (_Horizontal) Then _HandlePos := X-Pos.X Else _HandlePos := Y-Pos.Y; _Changed := True; If (_HandlePos<0) Then _HandlePos := 0 Else If (_HandlePos>Size.X) And (Self._Horizontal) Then _HandlePos := Size.X Else If (_HandlePos>Size.Y) And (Not Self._Horizontal) Then _HandlePos := Size.Y Else Begin _Value := (_HandlePos/GetLengthInPixels()) * _Max; If Assigned(OnChange) Then OnChange(Self); End; End; { UIScrollBarHandle } Function UIScrollBarHandle.OnMouseDown(X,Y:Integer;Button:Word):Boolean; Begin RemoveHint(Button); //TODO - check this stupid hint Result := False; If Not Visible Then Exit; If OnRegion(X,Y) Then Begin UI.Dragger := Self; Log(logDebug, 'UI', 'Scrollbar handle now dragging'); Result := True; End; End; Function UIScrollBarHandle.OnMouseUp(X,Y:Integer;Button:Word):Boolean; Begin IntToString(X+Y+Button); //TODO - check this stupid hint If (UI.Dragger = Self) Then Begin UI.Dragger := Nil; Log(logDebug, 'UI', 'Scrollbar handle now released'); End; Result := False; End; Function UIScrollBarHandle.OnMouseMove(X,Y:Integer):Boolean; Begin If (UI.Dragger = Self) Then Begin Log(logDebug, 'UI', 'Scrollbar handle now moving'); UIScrollBar(_Parent).HandleMove(X, Y); Self._TransformChanged := True; Result := True; End Else Result := False; End; { UIProgressBar } Constructor UIProgressBar.Create(Name:TERRAString; UI:UI; Parent:Widget; X, Y, Z: Single; Skin:TERRAString; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent); Self._TabIndex := TabIndex; Self._Percent := 0; Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; If Skin = '' Then Skin := 'ui_progressbar'; Self.LoadComponent(Skin); If (Length(_ComponentList)>0) And (Assigned(_ComponentList[0])) And (Assigned(Self._ComponentList[0].Buffer)) Then Begin _Width := Self._ComponentList[0].Buffer.Width; _Height := Self._ComponentList[0].Buffer.Height Div 2; End; End; Function UIProgressBar.CreateCustomTween(TweenType: Integer; TargetValue: Single): Tween; Begin Case TweenType Of wtValue: Result := Tween.Create(Self, tweenFloat, @Self._Percent, TargetValue, Self); Else Result := Nil; End; End; Procedure UIProgressBar.UpdateRects(); Begin _Size.X := _Width; _Size.Y := _Height; End; Procedure UIProgressBar.Render; Var K:Single; MyColor:TERRA_Color.Color; Begin Self.UpdateRects(); Self.UpdateTransform(); MyColor := Self.GetColor; If (_Percent<0) Then _Percent := 0; If (_Percent>100) Then _Percent := 100; K := _Percent/100; If K>0.0 Then Self.DrawComponent(0, VectorCreate(0.0, 0, 0.0), 0.0, 0.0, K, 0.5, MyColor, False); If K<1.0 Then Begin MyColor := ColorGrey(255, MyColor.A); Self.DrawComponent(0, VectorCreate(0.0, -_Height, 0.0), K, 0.5, 1.0, 1.0, MyColor, False); End; Inherited; End; { UIComboBox } Constructor UIComboBox.Create(Name:TERRAString; UI:UI; Parent:Widget; X, Y, Z: Single; Width:Integer; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent); Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self._TabIndex := TabIndex; Self._Width := Width; Self.LoadComponent('ui_combobox'); Self.LoadComponent('ui_combobox2'); Self.LoadComponent('ui_list'); Self._ItemHighlight := -1; Self._Content := Nil; If (Length(_ComponentList)>0) Then Begin _BarWidth := _ComponentList[0].Buffer.Width; _BarSlices := Trunc(_BarWidth*0.5); End; If (Length(_ComponentList)>1) Then Begin _HandlePos := Trunc(_Width*_BarSlices + _BarSlices * 0.5); _HandleWidth := _ComponentList[1].Buffer.Width; _HandleHeight := _ComponentList[1].Buffer.Height; End; If (Length(_ComponentList)>2) Then Begin _ListWidth := _ComponentList[2].Buffer.Width; _ListHeight := _ComponentList[2].Buffer.Height; _ListSlicesX := Trunc(_ListWidth*0.5); _ListSlicesY := Trunc(_ListHeight*0.5); End; End; Procedure UIComboBox.SetContent(Content:List); Begin _Content := Content; _ItemIndex := 0; _Selected := Nil; _ItemHighlight := -1; End; Function UIComboBox.GetItem(Index: Integer):CollectionObject; Begin If (_Content<>Nil) And (Index>=0) And (Index<_Content.Count) Then Result := _Content.GetItemByIndex(Index) Else Result := Nil; End; Procedure UIComboBox.SetItemIndex(Const Value:Integer); Begin _ItemIndex := Value; _Selected := _Content.GetItemByIndex(Value); End; Function UIComboBox.GetItemAtIndex(X,Y:Integer):Integer; Var Pos:Vector2D; I,HH:Integer; X1,X2,Y1,Y2:Integer; Begin Result := -1; Pos := Self.GetAbsolutePosition(); X1 := Trunc(Pos.X + _ListWidth*0.25); X2 := Trunc(Pos.X+Succ(_Width)*_BarSlices); If (Assigned(_Content)) Then For I:=0 To Pred(_Content.Count) Do Begin HH := Trunc(_HandleHeight + _ListHeight * 0.25 + 8+_ListSlicesY*I); Y1 := Trunc(Pos.Y+HH); Y2 := Trunc(Pos.Y+HH+_ListHeight*0.25); If (X>=X1) And (X<=X2) And (Y>=Y1) And (Y<=Y2) Then Begin Result := I; Exit; End; End; End; Function UIComboBox.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Var Pos:Vector2D; CurrentHeight:Single; Begin Result := False; RemoveHint(Button); //TODO - check this stupid hint If Not Visible Then Exit; Pos := Self.GetAbsolutePosition(); If (_ItemHighlight < 0) And (_ShowList) Then _ItemHighlight := Self.GetItemAtIndex(X,Y); CurrentHeight := _HandleHeight; If (Self._ShowList) And (Assigned(_Content)) Then CurrentHeight := CurrentHeight + _ListHeight * 0.5 + _ListSlicesY * _Content.Count; If (_ItemHighlight>=0) Then Begin SetItemIndex(_ItemHighlight); _ItemHighlight := -1; _ShowList := False; UI.Focus := Nil; If (Assigned(OnMouseClick)) Then Result := OnMouseClick(Self) Else Result := True; End Else If (X>=Pos.X+_HandlePos) And (X<=Pos.X+_HandlePos+_HandleWidth) And (Y>=Pos.Y) And (Y<=Pos.Y+_HandleHeight) And (Not ShowLabelOnly) Then Begin _ShowList := Not _ShowList; Result := True; If (_ShowList) Then UI.Focus := Self; End Else If (X>=Pos.X) And (X<=Pos.X+_HandlePos+_HandleWidth) And (Y>=Pos.Y) And (Y<=Pos.Y+CurrentHeight) Then Begin Result := True; End; End; Function UIComboBox.OnMouseMove(X, Y: Integer): Boolean; Begin Result := False; _ItemHighLight := -1; If Not _ShowList Then Exit; _ItemHighLight := Self.GetItemAtIndex(X,Y); End; Procedure UIComboBox.Render; Var LW,YY:Integer; I,J:Integer; MyColor:TERRA_Color.Color; P:CollectionObject; ZOfs:Single; S:TERRAString; Begin Self.UpdateRects(); Self.UpdateTransform(); If (_ItemIndex<0) Or (_Content = Nil) Then Exit; If (Not ShowLabelOnly) Then Begin Self.DrawComponent(0, VectorCreate(0, 0, 0), 0.0, 0.0, 1.0/4, 1.0, ColorWhite); For J:=0 To Pred(_Width) Do Begin Self.DrawComponent(0, VectorCreate(J*_BarSlices, 0, 0.0), 0.25, 0.0, 0.75, 1.0, ColorWhite); End; Self.DrawComponent(0, VectorCreate(-_BarWidth*0.75 + _Width *_BarSlices, 0, 0.0), 0.75, 0.0, 1.0, 1.0, ColorWhite); End; Self.DrawComponent(1, VectorCreate(_HandlePos, 0, 0.0), 0.0, 0.0, 1.0, 1.0, ColorWhite); If (_Selected<>Nil) And (Assigned(Self.Font)) Then Begin S := _Selected.ToString(); If (S<>'') And (S[1]='#') Then S := LocalizationManager.Instance.GetString(Copy(S, 2, MaxInt)); Self.DrawText(S, VectorCreate(5, 5, 2.0), Self.Color, Scale); End; If (_ShowList) And (UI.Focus<>Self) Then _Showlist := False; I := 0; LW := 0; While (I<_BarSlices*Pred(_Width)) Do Begin Inc(LW); Inc(I, _ListSlicesX); End; IntToString(LW+I); If (_ShowList) Then Begin ZOfs := 8; Self.DrawComponent(2, VectorCreate(0.0, _HandleHeight, ZOfs), 0.0, 0.0, 0.25, 0.25, ColorWhite); For I:=0 To LW Do Self.DrawComponent(2, VectorCreate(I*_ListSlicesX, _HandleHeight, ZOfs), 0.25, 0.0, 0.75, 0.25, ColorWhite); Self.DrawComponent(2, VectorCreate(LW*Pred(_ListSlicesX), _HandleHeight, ZOfs), 0.75, 0.0, 1.0, 0.25, ColorWhite); P := _Content.First; For J:=0 To Pred(_Content.Count) Do Begin YY := _HandleHeight+_ListSlicesY*J; Self.DrawComponent(2, VectorCreate(0.0, YY, ZOfs), 0.0, 0.25 , 0.25, 0.75, ColorWhite); For I:=0 To LW Do Self.DrawComponent(2, VectorCreate(I*_ListSlicesX, YY, ZOfs), 0.25, 0.25 , 0.75, 0.75, ColorWhite); Self.DrawComponent(2, VectorCreate(LW*Pred(_ListSlicesX), YY, ZOfs), 0.75, 0.25 , 1.0, 0.75, ColorWhite); {$IFNDEF MOBILE} If (J<>_ItemHighlight) Then MyColor := ColorGrey(64, Self.Color.A) Else {$ENDIF} MyColor := Self.Color; If Assigned(Self.Font) Then Begin S := P.ToString(); If (S<>'') And (S[1]='#') Then S := LocalizationManager.Instance.GetString(Copy(S, 2, MaxInt)); Self.DrawText(S, VectorCreate(_ListWidth*0.25, _HandleHeight + _ListHeight * 0.25 + 8+_ListSlicesY*J, ZOfs + 0.5), MyColor, Scale); End; P := P.Next; End; YY := _HandleHeight+_ListSlicesY*Pred(_Content.Count); Self.DrawComponent(2, VectorCreate(0.0, YY, ZOfs), 0.0, 0.75, 0.25, 1.0, ColorWhite); For I:=0 To LW Do Self.DrawComponent(2, VectorCreate(I*_ListSlicesX, YY, ZOfs), 0.25, 0.75, 0.75, 1.0, ColorWhite); Self.DrawComponent(2, VectorCreate(LW*Pred(_ListSlicesX), YY, ZOfs), 0.75, 0.75, 1.0, 1.0, ColorWhite); End; Inherited; End; Procedure UIComboBox.UpdateRects(); Begin _Size.X := _HandlePos+_HandleWidth; _Size.Y := Self._HandleHeight; End; Procedure UIComboBox.Select(const Value: TERRAString); Var P:CollectionObject; I:Integer; Begin I := 0; P := _Content.First; While Assigned(P) Do If (P.ToString() = Value) Then Begin SetItemIndex(I); Exit; End Else Begin Inc(I); P := P.Next; End; End; { UIEditText } Constructor UIEditText.Create(Name:TERRAString; UI:UI; Parent:Widget; X, Y, Z: Single; Width:Integer; Skin:TERRAString; TabIndex:Integer); Begin Inherited Create(Name, UI, Parent); Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; If Skin = '' Then Skin := 'ui_edit'; Self._TabIndex := TabIndex; Self.LoadComponent(Skin); Self.LoadComponent(Skin+'2'); Self.Text := ''; Self._Width := Width; Self.SetLineCount(1); Self._LineIndex := 0; Self._MaxLines := 0; Self._SelectedColor := ColorWhite; Self.PasswordField := False; Self.TextColor := ColorWhite; Self._KoreanInitialJamo := -1; Self._KoreanMedialJamo := -1; Self._KoreanFinalJamo := -1; If (Length(_ComponentList)>0) Then Begin _Height := Self._ComponentList[0].Buffer.Height; End; End; Procedure UIEditText.SetLineCount(const Value: Integer); Begin If (LineCount = Value) Then Exit; _LineCount := Value; _MaxLines := 1; SetLength(_Lines, _LineCount); Self.UpdateRects(); {If (LineCount>1) And (_HorScroll=Nil) Then Begin _HorScroll := UIScrollBar.Create(Name+'_horizontal_scroll', UI, Self, 0, 5, 1, 1, True); _HorScroll.Align := waBottomCenter; Repeat _HorScroll._Length := _HorScroll._Length + 1; _HorScroll.UpdateRects(); Until (_HorScroll.Size.X>=Self.Size.X - 100); End; If (LineCount>1) And (_VertScroll=Nil) Then Begin _VertScroll := UIScrollBar.Create(Name+'_vertical_scroll', UI, Self, 5, 0, 1, 1, False); _VertScroll.Align := waRightCenter; Repeat _VertScroll._Length := _VertScroll._Length + 1; _VertScroll.UpdateRects(); Until (_VertScroll.Size.Y>=Self.Size.Y - _Height); End;} End; Procedure UIEditText.UpdateRects(); Begin If (_ComponentList=Nil) Or (Self._ComponentList[0]=Nil) Then Exit; _Size.X := (Self._ComponentList[0].Buffer.Width/2)+(Self._ComponentList[0].Buffer.Width/4)*(Self._Width); _Size.Y := _LineCount * _Height; End; Procedure UIEditText.SetFocus(ShowKeyboard:Boolean); Begin UI.Focus := Self; If Not ShowKeyboard Then Exit; {$IFDEF MOBILE} {$IFDEF VIRTUALKEYBOARD} If (Not UseNativeKeyboard) Then VirtualKeyboard(UI.VirtualKeyboard).ShowFocus() Else {$ENDIF} // focusKeyboard(PAnsiChar(Self.Text)); {$ELSE} {$IFDEF VIRTUALKEYBOARD} VirtualKeyboard(UI.VirtualKeyboard).ShowFocus(); {$ENDIF} {$ENDIF} End; Function UIEditText.OnMouseUp(X, Y: Integer; Button: Word): Boolean; Begin RemoveHint(X+Y+Button); //TODO - check this stupid hint {If (Assigned(Self._HorScroll)) And (_HorScroll.OnRegion(X,Y)) Then Begin Result := _HorScroll.OnMouseUp(X, Y, Button); Exit; End; If (Assigned(Self._VertScroll)) And (_VertScroll.OnRegion(X,Y)) Then Begin Result := _VertScroll.OnMouseUp(X, Y, Button); Exit; End;} Result := False; End; Function UIEditText.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Var I:Integer; Begin Result := False; If Not Visible Then Exit; RemoveHint(Button); //TODO - check this stupid hint {If (Assigned(Self._HorScroll)) And (_HorScroll.OnRegion(X,Y)) Then Begin Result := _HorScroll.OnMouseDown(X, Y, Button); Exit; End; If (Assigned(Self._VertScroll)) And (_VertScroll.OnRegion(X,Y)) Then Begin Result := _VertScroll.OnMouseDown(X, Y, Button); Exit; End;} //Pos := Self.GetAbsolutePosition(); If (OnRegion(X,Y)) Then Begin SetFocus(True); Result := True; End; End; Function UIEditText.UpdateTransform:Boolean; Var P:Vector2D; Begin Result := Inherited UpdateTransform; If Not Result Then Exit; P := Self.GetAbsolutePosition(); _Clip.X := P.X; _Clip.Y := P.Y; _Clip.Width := Size.X; _Clip.Height := Size.Y; // _Clip.Name := Self.Name; _Clip.Transform(Self.UI.Transform); Self._ClipRect := _Clip; End; Procedure UIEditText.Render; Var I,J,N, Count:Integer; A,B,X:Single; MyColor:TERRA_Color.Color; S:TERRAString; P, Tx:Vector2D; Begin Self.UpdateRects(); Self.UpdateTransform(); P := Self.GetAbsolutePosition(); {If (UI.Highlight<>Nil) And (Not Self.IsHighlighted()) And (UI.Focus=Self) And (Pos('KEY_', UI.Highlight.Name)<>1) Then UI.Focus := Nil;} Self.UpdateHighlight((UI.Focus = Self)); If (UI.Focus <> Self) And (Self.IsHighlighted()) Then Self.SetFocus(False); MyColor := ColorMultiply(Self.GetColor(), _SelectedColor); TextColor.A := MyColor.A; For J:=1 To _LineCount Do Begin If (_LineCount<=1) Then N := 0 Else N := 1; Self.DrawComponent(N, VectorCreate(0, _Height * Pred(J), 0), 0.0, 0.0, 1.0/4, 1.0, MyColor, False); For I:=1 To _Width Do Begin If (Odd(I)) Then Self.DrawComponent(N, VectorCreate(-32+I*32, _Height * Pred(J), 0.0), 0.25, 0.0, 0.5, 1.0, MyColor, False) Else Self.DrawComponent(N, VectorCreate(-64+I*32, _Height * Pred(J), 0.0), 0.5, 0.0, 0.75, 1.0, MyColor, False); End; Self.DrawComponent(N, VectorCreate(-96+Succ(_Width)*32, _Height * Pred(J), 0.0), 0.75, 0.0, 1.0, 1.0, MyColor, False); End; Count := 0; For J:=0 To Pred(_LineCount) Do If (_Lines[J]<>'') Then Begin Inc(Count); If PasswordField Then Begin SetLength(S, StringLength(_Lines[J])); For I:=1 To Length(S) Do S[I] := '*'; End Else S := _Lines[J]; Tx := _FontRenderer.GetTextRect(S, 1.0); Tx.Y := _FontRenderer.GetTextHeight('W', 1.0); If (UI.Focus = Self) And (J=_LineIndex) And (Blink(200)) Then S := S +'_'; If (Centered) Then X := (Self.Size.X-Tx.X)*0.5 Else X := 10; Self.DrawText(S, VectorCreate(X-_ScrollIndex, _Height * J + (_Height-Tx.Y)*0.5, 1.0), ColorScale(Self.TextColor, 0.75), Scale); End; If (Caption<>'') And (Count = 0) Then Begin Tx := _FontRenderer.GetTextRect(Caption, 1.0); If (Centered) Then X := (Self.Size.X-Tx.X)*0.5 Else X := 10; Self.DrawText(Caption, VectorCreate(X, (Self.Size.Y-Tx.Y)*0.5, 1.0), ColorScale(Self.TextColor, 0.75), Scale); End; Inherited; End; Procedure UIEditText.UpdateJamos; Var Jamo:Word; N:Integer; Begin Delete(_Lines[_LineIndex], Length(_Lines[_LineIndex])-2, 3); If (_KoreanMedialJamo>=0) Then Begin If (_KoreanFinalJamo>=0) Then N := _KoreanFinalJamo Else N := 0; Jamo := (_KoreanInitialJamo*588)+(_KoreanMedialJamo*28)+N+44032; End Else Jamo := _KoreanBaseJamo; StringAppendChar(_Lines[_LineIndex], Jamo); End; Function UIEditText.OnKeyPress(Key:Word): Boolean; Var I, Len:Integer; //KeyValue:TERRAString; W,W2:Single; ChangedLine, Found:Boolean; It:Iterator; Wd:Widget; Begin If (Not Self.Visible) Or (Self.HasTweens()) Then Begin Result := False; Exit; End; If (Key = keyShift) Or (Key = keyControl) Or (Key = keyAlt) Then Begin Result := False; Exit; End; {$IFDEF DEBUG_CORE}Log(logDebug, 'UI', 'EditText: Got key : '+IntToString(Key));{$ENDIF} {$IFDEF DEBUG_CORE}Log(logDebug, 'UI', 'Backspace Is '+IntToString(keyBackspace));{$ENDIF} ChangedLine := False; If (Key = keyBackspace) Then Begin W := _FontRenderer.GetTextWidth(_Lines[_LineIndex]); If (_KoreanFinalJamo>=0) Then Begin _KoreanFinalJamo := -1; UpdateJamos(); End Else If (_KoreanMedialJamo>=0) Then Begin _KoreanMedialJamo := -1; UpdateJamos(); End Else Begin _KoreanInitialJamo := -1; Len := StringLength(_Lines[_LineIndex]); // check for font control chars/effects If (Len>=2) And (StringGetChar(_Lines[_LineIndex], -1) = Ord('\')) Then Begin StringDropChars(_Lines[_LineIndex], -2); End Else If (_Lines[_LineIndex]<>'') Then Begin I := Len; If (StringLastChar(_Lines[_LineIndex]) = Ord('}')) Then Begin While (I>=1) Do If (StringGetChar(_Lines[_LineIndex], I) = Ord('\')) Then Break Else Dec(I); If (I>0) Then _Lines[_LineIndex] := StringCopy(_Lines[_LineIndex], 1, Pred(I)) Else _Lines[_LineIndex] := StringCopy(_Lines[_LineIndex], 1, Pred(Len)); End Else _Lines[_LineIndex] := StringCopy(_Lines[_LineIndex], 1, Pred(Len)); End Else If (_LineCount>1) And (_LineIndex>0) Then Begin Dec(_LineIndex); ChangedLine := True; W := _FontRenderer.GetTextWidth(_Lines[_LineIndex]); If (W>_Width*32) Then _ScrollIndex := W - (_Width*32) Else _ScrollIndex := 0; End; End; W2 := _FontRenderer.GetTextWidth(_Lines[_LineIndex]); If (Not ChangedLine) And (_ScrollIndex>0) And (W2<W) Then _ScrollIndex := _ScrollIndex - (W-W2); End Else If (Key = keyEnter) Then Begin If (_LineCount>1) And (_LineIndex<Pred(_LineCount)) Then Begin Inc(_LineIndex); _ScrollIndex := 0; _MaxLines := _LineIndex; End; If Assigned(OnEnter) Then OnEnter(Self); End Else If (Key = keyTab) Then Begin Found := False; It := UI.Widgets.GetIterator(); While It.HasNext Do Begin Wd := Widget(It.Value); If (Wd.Visible) And (Wd<>Self) And (Wd Is UIEditText) And (WD.Position.Y>Self.Position.Y) Then Begin UIEditText(Wd).SetFocus(True); Found := True; Break; End; End; ReleaseObject(It); If Not Found Then Begin It := UI.Widgets.GetIterator(); While It.HasNext Do Begin Wd := Widget(It.Value); If (Wd.Visible) And (Wd<>Self) And (Wd Is UIEditText) And (WD.Position.Y<=Self.Position.Y) Then Begin UIEditText(Wd).SetFocus(True); Found := True; Break; End; End; ReleaseObject(It); End; End Else Begin //KeyValue := UnicodeToUCS2(Key); If (Assigned(Self.Font)) Then Begin W := _FontRenderer.GetTextWidth(_Lines[_LineIndex]); If (_KoreanInitialJamo<0) Or (_KoreanFinalJamo>=0) Then Begin _KoreanInitialJamo := GetKoreanInitialJamo(Key); _KoreanMedialJamo := -1; _KoreanFinalJamo := -1; _KoreanBaseJamo := Key; StringAppendChar(_Lines[_LineIndex], Key); End Else If (_KoreanMedialJamo<0) And (_KoreanFinalJamo<0) Then Begin _KoreanMedialJamo := GetKoreanMedialJamo(Key); If _KoreanMedialJamo<0 Then Begin _KoreanInitialJamo := GetKoreanInitialJamo(Key); StringAppendChar(_Lines[_LineIndex], Key); End Else UpdateJamos(); End Else If (_KoreanFinalJamo<0) Then Begin _KoreanFinalJamo := GetKoreanFinalJamo(Key); If (_KoreanFinalJamo<0) Then Begin _KoreanInitialJamo := GetKoreanInitialJamo(Key); _KoreanMedialJamo := -1; StringAppendChar(_Lines[_LineIndex], Key); End Else UpdateJamos(); End Else Begin StringAppendChar(_Lines[_LineIndex], Key); End; W2 := _FontRenderer.GetTextWidth(_Lines[_LineIndex]); If (W2>_Width*32) And (W2>W) Then _ScrollIndex := _ScrollIndex + (W2-W); End; End; If (Assigned(OnChange)) And (Not _InsideEvent) Then Begin _InsideEvent := True; OnChange(Self); _InsideEvent := False; End; Result := True; End; Procedure UISlider.SetValue(X: Single); Begin _Changed := (_Value <> X); _Value := X; End; Procedure UIEditText.SetText(const Value:TERRAString); Begin Self._KoreanInitialJamo := -1; Self._KoreanMedialJamo := -1; Self._KoreanFinalJamo := -1; If (_LineCount<1) Then SetLineCount(1); Self._ScrollIndex := 0; Self._LineIndex := 0; Self.SetCurrentLine(Value); End; Function UIEditText.GetText:TERRAString; Var I:Integer; Begin If (_LineCount=1) Then Result := _Lines[0] Else Begin Result := ''; For I:=0 To _LineIndex Do Begin Result := Result + _Lines[I]; If (I<_LineIndex) Then Result := Result + '\n'; End; End; End; Function UIEditText.GetCurrentLine:TERRAString; Begin Result := _Lines[_LineIndex]; End; Procedure UIEditText.SetCurrentLine(const Value:TERRAString); Begin _Lines[_LineIndex] := ConvertFontCodes(Value); If (Assigned(OnChange)) And (Not _InsideEvent) Then Begin _InsideEvent := True; OnChange(Self); _InsideEvent := False; End; End; Procedure UIEditText.StartHighlight; Begin _SelectedColor := ColorBlack; End; Procedure UIEditText.StopHighlight; Begin _SelectedColor := ColorWhite; End; Function UIEditText.IsSelectable: Boolean; Begin Result := True; End; { UILayout } Constructor UILayout.Create(Name:TERRAString; UI:UI; X,Y,Z:Single; Width,Height, LayoutMode:Integer; TabIndex:Integer=-1); Begin Inherited Create(Name, UI, Parent); RemoveHint(LayoutMode); Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self._TabIndex := TabIndex; Self._Width := Width; Self._Height := Height; Self.VerticalSpacing := 10; Self.HorizontalSpacing := 10; End; {Procedure UILayout.Render; Var Pos, Size:Vector2D; X,Y, Max:Single; I:Integer; Begin Pos := Self.GetPosition; X := 0; Y := 0; Max := 0; For I:=0 To Pred(_ChildrenCount) Do Begin _ChildrenList[I].Align := waTopLeft; _ChildrenList[I].Position := VectorCreate2D(X, Y); _ChildrenList[I].Render; Size := _ChildrenList[I].Size; Case LayoutMode Of layoutHorizontal: Begin If (Size.Y>Max) Then Max := Size.Y; X := X + Size.X + HorizontalSpacing; If (X>=Width) Then Begin X := 0; Y := Y + Max + VerticalSpacing; Max := 0; End; End; layoutVertical: Begin If (Size.X>Max) Then Max := Size.X; Y := Y + Size.Y + VerticalSpacing; If (X>=Width) Then Begin Y := 0; X := X + Max + HorizontalSpacing; Max := 0; End; End; End; End; End;} Procedure UILayout.Render; Var Size:Vector2D; X,Y, Padding, Max:Single; I:Integer; W:Widget; Begin _Size.X := _Width; _Size.Y := _Height; Self.UpdateRects(); Self.UpdateTransform(); Case LayoutMode Of layoutHorizontal: Max := HorizontalSpacing; layoutVertical: Max := VerticalSpacing; End; Max := 0.0; For I:=0 To Pred(Self.ChildrenCount) Do Begin W := Self.GetChild(I); If (W=Nil) Or (Not W.Visible) Then Continue; W.UpdateRects(); Case LayoutMode Of layoutHorizontal: Max := Max + W.Size.X + HorizontalSpacing; layoutVertical: Max := Max + W.Size.Y + VerticalSpacing; End; End; Padding := 0.0; Case LayoutMode Of layoutHorizontal: Padding := Width - Max; layoutVertical: Padding := Height - Max; End; If (Padding<0) Then Padding := 0; Padding := Padding * 0.5; X := 0; Y := 0; Case LayoutMode Of layoutHorizontal: Begin X := Padding; Y := 0; End; layoutVertical: Begin X := 0; Y := Padding; End; End; For I:=0 To Pred(Self.ChildrenCount) Do Begin W := Self.GetChild(I); If (W=Nil) Or (Not W.Visible) Then Continue; W.Align := waTopLeft; W.Position := VectorCreate2D(X, Y); W.Render(); Size := W.Size; Case LayoutMode Of layoutHorizontal: Begin If (Size.Y>Max) Then Max := Size.Y; X := X + Size.X + HorizontalSpacing; If (X>=Width) Then Begin X := Padding; Y := Y + Max + VerticalSpacing; Max := 0; End; End; layoutVertical: Begin If (Size.X>Max) Then Max := Size.X; Y := Y + Size.Y + VerticalSpacing; If (X>=Width) Then Begin Y := Padding; X := X + Max + HorizontalSpacing; Max := 0; End; End; End; End; Inherited; End; { UISprite } Constructor UISprite.Create(Name:TERRAString; UI:UI; Parent:Widget; X, Y, Z: Single; Picture:TERRAString; TabIndex: Integer); Begin Inherited Create(Name, UI, Parent); Self._TabIndex := TabIndex; Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self.Filter := filterLinear; Self.Rect.U1 := 0; Self.Rect.U2 := 1.0; Self.Rect.V1 := 0; Self.Rect.V2 := 1.0; If (Picture<>'') Then Begin Self.Texture := TextureManager.Instance.GetTexture(Picture); If (Assigned(Self.Texture)) Then Self.Texture.PreserveQuality := True Else Log(logWarning, 'UI', 'Missing texture for SpriteWidget: '+Picture); End Else Self.Texture := Nil; Self.Pivot := VectorCreate2D(0, 0); Self.Anchor := VectorCreate2D(0, 0); End; Function UISprite.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Var Pos:Vector2D; Begin Result := Inherited OnMouseDown(X,Y, Button); If (OnRegion(X,Y)) And (Assigned(OnMouseClick)) And (Self.Visible) And (Not Self.HasTweens) Then Begin Self.OnHit(); Result := OnMouseClick(Self); End; End; Function UISprite.OnMouseUp(X, Y: Integer; Button: Word): Boolean; Var Pos:Vector2D; Begin RemoveHint(Button); If (OnRegion(X,Y)) And (Self.Visible) And (Assigned(OnMouseClick)) Then Begin Result := True; End Else Result := False; End; {Function UISprite.OnRegion(X, Y: Integer): Boolean; Var WH, Pos:Vector2d; OfsX, OfsY:Single; Begin If (OutsideClipRect(X,Y)) Then Begin Result := False; Exit; End; Pos := Self.GetAbsolutePosition; Self.GetScrollOffset(OfsX, OfsY); Pos.X := Pos.X + OfsX; Pos.Y := Pos.Y + OfsY; WH := Self.Size; Result := (X>=Pos.X) And (Y>=Pos.Y) And (X<=Pos.X+WH.X*Scale) And (Y<=Pos.Y+WH.Y*Scale); End;} Procedure UISprite.Render; Var ID:Integer; MyColor:TERRA_Color.Color; S:QuadSprite; Temp, Pos, Center, TC1, TC2:Vector2D; OfsX, OfsY:Single; Begin Self.UpdateRects(); Self.UpdateTransform(); If (Not DisableHighlights) And (Assigned(Self.OnMouseClick)) Then Self.UpdateHighlight(); MyColor := Self.Color; {$IFDEF OUYA} If (UI.Highlight<>Nil) And (Not Self.IsHighlighted) And (Assigned(Self.OnMouseClick)) Then MyColor := ColorGrey(64); {$ENDIF} If Self.Texture=Nil Then Exit; Self.GetScrollOffset(OfsX, OfsY); If (OfsX<>0) Or (OfsY<>0) Then Begin Temp := _Position; _Position.X := _Position.X + OfsX; _Position.Y := _Position.Y + OfsY; Self._TransformChanged := True; Self.UpdateTransform(); Pos := Self.GetAbsolutePosition(); _Position := Temp; End Else Pos := Self.GetAbsolutePosition(); If (Pos.X>UIManager.Instance.Width) Or (Pos.Y>UIManager.Instance.Height) Or (Pos.X<-Size.X) Or (Pos.Y<-Size.Y) Then Exit; Center := Self.GetSize(); Center.X := Center.X * _Pivot.X * Scale; Center.Y := Center.Y * _Pivot.Y * Scale; Center.Add(Pos); S := SpriteManager.Instance.DrawSprite(Pos.X, Pos.Y, Self.GetLayer(), Self.Texture, Nil, BlendBlend, Self.GetSaturation(), Filter); S.Anchor := Anchor; S.SetColor(MyColor); S.Rect := Rect; S.SetTransform(_Transform); S.Flip := Self.Flip; S.ClipRect := Self.GetClipRect(); S.Mirror := Self.Mirror; Inherited; End; Procedure UISprite.SetTexture(Tex: Texture); Begin Self._Texture := Tex; If Tex = Nil Then Exit; Self.Rect.Width := Tex.Width; Self.Rect.Height := Tex.Height; Self.Rect.U1 := 0.0; Self.Rect.V1 := 0.0; Self.Rect.U2 := 1.0; Self.Rect.V2 := 1.0; End; Procedure UISprite.UpdateRects(); Begin If Assigned(_Texture) Then Begin _Texture.Prefetch(); If (Rect.Width<=0) Then Rect.Width := Trunc(SafeDiv(_Texture.Width, _Texture.Ratio.X)); If (Rect.Height<=0) Then Rect.Height := Trunc(SafeDiv(_Texture.Height, _Texture.Ratio.Y)); End; _Size.X := Rect.Width; _Size.Y := Rect.Height; End; { UITooltip } Constructor UITooltip.Create(Name: TERRAString; UI: UI; Parent: Widget; X, Y, Z: Single; Caption, Skin:TERRAString); Begin Inherited Create(Name, UI, Parent); Self._TabIndex := -1; Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self._Width := 0; Self._Height := 0; Self.SetCaption(Caption); _NeedsUpdate := True; If Skin = '' Then Skin := 'ui_tooltip'; Self.LoadComponent(Skin); If (Length(_ComponentList)>0) Then Begin _Width := Self._ComponentList[0].Buffer.Width; _Height := Self._ComponentList[0].Buffer.Height; End; End; Procedure UITooltip.Render; Var I:Integer; MyColor:TERRA_Color.Color; TX, TY:Single; Begin MyColor := Self.GetColor(); Self.DrawComponent(0, VectorZero, 0.0, 0.0, 0.25, 1.0, MyColor); For I:=1 To _Sections Do Self.DrawComponent(0, VectorCreate(_Width*0.25*I, 0, 0), 0.25, 0.0, 0.75, 1.0, MyColor); Self.DrawComponent(0, VectorCreate(_Width*0.25*Succ(_Sections), 0, 0), 0.75, 0.0, 1.0, 1.0, MyColor); TX := (Self._Size.X - _TextRect.X) * 0.5; TY := (Self._Size.Y - _TextRect.Y) * 0.5; Self.DrawText(_Caption, VectorCreate(TX, TY, 0.25), MyColor, 1.0); End; Procedure UITooltip.UpdateRects; Begin _Size.X := Succ(_Sections) * _Width * 0.5; _Size.Y := _Height; End; { UITabList } Constructor UITabList.Create(Name: TERRAString; UI: UI; Parent: Widget; X, Y, Z: Single; ComponentBG: TERRAString); Begin Inherited Create(Name, UI, Parent); Self.SetPosition(VectorCreate2D(X,Y)); Self._Layer := Z; Self._TabIndex := -1; {Self._Width := Width; Self._Height := Height;} If (ComponentBG='') Then ComponentBG := 'ui_tab'; Self.LoadComponent(ComponentBG+'_on'); Self.LoadComponent(ComponentBG+'_off'); If Assigned(Parent) Then Parent.TabControl := Self; If (Length(_ComponentList)>0) Then Begin _TabWidthOn := Self._ComponentList[0].Buffer.Width; _TabHeightOn := Self._ComponentList[0].Buffer.Height; End; If (Length(_ComponentList)>1) Then Begin _TabWidthOff := Self._ComponentList[1].Buffer.Width; _TabHeightOff := Self._ComponentList[1].Buffer.Height; End; Self.ClearTabs(); Self.UpdateRects(); End; Procedure UITabList.ClearTabs; Begin _TabCount := 0; _SelectedIndex := -1; _TabHighlight := -1; End; Procedure UITabList.AddTab(Name: TERRAString; Index: Integer); Var I:Integer; Begin For I:=0 To Pred(_TabCount) Do If (_Tabs[I].Index = Index) Then Begin _Tabs[I].Name := Name; Exit; End; Inc(_TabCount); SetLength(_Tabs, _TabCount); _Tabs[Pred(_TabCount)].Name := Name; _Tabs[Pred(_TabCount)].Index := Index; _Tabs[Pred(_TabCount)].Visible := True; _Tabs[Pred(_TabCount)].Caption := GetLocalizedString(Name); If _SelectedIndex<0 Then SetSelectedIndex(Pred(_TabCount)); End; Procedure UITabList.SetTabVisibility(Index: Integer; Visibility: Boolean); Var I,J:Integer; Begin For I:=0 To Pred(_TabCount) Do If (_Tabs[I].Index = Index) Then Begin _Tabs[I].Visible := Visibility; If (Not Visibility) And (_SelectedIndex = Index) Then Begin For J:=0 To Pred(_TabCount) Do If (_Tabs[J].Visible) Then Begin _SelectedIndex := J; Break; End; End; Exit; End; End; Procedure UITabList.UpdateRects; Begin _Size.X := _TabWidthOff * Pred(_TabCount) + _TabWidthOn; _Size.Y := FloatMax(_TabHeightOn, _TabHeightOff); End; Function UITabList.GetTabAt(X, Y: Integer): Integer; Var I:Integer; TX,WW:Single; Begin TX := 0; For I:=0 To Pred(_TabCount) Do If (_Tabs[I].Visible) Then Begin If (_Tabs[I].Index = Self._SelectedIndex) Or (_Tabs[I].Index = _TabHighlight) Then WW := _TabWidthOn Else WW := _TabWidthOff; If (Self.OnCustomRegion(X, Y, TX, 0, TX+WW, _TabHeightOn)) Then Begin Result := _Tabs[I].Index; Exit; End; TX := TX + WW; End; Result := -1; End; Procedure UITabList.SetSelectedCaption(const Value: TERRAString); Var I:Integer; Begin For I:=0 To Pred(_TabCount) Do If (_Tabs[I].Index = Self._SelectedIndex) Then Begin _Tabs[I].Caption := Value; Exit; End; End; Function UITabList.GetSelectedCaption: TERRAString; Var I:Integer; Begin For I:=0 To Pred(_TabCount) Do If (_Tabs[I].Index = Self._SelectedIndex) Then Begin Result := _Tabs[I].Caption; Exit; End; Result := ''; End; Procedure UITabList.Render; Var I:Integer; MyColor:TERRA_Color.Color; Fnt:TERRA_Font.Font; Rect:Vector2D; X, WW, HH, Add:Single; IsSel:Boolean; Begin Self.UpdateRects(); Self.UpdateTransform(); If (Not DisableHighlights) Then Self.UpdateHighlight(); If (_TabCount<=0) Then Exit; X := 0.0; For I:=0 To Pred(_TabCount) Do If (_Tabs[I].Visible) Then Begin IsSel := (I=_TabHighlight) Or (I=_SelectedIndex); GetTabProperties(IsSel, MyColor, Fnt); If (IsSel) Then Begin Self.DrawComponent(0, VectorCreate(X, 0, 0), 0.0, 0.0, 1.0, 1.0, MyColor); WW := _TabWidthOn; HH := _TabHeightOn; Add := 0; End Else Begin Self.DrawComponent(1, VectorCreate(X, _TabHeightOn - _TabHeightOff, 0), 0.0, 0.0, 1.0, 1.0, MyColor); WW := _TabWidthOff; HH := _TabHeightOff; Add := _TabHeightOn - _TabHeightOff; End; Rect := _FontRenderer.GetTextRect(_Tabs[I].Caption); Self.DrawText(_Tabs[I].Caption, VectorCreate(X + ((WW-Rect.X) * 0.5), Add + (HH - Rect.Y) * 0.5, 1.0), MyColor, Scale, Fnt); X := X + WW; End; End; Function UITabList.OnMouseDown(X, Y: Integer; Button: Word): Boolean; Var N:Integer; Begin N := GetTabAt(X, Y); If (N>=0) And (N<>_SelectedIndex) Then Begin _SelectedIndex := N; _TabHighlight := -1; Self.OnHit(); Result := True; Exit; End; Result := Inherited OnMouseDown(X,Y, Button); End; Function UITabList.OnMouseMove(X,Y:Integer):Boolean; Var I:Integer; Begin {Result := False; If (Visible) Then Begin _TabHighlight := GetTabAt(X,Y); End;} Result := Inherited OnMouseMove(X,Y); End; Procedure UITabList.GetTabProperties(const Selected: Boolean; Out TabColor: Color; Out TabFont: Font); Begin If Selected Then TabColor := Self.Color Else TabColor := ColorGrey(200, Self.Color.A); TabFont := Self.GetFont(); End; Procedure UITabList.OnLanguageChange; Var I:Integer; Begin For I:=0 To Pred(_TabCount) Do _Tabs[I].Caption := GetLocalizedString(_Tabs[I].Name); End; Function UITabList.OnSelectLeft():Boolean; Var I:Integer; Begin Result := False; If (Not Self.Selected) Then Exit; I := _SelectedIndex; While (I=_SelectedIndex) Or (Not _Tabs[I].Visible) Do Begin If I<=0 Then I := Pred(_TabCount) Else Dec(I); If (I = _SelectedIndex) Then Exit; End; SetSelectedIndex(I); Result := True; End; Function UITabList.OnSelectRight():Boolean; Var I:Integer; Begin Result := False; If (Not Self.Selected) Then Exit; I := _SelectedIndex; While (I=_SelectedIndex) Or (Not _Tabs[I].Visible) Do Begin If I>=Pred(_TabCount) Then I := 0 Else Inc(I); If (I = _SelectedIndex) Then Exit; End; SetSelectedIndex(I); Result := True; End; Procedure UITabList.SetSelectedIndex(const Value: Integer); Begin If (Self.IsSelected()) Then Self.UpdateHighlight(False); _SelectedIndex := Value; _TabHighlight := -1; If (Self.IsSelected()) Then Self.UpdateHighlight(True); Self.OnHit(); End; Function UITabList.IsSelectable: Boolean; Begin Result := True; End; End.
(* * 发送数据的专用单元 * * 注:1. 服务端每个业务线程一个数据发送器, * 见 iocp_threads.TBusiThread; * 2. 客户端每个发送线程一个数据发送器; * 3. TransmitFile 模式发送时,每 TBaseSocket 对象一个 * TTransmitObject 发送器 *) unit iocp_senders; interface {$I in_iocp.inc} uses {$IFDEF DELPHI_XE7UP} Winapi.Windows, System.Classes, System.Variants, System.Sysutils, {$ELSE} Windows, Classes, Variants, Sysutils, {$ENDIF} iocp_Winsock2, iocp_base, iocp_msgPacks, iocp_objPools, iocp_wsExt; type // ================= 待发数据信息 基类 ================= // 服务端、客户端均用 TPerIOData,但客户端用 Send 发送; // 发送器不检查待发送数据的有效性!要在调用前检查。 TSendDataEvent = procedure(Msg: TBasePackObject; MsgPart: TMessagePart; OutSize: Integer) of object; TSendErrorEvent = procedure(IOType: TIODataType; ErrorCode: Integer) of object; TBaseTaskObject = class(TObject) private FOwner: TObject; // 宿主 FSendBuf: PPerIOData; // 重叠结构 FSocket: TSocket; // 客户端对应的套接字 FTask: TTransmitTask; // 待发送数据描述 FErrorCode: Integer; // 异常代码 FOnDataSend: TSendDataEvent; // 发出事件 FOnError: TSendErrorEvent; // 异常事件 function GetData: PWsaBuf; function GetIOType: TIODataType; procedure SetOwner(const Value: TObject); protected procedure InterSetTask(const Data: PAnsiChar; Size: Cardinal; AutoFree: Boolean); overload; procedure InterSetTask(const Data: AnsiString; AutoFree: Boolean); overload; procedure InterSetTask(Handle: THandle; Size, Offset, OffsetEnd: TFileSize; AutoFree: Boolean); overload; procedure InterSetTaskVar(const Data: Variant); public procedure FreeResources(FreeRes: Boolean = True); virtual; abstract; public property Data: PWsaBuf read GetData; property ErrorCode: Integer read FErrorCode; property IOType: TIODataType read GetIOType; property Owner: TObject read FOwner write SetOwner; // r/w property Socket: TSocket read FSocket write FSocket; // r/w public property OnDataSend: TSendDataEvent read FOnDataSend write FOnDataSend; property OnError: TSendErrorEvent read FOnError write FOnError; // r/w end; // ================= 套接字对象数据发送器 类 ================= // 服务端用 TransmitFile() 模式发送的数据描述 // 此类对象附属于 TBaseSocket,开启编译项 TRANSMIT_FILE 有效 {$IFDEF TRANSMIT_FILE} TTransmitObject = class(TBaseTaskObject) private FExists: Integer; // 是否有数据 function GetExists: Boolean; function GetSendDone: Boolean; public constructor Create(AOwner: TObject); destructor Destroy; override; procedure FreeResources(FreeRes: Boolean = True); override; procedure SetTask(const Data: PAnsiChar; Size: Cardinal); overload; procedure SetTask(const Data: AnsiString); overload; procedure SetTask(Handle: THandle; Size: TFileSize); overload; procedure SetTask(Stream: TMemoryStream; Size: Cardinal); overload; procedure SetTask(Stream: TStream; Size: TFileSize; Offset: TFileSize = 0; OffsetEnd: TFileSize = 0); overload; procedure SetTaskVar(const Data: Variant); procedure TransmitFile; public property Exists: Boolean read GetExists; property SendDone: Boolean read GetSendDone; end; {$ENDIF} // ================= 线程数据发送器 基类 ================= TBaseTaskSender = class(TBaseTaskObject) private FBufferSize: Cardinal; // 发送缓存长度 FChunked: Boolean; // HTTP 服务端分块发送数据 FStoped: Boolean; // 停止发送 FMasking: Boolean; // WebSocket 使用掩码 FOpCode: TWSOpCode; // WebSocket 操作 FWebSocket: Boolean; // WebSocket 类型 FWSCount: UInt64; // WebSocket 发出数据计数 FWSMask: TWSMask; // WebSocket 掩码 procedure ChunkDone; procedure MakeFrameInf(Payload: UInt64); procedure InitHeadTail(DataLength: Cardinal; Fulled: Boolean); procedure InterSendBuffer(Data: PAnsiChar; ByteCount, Offset, OffsetEnd: Cardinal); procedure InterSendFile; procedure InternalSend; procedure SetChunked(const Value: Boolean); procedure SetOpCode(Value: TWSOpCode); protected procedure DirectSend(OutBuf: PAnsiChar; OutSize, FrameSize: Integer); virtual; abstract; procedure ReadSendBuffers(InBuf: PAnsiChar; ReadCount, FrameSize: Integer); virtual; abstract; public procedure FreeResources(FreeRes: Boolean = True); override; procedure Send(const Data: PAnsiChar; Size: Cardinal; AutoFree: Boolean = True); overload; procedure Send(const Data: AnsiString); overload; procedure Send(Handle: THandle; Size: TFileSize; Offset: TFileSize = 0; OffsetEnd: TFileSize = 0; AutoFree: Boolean = True); overload; procedure Send(Stream: TStream; Size: TFileSize; Offset: TFileSize = 0; OffsetEnd: TFileSize = 0; AutoFree: Boolean = True); overload; procedure Send(Stream: TStream; Size: TFileSize; AutoFree: Boolean = True); overload; procedure SendVar(const Data: Variant); procedure SendBuffers; protected property Chunked: Boolean read FChunked write SetChunked; public property Masking: Boolean read FMasking write FMasking; property Stoped: Boolean read FStoped write FStoped; property OpCode: TWSOpCode read FOpCode write SetOpCode; // r/w end; // ================= 业务数据发送器 类 ================= // 用 WSASend 发送 TPerIOData.Data.Buf // 此类对象附属于业务线程 TBusiThread TServerTaskSender = class(TBaseTaskSender) protected procedure DirectSend(OutBuf: PAnsiChar; OutSize, FrameSize: Integer); override; procedure ReadSendBuffers(InBuf: PAnsiChar; ReadCount, FrameSize: Integer); override; public constructor Create(BufferPool: TIODataPool); procedure CopySend(ARecvBuf: PPerIOData); procedure FreeBuffers(BufferPool: TIODataPool); public property Chunked; end; // ================= 客户端数据发送器 类 ================= // 用 Send 发送 TPerIOData.Data.Buf TClientTaskSender = class(TBaseTaskSender) private FMsgPart: TMessagePart; // 数据类型 protected procedure DirectSend(OutBuf: PAnsiChar; OutSize, FrameSize: Integer); override; procedure ReadSendBuffers(InBuf: PAnsiChar; ReadCount, FrameSize: Integer); override; public constructor Create; destructor Destroy; override; public property MsgPart: TMessagePart read FMsgPart write FMsgPart; end; procedure MakeFrameHeader(const Data: PWsaBuf; OpCode: TWSOpCode; Payload: UInt64 = 0); implementation uses iocp_utils, iocp_api, iocp_sockets, http_base; procedure MakeFrameHeader(const Data: PWsaBuf; OpCode: TWSOpCode; Payload: UInt64); var i: Integer; p: PByte; begin // 服务端:构造短消息的 WebSocket 帧信息 // 忽略 RSV1/RSV2/RSV3 p := PByte(Data^.buf); p^ := Byte($80) + Byte(OpCode); Inc(p); case Payload of 0..125: begin if (OpCode >= ocClose) then p^ := 0 else p^ := Payload; Inc(p); end; 126..$FFFF: begin p^ := 126; Inc(p); TByteAry(p)[0] := TByteAry(@Payload)[1]; TByteAry(p)[1] := TByteAry(@Payload)[0]; Inc(p, 2); end; else begin p^ := 127; Inc(p); for i := 0 to 7 do TByteAry(p)[i] := TByteAry(@Payload)[7 - i]; Inc(p, 8); end; end; Data^.len := PAnsiChar(p) - Data^.buf; end; { TBaseTaskObject } procedure TBaseTaskObject.InterSetTask(const Data: AnsiString; AutoFree: Boolean); begin // 发送 AnsiString(不是双字节的 String) FTask.RefStr := Data; FTask.Head := PAnsiChar(Data); FTask.HeadLength := Length(Data); FTask.AutoFree := AutoFree; end; procedure TBaseTaskObject.InterSetTask(const Data: PAnsiChar; Size: Cardinal; AutoFree: Boolean); begin // 发送一段内存 Buffer FTask.Head := Data; FTask.HeadLength := Size; FTask.AutoFree := AutoFree; end; function TBaseTaskObject.GetData: PWsaBuf; begin // 返回发送缓存地址,让外部直接写数据,与 SendBuffers 对应 Result := @FSendBuf^.Data; end; function TBaseTaskObject.GetIOType: TIODataType; begin // 取 FSendBuf^.IOType(客户端无意义) Result := FSendBuf^.IOType; end; procedure TBaseTaskObject.InterSetTask(Handle: THandle; Size, Offset, OffsetEnd: TFileSize; AutoFree: Boolean); begin // 发送文件句柄 Handle // Handle > 0 为有效句柄,见 iocp_utils.InternalOpenFile FTask.Handle := Handle; FTask.Size := Size; FTask.Offset := Offset; FTask.OffsetEnd := OffsetEnd; FTask.AutoFree := AutoFree; end; procedure TBaseTaskObject.InterSetTaskVar(const Data: Variant); var p, Buf: Pointer; BufLength: Integer; begin // 发送可变类型数据(数据集) if VarIsNull(Data) then Exit; BufLength := VarArrayHighBound(Data, 1) - VarArrayLowBound(Data, 1) + 1; GetMem(Buf, BufLength); p := VarArrayLock(Data); try System.Move(p^, Buf^, BufLength); finally VarArrayUnlock(Data); end; // 发送内存数据 FTask.Head := Buf; FTask.HeadLength := BufLength; FTask.AutoFree := True; end; procedure TBaseTaskObject.SetOwner(const Value: TObject); begin FOwner := Value; FTask.ObjType := Value.ClassType; end; { TTransmitObject } {$IFDEF TRANSMIT_FILE} constructor TTransmitObject.Create(AOwner: TObject); begin inherited Create; FOwner := AOwner; FTask.ObjType := AOwner.ClassType; GetMem(FSendBuf, SizeOf(TPerIOData)); // 直接分配 FSendBuf^.Data.len := 0; FSendBuf^.Node := nil; // 不是池里面的节点 end; destructor TTransmitObject.Destroy; begin // 释放资源 FreeResources; FreeMem(FSendBuf); inherited; end; procedure TTransmitObject.FreeResources(FreeRes: Boolean); begin // 释放 TransmitFile 模式的数据资源 // 已在外部释放时,参数 FreeRes=False try try if (InterlockedDecrement(FExists) = 0) and FreeRes then if (FTask.ObjType = TIOCPSocket) then begin // 1. 只有 Stream、Stream2 两资源 if Assigned(FTask.Stream) then // 主体流 FTask.Stream.Free; if Assigned(FTask.Stream2) then // 附件流 FTask.Stream2.Free; end else if (FTask.ObjType = THttpSocket) then begin // 2. 只有 AnsiString、Handle、Stream 三资源, // 且相互排斥,见:THttpResponse.SendWork; if Assigned(FTask.Stream) then // 内存流、文件流 FTask.Stream.Free else if (FTask.Handle > 0) then // 纯粹的文件句柄 CloseHandle(FTask.Handle) else if (FTask.RefStr <> '') then FTask.RefStr := ''; end else begin // 3. TStreamSocket 或其他对象的各种发送资源,相互排斥 if Assigned(FTask.Stream) then // 内存流、文件流 FTask.Stream.Free else if (FTask.Handle > 0) then // 纯粹的文件句柄 CloseHandle(FTask.Handle) else if (FTask.RefStr <> '') then FTask.RefStr := '' else begin if Assigned(FTask.Head) then FreeMem(FTask.Head); if Assigned(FTask.Tail) then FreeMem(FTask.Tail); end; end; finally FillChar(FTask, TASK_SPACE_SIZE, 0); // 清零 FTask.ObjType := FOwner.ClassType; // 会被清 end; except // 正常不应该有 end; end; function TTransmitObject.GetExists: Boolean; begin // 是否有发送数据 Result := (iocp_api.InterlockedCompareExchange(FExists, 0, 0) > 0); end; function TTransmitObject.GetSendDone: Boolean; begin // 是否发送完毕 Result := InterlockedDecrement(FExists) = 1; end; procedure TTransmitObject.SetTask(const Data: AnsiString); begin // 设置字符串 InterSetTask(Data, False); FExists := 1; end; procedure TTransmitObject.SetTask(const Data: PAnsiChar; Size: Cardinal); begin // 设置内存块 InterSetTask(Data, Size, False); FExists := 1; end; procedure TTransmitObject.SetTask(Handle: THandle; Size: TFileSize); begin // 设置文件句柄(整个文件) InterSetTask(Handle, Size, 0, 0, False); FExists := 1; end; procedure TTransmitObject.SetTask(Stream: TMemoryStream; Size: Cardinal); begin // 设置 C/S 主体流(不是 HTTP 时实体) FTask.Stream := Stream; // 对应 Stream FTask.Head := Stream.Memory; FTask.HeadLength := Size; FExists := 1; end; procedure TTransmitObject.SetTask(Stream: TStream; Size, Offset, OffsetEnd: TFileSize); begin // 增加一个流,作为: // 1. C/S 模式的附件流 // 2. HTTP 的实体数据流 if (FTask.ObjType = THttpSocket) then // THttpSocket begin FTask.Stream := Stream; if (Stream is TMemoryStream) then begin // 发送内存流 FTask.Head := TMemoryStream(Stream).Memory; FTask.HeadLength := Size; end else begin // 发送文件流的句柄 FTask.Handle := THandleStream(Stream).Handle; FTask.Size := Size; FTask.Offset := Offset; FTask.OffsetEnd := OffsetEnd; end; end else begin FTask.Stream2 := Stream; // C/S 模式,TBaseSocket 对应 Stream2 if (Stream is TMemoryStream) then begin // 作为尾 FTask.Tail := TMemoryStream(Stream).Memory; FTask.TailLength := Size; end else begin // 发送文件流的句柄 FTask.Handle := THandleStream(Stream).Handle; FTask.Size := Size; FTask.Offset := Offset; FTask.OffsetEnd := OffsetEnd; end; end; FExists := 1; end; procedure TTransmitObject.SetTaskVar(const Data: Variant); begin // 设置变长类型 InterSetTaskVar(Data); FExists := 1; end; procedure TTransmitObject.TransmitFile; function InterTransmit(hHandle: THandle; iSendSize: Cardinal; LowPart: Cardinal; HighPart: Integer): Boolean; begin // 发送计数 Result := True; InterlockedIncrement(FExists); // 清重叠结构 FillChar(FSendBuf^.Overlapped, SizeOf(TOverlapped), 0); if (LowPart > 0) then begin FSendBuf^.Overlapped.Offset := LowPart; // 设置位移 FSendBuf^.Overlapped.OffsetHigh := HighPart; // 位移高位 end; // 发送数据 if (gTransmitFile(FSocket, // 套接字 hHandle, // 文件句柄(可能=0) iSendSize, // 发送长度(可能=0) IO_BUFFER_SIZE * 8, // 每次发送长度 @FSendBuf^.Overlapped, // 重叠结构 PTransmitBuffers(@FTask), // 头尾数据块 TF_USE_KERNEL_APC // 用内核线程 ) = False) then begin FErrorCode := WSAGetLastError; if (FErrorCode <> ERROR_IO_PENDING) then // 异常 begin InterlockedDecrement(FExists); FOnError(ioSend, FErrorCode); Result := False; end else FErrorCode := 0; end; end; var LargeInt: LARGE_INTEGER; SendSize: Cardinal; begin // 用 TransmitFile() 发送 Task 的内容 // 提交后有三种结果: // 1. 失败,在当前线程处理 // 2. 提交成功,有两种情况: // A. 全部发送完毕,被工作线程监测到(只一次),执行 TBaseSocket.FreeTransmitRes 释放资源 // B. 发送出现异常,也被工作线程监测到,执行 TBaseSocket.TryClose 尝试关闭 FSendBuf^.Owner := FOwner; // 宿主 FSendBuf^.IOType := ioTransmit; // iocp_server 中判断用 FErrorCode := 0; if (FTask.Handle = 0) then // 没有文件,只发送 PTransmitBuffers begin InterTransmit(0, 0, 0, 0); Exit; end; // 发送长度 if (FTask.Offset = 0) and (FTask.OffsetEnd = 0) then FTask.Size := GetFileSize64(FTask.Handle) else FTask.Size := FTask.OffsetEnd - FTask.Offset + 1; while (FTask.Size > 0) do begin // 每次最多只能发送 MAX_TRANSMIT_SIZE 字节 if (FTask.Size >= MAX_TRANSMIT_SIZE) then SendSize := MAX_TRANSMIT_SIZE else SendSize := FTask.Size; // 位移 LargeInt.QuadPart := FTask.Offset; // 定位 SetFilePointer(FTask.Handle, LargeInt.LowPart, @LargeInt.HighPart, FILE_BEGIN); // 发送一段内容 if InterTransmit(FTask.Handle, SendSize, LargeInt.LowPart, LargeInt.HighPart) then begin Inc(FTask.Offset, SendSize); // 位移+ Dec(FTask.Size, SendSize); // 剩余- end else Break; end; end; {$ENDIF} { TBaseTaskSender } procedure TBaseTaskSender.ChunkDone; begin // 发送分块结束标志 with FSendBuf^.Data do begin PAnsiChar(buf)^ := AnsiChar('0'); // 0 PStrCRLF2(buf + 1)^ := STR_CRLF2; // 回车换行, 两个 end; DirectSend(nil, 5, 0); // 发送 5 字节 end; procedure TBaseTaskSender.FreeResources(FreeRes: Boolean); begin // 释放 WSASend、Send 模式的数据资源 try if Assigned(FTask.Stream) then begin if FTask.AutoFree then FTask.Stream.Free; end else if (FTask.Handle > 0) then CloseHandle(FTask.Handle) else if (FTask.RefStr <> '') then begin FTask.RefStr := ''; FTask.Head := nil; end else if Assigned(FTask.Head) then // 未用 FTask.Tail begin if FTask.AutoFree then FreeMem(FTask.Head); end; finally FillChar(FTask, TASK_SPACE_SIZE, 0); // 清零 FTask.ObjType := FOwner.ClassType; // 会被清 end; end; procedure TBaseTaskSender.InitHeadTail(DataLength: Cardinal; Fulled: Boolean); begin // 填写分块的头尾:长度描述(6字节)、回车换行 PChunkSize(FSendBuf^.Data.buf)^ := PChunkSize(AnsiString(IntToHex(DataLength, 4)) + STR_CRLF)^; PStrCRLF(FSendBuf^.Data.buf + DataLength + 6)^ := STR_CRLF; end; procedure TBaseTaskSender.MakeFrameInf(Payload: UInt64); var i: Integer; iByte: Byte; p: PByte; begin // 构造 WebSocket 帧信息 // 忽略 RSV1/RSV2/RSV3 p := PByte(FSendBuf^.Data.buf); p^ := Byte($80) + Byte(FOpCode); Inc(p); if FMasking then // 加掩码 iByte := Byte($80) else iByte := 0; case Payload of 0..125: begin if (OpCode >= ocClose) then p^ := iByte else p^ := iByte + Payload; Inc(p); end; 126..$FFFF: begin p^ := iByte + 126; Inc(p); TByteAry(p)[0] := TByteAry(@Payload)[1]; TByteAry(p)[1] := TByteAry(@Payload)[0]; Inc(p, 2); end; else begin p^ := iByte + 127; Inc(p); for i := 0 to 7 do TByteAry(p)[i] := TByteAry(@Payload)[7 - i]; Inc(p, 8); end; end; if FMasking then // 客户端的掩码,4字节 begin Cardinal(FWsMask) := GetTickCount + $10100000; PCardinal(p)^ := Cardinal(FWsMask); Inc(p, 4); end; FSendBuf^.Data.len := PAnsiChar(p) - FSendBuf^.Data.buf; FWSCount := 0; end; procedure TBaseTaskSender.InternalSend; begin // 发送任务 FTask 描述的数据(几种数据不共存) FStoped := False; FErrorCode := 0; // 无异常 try try if Assigned(FTask.Head) then // 1. 发送内存块 InterSendBuffer(FTask.Head, FTask.HeadLength, FTask.Offset, FTask.OffsetEnd) else if (FTask.Handle > 0) then // 2. 发送文件 InterSendFile else if Assigned(FTask.Tail) then // 3. 发送内存块 InterSendBuffer(FTask.Tail, FTask.TailLength, FTask.Offset, FTask.OffsetEnd); finally FreeResources; // 4. 释放资源 if FChunked then FChunked := False; end; except FErrorCode := GetLastError; end; end; procedure TBaseTaskSender.InterSendBuffer(Data: PAnsiChar; ByteCount, Offset, OffsetEnd: Cardinal); var FrameSize: Cardinal; // 数据描述长度 BufLength: Cardinal; // 分块模式的缓存长度 BytesToRead: Cardinal; // 期望读入长度 begin // 发送一段内存(不应很长) // 范围:Offset - OffsetEnd // Chunk 发送的格式: // 长度描述(6字节) + 回车换行 + 内容 + 回车换行(2字节) // 内容大于 IO_BUFFER_SIZE 时,先预填 长度描述、末尾的回车换行 if (OffsetEnd > Offset) then // 发送部分内容,定位 begin Inc(Data, Offset); ByteCount := OffsetEnd - Offset + 1; end; if FWebSocket then // 发送 webSocket 数据 begin MakeFrameInf(ByteCount); FrameSize := FSendBuf^.Data.len; // 描述长度 BufLength := FBufferSize - FrameSize; // 最大读入长度 end else if FChunked then // Chunk 发送 begin FrameSize := 6; // 描述长度 BufLength := FBufferSize - 8; // 减头尾长度,6+2 if (ByteCount >= BufLength) then // 预填头尾 InitHeadTail(BufLength, True); end else begin FrameSize := 0; BufLength := FBufferSize; end; while (ByteCount > 0) and (FStoped = False) do begin if (ByteCount >= BufLength) then // 超长 BytesToRead := BufLength else begin BytesToRead := ByteCount; if FChunked then // 内容未满 InitHeadTail(BytesToRead, False); // 调整头尾 end; // 读入数据,发送 ReadSendBuffers(Data, BytesToRead, FrameSize); if (FErrorCode <> 0) then // 退出 Break; Inc(Data, BytesToRead); // 地址向前 Dec(ByteCount, BytesToRead); // 剩余数 - if FWebSocket and (FrameSize > 0) then // 下次不带描述 begin FrameSize := 0; BufLength := FBufferSize; // 恢复最大长度 end; end; if FChunked and (FStoped = False) then // 发送分块结束标志 ChunkDone; end; procedure TBaseTaskSender.InterSendFile; var FrameSize: Cardinal; // WebSocket帧结构长度 BufLength: Cardinal; // 分块模式的缓存长度 ByteCount: TFileSize; // 总长度 BytesToRead, BytesReaded: Cardinal; Offset: LARGE_INTEGER; begin // 发送一段文件 // 范围:Task^.Offset ... Task^.OffsetEnd try if (FTask.Offset = 0) and (FTask.OffsetEnd = 0) then ByteCount := FTask.Size else ByteCount := FTask.OffsetEnd - FTask.Offset + 1; // 定位(可能大于 2G,用 LARGE_INTEGER 确定位移) Offset.QuadPart := FTask.Offset; SetFilePointer(FTask.Handle, Offset.LowPart, @Offset.HighPart, FILE_BEGIN); if FWebSocket then // 发送 webSocket 数据 begin MakeFrameInf(ByteCount); FrameSize := FSendBuf^.Data.len; BufLength := FBufferSize - FrameSize; // 最大读入长度 end else if FChunked then // Chunk 发送 begin FrameSize := 6; // 有描述 BufLength := FBufferSize - 8; // 减头尾长度,6+2 if (ByteCount >= BufLength) then // 预填头尾 InitHeadTail(BufLength, True); end else begin FrameSize := 0; BufLength := FBufferSize; end; while (ByteCount > 0) and (FStoped = False) do begin if (ByteCount >= BufLength) then // 超长 BytesToRead := BufLength else begin BytesToRead := ByteCount; if FChunked then // 内容未满 InitHeadTail(BytesToRead, False); // 调整头尾 end; // 先读入一块数据 if (FrameSize > 0) then // 读入到长度描述后位置 ReadFile(FTask.Handle, (FSendBuf^.Data.buf + FrameSize)^, BytesToRead, BytesReaded, nil) else ReadFile(FTask.Handle, FSendBuf^.Data.buf^, BytesToRead, BytesReaded, nil); if (BytesToRead = BytesReaded) then // 读入成功 begin if FWebSocket then DirectSend(FSendBuf^.Data.buf, BytesToRead + FrameSize, FrameSize) // 发送,长度+FrameSize else if FChunked then DirectSend(FSendBuf^.Data.buf, BytesToRead + 8, 0) // 发送,长度+6+2 else DirectSend(FSendBuf^.Data.buf, BytesToRead, 0); // 发送,长度不变 if (FErrorCode <> 0) then // 退出 Break; Dec(ByteCount, BytesToRead); // 剩余数 - if FWebSocket and (FrameSize > 0) then // 下次不带描述 begin FrameSize := 0; BufLength := FBufferSize; end; end else begin FErrorCode := GetLastError; Break; end; end; if FChunked and (FStoped = False) then // 发送分块结束标志 ChunkDone; except FErrorCode := GetLastError; end; end; procedure TBaseTaskSender.Send(const Data: PAnsiChar; Size: Cardinal; AutoFree: Boolean); begin // 发送 Buffer InterSetTask(Data, Size, AutoFree); InternalSend; end; procedure TBaseTaskSender.Send(Handle: THandle; Size, Offset, OffsetEnd: TFileSize; AutoFree: Boolean); begin // 发送文件 Handle // Handle > 0 为有效句柄,见 iocp_utils.InternalOpenFile InterSetTask(Handle, Size, Offset, OffsetEnd, AutoFree); InternalSend; end; procedure TBaseTaskSender.Send(const Data: AnsiString); begin // 发送 AnsiString(不是双字节的 String) InterSetTask(Data, True); InternalSend; end; procedure TBaseTaskSender.Send(Stream: TStream; Size, Offset, OffsetEnd: TFileSize; AutoFree: Boolean); begin // 设置 C/S 模式的附件流, 根据 AutoFree 释放 FTask.Stream := Stream; FTask.AutoFree := AutoFree; if (Stream is TMemoryStream) then begin // 发送内存流 FTask.Head := TMemoryStream(Stream).Memory; FTask.HeadLength := Size; end else begin // 发送文件流的句柄 FTask.Handle := THandleStream(Stream).Handle; FTask.Size := Size; FTask.Offset := Offset; FTask.OffsetEnd := OffsetEnd; end; InternalSend; end; procedure TBaseTaskSender.Send(Stream: TStream; Size: TFileSize; AutoFree: Boolean); begin // 发送整个数据流,根据 AutoFree 决定是否释放 Send(Stream, Size, 0, 0, AutoFree); end; procedure TBaseTaskSender.SendBuffers; begin // 数据已经填写到 Buf,直接发送 //(FramSize = 0,WebSocket客户端不能使用) DirectSend(FSendBuf^.Data.Buf, FSendBuf^.Data.len, 0); end; procedure TBaseTaskSender.SendVar(const Data: Variant); begin // 发送可变类型数据 InterSetTaskVar(Data); InternalSend; end; procedure TBaseTaskSender.SetChunked(const Value: Boolean); begin // 设置 HTTP 分块模式 FChunked := Value; FOpCode := ocContinuation; FWebSocket := False; // 不是 WebSocket 发送 end; procedure TBaseTaskSender.SetOpCode(Value: TWSOpCode); begin // 设置 WebSocket 协议的操作 FOpCode := Value; FWebSocket := True; FChunked := False; // 不是分块发送了 end; { TServerTaskSender } procedure TServerTaskSender.CopySend(ARecvBuf: PPerIOData); begin // 复制 ARecvBuf 发送 FSendBuf^.Data.len := ARecvBuf^.Overlapped.InternalHigh; System.Move(ARecvBuf^.Data.buf^, FSendBuf^.Data.buf^, FSendBuf^.Data.len); DirectSend(nil, FSendBuf^.Data.len, 0); // 直接发送 end; constructor TServerTaskSender.Create(BufferPool: TIODataPool); begin inherited Create; FSendBuf := BufferPool.Pop^.Data; FSendBuf^.Data.len := IO_BUFFER_SIZE; FBufferSize := IO_BUFFER_SIZE; FWebSocket := False; end; procedure TServerTaskSender.DirectSend(OutBuf: PAnsiChar; OutSize, FrameSize: Integer); var ByteCount, Flags: Cardinal; begin // 直接发送 FSendBuf 的内容(忽略参数 OutBuf、FrameSize) // 清重叠结构 FillChar(FSendBuf^.Overlapped, SizeOf(TOverlapped), 0); FSendBuf^.Owner := FOwner; // 宿主 FSendBuf^.IOType := ioSend; // iocp_server 中判断用 FSendBuf^.Data.len := OutSize; // 长度 ByteCount := 0; Flags := 0; // FSendBuf^.Overlapped 与 TPerIOData 同地址 if (iocp_Winsock2.WSASend(FSocket, @(FSendBuf^.Data), 1, ByteCount, Flags, LPWSAOVERLAPPED(@FSendBuf^.Overlapped), nil) = SOCKET_ERROR) then begin FErrorCode := WSAGetLastError; if (FErrorCode <> ERROR_IO_PENDING) then // 异常 FOnError(ioSend, FErrorCode) // 执行 TBaseSocket 方法 else begin // 发出时会收到消息, // 严格来说要在工作线程处理,那要调整发送器 WaitForSingleObject(FSocket, INFINITE); FErrorCode := 0; end; end else FErrorCode := 0; end; procedure TServerTaskSender.FreeBuffers(BufferPool: TIODataPool); begin BufferPool.Push(FSendBuf^.Node); FSendBuf := nil; end; procedure TServerTaskSender.ReadSendBuffers(InBuf: PAnsiChar; ReadCount, FrameSize: Integer); begin // 读数据到发送缓存,发送 if FChunked or (FrameSize > 0) then // 要分块发送 begin // 1. 发送 Chunk, WebSocket 首次数据 System.Move(InBuf^, (FSendBuf^.Data.buf + FrameSize)^, ReadCount); // 内容 if FChunked then DirectSend(nil, ReadCount + 8, 0) // ReadCount + 描述长度 + 末尾的回车换行 else // WebSocket 数据 DirectSend(nil, ReadCount + FrameSize, FrameSize); end else begin // 2. 无分块描述的数据,直接读入 System.Move(InBuf^, FSendBuf^.Data.buf^, ReadCount); DirectSend(nil, ReadCount, 0); end; end; { TClientTaskSender } constructor TClientTaskSender.Create; begin inherited; // 直接分配发送内存块 FSendBuf := New(PPerIOData); GetMem(FSendBuf^.Data.Buf, IO_BUFFER_SIZE_2); FSendBuf^.Data.len := IO_BUFFER_SIZE_2; FBufferSize := IO_BUFFER_SIZE_2; FWebSocket := False; end; destructor TClientTaskSender.Destroy; begin // 释放发送内存块 FreeMem(FSendBuf^.Data.Buf); Dispose(FSendBuf); inherited; end; procedure TClientTaskSender.DirectSend(OutBuf: PAnsiChar; OutSize, FrameSize: Integer); var i: Integer; TotalCount: UInt64; // 总发出 p: PByte; begin // 发送数据块 if FWebSocket and FMasking then // 对内容作掩码处理 begin p := PByte(FSendBuf^.Data.buf + FrameSize); TotalCount := FWSCount + OutSize - FrameSize; for i := FWSCount to TotalCount - 1 do begin p^ := p^ xor FWSMask[i mod 4]; Inc(p); end; FWSCount := TotalCount; end; if (Stoped = False) then FErrorCode := iocp_Winsock2.Send(FSocket, OutBuf^, OutSize, 0) else begin if (FMsgPart <> mdtHead) then // 发送取消标志 iocp_Winsock2.Send(FSocket, IOCP_SOCKET_CANCEL[1], IOCP_CANCEL_LENGTH, 0); FErrorCode := -2; // 停止,特殊编码 end; if Stoped or (FErrorCode <= 0) then begin if Assigned(FOnError) then FOnError(ioSend, 0); end else begin FErrorCode := 0; // 无异常 if Assigned(FOnDataSend) then FOnDataSend(Nil, FMsgPart, OutSize); end; end; procedure TClientTaskSender.ReadSendBuffers(InBuf: PAnsiChar; ReadCount, FrameSize: Integer); begin // 发送缓存 if FWebSocket then // 读内容到缓存 begin System.Move(InBuf^, (FSendBuf^.Data.buf + FrameSize)^, ReadCount); DirectSend(FSendBuf^.Data.buf, ReadCount + FrameSize, FrameSize); end else DirectSend(InBuf, ReadCount, FrameSize); end; end.
unit AddContact; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DialMessages, Utils, Placemnt, DataErrors; type TAddContactForm = class(TForm) ContactPropsGroupBox: TGroupBox; UserNameLabel: TLabel; UserNameEdit: TEdit; CancelButton: TButton; OKButton: TButton; FormPlacement: TFormPlacement; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure UserNameEditExit(Sender: TObject); private { Private declarations } public { Public declarations } end; var AddContactForm: TAddContactForm; implementation {$R *.dfm} resourcestring rsUserNameEmpty = 'User name is empty!'; rsBadUserName = 'Bad user name!'; procedure TAddContactForm.FormClose(Sender: TObject; var Action: TCloseAction); var ErrorStr: string; begin if ModalResult = mrOk then begin ErrorStr := EmptyStr; CheckError(UserNameEdit.Text = EmptyStr, ErrorStr, rsUserNameEmpty); TryCloseModal(ErrorStr, Action); end; end; procedure TAddContactForm.UserNameEditExit(Sender: TObject); begin with UserNameEdit do begin if Text <> EmptyStr then begin if IsError(not StrConsistsOfChars(Text, UserNameCharSet), rsBadUserName) then begin SetFocus; end; end; end; end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clEncryptor; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, Windows, SysUtils, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clUtils, clWUtils, clCryptUtils, clCryptAPI, clCertificateStore, clCertificate{$IFDEF LOGGER}, clLogger{$ENDIF}; type TclEncryptor = class(TComponent) private FSignAlgorithm: string; FSignStore: string; FEncryptCertificate: string; FEncodingType: Integer; FEncryptAlgorithm: string; FEncryptStore: string; FSignCertificate: string; FCertificateStore: TclCertificateStore; FExtractCertificates: Boolean; FOnProgress: TclProgressEvent; FExtractedCertificates: TclCertificateStore; procedure CheckCertificate(ACertificate: TclCertificate); procedure CheckCertificates(ACertificates: TclCertificateList); function FindCertificate(AStore: TclCertificateStore; const ACertificate: string; ARequirePrivateKey: Boolean): TclCertificate; protected function GetCertificateStore(const AStoreName: string): TclCertificateStore; virtual; function GetCertificate(const AStoreName, ACertificate: string; ARequirePrivateKey: Boolean): TclCertificate; virtual; function GetExtractedCertificate: TclCertificate; virtual; procedure DoProgress(ABytesProceed, ATotalBytes: Int64); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Close; virtual; procedure Sign(const ASourceFile, ADestinationFile: string; ADetachedSignature: Boolean); overload; procedure Sign(ASource, ADestination: TStream; ADetachedSignature: Boolean); overload; procedure Sign(ASource, ADestination: TStream; ADetachedSignature, AIncludeCertificate: Boolean; ACertificate: TclCertificate; ACertificates: TclCertificateList); overload; function Sign(const AData: TclCryptData; ADetachedSignature, AIncludeCertificate: Boolean; ACertificate: TclCertificate; ACertificates: TclCertificateList): TclCryptData; overload; function Sign(const AData: TclCryptData; ADetachedSignature, AIncludeCertificate: Boolean; ACertificate: TclCertificate): TclCryptData; overload; procedure VerifyEnveloped(const ASourceFile, ADestinationFile: string); overload; procedure VerifyEnveloped(ASource, ADestination: TStream); overload; procedure VerifyEnveloped(ASource, ADestination: TStream; ACertificate: TclCertificate); overload; function VerifyEnveloped(const AData: TclCryptData; ACertificate: TclCertificate): TclCryptData; overload; procedure VerifyDetached(const ASourceFile, ASignatureFile: string); overload; procedure VerifyDetached(ASource, ASignature: TStream); overload; procedure VerifyDetached(ASource, ASignature: TStream; ACertificate: TclCertificate); overload; procedure VerifyDetached(const AData, ASignature: TclCryptData; ACertificate: TclCertificate); overload; procedure Encrypt(const ASourceFile, ADestinationFile: string); overload; procedure Encrypt(ASource, ADestination: TStream); overload; procedure Encrypt(ASource, ADestination: TStream; ACertificates: TclCertificateList); overload; function Encrypt(const AData: TclCryptData; ACertificates: TclCertificateList): TclCryptData; overload; function Encrypt(const AData: TclCryptData; ACertificate: TclCertificate): TclCryptData; overload; procedure Decrypt(const ASourceFile, ADestinationFile: string); overload; procedure Decrypt(ASource, ADestination: TStream); overload; procedure Decrypt(ASource, ADestination: TStream; ACertificate: TclCertificate); overload; function Decrypt(const AData: TclCryptData; ACertificate: TclCertificate): TclCryptData; overload; property ExtractedCertificates: TclCertificateStore read FExtractedCertificates; published property SignStore: string read FSignStore write FSignStore; property EncryptStore: string read FEncryptStore write FEncryptStore; property SignCertificate: string read FSignCertificate write FSignCertificate; property EncryptCertificate: string read FEncryptCertificate write FEncryptCertificate; property SignAlgorithm: string read FSignAlgorithm write FSignAlgorithm; property EncryptAlgorithm: string read FEncryptAlgorithm write FEncryptAlgorithm; property EncodingType: Integer read FEncodingType write FEncodingType default DefaultEncoding; property ExtractCertificates: Boolean read FExtractCertificates write FExtractCertificates default True; property OnProgress: TclProgressEvent read FOnProgress write FOnProgress; end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsEncryptorDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} implementation { TclEncryptor } procedure TclEncryptor.CheckCertificates(ACertificates: TclCertificateList); begin if (ACertificates.Count = 0) then begin RaiseCryptError(CertificateNotFound, CertificateNotFoundCode); end; end; procedure TclEncryptor.CheckCertificate(ACertificate: TclCertificate); begin if (ACertificate = nil) then begin RaiseCryptError(CertificateNotFound, CertificateNotFoundCode); end; end; procedure TclEncryptor.Close; begin if (FCertificateStore <> nil) then begin FCertificateStore.Close(); end; ExtractedCertificates.Close(); end; constructor TclEncryptor.Create(AOwner: TComponent); begin inherited Create(AOwner); FExtractedCertificates := TclCertificateStore.Create(nil); FExtractedCertificates.StoreName := 'addressbook'; FCertificateStore := nil; FEncodingType := DefaultEncoding; FSignAlgorithm := szOID_RSA_SHA1RSA; FEncryptAlgorithm := szOID_RSA_RC2CBC; FExtractCertificates := True; end; function TclEncryptor.Decrypt(const AData: TclCryptData; ACertificate: TclCertificate): TclCryptData; var decryptPara: CRYPT_DECRYPT_MESSAGE_PARA; cbDecrypted: DWORD; rghCertStore: array[0..0] of HCERTSTORE; hStore: HCERTSTORE; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsEncryptorDemoDisplayed) and (not IsCertDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncryptorDemoDisplayed := True; IsCertDemoDisplayed := True; {$ENDIF} end; {$ENDIF} {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Decrypt');{$ENDIF} if ExtractCertificates then begin ExtractedCertificates.ImportFromMessage(AData); end; CheckCertificate(ACertificate); Result := TclCryptData.Create(); try ZeroMemory(@decryptPara, SizeOf(decryptPara)); decryptPara.cbSize := SizeOf(decryptPara); decryptPara.dwMsgAndCertEncodingType := FEncodingType; decryptPara.rghCertStore := @rghCertStore[0]; decryptPara.cCertStore := 1; cbDecrypted := 0; hStore := CertOpenStore(CERT_STORE_PROV_MEMORY, 0, nil, 0, nil); try if (hStore = nil) or (not CertAddCertificateContextToStore(hStore, ACertificate.Context, CERT_STORE_ADD_NEW, nil)) then begin RaiseCryptError('CertAddCertificateContextToStore'); end; rghCertStore[0] := hStore; if CryptDecryptMessage(@decryptPara, AData.Data, AData.DataSize, nil, @cbDecrypted, nil) then begin Result.Allocate(cbDecrypted); if CryptDecryptMessage(@decryptPara, AData.Data, AData.DataSize, Result.Data, @cbDecrypted, nil) then begin Result.Reduce(cbDecrypted); Exit; end; end; RaiseCryptError('Decrypt'); finally if (hStore <> nil) then begin CertCloseStore(hStore, 0); end; end; except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Decrypt'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Decrypt', E); raise; end; end;{$ENDIF} end; procedure TclEncryptor.Decrypt(ASource, ADestination: TStream; ACertificate: TclCertificate); var srcData, dstData: TclCryptData; sourceSize, sourceStart: Integer; begin sourceSize := ASource.Size - ASource.Position; sourceStart := ASource.Position; DoProgress(ASource.Position - sourceStart, sourceSize); srcData := nil; dstData := nil; try srcData := TclCryptData.Create(); srcData.Allocate(ASource.Size - ASource.Position); ASource.Read(srcData.Data^, srcData.DataSize); dstData := Decrypt(srcData, ACertificate); ADestination.Write(dstData.Data^, dstData.DataSize); finally dstData.Free(); srcData.Free(); end; DoProgress(ASource.Position - sourceStart, sourceSize); end; procedure TclEncryptor.Decrypt(ASource, ADestination: TStream); begin Decrypt(ASource, ADestination, GetCertificate(EncryptStore, EncryptCertificate, True)); end; procedure TclEncryptor.Decrypt(const ASourceFile, ADestinationFile: string); var src, dst: TStream; begin src := nil; dst := nil; try src := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite); dst := TFileStream.Create(ADestinationFile, fmCreate); Decrypt(src, dst); finally dst.Free(); src.Free(); end; end; destructor TclEncryptor.Destroy; begin Close(); FreeAndNil(FCertificateStore); FExtractedCertificates.Free(); inherited Destroy(); end; procedure TclEncryptor.DoProgress(ABytesProceed, ATotalBytes: Int64); begin if Assigned(FOnProgress) then begin FOnProgress(Self, ABytesProceed, ATotalBytes); end; end; function TclEncryptor.Encrypt(const AData: TclCryptData; ACertificate: TclCertificate): TclCryptData; var list: TclCertificateList; begin list := TclCertificateList.Create(False); try list.Add(ACertificate); Result := Encrypt(AData, list); finally list.Free(); end; end; procedure TclEncryptor.Encrypt(const ASourceFile, ADestinationFile: string); var src, dst: TStream; begin src := nil; dst := nil; try src := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite); dst := TFileStream.Create(ADestinationFile, fmCreate); Encrypt(src, dst); finally dst.Free(); src.Free(); end; end; procedure TclEncryptor.Encrypt(ASource, ADestination: TStream); var list: TclCertificateList; cert: TclCertificate; begin list := TclCertificateList.Create(False); try cert := GetCertificate(EncryptStore, EncryptCertificate, False); list.Add(cert); Encrypt(ASource, ADestination, list); finally list.Free(); end; end; procedure TclEncryptor.Encrypt(ASource, ADestination: TStream; ACertificates: TclCertificateList); var srcData, dstData: TclCryptData; sourceSize, sourceStart: Integer; begin sourceSize := ASource.Size - ASource.Position; sourceStart := ASource.Position; DoProgress(ASource.Position - sourceStart, sourceSize); srcData := nil; dstData := nil; try srcData := TclCryptData.Create(); srcData.Allocate(ASource.Size - ASource.Position); ASource.Read(srcData.Data^, srcData.DataSize); dstData := Encrypt(srcData, ACertificates); ADestination.Write(dstData.Data^, dstData.DataSize); finally dstData.Free(); srcData.Free(); end; DoProgress(ASource.Position - sourceStart, sourceSize); end; function TclEncryptor.FindCertificate(AStore: TclCertificateStore; const ACertificate: string; ARequirePrivateKey: Boolean): TclCertificate; begin Result := AStore.FindByEmail(ACertificate, ARequirePrivateKey); if (Result = nil) then begin Result := AStore.FindByIssuedTo(ACertificate, ARequirePrivateKey); end; if (Result = nil) then begin Result := AStore.FindBySerialNo(ACertificate, '', ARequirePrivateKey); end; end; function TclEncryptor.GetCertificate(const AStoreName, ACertificate: string; ARequirePrivateKey: Boolean): TclCertificate; begin if (AStoreName <> '') and (ACertificate <> '') then begin Result := FindCertificate(GetCertificateStore(AStoreName), ACertificate, ARequirePrivateKey); end else begin Result := nil; end; end; function TclEncryptor.GetCertificateStore(const AStoreName: string): TclCertificateStore; begin if (FCertificateStore = nil) then begin FCertificateStore := TclCertificateStore.Create(nil); FCertificateStore.Open(AStoreName); end; Result := FCertificateStore; if (Result.StoreName <> AStoreName) then begin Result.Open(AStoreName); end; end; function TclEncryptor.GetExtractedCertificate: TclCertificate; begin Result := FindCertificate(ExtractedCertificates, SignCertificate, False); if (Result = nil) and (ExtractedCertificates.Items.Count > 0) then begin Result := ExtractedCertificates.Items[0]; end; end; function TclEncryptor.Sign(const AData: TclCryptData; ADetachedSignature, AIncludeCertificate: Boolean; ACertificate: TclCertificate; ACertificates: TclCertificateList): TclCryptData; var data: array[0..0] of PByte; msgCert: PCCERT_CONTEXT; dwDataSizeArray: array[0..0] of DWORD; sigParams: CRYPT_SIGN_MESSAGE_PARA; cbSignedBlob: DWORD; p: ^PCCERT_CONTEXT; i, cnt: Integer; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsEncryptorDemoDisplayed) and (not IsCertDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncryptorDemoDisplayed := True; IsCertDemoDisplayed := True; {$ENDIF} end; {$ENDIF} CheckCertificate(ACertificate); {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Sign');{$ENDIF} Result := TclCryptData.Create(); try ZeroMemory(@sigParams, SizeOf(CRYPT_SIGN_MESSAGE_PARA)); sigParams.cbSize := SizeOf(CRYPT_SIGN_MESSAGE_PARA); sigParams.dwMsgEncodingType := FEncodingType; sigParams.pSigningCert := ACertificate.Context; sigParams.HashAlgorithm.pszObjId := PclChar(GetTclString(FSignAlgorithm)); if (ACertificates <> nil) then begin cnt := ACertificates.Count; end else begin cnt := 0; end; GetMem(msgCert, SizeOf(PCCERT_CONTEXT) * (cnt + 1)); try if AIncludeCertificate then begin p := Pointer(TclIntPtr(msgCert) + SizeOf(PCCERT_CONTEXT) * 0); p^ := ACertificate.Context; for i := 0 to cnt - 1 do begin p := Pointer(TclIntPtr(msgCert) + SizeOf(PCCERT_CONTEXT) * (i + 1)); p^ := ACertificates[i].Context; end; sigParams.cMsgCert := cnt + 1; sigParams.rgpMsgCert := msgCert; end; data[0] := AData.Data; dwDataSizeArray[0] := AData.DataSize; cbSignedBlob := 0; if CryptSignMessage(@sigParams, ADetachedSignature, 1, @data[0], @dwDataSizeArray[0], nil, @cbSignedBlob) then begin Result.Allocate(cbSignedBlob); if CryptSignMessage(@sigParams, ADetachedSignature, 1, @data[0], @dwDataSizeArray[0], Result.Data, @cbSignedBlob) then begin Result.Reduce(cbSignedBlob); Exit; end; end; RaiseCryptError('Sign'); finally FreeMem(msgCert); end; except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Sign'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Sign', E); raise; end; end;{$ENDIF} end; function TclEncryptor.Sign(const AData: TclCryptData; ADetachedSignature, AIncludeCertificate: Boolean; ACertificate: TclCertificate): TclCryptData; begin Result := Sign(AData, ADetachedSignature, AIncludeCertificate, ACertificate, nil); end; procedure TclEncryptor.Sign(const ASourceFile, ADestinationFile: string; ADetachedSignature: Boolean); var src, dst: TStream; begin src := nil; dst := nil; try src := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite); dst := TFileStream.Create(ADestinationFile, fmCreate); Sign(src, dst, ADetachedSignature); finally dst.Free(); src.Free(); end; end; procedure TclEncryptor.Sign(ASource, ADestination: TStream; ADetachedSignature: Boolean); begin Sign(ASource, ADestination, ADetachedSignature, True, GetCertificate(SignStore, SignCertificate, True), nil); end; procedure TclEncryptor.Sign(ASource, ADestination: TStream; ADetachedSignature, AIncludeCertificate: Boolean; ACertificate: TclCertificate; ACertificates: TclCertificateList); var srcData, dstData: TclCryptData; sourceSize, sourceStart: Integer; begin sourceSize := ASource.Size - ASource.Position; sourceStart := ASource.Position; DoProgress(ASource.Position - sourceStart, sourceSize); srcData := nil; dstData := nil; try srcData := TclCryptData.Create(); srcData.Allocate(ASource.Size - ASource.Position); ASource.Read(srcData.Data^, srcData.DataSize); dstData := Sign(srcData, ADetachedSignature, AIncludeCertificate, ACertificate, ACertificates); ADestination.Write(dstData.Data^, dstData.DataSize); finally dstData.Free(); srcData.Free(); end; DoProgress(ASource.Position - sourceStart, sourceSize); end; function GetSignerCertificate(pvGetArg: PVOID; dwCertEncodingType: DWORD; pSignerId: PCERT_INFO; hMsgCertStore: HCERTSTORE): PCCERT_CONTEXT; stdcall; begin Result := CertDuplicateCertificateContext(PCCERT_CONTEXT(pvGetArg)); end; procedure TclEncryptor.VerifyDetached(const AData, ASignature: TclCryptData; ACertificate: TclCertificate); var verifyPara: CRYPT_VERIFY_MESSAGE_PARA; rgpbToBeSigned: array[0..0] of PBYTE; rgcbToBeSigned: array[0..0] of DWORD; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsEncryptorDemoDisplayed) and (not IsCertDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncryptorDemoDisplayed := True; IsCertDemoDisplayed := True; {$ENDIF} end; {$ENDIF} {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'VerifyDetached');{$ENDIF} if ExtractCertificates then begin ExtractedCertificates.ImportFromMessage(ASignature); end; if (ACertificate = nil) then begin ACertificate := GetExtractedCertificate(); end; CheckCertificate(ACertificate); ZeroMemory(@verifyPara, SizeOf(verifyPara)); verifyPara.cbSize := SizeOf(verifyPara); verifyPara.dwMsgAndCertEncodingType := FEncodingType; verifyPara.pfnGetSignerCertificate := GetSignerCertificate; verifyPara.pvGetArg := ACertificate.Context; rgpbToBeSigned[0] := AData.Data; rgcbToBeSigned[0] := AData.DataSize; if not CryptVerifyDetachedMessageSignature(@verifyPara, 0, ASignature.Data, ASignature.DataSize, 1, @rgpbToBeSigned[0], @rgcbToBeSigned[0], nil) then begin RaiseCryptError('CryptVerifyDetachedMessageSignature'); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'VerifyDetached'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'VerifyDetached', E); raise; end; end;{$ENDIF} end; procedure TclEncryptor.VerifyEnveloped(const ASourceFile, ADestinationFile: string); var src, dst: TStream; begin src := nil; dst := nil; try src := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite); dst := TFileStream.Create(ADestinationFile, fmCreate); VerifyEnveloped(src, dst); finally dst.Free(); src.Free(); end; end; procedure TclEncryptor.VerifyEnveloped(ASource, ADestination: TStream); begin VerifyEnveloped(ASource, ADestination, GetCertificate(SignStore, SignCertificate, False)); end; procedure TclEncryptor.VerifyEnveloped(ASource, ADestination: TStream; ACertificate: TclCertificate); var srcData, dstData: TclCryptData; sourceSize, sourceStart: Integer; begin sourceSize := ASource.Size - ASource.Position; sourceStart := ASource.Position; DoProgress(ASource.Position - sourceStart, sourceSize); srcData := nil; dstData := nil; try srcData := TclCryptData.Create(); srcData.Allocate(ASource.Size - ASource.Position); ASource.Read(srcData.Data^, srcData.DataSize); dstData := VerifyEnveloped(srcData, ACertificate); ADestination.Write(dstData.Data^, dstData.DataSize); finally dstData.Free(); srcData.Free(); end; DoProgress(ASource.Position - sourceStart, sourceSize); end; procedure TclEncryptor.VerifyDetached(ASource, ASignature: TStream; ACertificate: TclCertificate); var srcData, sigData: TclCryptData; sourceSize, sourceStart: Integer; begin sourceSize := ASource.Size - ASource.Position; sourceStart := ASource.Position; DoProgress(ASource.Position - sourceStart, sourceSize); srcData := nil; sigData := nil; try srcData := TclCryptData.Create(); srcData.Allocate(ASource.Size - ASource.Position); ASource.Read(srcData.Data^, srcData.DataSize); sigData := TclCryptData.Create(); sigData.Allocate(ASignature.Size - ASignature.Position); ASignature.Read(sigData.Data^, sigData.DataSize); VerifyDetached(srcData, sigData, ACertificate); finally sigData.Free(); srcData.Free(); end; DoProgress(ASource.Position - sourceStart, sourceSize); end; procedure TclEncryptor.VerifyDetached(ASource, ASignature: TStream); begin VerifyDetached(ASource, ASignature, GetCertificate(SignStore, SignCertificate, False)); end; procedure TclEncryptor.VerifyDetached(const ASourceFile, ASignatureFile: string); var src, sig: TStream; begin src := nil; sig := nil; try src := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite); sig := TFileStream.Create(ASignatureFile, fmOpenRead or fmShareDenyWrite); VerifyDetached(src, sig); finally sig.Free(); src.Free(); end; end; function TclEncryptor.VerifyEnveloped(const AData: TclCryptData; ACertificate: TclCertificate): TclCryptData; var verifyPara: CRYPT_VERIFY_MESSAGE_PARA; cbVerified: DWORD; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsEncryptorDemoDisplayed) and (not IsCertDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncryptorDemoDisplayed := True; IsCertDemoDisplayed := True; {$ENDIF} end; {$ENDIF} {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'VerifyEnveloped');{$ENDIF} if ExtractCertificates then begin ExtractedCertificates.ImportFromMessage(AData); end; if (ACertificate = nil) then begin ACertificate := GetExtractedCertificate(); end; CheckCertificate(ACertificate); Result := TclCryptData.Create(); try ZeroMemory(@verifyPara, SizeOf(verifyPara)); verifyPara.cbSize := SizeOf(verifyPara); verifyPara.dwMsgAndCertEncodingType := FEncodingType; verifyPara.pfnGetSignerCertificate := GetSignerCertificate; verifyPara.pvGetArg := ACertificate.Context; cbVerified := 0; if CryptVerifyMessageSignature(@verifyPara, 0, AData.Data, AData.DataSize, nil, @cbVerified, nil) then begin Result.Allocate(cbVerified); if CryptVerifyMessageSignature(@verifyPara, 0, AData.Data, AData.DataSize, Result.Data, @cbVerified, nil) then begin Result.Reduce(cbVerified); Exit; end; end; RaiseCryptError('VerifyEnveloped'); except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'VerifyEnveloped'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'VerifyEnveloped', E); raise; end; end;{$ENDIF} end; function TclEncryptor.Encrypt(const AData: TclCryptData; ACertificates: TclCertificateList): TclCryptData; var i: Integer; encryptPara: CRYPT_ENCRYPT_MESSAGE_PARA; cbEncrypted: DWORD; gpRecipientCerts: PCCERT_CONTEXT; p: ^PCCERT_CONTEXT; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsEncryptorDemoDisplayed) and (not IsCertDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsEncryptorDemoDisplayed := True; IsCertDemoDisplayed := True; {$ENDIF} end; {$ENDIF} CheckCertificates(ACertificates); Result := TclCryptData.Create(); try ZeroMemory(@encryptPara, SizeOf(encryptPara)); encryptPara.cbSize := SizeOf(encryptPara); encryptPara.dwMsgEncodingType := FEncodingType; encryptPara.ContentEncryptionAlgorithm.pszObjId := PclChar(GetTclString(FEncryptAlgorithm)); GetMem(gpRecipientCerts, SizeOf(PCCERT_CONTEXT) * ACertificates.Count); try for i := 0 to ACertificates.Count - 1 do begin p := Pointer(TclIntPtr(gpRecipientCerts) + SizeOf(PCCERT_CONTEXT) * i); p^ := ACertificates[i].Context; end; cbEncrypted := 0; if CryptEncryptMessage(@encryptPara, ACertificates.Count, gpRecipientCerts, AData.Data, AData.DataSize, nil, @cbEncrypted) then begin Result.Allocate(cbEncrypted); if CryptEncryptMessage(@encryptPara, ACertificates.Count, gpRecipientCerts, AData.Data, AData.DataSize, Result.Data, @cbEncrypted) then begin Result.Reduce(cbEncrypted); Exit; end; end; finally FreeMem(gpRecipientCerts); end; RaiseCryptError('Encrypt'); except Result.Free(); raise; end; end; end.
unit ULicenca; interface uses uDM, System.SysUtils, FireDAC.Stan.Param, Data.DB, ULicencaVO, uFireDAC, uLicencaItensVO, uGenericDAO, FireDAC.Comp.Client, uEnumerador, Vcl.Dialogs, uCadastroInterface, System.Generics.Collections, uDMFB, uFiltroLicenca, uFuncoesServidor, uClienteVO, uCliente, System.MaskUtils; const CConsulta: string = 'SELECT Lic_Id, Lic_Codigo, Lic_CNPJCPF,Lic_Empresa,Lic_QtdeEstacao,Lic_QtdeUsuario,Lic_IPExterno,Lic_DataAtualizacao,Lic_Build,Lic_IPLocal, Lic_Cliente, Cli_Nome, Rev_Nome FROM Licenca' + ' LEFT JOIN Cliente ON Lic_Cliente = Cli_Id' + ' LEFT JOIN Revenda ON Cli_Revenda = Rev_Id'; const CConsultaItens: string = 'SELECT LicIte_Id, LicIte_Codigo, LicIte_CNPJCPF,LicIte_DataLcto,LicIte_Licenca,LicIte_DataUtilizacao,LicIte_Situacao, LicIte_Utilizada, LicIte_Cliente, Cli_Nome, Rev_Nome FROM Licenca_Itens' + ' LEFT JOIN Cliente ON LicIte_Cliente = Cli_Id' + ' LEFT JOIN Revenda ON Cli_Revenda = Rev_Id'; type TLicenca = class private { Somente os métodos abaixo estão sendo utilizados: ListarTodos(AFiltro: TFiltroLicenca) ListarTodosItens(AFiltro: TFiltroLicenca) Os demais ainda não estão sendo utilizados por enquanto. } function LocalizarPorId(AId: Integer): TLicencaVO; function LocalizarPorCNPJ(ACNPJ: string): Integer; function LocalizarPorCodigo(ACodigo: integer): Integer; procedure Salvar(ALicenca: TLicencaVO); //--- ITENS--------------------------------------------------------------------- function LocalizarItensPorId(AId: Integer): TLicencaItensVO; function LocalizarItensPorCNPJ(ACNPJ: string): Integer; function LocalizarItensPorCodigo(ACodigo: integer): Integer; procedure SalvarItem(ALicencaItem: TLicencaItensVO); //--- FIREBIRD------------------------------------------------------------------ function FBListarLicenca: TObjectList<TLicencaVO>; function FBListarLicencaItens: TObjectList<TLicencaItensVO>; public procedure Importar(); procedure ImportarItens(); function ListarTodos(AFiltro: TFiltroLicenca): TObjectList<TLicencaVO>; function ListarTodosItens(AFiltro: TFiltroLicenca): TObjectList<TLicencaItensVO>; function LicencaSalvar(ALicenca: TObjectList<TLicencaVO>): string; function LicencaItensSalvar(ALicencaItens: TObjectList<TLicencaItensVO>): string; function LocalizarPorDoct(ADoc: string; var AIdCliente: integer; var ARazaoSocial: string): string; function LimparLicencas(): string; end; implementation uses uParametros; { TLicenca } function TLicenca.FBListarLicenca: TObjectList<TLicencaVO>; var sb: TStringBuilder; Qry: TFDQuery; lista: TObjectList<TLicencaVO>; model: TLicencaVO; begin lista := TObjectList<TLicencaVO>.Create(); sb := TStringBuilder.Create; Qry := TFDQuery.create(nil); try sb.AppendLine('select '); sb.AppendLine('clilicid,'); sb.AppendLine('cliliccnpjcpf,'); sb.AppendLine('clilicempresa,'); sb.AppendLine('clilicquantestacao,'); sb.AppendLine('clilicquantusuario,'); sb.AppendLine('clilicipexterno,'); sb.AppendLine('clilicdatahratualizacao,'); sb.AppendLine('clilicbuild,'); sb.AppendLine('cliliciplocal'); sb.AppendLine(' from tclientelicenca'); Qry.Connection := DMFB.FBConexao; Qry.SQL.Text := sb.ToString(); Qry.Open(); while not Qry.Eof do begin model := TLicencaVO.Create; model.Codigo := Qry.FieldByName('clilicid').AsInteger; model.CNPJCPF := Qry.FieldByName('cliliccnpjcpf').AsString; model.Empresa := Qry.FieldByName('clilicempresa').AsString; model.QtdeEstacao := Qry.FieldByName('clilicquantestacao').AsInteger; model.QtdeUsuario := Qry.FieldByName('clilicquantusuario').AsInteger; model.IPExterno := Qry.FieldByName('clilicipexterno').AsString; model.DataAtualizacao := Qry.FieldByName('clilicdatahratualizacao').AsDateTime; model.Build := Qry.FieldByName('clilicbuild').AsString; model.IPLocal := Qry.FieldByName('cliliciplocal').AsString; lista.Add(model); Qry.Next; end; finally FreeAndNil(sb); freeAndNil(Qry); end; Result := lista; end; function TLicenca.FBListarLicencaItens: TObjectList<TLicencaItensVO>; var sb: TStringBuilder; FD: TFDQuery; lista: TObjectList<TLicencaItensVO>; model: TLicencaItensVO; begin lista := TObjectList<TLicencaItensVO>.Create(); sb := TStringBuilder.Create; FD := TFDQuery.create(nil); try sb.AppendLine('select '); sb.AppendLine('licid,'); sb.AppendLine('liccnpjcpf,'); sb.AppendLine('licdatahoralcto,'); sb.AppendLine('liclicenca,'); sb.AppendLine('licutilizada,'); sb.AppendLine('licdatahrutilizacao,'); sb.AppendLine('licsituacao'); sb.AppendLine(' from tlicenca'); FD.Connection := DMFB.FBConexao; FD.SQL.Text := sb.ToString(); FD.Open(); while not FD.Eof do begin model := TLicencaItensVO.Create; model.Codigo := FD.FieldByName('licid').AsInteger; model.CNPJCPF := FD.FieldByName('liccnpjcpf').AsString; model.DataLcto := FD.FieldByName('licdatahoralcto').AsDateTime; model.Licenca := FD.FieldByName('liclicenca').AsString; model.LicencaUtilizada := FD.FieldByName('licutilizada').AsString; model.DataUtilizacao := FD.FieldByName('licdatahrutilizacao').AsDateTime; model.Situacao := FD.FieldByName('licsituacao').AsString; lista.Add(model); FD.Next; end; finally FreeAndNil(sb); freeAndNil(FD); end; Result := lista; end; procedure TLicenca.Importar(); var lista: TObjectList<TLicencaVO>; model: TLicencaVO; Item: TLicencaVO; id: Integer; Cliente: TClienteVO; ClienteNegocio: TCliente; begin lista := FBListarLicenca(); model := TLicencaVO.Create; ClienteNegocio := TCliente.Create; try for Item in lista do begin id := LocalizarPorCNPJ(Item.CNPJCPF); model.Id := id; model.CNPJCPF := Item.CNPJCPF; model.Empresa := Item.Empresa; model.QtdeEstacao := Item.QtdeEstacao; model.QtdeUsuario := Item.QtdeUsuario; model.IPExterno := Item.IPExterno; model.DataAtualizacao := Item.DataAtualizacao; model.Build := Item.Build; model.IPLocal := Item.IPLocal; model.Codigo := Item.Codigo; Cliente := ClienteNegocio.LocalizarPorDoct(item.CNPJCPF); if Cliente.Id > 0 then begin model.IdCliente := Cliente.Id; model.RazaoSocial := Cliente.RazaoSocial; end; Salvar(model); end; finally FreeAndNil(lista); FreeAndNil(model); FreeAndNil(ClienteNegocio); end; end; procedure TLicenca.ImportarItens; var lista: TObjectList<TLicencaItensVO>; model: TLicencaItensVO; Item: TLicencaItensVO; id: Integer; begin lista := FBListarLicencaItens(); model := TLicencaItensVO.Create; try for Item in lista do begin id := LocalizarItensPorCNPJ(Item.CNPJCPF); model.Id := id; model.CNPJCPF := Item.CNPJCPF; model.Codigo := Item.Codigo; model.DataLcto := Item.DataLcto; model.Licenca := Item.Licenca; model.DataUtilizacao := Item.DataUtilizacao; model.Situacao := Item.Situacao; model.LicencaUtilizada := Item.LicencaUtilizada; SalvarItem(model); end; finally FreeAndNil(lista); FreeAndNil(model); end; end; function TLicenca.LicencaItensSalvar( ALicencaItens: TObjectList<TLicencaItensVO>): string; var model: TLicencaItensVO; Item: TLicencaItensVO; id: Integer; iContador: Integer; idCliente: Integer; sRazaoSocial: string; begin model := TLicencaItensVO.Create; iContador := 1; try try for Item in ALicencaItens do begin id := LocalizarItensPorCodigo(Item.Codigo); model.Id := id; model.CNPJCPF := Item.CNPJCPF; model.Codigo := Item.Codigo; model.DataLcto := Item.DataLcto; model.Licenca := Item.Licenca; model.DataUtilizacao := Item.DataUtilizacao; model.Situacao := Item.Situacao; model.LicencaUtilizada := Copy(Item.LicencaUtilizada,1,1); model.SituacaoTela := model.Situacao; model.UtilizadaTela := model.LicencaUtilizada; LocalizarPorDoct(Item.CNPJCPF, idCliente, sRazaoSocial); model.IdCliente := idCliente; model.RazaoSocial := sRazaoSocial; SalvarItem(model); Inc(iContador); end; Result := ''; except on E: Exception do begin Result := E.Message + IntToStr(iContador); end; end; finally FreeAndNil(model); end; end; function TLicenca.LicencaSalvar(ALicenca: TObjectList<TLicencaVO>): string; var model: TLicencaVO; Item: TLicencaVO; id: Integer; idCliente: Integer; sRazaoSocial: string; Cliente: TCliente; begin Cliente := TCliente.Create; model := TLicencaVO.Create; try try for Item in ALicenca do begin id := LocalizarPorCodigo(Item.Codigo); LocalizarPorDoct(item.CNPJCPF, idCliente, sRazaoSocial); if idCliente > 0 then Cliente.AtualizaVersao(idCliente, item.Build); model.Id := id; model.IdCliente := idCliente; model.RazaoSocial := sRazaoSocial; model.CNPJCPF := Item.CNPJCPF; model.Empresa := Item.Empresa; model.QtdeEstacao := Item.QtdeEstacao; model.QtdeUsuario := Item.QtdeUsuario; model.IPExterno := Item.IPExterno; model.DataAtualizacao := Item.DataAtualizacao; model.Build := Item.Build; model.IPLocal := Item.IPLocal; model.Codigo := Item.Codigo; Salvar(model); end; Result := ''; except on E: Exception do begin Result := E.Message; end; end; finally if Assigned(model) then FreeAndNil(model); FreeAndNil(Cliente); end; end; function TLicenca.LimparLicencas: string; var obj: TFireDAC; begin obj := TFireDAC.create; try dm.StartTransacao(); try obj.ExecutarSQL('DELETE FROM Licenca_Itens'); obj.ExecutarSQL('DELETE FROM Licenca'); dm.Commit(); except On E: Exception do begin dm.Roolback(); Result := E.Message; end; end; finally FreeAndNil(obj); end; end; function TLicenca.ListarTodos(AFiltro: TFiltroLicenca): TObjectList<TLicencaVO>; var obj: TFireDAC; lista: TObjectList<TLicencaVO>; model: TLicencaVO; InstrucaoSQL: string; sData: string; begin lista := TObjectList<TLicencaVO>.Create(); obj := TFireDAC.create; try InstrucaoSQL := CConsulta; InstrucaoSQL := InstrucaoSQL + ' WHERE Lic_Id > 0'; sData := Trim(AFiltro.DataUtilizacaoInicial); if sData <> DataEmBranco then InstrucaoSQL := InstrucaoSQL + ' AND Lic_DataAtualizacao >= ' + TFuncoes.DataIngles(sData); sData := Trim(AFiltro.DataUtilizacaoFinal); if sData <> DataEmBranco then InstrucaoSQL := InstrucaoSQL + ' AND Lic_DataAtualizacao <= ' + TFuncoes.DataIngles(sData); if AFiltro.IdCliente > 0 then InstrucaoSQL := InstrucaoSQL + ' AND Cli_Id = ' + AFiltro.IdCliente.ToString(); if AFiltro.Cliente.IdRevenda <> '' then InstrucaoSQL := InstrucaoSQL + ' AND Rev_Id = ' + AFiltro.Cliente.IdRevenda; obj.OpenSQL(InstrucaoSQL); while not obj.Model.Eof do begin model := TLicencaVO.Create; model.Id := obj.Model.FieldByName('Lic_Id').AsInteger; model.Codigo := obj.Model.FieldByName('Lic_Codigo').AsInteger; model.CNPJCPF := obj.Model.FieldByName('Lic_CNPJCPF').AsString; model.Empresa := obj.Model.FieldByName('Lic_Empresa').AsString; model.QtdeEstacao := obj.Model.FieldByName('Lic_QtdeEstacao').AsInteger; model.QtdeUsuario := obj.Model.FieldByName('Lic_QtdeUsuario').AsInteger; model.IPExterno := obj.Model.FieldByName('Lic_IPExterno').AsString; model.DataAtualizacao := obj.Model.FieldByName('Lic_DataAtualizacao').AsDateTime; model.Build := obj.Model.FieldByName('Lic_Build').AsString; model.IPLocal := obj.Model.FieldByName('Lic_IPLocal').AsString; model.IdCliente := obj.Model.FieldByName('Lic_Cliente').AsInteger; model.RazaoSocial := obj.Model.FieldByName('Cli_Nome').AsString; lista.Add(model); obj.Model.Next; end; finally FreeAndNil(obj); end; Result := lista; end; function TLicenca.ListarTodosItens(AFiltro: TFiltroLicenca): TObjectList<TLicencaItensVO>; var obj: TFireDAC; lista: TObjectList<TLicencaItensVO>; model: TLicencaItensVO; InstrucaoSQL: string; sSituacao: string; sUtilizada: string; begin lista := TObjectList<TLicencaItensVO>.Create(); obj := TFireDAC.create; try InstrucaoSQL := CConsultaItens; InstrucaoSQL := InstrucaoSQL + ' WHERE LicIte_Id > 0'; if AFiltro.DataUtilizacaoInicial.Trim <> DataEmBranco then InstrucaoSQL := InstrucaoSQL + ' AND LicIte_DataLcto >= ' + TFuncoes.DataIngles(AFiltro.DataUtilizacaoInicial); if AFiltro.DataUtilizacaoFinal.Trim <> DataEmBranco then InstrucaoSQL := InstrucaoSQL + ' AND LicIte_DataLcto <= ' + TFuncoes.DataIngles(AFiltro.DataUtilizacaoFinal); if AFiltro.IdCliente > 0 then InstrucaoSQL := InstrucaoSQL + ' AND Cli_Id = ' + AFiltro.IdCliente.ToString(); if AFiltro.Cliente.IdRevenda <> '' then InstrucaoSQL := InstrucaoSQL + ' AND Rev_Id = ' + AFiltro.Cliente.IdRevenda; sUtilizada := Copy(AFiltro.Utilizadas,1,1); if sUtilizada <> 'T' then InstrucaoSQL := InstrucaoSQL + ' AND LicIte_Utilizada = ' + QuotedStr(sUtilizada); sSituacao := Copy(AFiltro.Situacao,1,1); if sSituacao <> 'T' then begin if sSituacao = 'N' then InstrucaoSQL := InstrucaoSQL + ' AND LicIte_Situacao = 1' else InstrucaoSQL := InstrucaoSQL + ' AND LicIte_Situacao = 2'; end; obj.OpenSQL(InstrucaoSQL); while not obj.Model.Eof do begin model := TLicencaItensVO.Create; model.Id := obj.Model.FieldByName('LicIte_Id').AsInteger; try model.Codigo := obj.Model.FieldByName('LicIte_Codigo').AsInteger; except model.Codigo := 0; end; model.CNPJCPF := obj.Model.FieldByName('LicIte_CNPJCPF').AsString; model.DataLcto := obj.Model.FieldByName('LicIte_DataLcto').AsDateTime; model.Licenca := obj.Model.FieldByName('LicIte_Licenca').AsString; model.LicencaUtilizada := obj.Model.FieldByName('LicIte_Utilizada').AsString; model.DataUtilizacao := obj.Model.FieldByName('LicIte_DataUtilizacao').AsDateTime; model.Situacao := obj.Model.FieldByName('LicIte_Situacao').AsString; model.IdCliente := obj.Model.FieldByName('LicIte_Cliente').AsInteger; model.RazaoSocial := obj.Model.FieldByName('Cli_Nome').AsString; lista.Add(model); obj.Model.Next; end; finally FreeAndNil(obj); end; Result := lista; end; function TLicenca.LocalizarItensPorCNPJ(ACNPJ: string): Integer; var obj: TFireDAC; begin obj := TFireDAC.create; try obj.OpenSQL(CConsultaItens + ' WHERE LicIte_CNPJCPF = ' + QuotedStr(ACNPJ)); Result := obj.Model.FieldByName('LicIte_Id').AsInteger; finally FreeAndNil(obj); end; end; function TLicenca.LocalizarItensPorCodigo(ACodigo: integer): Integer; var obj: TFireDAC; begin obj := TFireDAC.create; try obj.OpenSQL(CConsultaItens + ' WHERE LicIte_Codigo = ' + IntToStr(ACodigo)); Result := obj.Model.FieldByName('LicIte_Id').AsInteger; finally FreeAndNil(obj); end; end; function TLicenca.LocalizarItensPorId(AId: Integer): TLicencaItensVO; var obj: TFireDAC; model: TLicencaItensVO; begin model := TLicencaItensVO.Create; obj := TFireDAC.create; try obj.OpenSQL(CConsulta + ' WHERE LicIte_Id = ' + IntToStr(AId)); model.Id := obj.Model.FieldByName('LicIte_Id').AsInteger; model.Codigo := obj.Model.FieldByName('LicIte_Codigo').AsInteger; model.CNPJCPF := obj.Model.FieldByName('LicIte_CNPJCPF').AsString; model.DataLcto := obj.Model.FieldByName('LicIte_DataLcto').AsDateTime; model.Licenca := obj.Model.FieldByName('LicIte_Licenca').AsString; model.DataUtilizacao := obj.Model.FieldByName('LicIte_DataUtilizacao').AsDateTime; model.Situacao := obj.Model.FieldByName('LicIte_Situacao').AsString; model.LicencaUtilizada := obj.Model.FieldByName('LicIte_Utilizada').AsString; finally FreeAndNil(obj); end; Result := model; end; function TLicenca.LocalizarPorCNPJ(ACNPJ: string): Integer; var obj: TFireDAC; begin obj := TFireDAC.create; try obj.OpenSQL(CConsulta + ' WHERE Lic_CNPJCPF = ' + QuotedStr(ACNPJ)); Result := obj.Model.FieldByName('Lic_Id').AsInteger; finally FreeAndNil(obj); end; end; function TLicenca.LocalizarPorCodigo(ACodigo: integer): Integer; var obj: TFireDAC; begin obj := TFireDAC.create; try obj.OpenSQL(CConsulta + ' WHERE Lic_Codigo = ' + IntToStr(ACodigo)); Result := obj.Model.FieldByName('Lic_Id').AsInteger; finally FreeAndNil(obj); end; end; function TLicenca.LocalizarPorDoct(ADoc: string; var AIdCliente: integer; var ARazaoSocial: string): string; var obj: TFireDAC; sDoc: string; begin obj := TFireDAC.create; sDoc := ADoc; if Copy(sDoc, 1, 3) = '000' then sDoc := Copy(sDoc, 4, 15); if length(sDoc) = 14 then sDoc := FormatMaskText('##.###.###/####-##;0;_', sDoc) else sDoc := FormatMaskText('###.###.###-##;0;_', sDoc); try obj.OpenSQL('SELECT Cli_Id, Cli_Revenda, Cli_Nome FROM Cliente WHERE Cli_Dcto = ' + QuotedStr(SDoc) ); AIdCliente := obj.Model.FieldByName('Cli_Id').AsInteger; if AIdCliente > 0 then ARazaoSocial := obj.Model.FieldByName('Cli_Nome').AsString else ARazaoSocial := ''; Result := ''; finally FreeAndNil(obj); end; end; function TLicenca.LocalizarPorId(AId: Integer): TLicencaVO; var obj: TFireDAC; model: TLicencaVO; begin model := TLicencaVO.Create(); obj := TFireDAC.create; try obj.OpenSQL(CConsulta + ' WHERE Lic_Id = ' + IntToStr(AId)); model.Id := obj.Model.FieldByName('Lic_Id').AsInteger; model.Codigo := obj.Model.FieldByName('Lic_Codigo').AsInteger; model.CNPJCPF := obj.Model.FieldByName('Lic_CNPJCPF').AsString; model.Empresa := obj.Model.FieldByName('Lic_Empresa').AsString; model.QtdeEstacao := obj.Model.FieldByName('Lic_QtdeEstacao').AsInteger; model.QtdeUsuario := obj.Model.FieldByName('Lic_QtdeUsuario').AsInteger; model.IPExterno := obj.Model.FieldByName('Lic_IPExterno').AsString; model.DataAtualizacao := obj.Model.FieldByName('Lic_DataAtualizacao').AsDateTime; model.Build := obj.Model.FieldByName('Lic_Build').AsString; model.IPLocal := obj.Model.FieldByName('Lic_IPLocal').AsString; finally FreeAndNil(obj); end; Result := model; end; procedure TLicenca.Salvar(ALicenca: TLicencaVO); begin TGenericDAO.Save<TLicencaVO>(ALicenca); end; procedure TLicenca.SalvarItem(ALicencaItem: TLicencaItensVO); begin TGenericDAO.Save<TLicencaItensVO>(ALicencaItem); end; end.
{* CSI 1101-X, Winter, 1999 *} {* Assignment 6, Question #1 *} {* Identification: Mark Sattolo, student# 428500 *} {* tutorial group DGD-4, t.a. = Jensen Boire *} UNIT A6Q1TPU ; INTERFACE type nodeptr = ^node ; stackitem = string ; node = record value: stackitem ; next: nodeptr end ; stack = nodeptr ; var memory_count: integer ; procedure get_node( var P: nodeptr ); procedure return_node(var P: nodeptr) ; procedure create(var S:stack); procedure destroy(var S: stack); function is_empty(S:stack): boolean ; procedure top( s:stack; var v:stackitem ); procedure pop(var S:stack); procedure push(v:stackitem; var S:stack); IMPLEMENTATION {******* MEMORY MANAGEMENT PROCEDURES **********} { get_node - Returns a pointer to a new node. } procedure get_node( var P: nodeptr ); BEGIN memory_count := memory_count + 1 ; new( P ) END ; { return_node - returns the dynamic memory to which P points to the global pool. } procedure return_node(var P: nodeptr) ; BEGIN memory_count := memory_count - 1 ; P^.value := 'I am free' ; P^.next := nil ; dispose( P ) END ; {************ IMPLEMENTATION of 'STACK' *****************} procedure create(var S:stack); BEGIN S := nil END; { proc create } procedure destroy(var S: stack); BEGIN if S <> nil then BEGIN destroy(S^.next); return_node(S) ; S := nil { optional, simply as an aid to debugging } END ; END; { proc destroy } function is_empty(S:stack): boolean ; BEGIN is_empty := (S = nil) END; { fxn is_empty } procedure top( s:stack; var v:stackitem ); BEGIN if is_empty(S) then BEGIN writeln('** error, tried to top an empty stack **') ; writeln('hit enter once or twice to halt the program'); readln; { clears the input if there is any left } readln; { this is the one the user enters } halt END { if } else BEGIN v := s^.value END { else } END; { proc top } procedure pop(var S:stack); var temp: nodeptr; BEGIN if is_empty(S) then BEGIN writeln('** error, tried to pop an empty stack **') ; writeln('hit enter once or twice to halt the program'); readln; { clears the input if there is any left } readln; { this is the one the user enters } halt END { if } else BEGIN temp := S; S := S^.next ; return_node(temp) END { else } END; { proc pop } procedure push(v:stackitem; var S:stack); var temp: nodeptr; BEGIN temp := S ; get_node( S ); S^.value := v ; S^.next := temp END; {proc push } END.
unit session; {$mode objfpc}{$H+} interface uses Classes, SysUtils, syncobjs, visa, visatype; type TOnCloseNotify = procedure(ASender: TObject) of object; { TVisaSession } TVisaSession = class(TComponent) private fThrowException, fActive: boolean; fAddress: string; fConnectTimeout: longint; fLock: TCriticalSection; fOnClose: TOnCloseNotify; fHandle: ViSession; function Send(const Str: string): longint; function Recv(ALength: longint; out res: ViStatus): string; procedure SetActive(AValue: boolean); procedure CheckError(EC: ViStatus); procedure Connect; procedure Disconnect; protected procedure Loaded; override; public procedure Write(const Str: string); function Read: string; procedure Lock(ATimeout: longint = 2000); procedure Unlock; function Query(const AQuery: string): string; procedure Command(const ACmd: string); procedure Command(const ACmd: string; const Args: array of const); procedure DeviceClear; function ReadSTB: byte; function QueryBlock(const AQuery: string; var Data; ALength: longint): longint; function CommandBlock(const ACmd: string; const Data; ALength: longint): longint; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Address: string read fAddress write fAddress; property ConnectTimeout: longint read fConnectTimeout write fConnectTimeout; property Active: boolean read fActive write SetActive; property OnClose: TOnCloseNotify read fOnClose write fOnClose; end; EVisaException = class(Exception); procedure Register; implementation { TVisaSession } function TVisaSession.Send(const Str: string): longint; var res: ViUInt32; begin CheckError(viWrite(fHandle, @str[1], length(str), @res)); result := res; end; function TVisaSession.Recv(ALength: longint; out res: ViStatus): string; var buf: array of char; res2: ViUInt32; begin setlength(buf, alength); res := viRead(fHandle, @buf[0], Alength, @res2); CheckError(res); setlength(result, res2); move(buf[0], result[1], res2); end; procedure TVisaSession.SetActive(AValue: boolean); begin if fActive=AValue then Exit; fActive := AValue; //if (ComponentState*[csDesigning,csLoading])<>[] then exit; if AValue then begin try connect; except fActive := false; raise exception.create('Failed to connect'); end; end else disconnect; end; procedure TVisaSession.CheckError(EC: ViStatus); var buffer: array[0..4095] of char; begin if (ec < VI_SUCCESS) then begin if EC = VI_ERROR_CONN_LOST then begin if assigned(fOnClose) then fOnClose(self); fActive := false; end; if fThrowException then begin if viStatusDesc(fHandle, EC, @buffer[0]) >= VI_SUCCESS then raise EVisaException.CreateFmt('VISA Error(%d) "%s"', [ec, pchar(buffer)]) at get_caller_addr(get_frame) else raise EVisaException.CreateFmt('VISA Unknown error %d', [ec]); end; end; end; procedure TVisaSession.Connect; var p: ViSession; begin CheckError(viGetDefaultRM(@p)); CheckError(viOpen(p, pchar(fAddress), VI_NO_LOCK, fConnectTimeout, @fHandle)); viSetAttribute(fHandle, VI_ATTR_TMO_VALUE, fConnectTimeout); end; procedure TVisaSession.Disconnect; begin CheckError(viClose(fHandle)); end; procedure TVisaSession.Loaded; begin //if fActive then Connect; end; procedure TVisaSession.Write(const Str: string); var i: longint; begin i := 0; while i < length(str) do i := i+Send(copy(str, i+1, length(str)-i)); end; function TVisaSession.Read: string; var res: ViStatus; begin result := ''; repeat result := result + recv(1024, res); until (res <> VI_SUCCESS_MAX_CNT); end; procedure TVisaSession.Lock(ATimeout: longint); begin CheckError(viLock(fHandle, VI_EXCLUSIVE_LOCK, atimeout, nil, nil)); end; procedure TVisaSession.Unlock; begin CheckError(viUnlock(fHandle)); end; function TVisaSession.Query(const AQuery: string): string; begin fLock.Enter; try Write(AQuery); result := Read; finally fLock.Leave; end; end; procedure TVisaSession.Command(const ACmd: string); begin fLock.Enter; try Write(ACmd); finally fLock.Leave; end; end; procedure TVisaSession.Command(const ACmd: string; const Args: array of const); begin Command(format(ACmd, args)); end; procedure TVisaSession.DeviceClear; begin CheckError(viClear(fHandle)); end; function TVisaSession.ReadSTB: byte; var res: ViUInt16; begin CheckError(viReadSTB(fHandle, @res)); result := res; end; function TVisaSession.QueryBlock(const AQuery: string; var Data; ALength: longint): longint; var st: string; digits,size,ofs: longint; begin fLock.Enter; try Write(AQuery); st := Read; if length(st) < 2 then raise exception.Create('Invalid IEEE488.2 data block'); if st[1] <> '#' then raise exception.Create('Invalid IEEE488.2 data block'); digits := strtoint(st[2]); if digits = 0 then begin ofs := 2; size := length(st)-2; end else begin ofs := 3+digits; size := strtoint(copy(st,3,digits)); end; if size > ALength then size := ALength; move(st[ofs], data, size); result := size; finally fLock.Leave; end; end; function TVisaSession.CommandBlock(const ACmd: string; const Data; ALength: longint): longint; var msg, lenStr: string; begin result := ALength; fLock.Enter; try lenStr:=inttostr(ALength); setlength(msg, length(ACmd)+1+1+length(lenStr)+alength); move(ACmd[1], msg[1], length(ACmd)); msg[1+length(ACmd)] := '#'; msg[1+length(ACmd)+1] := char(byte('0')+length(lenStr)); move(lenstr[1], msg[1+length(ACmd)+2], length(lenStr)); move(data, msg[1+length(ACmd)+2+length(lenstr)], ALength); Write(msg); finally fLock.Leave; end; end; constructor TVisaSession.Create(AOwner: TComponent); begin inherited Create(AOwner); fThrowException := true; fLock := TCriticalSection.Create; fActive := false; fAddress := ''; fHandle := 0; fConnectTimeout := 2000; end; destructor TVisaSession.Destroy; begin fThrowException := false; Active := false; fLock.Free; inherited Destroy; end; procedure Register; begin RegisterComponents('FP-Visa', [TVisaSession]); end; end.
unit EditApplianceForma; interface {$I defines.inc} uses WinAPI.Windows, WinAPI.Messages, System.SysUtils, System.Variants, System.Classes, VCL.Graphics, VCL.Controls, VCL.Forms, VCL.Menus, VCL.Dialogs, VCL.StdCtrls, VCL.Mask, Data.DB, VCL.DBCtrls, VCL.Buttons, VCL.ActnList, System.Actions, OkCancel_frame, DBCtrlsEh, FIBDataSet, pFIBDataSet, DBGridEh, DBLookupEh, GridsEH, DM, PrjConst, CnErrorProvider, FIBDatabase, pFIBDatabase, A4onTypeUnit, EhlibFIB, VCL.ExtCtrls; type TEditApplianceForm = class(TForm) dsAppl: TpFIBDataSet; cnError: TCnErrorProvider; trRead: TpFIBTransaction; trWrite: TpFIBTransaction; pnlOkCancel: TPanel; bbOk: TBitBtn; bbCancel: TBitBtn; mmoNotice: TDBMemoEh; edtName: TDBEditEh; edtMAC: TDBEditEh; cbApplProperty: TDBComboBoxEh; lcbApplType: TDBLookupComboboxEh; edtSN: TDBEditEh; ednCost: TDBNumberEditEh; Label1: TLabel; Label2: TLabel; Label3: TLabel; lbl1: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; dsDevType: TpFIBDataSet; srcDevType: TDataSource; dsMat: TpFIBDataSet; srcMat: TDataSource; lcbApplMID: TDBLookupComboboxEh; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure bbOkClick(Sender: TObject); procedure cbApplPropertyChange(Sender: TObject); procedure lcbApplMIDExit(Sender: TObject); private { Private declarations } fCI: TCustomerInfo; fApplID: Integer; procedure ReadData(); procedure SaveData(); function CheckData: Boolean; function CheckSN(const SN: String): string; function CheckMAC(const MAC: String): string; procedure OpenDS(); procedure CloseDS(); public { Public declarations } property CI: TCustomerInfo write fCI; property ApplID: Integer write fApplID; end; function EditAppliance(const aCI: TCustomerInfo; aAppl_ID: Int64): Integer; implementation uses MAIN, AtrCommon, AtrStrUtils, StrUtils, EquipEditForma, pFIBQuery, TelnetForma, atrCmdUtils; {$R *.dfm} function EditAppliance(const aCI: TCustomerInfo; aAppl_ID: Int64): Integer; begin Result := -1; if aCI.CUSTOMER_ID = -1 then Exit; with TEditApplianceForm.Create(application) do begin try CI := aCI; ApplID := aAppl_ID; OpenDS; ReadData; if ShowModal = mrOk then begin SaveData; Result := dsAppl['ID']; end; CloseDS; finally free; end; end; end; procedure TEditApplianceForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then bbOkClick(Sender); end; procedure TEditApplianceForm.FormKeyPress(Sender: TObject; var Key: Char); var go: Boolean; begin if (Key = #13) then begin go := True; if (ActiveControl is TDBLookupComboboxEh) then go := not(ActiveControl as TDBLookupComboboxEh).ListVisible; if (ActiveControl is TDBMemoEh) then go := False; if go then begin Key := #0; // eat enter key PostMessage(Self.Handle, WM_NEXTDLGCTL, 0, 0); end; end; end; procedure TEditApplianceForm.lcbApplMIDExit(Sender: TObject); begin if (not edtName.Enabled) and (fApplID = -1) then begin if VarIsNull(lcbApplMID.Value) then begin cnError.SetError(lcbApplMID, rsRequiredDict, iaMiddleLeft, bsNeverBlink); ednCost.Text := ''; Exit; end else cnError.Dispose(lcbApplMID); edtName.Text := lcbApplMID.Text; if not dsMat.FieldByName('COST').IsNull then ednCost.Value := dsMat['COST'] else ednCost.Text := ''; end; end; procedure TEditApplianceForm.OpenDS(); begin dsDevType.Open; dsMat.Open; end; procedure TEditApplianceForm.CloseDS(); begin dsMat.Close; dsDevType.Close; end; procedure TEditApplianceForm.ReadData(); begin dsAppl.ParamByName('ID').AsInt64 := fApplID; dsAppl.Open; if not dsAppl.FieldByName('NAME').IsNull then edtName.Text := dsAppl['NAME']; if not dsAppl.FieldByName('MAC').IsNull then edtMAC.Text := dsAppl['MAC']; if not dsAppl.FieldByName('SN').IsNull then edtSN.Text := dsAppl['SN']; if not dsAppl.FieldByName('NOTICE').IsNull then mmoNotice.Lines.Text := dsAppl['NOTICE']; if not dsAppl.FieldByName('COST').IsNull then ednCost.Value := dsAppl['COST']; if not dsAppl.FieldByName('M_ID').IsNull then lcbApplMID.KeyValue := dsAppl['M_ID']; if not dsAppl.FieldByName('A_TYPE').IsNull then lcbApplType.KeyValue := dsAppl['A_TYPE']; if fCI.isType = 0 then begin if not dsAppl.FieldByName('PROPERTY').IsNull then cbApplProperty.Value := dsAppl['PROPERTY']; end else begin cbApplProperty.Value := 1; cbApplProperty.Enabled := False; end; end; function TEditApplianceForm.CheckSN(const SN: String): string; begin Result := ''; if SN = '' then Exit; with TpFIBQuery.Create(Nil) do begin try Database := dmMain.dbTV; Transaction := dmMain.trReadQ; sql.Text := 'select c.Account_No, a.NAME'; sql.Add(' from Appliance a left outer join customer c on (a.Own_Id = c.Customer_Id and Own_Type = 0)'); sql.Add(' where a.SN = :SN'); if fApplID <> -1 then begin sql.Add('and a.ID <> :fApplID'); ParamByName('fApplID').AsInteger := fApplID; end; ParamByName('SN').asString := SN; Transaction.StartTransaction; ExecQuery; if not FieldByName('Account_No').IsNull then Result := Result + rsACCOUNT + ' ' + FieldByName('Account_No').Value + ' '; if not FieldByName('NAME').IsNull then Result := Result + ' ' + FieldByName('NAME').Value; Close; Transaction.Commit; finally free; end; end; end; function TEditApplianceForm.CheckMAC(const MAC: String): string; begin Result := ''; if MAC = '' then Exit; with TpFIBQuery.Create(Nil) do begin try Database := dmMain.dbTV; Transaction := dmMain.trReadQ; sql.Text := 'select c.Account_No, a.NAME'; sql.Add(' from Appliance a left outer join customer c on (a.Own_Id = c.Customer_Id and Own_Type = 0)'); sql.Add(' where a.MAC = :MAC'); if fApplID <> -1 then begin sql.Add('and a.ID <> :fApplID'); ParamByName('fApplID').AsInteger := fApplID; end; ParamByName('MAC').asString := MAC; Transaction.StartTransaction; ExecQuery; if not FieldByName('Account_No').IsNull then Result := Result + rsACCOUNT + ' ' + FieldByName('Account_No').Value + ' '; if not FieldByName('NAME').IsNull then Result := Result + ' ' + FieldByName('NAME').Value; Close; Transaction.Commit; finally free; end; end; end; procedure TEditApplianceForm.bbOkClick(Sender: TObject); begin if CheckData then ModalResult := mrOk; end; procedure TEditApplianceForm.cbApplPropertyChange(Sender: TObject); begin edtName.Enabled := (cbApplProperty.Value = 0); lcbApplMID.Enabled := (cbApplProperty.Value <> 0); end; function TEditApplianceForm.CheckData: Boolean; var ErrorNF: Boolean; // ErrorNotFound s: string; begin ErrorNF := True; if lcbApplType.Text = '' then begin cnError.SetError(lcbApplType, rsRequiredField, iaMiddleLeft, bsNeverBlink); // lcbApplType.SetFocus; // ErrorNF := False; end else cnError.Dispose(lcbApplType); if cbApplProperty.Text = '' then begin cnError.SetError(cbApplProperty, rsRequiredField, iaMiddleLeft, bsNeverBlink); cbApplProperty.SetFocus; ErrorNF := False; end else cnError.Dispose(cbApplProperty); if edtName.Text = '' then begin cnError.SetError(edtName, rsRequiredField, iaMiddleLeft, bsNeverBlink); if edtName.Enabled then edtName.SetFocus; ErrorNF := False; end else cnError.Dispose(edtName); s := CheckSN(edtSN.Text); if s <> '' then begin // если такой ип есть сообщим где cnError.SetError(edtSN, s, iaMiddleLeft, bsNeverBlink); edtSN.SetFocus; ErrorNF := False; end else cnError.Dispose(edtSN); if (edtMAC.Text <> '') then begin s := ValidateMAC(edtMAC.Text); if (s = '') then begin cnError.SetError(edtMAC, rsMACIncorrect, iaMiddleLeft, bsNeverBlink); ErrorNF := False; edtMAC.SetFocus; end else begin s := CheckMAC(edtMAC.Text); if s <> '' then begin cnError.SetError(edtMAC, s, iaMiddleLeft, bsNeverBlink); edtMAC.SetFocus; ErrorNF := False; end else cnError.Dispose(edtMAC); end; end else cnError.Dispose(edtMAC); Result := ErrorNF; end; procedure TEditApplianceForm.SaveData(); begin if fApplID = -1 then begin dsAppl.Insert; dsAppl['ID'] := dmMain.dbTV.Gen_Id('GEN_APPLIANCE_UID', 1); end else begin dsAppl.Edit; dsAppl['ID'] := fApplID; end; if fCI.isType = 1 // узел then dsAppl['OWN_TYPE'] := 1 else dsAppl['OWN_TYPE'] := 0; // абонент dsAppl['OWN_ID'] := fCI.CUSTOMER_ID; dsAppl['NAME'] := edtName.Text; dsAppl['PROPERTY'] := cbApplProperty.Value; dsAppl['MAC'] := edtMAC.Text; dsAppl['SN'] := edtSN.Text; dsAppl['NOTICE'] := mmoNotice.Lines.Text; if ednCost.Text <> '' then dsAppl['COST'] := ednCost.Value; if lcbApplMID.Text <> '' then dsAppl['M_ID'] := lcbApplMID.KeyValue; if lcbApplType.Text <> '' then dsAppl['A_TYPE'] := lcbApplType.KeyValue; dsAppl.Post; { ID UID A_TYPE Тип устройства. в справочнике Objects_type = 48 OWN_ID ID владельца (абонента/узла) OWN_TYPE где установлен 0=абонента, 1=узел NAME Название NOTICE Примечание M_ID Ссылка на материал, если это собственность компании MAC MAC адрес устройства SN Серийный номер COST D_N15_2 PROPERTY Собственность. 0-абонента. 1-компании. 2-рассрочка. 3-аренда. } end; end.
unit DirectionStepUnit; interface uses REST.Json.Types, System.Generics.Collections, Generics.Defaults, JSONNullableAttributeUnit, DirectionPathPointUnit, EnumsUnit, NullableBasicTypesUnit; type /// <summary> /// Direction Step /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Direction.dtd /// </remarks> TDirectionStep = class private [JSONName('direction')] [Nullable] FDirection: NullableString; [JSONName('directions')] [Nullable] FDirections: NullableString; [JSONName('distance')] [Nullable] FDistance: NullableDouble; [JSONName('distance_unit')] [Nullable] FDistanceUnit: NullableString; [JSONName('maneuverType')] [Nullable] FManeuverType: NullableString; [JSONName('compass_direction')] [Nullable] FCompassDirection: NullableString; [JSONName('duration_sec')] [Nullable] FDurationSec: NullableInteger; [JSONName('maneuverPoint')] [NullableObject(TDirectionPathPoint)] FManeuverPoint: NullableObject; function GetCompassDirection: TCompassDirection; function GetDirections: TDirectionEnum; function GetDistanceUnit: TDistanceUnit; function GetManeuverPoint: TDirectionPathPoint; function GetManeuverType: TDirectionEnum; procedure SetCompassDirection(const Value: TCompassDirection); procedure SetDirections(const Value: TDirectionEnum); procedure SetDistanceUnit(const Value: TDistanceUnit); procedure SetManeuverPoint(const Value: TDirectionPathPoint); procedure SetManeuverType(const Value: TDirectionEnum); public constructor Create; destructor Destroy; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// Text for current direction /// </summary> property Direction: NullableString read FDirection write FDirection; /// <summary> /// Directions of movement /// </summary> property Directions: TDirectionEnum read GetDirections write SetDirections; /// <summary> /// Step distance /// </summary> property Distance: NullableDouble read FDistance write FDistance; /// <summary> /// Distance unit - 'mi' or 'km' /// </summary> property DistanceUnit: TDistanceUnit read GetDistanceUnit write SetDistanceUnit; /// <summary> /// Maneuver type /// </summary> property ManeuverType: TDirectionEnum read GetManeuverType write SetManeuverType; /// <summary> /// Compass direction /// </summary> property CompassDirection: TCompassDirection read GetCompassDirection write SetCompassDirection; /// <summary> /// Step duration (sec) /// </summary> property DurationSec: NullableInteger read FDurationSec write FDurationSec; /// <summary> /// Step distance /// </summary> property ManeuverPoint: TDirectionPathPoint read GetManeuverPoint write SetManeuverPoint; end; TDirectionStepArray = TArray<TDirectionStep>; function SortDirectionSteps(DirectionSteps: TDirectionStepArray): TDirectionStepArray; implementation function SortDirectionSteps(DirectionSteps: TDirectionStepArray): TDirectionStepArray; begin SetLength(Result, Length(DirectionSteps)); if Length(DirectionSteps) = 0 then Exit; TArray.Copy<TDirectionStep>(DirectionSteps, Result, Length(DirectionSteps)); TArray.Sort<TDirectionStep>(Result, TComparer<TDirectionStep>.Construct( function (const DirectionStep1, DirectionStep2: TDirectionStep): Integer begin Result := DirectionStep1.Direction.Compare(DirectionStep2.Direction); end)); end; { TDirectionStep } constructor TDirectionStep.Create; begin FDirection := NullableString.Null; FDirections := NullableString.Null; FDistance := NullableDouble.Null; FDistanceUnit := NullableString.Null; FManeuverType := NullableString.Null; FCompassDirection := NullableString.Null; FDurationSec := NullableInteger.Null; FManeuverPoint := NullableObject.Null; end; destructor TDirectionStep.Destroy; begin FManeuverPoint.Free; inherited; end; function TDirectionStep.Equals(Obj: TObject): Boolean; var Other: TDirectionStep; begin Result := False; if not (Obj is TDirectionStep) then Exit; Other := TDirectionStep(Obj); Result := (FDirection = Other.FDirection) and (FDirections = Other.FDirections) and (FDistance = Other.FDistance) and (FDistanceUnit = Other.FDistanceUnit) and (FManeuverType = Other.FManeuverType) and (FCompassDirection = Other.FCompassDirection) and (FDurationSec = Other.FDurationSec) and (FManeuverPoint = Other.FManeuverPoint); end; function TDirectionStep.GetCompassDirection: TCompassDirection; var CompassDirection: TCompassDirection; begin Result := TCompassDirection.cdUndefined; if FCompassDirection.IsNotNull then for CompassDirection := Low(TCompassDirection) to High(TCompassDirection) do if (FCompassDirection = TCompassDirectionDescription[CompassDirection]) then Exit(CompassDirection); end; function TDirectionStep.GetDirections: TDirectionEnum; var DirectionEnum: TDirectionEnum; begin Result := TDirectionEnum.dUnknown; if FDirections.IsNotNull then for DirectionEnum := Low(TDirectionEnum) to High(TDirectionEnum) do if (FDirections = TDirectionDescription[DirectionEnum]) then Exit(DirectionEnum); end; function TDirectionStep.GetDistanceUnit: TDistanceUnit; var DistanceUnit: TDistanceUnit; begin Result := TDistanceUnit.Undefinded; if FDistanceUnit.IsNotNull then for DistanceUnit := Low(TDistanceUnit) to High(TDistanceUnit) do if (FDistanceUnit = TDistanceUnitDescription[DistanceUnit]) then Exit(DistanceUnit); end; function TDirectionStep.GetManeuverPoint: TDirectionPathPoint; begin if FManeuverPoint.IsNull then Result := nil else Result := FManeuverPoint.Value as TDirectionPathPoint; end; function TDirectionStep.GetManeuverType: TDirectionEnum; var ManeuverType: TDirectionEnum; begin Result := TDirectionEnum.dUnknown; if FDistanceUnit.IsNotNull then for ManeuverType := Low(TDirectionEnum) to High(TDirectionEnum) do if (FManeuverType = TManeuverTypeDescription[ManeuverType]) then Exit(ManeuverType); end; procedure TDirectionStep.SetCompassDirection(const Value: TCompassDirection); begin FCompassDirection := TCompassDirectionDescription[Value]; end; procedure TDirectionStep.SetDirections(const Value: TDirectionEnum); begin FDirections := TDirectionDescription[Value]; end; procedure TDirectionStep.SetDistanceUnit(const Value: TDistanceUnit); begin FDistanceUnit := TDistanceUnitDescription[Value]; end; procedure TDirectionStep.SetManeuverPoint(const Value: TDirectionPathPoint); begin FManeuverPoint := Value; end; procedure TDirectionStep.SetManeuverType(const Value: TDirectionEnum); begin FManeuverType := TManeuverTypeDescription[Value]; end; end.
unit InfoXTRANTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoXTRANRecord = record PCode: String[2]; PDescription: String[30]; PGroup: String[1]; PCertificateCoverage: Boolean; PActive: Boolean; PModCount: SmallInt; End; TInfoXTRANClass2 = class public PCode: String[2]; PDescription: String[30]; PGroup: String[1]; PCertificateCoverage: Boolean; PActive: Boolean; PModCount: SmallInt; End; // function CtoRInfoXTRAN(AClass:TInfoXTRANClass):TInfoXTRANRecord; // procedure RtoCInfoXTRAN(ARecord:TInfoXTRANRecord;AClass:TInfoXTRANClass); TInfoXTRANBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoXTRANRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoXTRAN = (InfoXTRANPrimaryKey); TInfoXTRANTable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFGroup: TStringField; FDFCertificateCoverage: TBooleanField; FDFActive: TBooleanField; FDFModCount: TSmallIntField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPGroup(const Value: String); function GetPGroup:String; procedure SetPCertificateCoverage(const Value: Boolean); function GetPCertificateCoverage:Boolean; procedure SetPActive(const Value: Boolean); function GetPActive:Boolean; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetEnumIndex(Value: TEIInfoXTRAN); function GetEnumIndex: TEIInfoXTRAN; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoXTRANRecord; procedure StoreDataBuffer(ABuffer:TInfoXTRANRecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFGroup: TStringField read FDFGroup; property DFCertificateCoverage: TBooleanField read FDFCertificateCoverage; property DFActive: TBooleanField read FDFActive; property DFModCount: TSmallIntField read FDFModCount; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PGroup: String read GetPGroup write SetPGroup; property PCertificateCoverage: Boolean read GetPCertificateCoverage write SetPCertificateCoverage; property PActive: Boolean read GetPActive write SetPActive; property PModCount: SmallInt read GetPModCount write SetPModCount; published property Active write SetActive; property EnumIndex: TEIInfoXTRAN read GetEnumIndex write SetEnumIndex; end; { TInfoXTRANTable } TInfoXTRANQuery = class( TDBISAMQueryAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFGroup: TStringField; FDFCertificateCoverage: TBooleanField; FDFActive: TBooleanField; FDFModCount: TSmallIntField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPGroup(const Value: String); function GetPGroup:String; procedure SetPCertificateCoverage(const Value: Boolean); function GetPCertificateCoverage:Boolean; procedure SetPActive(const Value: Boolean); function GetPActive:Boolean; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoXTRANRecord; procedure StoreDataBuffer(ABuffer:TInfoXTRANRecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFGroup: TStringField read FDFGroup; property DFCertificateCoverage: TBooleanField read FDFCertificateCoverage; property DFActive: TBooleanField read FDFActive; property DFModCount: TSmallIntField read FDFModCount; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PGroup: String read GetPGroup write SetPGroup; property PCertificateCoverage: Boolean read GetPCertificateCoverage write SetPCertificateCoverage; property PActive: Boolean read GetPActive write SetPActive; property PModCount: SmallInt read GetPModCount write SetPModCount; published property Active write SetActive; end; { TInfoXTRANTable } procedure Register; implementation procedure TInfoXTRANTable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFGroup := CreateField( 'Group' ) as TStringField; FDFCertificateCoverage := CreateField( 'CertificateCoverage' ) as TBooleanField; FDFActive := CreateField( 'Active' ) as TBooleanField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; end; { TInfoXTRANTable.CreateFields } procedure TInfoXTRANTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXTRANTable.SetActive } procedure TInfoXTRANTable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoXTRANTable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoXTRANTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoXTRANTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoXTRANTable.SetPGroup(const Value: String); begin DFGroup.Value := Value; end; function TInfoXTRANTable.GetPGroup:String; begin result := DFGroup.Value; end; procedure TInfoXTRANTable.SetPCertificateCoverage(const Value: Boolean); begin DFCertificateCoverage.Value := Value; end; function TInfoXTRANTable.GetPCertificateCoverage:Boolean; begin result := DFCertificateCoverage.Value; end; procedure TInfoXTRANTable.SetPActive(const Value: Boolean); begin DFActive.Value := Value; end; function TInfoXTRANTable.GetPActive:Boolean; begin result := DFActive.Value; end; procedure TInfoXTRANTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoXTRANTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoXTRANTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 2, N'); Add('Description, String, 30, N'); Add('Group, String, 1, N'); Add('CertificateCoverage, Boolean, 0, N'); Add('Active, Boolean, 0, N'); Add('ModCount, SmallInt, 0, N'); end; end; procedure TInfoXTRANTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoXTRANTable.SetEnumIndex(Value: TEIInfoXTRAN); begin case Value of InfoXTRANPrimaryKey : IndexName := ''; end; end; function TInfoXTRANTable.GetDataBuffer:TInfoXTRANRecord; var buf: TInfoXTRANRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PGroup := DFGroup.Value; buf.PCertificateCoverage := DFCertificateCoverage.Value; buf.PActive := DFActive.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoXTRANTable.StoreDataBuffer(ABuffer:TInfoXTRANRecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFGroup.Value := ABuffer.PGroup; DFCertificateCoverage.Value := ABuffer.PCertificateCoverage; DFActive.Value := ABuffer.PActive; DFModCount.Value := ABuffer.PModCount; end; function TInfoXTRANTable.GetEnumIndex: TEIInfoXTRAN; var iname : string; begin result := InfoXTRANPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoXTRANPrimaryKey; end; procedure TInfoXTRANQuery.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFGroup := CreateField( 'Group' ) as TStringField; FDFCertificateCoverage := CreateField( 'CertificateCoverage' ) as TBooleanField; FDFActive := CreateField( 'Active' ) as TBooleanField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; end; { TInfoXTRANQuery.CreateFields } procedure TInfoXTRANQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXTRANQuery.SetActive } procedure TInfoXTRANQuery.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoXTRANQuery.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoXTRANQuery.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoXTRANQuery.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoXTRANQuery.SetPGroup(const Value: String); begin DFGroup.Value := Value; end; function TInfoXTRANQuery.GetPGroup:String; begin result := DFGroup.Value; end; procedure TInfoXTRANQuery.SetPCertificateCoverage(const Value: Boolean); begin DFCertificateCoverage.Value := Value; end; function TInfoXTRANQuery.GetPCertificateCoverage:Boolean; begin result := DFCertificateCoverage.Value; end; procedure TInfoXTRANQuery.SetPActive(const Value: Boolean); begin DFActive.Value := Value; end; function TInfoXTRANQuery.GetPActive:Boolean; begin result := DFActive.Value; end; procedure TInfoXTRANQuery.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoXTRANQuery.GetPModCount:SmallInt; begin result := DFModCount.Value; end; function TInfoXTRANQuery.GetDataBuffer:TInfoXTRANRecord; var buf: TInfoXTRANRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PGroup := DFGroup.Value; buf.PCertificateCoverage := DFCertificateCoverage.Value; buf.PActive := DFActive.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoXTRANQuery.StoreDataBuffer(ABuffer:TInfoXTRANRecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFGroup.Value := ABuffer.PGroup; DFCertificateCoverage.Value := ABuffer.PCertificateCoverage; DFActive.Value := ABuffer.PActive; DFModCount.Value := ABuffer.PModCount; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoXTRANTable, TInfoXTRANQuery, TInfoXTRANBuffer ] ); end; { Register } function TInfoXTRANBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..6] of string = ('CODE','DESCRIPTION','GROUP','CERTIFICATECOVERAGE','ACTIVE','MODCOUNT' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 6) and (flist[x] <> s) do inc(x); if x <= 6 then result := x else result := 0; end; function TInfoXTRANBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftBoolean; 5 : result := ftBoolean; 6 : result := ftSmallInt; end; end; function TInfoXTRANBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; 3 : result := @Data.PGroup; 4 : result := @Data.PCertificateCoverage; 5 : result := @Data.PActive; 6 : result := @Data.PModCount; end; end; end.
unit DW.Consts.Android; interface const cPermissionAccessBackgroundLocation = 'android.permission.ACCESS_BACKGROUND_LOCATION'; cPermissionAccessCoarseLocation = 'android.permission.ACCESS_COARSE_LOCATION'; cPermissionAccessFineLocation = 'android.permission.ACCESS_FINE_LOCATION'; cPermissionCamera = 'android.permission.CAMERA'; cPermissionReadContacts = 'android.permission.READ_CONTACTS'; cPermissionReadExternalStorage = 'android.permission.READ_EXTERNAL_STORAGE'; cPermissionReadPhoneState = 'android.permission.READ_PHONE_STATE'; cPermissionReadSMS = 'android.permission.READ_SMS'; cPermissionReceiveMMS = 'android.permission.RECEIVE_MMS'; cPermissionReceiveSMS = 'android.permission.RECEIVE_SMS'; cPermissionReceiveWAPPush = 'android.permission.RECEIVE_WAP_PUSH'; cPermissionRecordAudio = 'android.permission.RECORD_AUDIO'; cPermissionSendSMS = 'android.permission.SEND_SMS'; cPermissionUseFingerprint = 'android.permission.USE_FINGERPRINT'; cPermissionWriteExternalStorage = 'android.permission.WRITE_EXTERNAL_STORAGE'; implementation end.
// ************************************************************************************************** // // Unit uGlobalPreviewHandler // unit for the Delphi Preview Handler https://github.com/RRUZ/delphi-preview-handler // // 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 uGlobalPreviewHandler.pas. // // The Initial Developer of the Original Code is Rodrigo Ruz V. // Portions created by Rodrigo Ruz V. are Copyright (C) 2011-2023 Rodrigo Ruz V. // All Rights Reserved. // // ************************************************************************************************* unit uGlobalPreviewHandler; interface uses uStackTrace, Classes, Controls, StdCtrls, SysUtils, uEditor, uCommonPreviewHandler, uPreviewHandler; const GUID_GlobalPreviewHandler: TGUID = '{AD8855FB-F908-4DDF-982C-ADB9DE5FF000}'; type TGlobalPreviewHandler = class(TBasePreviewHandler) public constructor Create(AParent: TWinControl); override; end; implementation Uses uDelphiIDEHighlight, uDelphiVersions, uLogExcept, SynEdit, Windows, Forms, uMisc; type TWinControlClass = class(TWinControl); constructor TGlobalPreviewHandler.Create(AParent: TWinControl); begin TLogPreview.Add('TGlobalPreviewHandler.Create'); inherited Create(AParent); try if IsWindow(TWinControlClass(AParent).WindowHandle) then begin // TLogPreview.Add('TGlobalPreviewHandler TFrmEditor.Create'); // Editor := TFrmEditor.Create(AParent); // Editor.Parent := AParent; // Editor.Align := alClient; // Editor.BorderStyle := bsNone; // Editor.Extensions := FExtensions; // TFrmEditor.AParent := AParent; TFrmEditor.Extensions := FExtensions; TLogPreview.Add('TGlobalPreviewHandler Done'); end; except on E: Exception do TLogPreview.Add(Format('Error in %s.Create - Message: %s: Trace %s', [Self.ClassName, E.Message, E.StackTrace])); end; end; end.
unit FeatureIntf; interface uses Classes, dCucuberListIntf; type IFeature = interface(IInterface) ['{862178A4-5ACE-44C5-8990-4D96133984C1}'] function GetScenarios: ICucumberList; function GetDescricao: string; function GetTitulo: string; procedure SetDescricao(const Value: string); procedure SetTitulo(const Value: string); function Valid: Boolean; property Scenarios: ICucumberList read GetScenarios; property Descricao: string read GetDescricao write SetDescricao; property Titulo: string read GetTitulo write SetTitulo; end; implementation end.
unit MdiChilds.CopyStruct; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, Vcl.StdCtrls, Vcl.CheckLst, Vcl.ExtCtrls, JvComponentBase, JvDragDrop, GsDocument, MdiChilds.ProgressForm, MdiChilds.Reg, Contnrs, ActionHandler; type TFmCopyStruct = class(TFmProcess) pMain: TPanel; pLeft: TPanel; Splitter1: TSplitter; pRight: TPanel; lbDest: TCheckListBox; lbSource: TCheckListBox; Label1: TLabel; Label2: TLabel; gbOptions: TGroupBox; chkSaveCaptions: TCheckBox; chkSaveMeasure: TCheckBox; chkDoNotCopyBulletin: TCheckBox; chkDoNotCopyZones: TCheckBox; DoNotIgnoreNewRows: TCheckBox; dragDropLeft: TJvDragDrop; dragDropRight: TJvDragDrop; btnSave: TButton; mLog: TMemo; lblErrors: TLabel; procedure dragDropLeftDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure dragDropRightDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSaveClick(Sender: TObject); procedure Button1Click(Sender: TObject); private procedure RemoveDocuments(L: TCheckListBox); procedure ExecuteCopyStruct(D: TGsDocument); function FindSourceDocument(D: TGsDocument): TGsDocument; procedure DoCopyStruct(Dest, Source: TGsDocument); procedure DebugNotFound(D: TGsDocument); procedure EnumElements(S: TStringList; D: TGsDocument); protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; procedure DoResize(Sender: TObject); override; procedure BeforeExecute; override; public procedure UpdateList(L: TCheckListBox; Values: TStrings); end; TCopyStructActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmCopyStruct: TFmCopyStruct; implementation const notFound = '! НЕНАЙДЕННЫЕ ЭЛЕМЕНТЫ В '; {$R *.dfm} procedure TFmCopyStruct.BeforeExecute; begin inherited; mLog.Clear; end; procedure TFmCopyStruct.btnSaveClick(Sender: TObject); var I: Integer; begin for I := 0 to lbDest.Count - 1 do TGsDocument(lbDest.Items.Objects[I]).Save; if lbDest.Count > 0 then MessageBoxInfo('Документ(ы) сохранен(ы).'); end; procedure TFmCopyStruct.Button1Click(Sender: TObject); begin TGsDocument(lbDest.Items.Objects[0]) .Assign(lbSource.Items.Objects[0] as TGsDocument); TGsDocument(lbDest.Items.Objects[0]).Save; end; procedure TFmCopyStruct.DebugNotFound(D: TGsDocument); begin mLog.Lines.Add(Format('Не найдено соответствие для: %s. ' + #13#10 + 'Прверьте шифры и номера документов, а также типы документов.', [ExtractFileName(D.FileName)])); end; procedure TFmCopyStruct.DoCopyStruct(Dest, Source: TGsDocument); var DestList: TStringList; SourceList: TStringList; I, Index: Integer; SourceItem, DestItem: TGsAbstractItem; NoFoundedChapter: TGsAbstractContainer; NotFoundItem: TGsAbstractItem; TempDoc: TGsDocument; Caption, Measure: string; begin if Source.DocumentType <> Dest.DocumentType then begin DebugNotFound(Dest); Exit; end; TempDoc := NewGsDocument; try TempDoc.Assign(Source); if Source.DocumentType = dtBaseData then NoFoundedChapter := TGsChapter.Create(Source) else NoFoundedChapter := TGsAbstractContainer.Create(Source); case Source.DocumentType of dtPrice: Source.Materials.Insert(NoFoundedChapter, 0); dtIndex, dtBaseData: Source.Chapters.Insert(NoFoundedChapter, 0); end; NoFoundedChapter.Caption := notFound + ' ' + ExtractFileName(Source.FileName); SourceList := TStringList.Create; SourceList.Sorted := True; try EnumElements(SourceList, Source); DestList := TStringList.Create; DestList.Sorted := True; try EnumElements(DestList, Dest); for I := 0 to DestList.Count - 1 do begin DestItem := TGsAbstractItem(DestList.Objects[I]); Index := SourceList.IndexOf(DestList[I]); if Index <> -1 then begin SourceItem := TGsAbstractItem(SourceList.Objects[Index]); //AssignWithParams(SourceItem, DestItem, False); Caption := TGsAbstractElement(SourceItem).Caption; if SourceItem is TGsPriceElement then Measure := TGsPriceElement(SourceItem).Measure else if SourceItem is TGsRow then Measure := TGsRow(SourceItem).Measure else Measure := ''; SourceItem.Assign(DestItem); if not chkSaveCaptions.Checked then TGsAbstractElement(SourceItem).Caption := Caption; if not chkSaveMeasure.Checked then begin if SourceItem is TGsPriceElement then TGsPriceElement(SourceItem).Measure := Measure else if SourceItem is TGsRow then TGsRow(SourceItem).Measure := Measure; end; SourceItem.Tag := '1'; end else begin NotFoundItem := NoFoundedChapter.CreateCompatibleObject(DestItem); NotFoundItem.Assign(DestItem); if NotFoundItem is TGsRow then TGsRow(NotFoundItem).Code := TGsRow(DestItem).Number(False); NotFoundItem.Tag := '1'; NoFoundedChapter.Add(NotFoundItem); end; end; for I := 0 to SourceList.Count - 1 do begin SourceItem := TGsAbstractItem(SourceList.Objects[I]); if SourceItem.Tag <> '1' then begin SourceItem.Enabled := False; end; end; if not chkDoNotCopyZones.Checked then Source.Zones.Assign(Dest.Zones); Dest.Assign(Source); if chkDoNotCopyBulletin.Checked then Dest.ResourceBulletin.Clear; if chkDoNotCopyZones.Checked then //если не копировать зоны с шаблона то восстанавливаем наши зоны обратно Dest.Zones.Assign(TempDoc.Zones); finally DestList.Free; end; finally SourceList.Free; end; Source.Assign(TempDoc); finally TempDoc.Free; end; end; procedure TFmCopyStruct.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; D: TGsDocument; begin ShowMessage := True; ProgressForm.InitPB(lbDest.Count); for I := 0 to lbDest.Count - 1 do begin if not ProgressForm.InProcess then Break; if lbDest.Checked[I] then begin D := TGsDocument(lbDest.Items.Objects[I]); ExecuteCopyStruct(D); end; end; end; procedure TFmCopyStruct.DoResize(Sender: TObject); begin inherited; btnSave.Top := Bevel.Height + 10; end; procedure TFmCopyStruct.dragDropLeftDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin UpdateList(lbDest, Value); end; procedure TFmCopyStruct.dragDropRightDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin UpdateList(lbSource, Value); end; procedure TFmCopyStruct.EnumElements(S: TStringList; D: TGsDocument); var L: TList; I: Integer; Item: TGsAbstractItem; begin L := TList.Create; try case D.DocumentType of dtPrice: begin D.Workers.EnumItems(L, TGsPriceElement, True); D.Materials.EnumItems(L, TGsPriceElement, True); D.Mashines.EnumItems(L, TGsPriceElement, True); D.Mechanics.EnumItems(L, TGsPriceElement, True); end; dtIndex: D.Chapters.EnumItems(L, TGsIndexElement, True); dtBaseData: D.Chapters.EnumItems(L, TGsRow, True); end; for I := 0 to L.Count - 1 do begin Item := TGsAbstractItem(L[I]); if Item is TGsRow then S.AddObject(TGsRow(Item).Number(True), Item) else if Item is TGsPriceElement then S.AddObject(TGsPriceElement(Item).Code, Item) else S.AddObject(TGsIndexElement(Item).Code, Item); end; finally L.Free; end; end; procedure TFmCopyStruct.ExecuteCopyStruct(D: TGsDocument); var SourceDoc: TGsDocument; begin SourceDoc := FindSourceDocument(D); if SourceDoc <> nil then DoCopyStruct(D, SourceDoc) else Self.DebugNotFound(D); end; function TFmCopyStruct.FindSourceDocument(D: TGsDocument): TGsDocument; var I: Integer; Finded: TGsDocument; begin Result := nil; for I := 0 to lbSource.Count - 1 do begin if not lbSource.Checked[I] then Continue; Finded := TGsDocument(lbSource.Items.Objects[I]); if (Finded.DocumentType = D.DocumentType) then begin if (Finded.DocumentType = dtBaseData) then begin if (Finded.TypeAndNumber = D.TypeAndNumber) and (Finded.BaseDataType = D.BaseDataType) then begin Result := Finded; Exit; end; end else begin Result := Finded; Exit; end; end; end; end; procedure TFmCopyStruct.FormClose(Sender: TObject; var Action: TCloseAction); begin RemoveDocuments(lbDest); RemoveDocuments(lbSource); inherited; end; procedure TFmCopyStruct.RemoveDocuments(L: TCheckListBox); var I: Integer; D: TGsDocument; begin for I := 0 to L.Count - 1 do begin D := L.Items.Objects[I] as TGsDocument; FreeAndNil(D); end; L.Clear; end; procedure TFmCopyStruct.UpdateList(L: TCheckListBox; Values: TStrings); var I: Integer; D: TGsDocument; begin RemoveDocuments(L); for I := 0 to Values.Count - 1 do begin if Values[I].EndsText('.xml', Values[I]) then begin D := NewGsDocument; try D.LoadFromFile(Values[I]); L.AddItem(ExtractFileName(D.FileName), D); except MessageBoxError('Ошибка при загрузке файла: ' + ExtractFileName(Values[I])); D.Free; end; end; end; L.CheckAll(TCheckBoxState.cbChecked); end; { TCopyStructActionHandler } procedure TCopyStructActionHandler.ExecuteAction; begin TFmCopyStruct.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Копирование структуры', hkDefault, TCopyStructActionHandler); end.
unit uParametroVO; interface uses System.SysUtils, uKeyField, uTableName, System.Generics.Collections; type [TableName('Parametros')] TParametroVO = class private FObs: string; FValor: string; FCodigo: Integer; FId: Integer; FPrograma: Integer; FNome: string; procedure SetCodigo(const Value: Integer); procedure SetId(const Value: Integer); procedure SetNome(const Value: string); procedure SetObs(const Value: string); procedure SetPrograma(const Value: Integer); procedure SetValor(const Value: string); public [KeyField('Par_Id')] property Id: Integer read FId write SetId; [FieldName('Par_Codigo')] property Codigo: Integer read FCodigo write SetCodigo; [FieldNull('Par_Programa')] property Programa: Integer read FPrograma write SetPrograma; [FieldName('Par_Nome')] property Nome: string read FNome write SetNome; [FieldName('Par_Valor')] property Valor: string read FValor write SetValor; [FieldName('Par_Obs')] property Obs: string read FObs write SetObs; constructor Create(); overload; end; TListaParametros = TObjectList<TParametroVO>; implementation { TParametroVO } constructor TParametroVO.Create; begin inherited Create; end; procedure TParametroVO.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TParametroVO.SetId(const Value: Integer); begin FId := Value; end; procedure TParametroVO.SetNome(const Value: string); begin FNome := Value; end; procedure TParametroVO.SetObs(const Value: string); begin FObs := Value; end; procedure TParametroVO.SetPrograma(const Value: Integer); begin FPrograma := Value; end; procedure TParametroVO.SetValor(const Value: string); begin FValor := Value; end; end.
/// Definitions for the formats in a cell. unit tmsUFlxFormats; {$INCLUDE ..\FLXCOMPILER.INC} interface uses tmsUFlxMessages; type /// <summary> /// Horizontal Alignment on a cell. /// </summary> THFlxAlignment=( /// <summary> /// General Alignment. (Text to the left, numbers to the right and Errors and booleans centered) /// </summary> fha_general, /// <summary> /// Aligned to the left. /// </summary> fha_left, /// <summary> /// Horizontally centered on the cell. /// </summary> fha_center, /// <summary> /// Aligned to the right. /// </summary> fha_right, /// <summary> /// Repeat the text to fill the cell width. /// </summary> fha_fill, /// <summary> /// Justify with spaces the text so it fills the cell width. /// </summary> fha_justify, /// <summary> /// Centered on a group of cells. /// </summary> fha_center_across_selection); /// <summary> /// Vertical Alignment on a cell. /// </summary> TVFlxAlignment=( /// <summary> /// Aligned to the top. /// </summary> fva_top, /// <summary> /// Vertically centered on the cell. /// </summary> fva_center, /// <summary> /// Aligned to the bottom. /// </summary> fva_bottom, /// <summary> /// Justified on the cell. /// </summary> fva_justify, /// <summary> /// Distributed on the cell. /// </summary> fva_distributed ); /// <summary> /// Cell border style. /// </summary> TFlxBorderStyle= ( ///<summary>None</summary> fbs_None, ///<summary>Thin</summary> fbs_Thin, ///<summary>Medium</summary> fbs_Medium, ///<summary>Dashed</summary> fbs_Dashed, ///<summary>Dotted</summary> fbs_Dotted, ///<summary>Thick</summary> fbs_Thick, ///<summary>Double</summary> fbs_Double, ///<summary>Hair</summary> fbs_Hair, ///<summary>Medium dashed</summary> fbs_Medium_dashed, ///<summary>Dash dot</summary> fbs_Dash_dot, ///<summary>Medium_dash_dot</summary> fbs_Medium_dash_dot, ///<summary>Dash dot dot</summary> fbs_Dash_dot_dot, ///<summary>Medium dash dot dot</summary> fbs_Medium_dash_dot_dot, ///<summary>Slanted dash dot</summary> fbs_Slanted_dash_dot ); const /// <summary>Automatic </summary> TFlxPatternStyle_Automatic = 0; /// <summary>None </summary> TFlxPatternStyle_None = 1; /// <summary>Solid </summary> TFlxPatternStyle_Solid = 2; /// <summary>Gray50 </summary> TFlxPatternStyle_Gray50 = 3; /// <summary>Gray75 </summary> TFlxPatternStyle_Gray75 = 4; /// <summary>Gray25 </summary> TFlxPatternStyle_Gray25 = 5; /// <summary>Horizontal </summary> TFlxPatternStyle_Horizontal = 6; /// <summary>Vertical </summary> TFlxPatternStyle_Vertical = 7; /// <summary>Down </summary> TFlxPatternStyle_Down = 8; /// <summary>Up </summary> TFlxPatternStyle_Up = 9; /// <summary>Diagonal hatch.</summary> TFlxPatternStyle_Checker = 10; /// <summary>bold diagonal.</summary> TFlxPatternStyle_SemiGray75 = 11; /// <summary>thin horz lines </summary> TFlxPatternStyle_LightHorizontal = 12; /// <summary>thin vert lines</summary> TFlxPatternStyle_LightVertical = 13; /// <summary>thin \ lines</summary> TFlxPatternStyle_LightDown = 14; /// <summary>thin / lines</summary> TFlxPatternStyle_LightUp = 15; /// <summary>thin horz hatch</summary> TFlxPatternStyle_Grid = 16; /// <summary>thin diag</summary> TFlxPatternStyle_CrissCross = 17; /// <summary>12.5 % gray</summary> TFlxPatternStyle_Gray16 = 18; /// <summary>6.25 % gray</summary> TFlxPatternStyle_Gray8 = 19; type /// <summary> /// Pattern style for a cell. Use the constants TFlxPatternStyle_XXX to set this variable. /// </summary> TFlxPatternStyle=TFlxPatternStyle_Automatic..TFlxPatternStyle_Gray8; /// <summary> /// Defines a diagonal border for a cell. /// </summary> TFlxDiagonalBorder =( /// <summary> Cell doesn't have diagonal borders.</summary> fdb_None, /// <summary> Cell has a diagonal border going from top left to bottom right.</summary> fdb_DiagDown, /// <summary> Cell has a diagonal border going from top right to bottom left.</summary> fdb_DiagUp, /// <summary> Cell has both diagonal borders creating a cross.</summary> fdb_Both); /// <summary> /// Font style for a cell. /// </summary> TFlxFontStyle = ( /// <summary>Font is bold.</summary> flsBold, /// <summary>Font is italic.</summary> flsItalic, /// <summary>Font is striked out.</summary> flsStrikeOut, /// <summary>Font is superscript.</summary> flsSuperscript, /// <summary>Font is subscript.</summary> flsSubscript); /// <summary> /// Types of underline you can make in an Excel cell. /// </summary> TFlxUnderline = ( /// <summary>No underline.</summary> fu_None, /// <summary>Simple underline.</summary> fu_Single, /// <summary>Double underline.</summary> fu_Double, /// <summary>Simple underline but not underlining spaces between words.</summary> fu_SingleAccounting, /// <summary>Double underline but not underlining spaces between words.</summary> fu_DoubleAccounting); /// <summary>A set of TFlxFontStyle definitions.</summary> SetOfTFlxFontStyle= Set of TFlxFontStyle; /// <summary>this record describes an Excel font.</summary> TFlxFont=record /// <summary>Name of the font, like Arial or Times New Roman.</summary> Name: UTF16String; /// <summary> /// Height of the font (in units of 1/20th of a point). A Size20=200 means 10 points. /// </summary> Size20: Word; /// <summary> /// Index on the color palette. /// </summary> ColorIndex: integer; /// <summary> /// Style of the font, such as bold or italics. Underline is a different option. /// </summary> Style: SetOfTFlxFontStyle; /// <summary> /// Underline type. /// </summary> Underline: TFlxUnderline; /// <summary> /// Font family, (see Windows API LOGFONT structure). /// </summary> Family: byte; /// <summary> /// Character set. (see Windows API LOGFONT structure) /// </summary> CharSet: byte; end; /// <summary> /// Border style and color for one of the 4 sides of a cell. /// </summary> TFlxOneBorder=record /// <summary> /// Border style. /// </summary> Style: TFlxBorderStyle; /// <summary> /// Index to color palette. /// </summary> ColorIndex: integer; end; /// <summary> /// Defines the borders of a cell. /// </summary> TFlxBorders=record /// <summary> Left border.</summary> Left, /// <summary> Right border.</summary> Right, /// <summary> Top border.</summary> Top, /// <summary> Bottom border.</summary> Bottom, /// <summary> Diagonal borders.</summary> Diagonal: TFlxOneBorder; /// <summary> Style for the diagonal borders.</summary> DiagonalStyle: TFlxDiagonalBorder; end; /// <summary> /// Fill pattern and color for the background of a cell. /// </summary> TFlxFillPattern=record /// <summary> /// Fill style. /// </summary> Pattern: TFlxPatternStyle; /// <summary> /// Color for the foreground of the pattern. It is used when the pattern is solid, but not when it is automatic. /// </summary> FgColorIndex: integer; /// <summary> /// Color for the background of the pattern. If the pattern is solid it has no effect, but it is used when pattern is automatic. /// </summary> BgColorIndex: integer; end; /// <summary> /// Format for one cell. /// </summary> TFlxFormat=record /// <summary> /// Cell Font. /// </summary> Font: TFlxFont; /// <summary> /// Cell borders. /// </summary> Borders: TFlxBorders; /// <summary> /// Format string. (For example, "yyyy-mm-dd" for a date format, or "#.00" for a numeric 2 decimal format) /// <para/>This format string is the same you use in Excel unde "Custom" format when formatting a cell, and it is documented /// in Excel documentation. Under <b>"Finding out what format string to use in TFlxFormat.Format"</b> section in <b>UsingFlexCelAPI.pdf</b> /// you can find more detailed information on how to create this string. /// </summary> Format: UTF16String; /// <summary> /// Fill pattern. /// </summary> FillPattern: TFlxFillPattern; /// <summary> /// Horizontal alignment on the cell. /// </summary> HAlignment: THFlxAlignment; /// <summary> /// Vertical alignment on the cell. /// </summary> VAlignment: TVFlxAlignment; /// <summary> /// Cell is locked. /// </summary> Locked: boolean; /// <summary> /// Cell is Hidden. /// </summary> Hidden: boolean; /// <summary> /// Parent style. Not currently supported by flexcel. /// </summary> Parent: integer; /// <summary> /// Cell wrap. /// </summary> WrapText: boolean; /// <summary> /// Shrink to fit. /// </summary> ShrinkToFit: boolean; /// <summary> /// Text Rotation in degrees. <para/> /// 0 - 90 is up, <para/> /// 91 - 180 is down, <para/> /// 255 is vertical. /// </summary> Rotation: byte; /// <summary> /// Indent value. (in characters) /// </summary> Indent: byte; end; /// <summary> Pointer to a TFlxFormat </summary> PFlxFormat=^TFlxFormat; implementation end.
unit DW.FaderRectangle; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // RTL System.Classes, // FMX FMX.Objects, FMX.Controls; type /// <summary> /// Interposer class for fade in/out and integration with busy indicator (Enabled property should turn the indicator on/off) /// </summary> TRectangle = class(FMX.Objects.TRectangle) protected procedure Click; override; public /// <summary> /// Shows and enables, or disables and hides the indicator, and fades the rectangle in/out if required /// </summary> procedure Busy(const AIsBusy: Boolean; const AIndicator: TControl = nil; const AFade: Boolean = True; const AFadeInOpacity: Single = 0.4); /// <summary> /// Fades the rectangle in/out and enables the hit test so that OnClick can be used (when faded in) /// </summary> procedure Fade(const AFadeIn: Boolean; const AFadeInOpacity: Single = 0.4); overload; procedure Fade(const AFadeIn: Boolean; const AClickHandler: TNotifyEvent; const AFadeInOpacity: Single = 0.4); overload; end; implementation uses // RTL System.UITypes, // FMX FMX.Ani, FMX.StdCtrls; { TRectangle } procedure TRectangle.Busy(const AIsBusy: Boolean; const AIndicator: TControl = nil; const AFade: Boolean = True; const AFadeInOpacity: Single = 0.4); begin Enabled := not AIsBusy; if AIsBusy and AFade then Fade(True, AFadeInOpacity); if AIndicator <> nil then begin AIndicator.Enabled := AIsBusy; AIndicator.Visible := AIsBusy; AIndicator.BringToFront; end; if not AIsBusy and (Opacity > 0) then Fade(False); end; procedure TRectangle.Fade(const AFadeIn: Boolean; const AFadeInOpacity: Single = 0.4); var LFinalValue: Single; begin Visible := True; BringToFront; HitTest := AFadeIn; Fill.Color := TAlphaColorRec.Black; if AFadeIn then LFinalValue := AFadeInOpacity else LFinalValue := 0; TAnimator.AnimateFloat(Self, 'Opacity', LFinalValue); end; procedure TRectangle.Click; begin Fade(False); inherited; end; procedure TRectangle.Fade(const AFadeIn: Boolean; const AClickHandler: TNotifyEvent; const AFadeInOpacity: Single = 0.4); begin OnClick := AClickHandler; Fade(AFadeIn, AFadeInOpacity); end; end.
unit PlayerFlic; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, SpeedBmp, PlayerAnim, Flics, CodingFlic; type TFlicPlayer = class( TAnimPlayer ) private fFlicDecoder : TFlicDecoder; protected procedure ResetPalette; override; procedure InitPlayer; override; procedure DonePlayer; override; procedure SetPaintFlags( Value : TPaintFlags ); override; procedure SetAutoDelay( UseAutoDelay : boolean ); override; procedure SetStartingFrame( aStartingFrame : integer ); override; procedure SetEndingFrame( aEndingFrame : integer ); override; function GetStartingFrame : integer; override; function GetEndingFrame : integer; override; function GetKeyframed : boolean; override; function GetAnimFrame : integer; override; function GetAnimFrameCount : integer; override; public property FlicDecoder : TFlicDecoder read fFlicDecoder; constructor Create( AOwner : TComponent ); override; procedure LoadFromStream( aStream : TStream ); override; procedure SeekFrame( Index : integer ); override; procedure Next; override; function Empty : boolean; override; class function TimerResolution : integer; override; published property TimerInterval; property AutoDelay; property OnFramePlayed; property OnFinished; property OnFrameCountPlayed; property OnFatalException; property AutoSize; property Paused; property Center; property Stretch; property Loop; property Filename; property StartingFrame; property EndingFrame; // property Keyframed; property PlayFrom; property ShareTimer; property PaintFlags; published property Align; property Visible; property Enabled; property ParentShowHint; property ShowHint; property PopupMenu; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property DragMode; property DragCursor; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnStartDrag; end; // VCL Registration procedure Register; implementation uses WinUtils, GDI, ColorSpaces, Dibs, DibDraw, FlicPlayback, MemUtils, NumUtils, ViewUtils; {$R *.DCR} // Flic palette manipulation threadvar fCurrentPlayer : TFlicPlayer; function PlayColorChunks( Chunk : pointer; const FliSize : TPoint; Buffer : pointer; BufferWidth : integer ) : pointer; var ChunkColor : ^TFliChunkColor absolute Chunk; ColorPacket : ^TColorPacket; var i, j : integer; ColorCount : integer; CurrentColor : integer; FirstChanged : integer; LastChanged : integer; begin Result := pchar(Chunk) + PFliChunk(Chunk).Size; if (ChunkColor.Magic = idColor) or (ChunkColor.Magic = idColor256) then with fCurrentPlayer, AnimBuffer do begin FirstChanged := MaxInt; LastChanged := 0; ColorPacket := @ChunkColor.Packets; CurrentColor := 0; for i := 0 to ChunkColor.Count - 1 do begin with ColorPacket^ do begin inc( CurrentColor, Skip ); if Count = 0 // Count = 0 means all colors.. then ColorCount := 256 else ColorCount := Count; if FirstChanged > CurrentColor then FirstChanged := CurrentColor; if LastChanged < CurrentColor + ColorCount - 1 then LastChanged := CurrentColor + ColorCount - 1; for j := 0 to ColorCount - 1 do if not ( (CurrentColor + j) in LockedPalEntries ) then with RgbEntries[CurrentColor + j], Rgb[j] do begin if ChunkColor.Magic = idColor then begin rgbRed := r * 4; rgbGreen := g * 4; rgbBlue := b * 4; end else begin rgbRed := r; rgbGreen := g; rgbBlue := b; end; end; end; Inc( CurrentColor, ColorCount ); Inc( pchar(ColorPacket), sizeof(ColorPacket^) + sizeof( ColorPacket.Rgb[0] ) * ( ColorCount - 1 ) ); end; if FirstChanged <= LastChanged then ChangePaletteEntries( FirstChanged, LastChanged - FirstChanged + 1, RgbEntries^ ); end; end; // TFlicPlayer constructor TFlicPlayer.Create( AOwner : TComponent ); begin inherited; PlayFrom := pfAuto; end; function TFlicPlayer.Empty : boolean; begin Result := FlicDecoder = nil; end; const LoadInMemoryThreshold = 512 * 1024; procedure TFlicPlayer.InitPlayer; var bakAutoDelay : boolean; newInterval : integer; begin inherited; with fAnimRect do begin Left := 0; Top := 0; Right := FlicDecoder.Width; Bottom := FlicDecoder.Height; end; FlicDecoder.UnkChunkPlayer := PlayColorChunks; FlicDecoder.OnFinished := Finished; if ( PlayFrom = pfMemory ) or ( (PlayFrom = pfAuto) and (FlicDecoder.DiskSize < LoadInMemoryThreshold) ) then FlicDecoder.Stream.LoadInMemory; // Load the whole flic to memory fAnimBuffer := TSpeedBitmap.CreateSized( AnimWidth, -AnimHeight, 8 ); with AnimBuffer do begin FlicDecoder.AttachToDib( 0, 0, DibHeader, ScanLines ); if pfIgnorePalette in PaintFlags then IgnorePalette := true; if pfUseIdentityPalette in PaintFlags then ForcePaletteIdentity( true, true ); end; bakAutoDelay := AutoDelay; if AutoDelay then newInterval := FlicDecoder.FrameDelay[0] // All frames in Flic play at the same speed else newInterval := TimerInterval; TimerInterval := newInterval; // SetTimerInterval disables AutoDelay, fAutoDelay := bakAutoDelay; // so we must restore it.. Changed; Next; end; procedure TFlicPlayer.DonePlayer; begin inherited; FreeObject( fFlicDecoder ); end; class function TFlicPlayer.TimerResolution : integer; begin Result := 15; end; procedure TFlicPlayer.SetPaintFlags( Value : TPaintFlags ); var FullUpdate : boolean; begin inherited; FullUpdate := pfFullUpdate in Value; if FullUpdate <> (pfFullUpdate in PaintFlags) then begin if FullUpdate then Include( fPaintFlags, pfFullUpdate ) else Exclude( fPaintFlags, pfFullUpdate ); end; end; procedure TFlicPlayer.LoadFromStream( aStream : TStream ); begin DonePlayer; fFlicDecoder := TFlicDecoder.Create; try FlicDecoder.LoadFromStream( aStream ); InitPlayer; except DonePlayer; end; end; procedure TFlicPlayer.SetAutoDelay( UseAutoDelay : boolean ); begin if UseAutoDelay <> AutoDelay then begin if UseAutoDelay and Assigned( FlicDecoder ) then TimerInterval := FlicDecoder.FrameDelay[0]; fAutoDelay := UseAutoDelay; end; end; procedure TFlicPlayer.Next; var bakDontUpdateScreen : boolean; begin try fCurrentPlayer := Self; with FlicDecoder do begin if PFliFrame( CurrentFrame ).Chunks > 0 then begin ProcessFrame; inherited; end else // If no chunks, then we don't have to repaint begin bakDontUpdateScreen := DontUpdateScreen; DontUpdateScreen := true; inherited; DontUpdateScreen := bakDontUpdateScreen; end; NextFrame; end; except DonePlayer; // !!! FatalException; end; end; procedure TFlicPlayer.SeekFrame( Index : integer ); begin if Assigned( FlicDecoder ) then FlicDecoder.SeekFrame( Index ); inherited; end; function TFlicPlayer.GetAnimFrame : integer; begin if Assigned( FlicDecoder ) then Result := FlicDecoder.CurrentFrameIndx else Result := 0; end; function TFlicPlayer.GetAnimFrameCount : integer; begin if Assigned( FlicDecoder ) then Result := FlicDecoder.FrameCount else Result := 0; end; function TFlicPlayer.GetKeyframed : boolean; begin Result := false; end; procedure TFlicPlayer.SetStartingFrame( aStartingFrame : integer ); begin if Assigned( FlicDecoder ) then FlicDecoder.StartingFrame := aStartingFrame; inherited; end; procedure TFlicPlayer.SetEndingFrame( aEndingFrame : integer ); begin if Assigned( FlicDecoder ) then FlicDecoder.EndingFrame := aEndingFrame; inherited; end; function TFlicPlayer.GetStartingFrame : integer; begin if Assigned( FlicDecoder ) then Result := FlicDecoder.StartingFrame else Result := 1; end; function TFlicPlayer.GetEndingFrame : integer; begin if Assigned( FlicDecoder ) then Result := FlicDecoder.EndingFrame else Result := -1; end; procedure TFlicPlayer.ResetPalette; var bakCurrentFrame : integer; begin bakCurrentFrame := AnimFrame; SeekFrame( 1 ); // Make sure we replay the palette chunk SeekFrame( bakCurrentFrame ); end; // Registration procedure Register; begin RegisterComponents( 'Merchise', [TFlicPlayer] ); end; end.
unit nsDeferredTree; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Folders" // Автор: Лукьянец Р.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Folders/nsDeferredTree.pas" // Начат: 2006/10/23 08:36:25 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Основные прецеденты::Folders::Folders::Folders::TnsDeferredTree // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Tree_TLB, l3Base, l3Tree, FoldersDomainInterfaces ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsDeferredTreeWaitThread = class(Tl3ThreadContainer) private // private fields f_Tree : Pointer; {* InsDeferredTree} f_Root : Il3RootNode; private // private methods procedure AssignRoot; function Tree: InsDeferredTree; protected // realized methods procedure DoExecute; override; {* основная процедура нити. Для перекрытия в потомках } protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } public // public methods constructor Create(const aTree: InsDeferredTree); reintroduce; end;//TnsDeferredTreeWaitThread TnsDeferredTree = class(Tl3Tree, InsDeferredTree) private // private fields f_isReady : Boolean; f_BuilderThread : TnsDeferredTreeWaitThread; protected // realized methods function MakeRealRoot: Il3RootNode; procedure SetBuildedRoot(const aNewRoot: Il3RootNode); procedure WaitForReady; function IsReady: Boolean; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; protected // protected methods function DoMakeRealRoot: Il3RootNode; virtual; abstract; function MakeFakeRoot: Il3RootNode; virtual; abstract; procedure DoSetBuildedRoot(const aNewRoot: Il3RootNode); virtual; public // public methods class function Make: InsDeferredTree; reintroduce; end;//TnsDeferredTree {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} // start class TnsDeferredTreeWaitThread procedure TnsDeferredTreeWaitThread.AssignRoot; //#UC START# *4911B71302B4_4911B6CC0061_var* //#UC END# *4911B71302B4_4911B6CC0061_var* begin //#UC START# *4911B71302B4_4911B6CC0061_impl* Tree.SetBuildedRoot(f_Root); //#UC END# *4911B71302B4_4911B6CC0061_impl* end;//TnsDeferredTreeWaitThread.AssignRoot function TnsDeferredTreeWaitThread.Tree: InsDeferredTree; //#UC START# *4911B7220027_4911B6CC0061_var* //#UC END# *4911B7220027_4911B6CC0061_var* begin //#UC START# *4911B7220027_4911B6CC0061_impl* Result := InsDeferredTree(f_Tree); //#UC END# *4911B7220027_4911B6CC0061_impl* end;//TnsDeferredTreeWaitThread.Tree constructor TnsDeferredTreeWaitThread.Create(const aTree: InsDeferredTree); //#UC START# *4911B76C0033_4911B6CC0061_var* //#UC END# *4911B76C0033_4911B6CC0061_var* begin //#UC START# *4911B76C0033_4911B6CC0061_impl* f_Tree := Pointer(aTree); inherited Create(nil); Suspended := false; //#UC END# *4911B76C0033_4911B6CC0061_impl* end;//TnsDeferredTreeWaitThread.Create procedure TnsDeferredTreeWaitThread.DoExecute; //#UC START# *4911B69E037D_4911B6CC0061_var* //#UC END# *4911B69E037D_4911B6CC0061_var* begin //#UC START# *4911B69E037D_4911B6CC0061_impl* if Assigned(f_Tree) then begin try f_Root := Tree.MakeRealRoot; except f_Root := nil; end; Synchronize(AssignRoot); end; //#UC END# *4911B69E037D_4911B6CC0061_impl* end;//TnsDeferredTreeWaitThread.DoExecute procedure TnsDeferredTreeWaitThread.Cleanup; //#UC START# *479731C50290_4911B6CC0061_var* //#UC END# *479731C50290_4911B6CC0061_var* begin //#UC START# *479731C50290_4911B6CC0061_impl* f_Tree := nil; f_Root := nil; inherited; //#UC END# *479731C50290_4911B6CC0061_impl* end;//TnsDeferredTreeWaitThread.Cleanup class function TnsDeferredTree.Make: InsDeferredTree; var l_Inst : TnsDeferredTree; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; procedure TnsDeferredTree.DoSetBuildedRoot(const aNewRoot: Il3RootNode); //#UC START# *4911C5EC0155_4911B56101AD_var* //#UC END# *4911C5EC0155_4911B56101AD_var* begin //#UC START# *4911C5EC0155_4911B56101AD_impl* f_isReady := True; RootNode := aNewRoot; //#UC END# *4911C5EC0155_4911B56101AD_impl* end;//TnsDeferredTree.DoSetBuildedRoot function TnsDeferredTree.MakeRealRoot: Il3RootNode; //#UC START# *4911B2900238_4911B56101AD_var* //#UC END# *4911B2900238_4911B56101AD_var* begin //#UC START# *4911B2900238_4911B56101AD_impl* Result := DoMakeRealRoot; //#UC END# *4911B2900238_4911B56101AD_impl* end;//TnsDeferredTree.MakeRealRoot procedure TnsDeferredTree.SetBuildedRoot(const aNewRoot: Il3RootNode); //#UC START# *4911B29F0366_4911B56101AD_var* //#UC END# *4911B29F0366_4911B56101AD_var* begin //#UC START# *4911B29F0366_4911B56101AD_impl* DoSetBuildedRoot(aNewRoot); //#UC END# *4911B29F0366_4911B56101AD_impl* end;//TnsDeferredTree.SetBuildedRoot procedure TnsDeferredTree.WaitForReady; //#UC START# *4911B2AA014F_4911B56101AD_var* //#UC END# *4911B2AA014F_4911B56101AD_var* begin //#UC START# *4911B2AA014F_4911B56101AD_impl* if not f_isReady and Assigned(f_BuilderThread) then f_BuilderThread.WaitFor; //#UC END# *4911B2AA014F_4911B56101AD_impl* end;//TnsDeferredTree.WaitForReady function TnsDeferredTree.IsReady: Boolean; //#UC START# *4911B2B500D6_4911B56101AD_var* //#UC END# *4911B2B500D6_4911B56101AD_var* begin //#UC START# *4911B2B500D6_4911B56101AD_impl* Result := f_isReady; //#UC END# *4911B2B500D6_4911B56101AD_impl* end;//TnsDeferredTree.IsReady procedure TnsDeferredTree.Cleanup; //#UC START# *479731C50290_4911B56101AD_var* //#UC END# *479731C50290_4911B56101AD_var* begin //#UC START# *479731C50290_4911B56101AD_impl* f_isReady := False; l3Free(f_BuilderThread); inherited; //#UC END# *479731C50290_4911B56101AD_impl* end;//TnsDeferredTree.Cleanup procedure TnsDeferredTree.InitFields; //#UC START# *47A042E100E2_4911B56101AD_var* //#UC END# *47A042E100E2_4911B56101AD_var* begin //#UC START# *47A042E100E2_4911B56101AD_impl* inherited; RootNode := MakeFakeRoot; f_BuilderThread := TnsDeferredTreeWaitThread.Create(Self); //#UC END# *47A042E100E2_4911B56101AD_impl* end;//TnsDeferredTree.InitFields {$IfEnd} //not Admin AND not Monitorings end.
{ HIObjectCore.h Copyright (c) 2000-2003, Apple, Inc. All rights reserved. } { Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, 2004 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit HIObjectCore; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase; {$ALIGN MAC68K} { This file contains the base HIObjectxxx type declarations which should normally be in HIObject.p[.pas]. The declarations have been moved to this "core" file to fix a cyclic dependency which occurs with the present monlithic CarbonEvents.p[.pas] and an unfixed HIObject.p[.pas]. If/when the monlithic CarbonEvents.p[.pas] is broken up into two files corresponding to the Mac OS X headers CarbonEvents.h and CarbonEventsCore.h this file will no longer be needed and the type declarations can be returned to the HIObject.p[.pas] unit. } type HIObjectClassRef = ^SInt32; { an opaque 32-bit type } HIObjectClassRefPtr = ^HIObjectClassRef; { when a var xx:HIObjectClassRef parameter can be nil, it is changed to xx: HIObjectClassRefPtr } HIObjectRef = ^SInt32; { an opaque 32-bit type } end.
{ $Project$ $Workfile$ $Revision: 1.3 $ $DateUTC$ $Id: IdFiberWeaverThreaded.pas,v 1.3 2015/06/16 12:31:48 lukyanets Exp $ 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: IdFiberWeaverThreaded.pas,v $ Revision 1.3 2015/06/16 12:31:48 lukyanets Новый Indy 10 } { Rev 1.4 6/11/2004 8:39:56 AM DSiders Added "Do not Localize" comments. Rev 1.3 2004-04-23 19:46:52 Mattias TTempThread now uses WaitForFibers instead of sleep Rev 1.2 2004.04.22 11:45:18 PM czhower Bug fixes Rev 1.1 2004.02.09 9:16:40 PM czhower Updated to compile and match lib changes. Rev 1.0 2004.02.03 12:38:54 AM czhower Move Rev 1.2 2003.10.21 12:19:22 AM czhower TIdTask support and fiber bug fixes. Rev 1.1 2003.10.19 4:38:32 PM czhower Updates } unit IdFiberWeaverThreaded; interface uses Classes, IdFiberWeaverInline, IdThread, IdSchedulerOfThread, IdFiberWeaver, IdFiber; type TTempThread = class(TIdThread) protected FFiberWeaver: TIdFiberWeaverInline; // procedure AfterRun; override; procedure BeforeRun; override; procedure Run; override; end; TIdFiberWeaverThreaded = class(TIdFiberWeaver) protected FThreadScheduler: TIdSchedulerOfThread; FTempThread: TTempThread; // procedure InitComponent; override; public procedure Add( AFiber: TIdFiber ); override; destructor Destroy; override; published property ThreadScheduler: TIdSchedulerOfThread read FThreadScheduler write FThreadScheduler; end; implementation uses SysUtils; { TTempThread } procedure TTempThread.AfterRun; begin inherited; FreeAndNil(FFiberWeaver); end; procedure TTempThread.BeforeRun; begin inherited; //TODO: Make this pluggable at run time? depends where threads come //from - merge to scheduler? Base is in IdFiber though.... FFiberWeaver := TIdFiberWeaverInline.Create(nil); FFiberWeaver.FreeFibersOnCompletion := True; end; procedure TTempThread.Run; begin //TODO: Temp hack if FFiberWeaver.HasFibers then begin FFiberWeaver.ProcessInThisThread; end else begin //Sleep(50); FFiberWeaver.WaitForFibers(50); end; end; { TIdFiberWeaverThreaded } procedure TIdFiberWeaverThreaded.Add(AFiber: TIdFiber); begin FTempThread.FFiberWeaver.Add(AFiber); end; destructor TIdFiberWeaverThreaded.Destroy; begin // is only created at run time if FTempThread <> nil then begin FTempThread.TerminateAndWaitFor; FreeAndNil(FTempThread); end; inherited; end; procedure TIdFiberWeaverThreaded.InitComponent; begin inherited; if not (csDesigning in ComponentState) then begin FTempThread := TTempThread.Create(False, True, 'TIdSchedulerOfFiber Temp'); {do not localize} end; end; end.
unit MMCheck; interface uses Windows, MMSystem, SysUtils; type EMultimedia = class(Exception) public constructor Create(aResult : hResult); end; procedure TryMM(aResult : HResult); implementation constructor EMultimedia.Create(aResult : hResult); begin inherited Create('Multimedia system is busy'); end; procedure TryMM(aResult : HResult); begin if aResult <> MMSYSERR_NOERROR then raise EMultimedia.Create(aResult); end; end.
unit Validator; {$mode objfpc}{$H+} interface function IsFEN(const aStr: string): boolean; implementation uses Classes, SysUtils, RegExpr; type TValidator = class public function ExpandEmptySquares(ARegExpr: TRegExpr): string; function IsFEN(const aInputStr: string): boolean; end; function IsFEN(const aStr: string): boolean; var vld: TValidator; begin vld := TValidator.Create; result := vld.IsFen(aStr); vld.Free; end; function TValidator.ExpandEmptySquares(aRegExpr: TRegExpr): string; const SYMBOL = '-'; begin result := ''; with aRegExpr do result := StringOfChar(SYMBOL, StrToInt(Match[0])); end; function TValidator.IsFEN(const aInputStr: string): boolean; const WHITEKING = 'K'; BLACKKING = 'k'; PIECES = '^[1-8BKNPQRbknpqr]+$'; ACTIVE = '^[wb]$'; CASTLING = '^[KQkq]+$|^[A-Ha-h]+$|^\-$'; ENPASSANT = '^[a-h][36]$|^\-$'; HALFMOVE = '^\d+$'; FULLMOVE = '^[1-9]\d*$'; var a, b: TStrings; i: integer; e: TRegExpr; s: string; begin a := TStringList.Create; b := TStringList.Create; e := TRegExpr.Create; e.Expression := '\d'; (* ExtractStrings([' '], [], PChar(aInputStr), a); ExtractStrings(['/'], [], PChar(a[0]), b); *) SplitRegExpr(' ', aInputStr, a); result := (a.Count = 6); if result then begin SplitRegExpr('/', a[0], b); result := (b.Count = 8); end; if result then begin result := result and ExecRegExpr(WHITEKING, a[0]); result := result and ExecRegExpr(BLACKKING, a[0]); for i := 0 to 7 do begin result := result and ExecRegExpr(PIECES, b[i]); if result then begin s := b[i]; repeat s := e.Replace(s, @ExpandEmptySquares); until not ExecRegExpr('\d', s); (* ToLog(Format('%s %s', [{$I %LINE%}, s])); *) result := result and (Length(s) = 8); end; end; result := result and ExecRegExpr(ACTIVE, a[1]); result := result and ExecRegExpr(CASTLING, a[2]); result := result and ExecRegExpr(ENPASSANT, a[3]); result := result and ExecRegExpr(HALFMOVE, a[4]); result := result and ExecRegExpr(FULLMOVE, a[5]); end; a.Free; b.Free; e.Free; end; (* initialization loglist := TStringList.Create; logfile := ChangeFileExt({$I %FILE%}, '.log'); finalization with loglist do begin SaveToFile(logfile); Free; end; *) end.