classes.inc 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954
  1. {%MainUnit classes.pp}
  2. {
  3. This file is part of the Free Component Library (FCL)
  4. Copyright (c) 1999-2000 by Michael Van Canneyt and Florian Klaempfl
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. {**********************************************************************
  12. * Class implementations are in separate files. *
  13. **********************************************************************}
  14. type
  15. {$ifdef CPU16}
  16. TFilerFlagsInt = Byte;
  17. {$else CPU16}
  18. TFilerFlagsInt = LongInt;
  19. {$endif CPU16}
  20. var
  21. ClassList : TThreadlist;
  22. ClassAliasList : TStringList;
  23. {
  24. Include all message strings
  25. Add a language with IFDEF LANG_NAME
  26. just befor the final ELSE. This way English will always be the default.
  27. }
  28. {$IFDEF LANG_GERMAN}
  29. {$i constsg.inc}
  30. {$ELSE}
  31. {$IFDEF LANG_SPANISH}
  32. {$i constss.inc}
  33. {$ENDIF}
  34. {$ENDIF}
  35. { Utility routines }
  36. {$i util.inc}
  37. { TBits implementation }
  38. {$i bits.inc}
  39. { All streams implementations: }
  40. { Tstreams THandleStream TFileStream TResourcseStreams TStringStream }
  41. { TCustomMemoryStream TMemoryStream }
  42. {$i streams.inc}
  43. { TParser implementation}
  44. {$i parser.inc}
  45. { TCollection and TCollectionItem implementations }
  46. {$i collect.inc}
  47. { TList and TThreadList implementations }
  48. {$i lists.inc}
  49. { TStrings and TStringList implementations }
  50. {$i stringl.inc}
  51. { ObservableMemberAttribute, TObservers and TObserverMapping}
  52. {$i observer.inc}
  53. { TThread implementation }
  54. { system independend threading code }
  55. var
  56. { event executed by SychronizeInternal to wake main thread if it sleeps in
  57. CheckSynchronize }
  58. SynchronizeTimeoutEvent: PRtlEvent;
  59. { the head of the queue containing the entries to be Synchronized - Nil if the
  60. queue is empty }
  61. ThreadQueueHead: TThread.PThreadQueueEntry;
  62. { the tail of the queue containing the entries to be Synchronized - Nil if the
  63. queue is empty }
  64. ThreadQueueTail: TThread.PThreadQueueEntry;
  65. { used for serialized access to the queue }
  66. ThreadQueueLock: TRtlCriticalSection;
  67. { usage counter for ThreadQueueLock }
  68. ThreadQueueLockCounter : longint;
  69. { this list holds all instances of external threads that need to be freed at
  70. the end of the program }
  71. ExternalThreads: TThreadList;
  72. { this list signals that the ExternalThreads list is cleared and thus the
  73. thread instances don't need to remove themselves }
  74. ExternalThreadsCleanup: Boolean = False;
  75. { this must be a global var, otherwise unwanted optimizations might happen in
  76. TThread.SpinWait() }
  77. SpinWaitDummy: LongWord;
  78. {$ifdef FPC_HAS_FEATURE_THREADING}
  79. threadvar
  80. {$else}
  81. var
  82. {$endif}
  83. { the instance of the current thread; in case of an external thread this is
  84. Nil until TThread.GetCurrentThread was called once (the RTLs need to ensure
  85. that threadvars are initialized with 0!) }
  86. CurrentThreadVar: TThread;
  87. type
  88. { this type is used if a thread is created using
  89. TThread.CreateAnonymousThread }
  90. { TAnonymousThread }
  91. TAnonymousThread = class(TThread)
  92. private
  93. fProc: TProcedure;
  94. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  95. fAnonProc : TThreadProcedure;
  96. {$ENDIF}
  97. FMethod : TThreadMethod;
  98. protected
  99. procedure Execute; override;
  100. public
  101. constructor Create(aProc: TProcedure);
  102. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  103. constructor Create(aProc: TThreadProcedure);
  104. {$ENDIF}
  105. constructor Create(aProc: TThreadMethod);
  106. end;
  107. procedure TAnonymousThread.Execute;
  108. begin
  109. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  110. if assigned(fAnonProc) then
  111. fAnonProc()
  112. else
  113. {$ENDIF}
  114. if assigned(FMethod) then
  115. FMethod()
  116. else
  117. fProc();
  118. end;
  119. constructor TAnonymousThread.Create(aProc: TProcedure);
  120. begin
  121. { an anonymous thread is created suspended and with FreeOnTerminate set }
  122. inherited Create(True);
  123. FreeOnTerminate := True;
  124. fProc := aProc;
  125. end;
  126. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  127. constructor TAnonymousThread.Create(aProc: TThreadProcedure);
  128. begin
  129. inherited Create(True);
  130. FreeOnTerminate := True;
  131. fAnonProc := aProc;
  132. end;
  133. {$ENDIF}
  134. constructor TAnonymousThread.Create(aProc: TThreadMethod);
  135. begin
  136. inherited Create(True);
  137. FreeOnTerminate := True;
  138. FMethod := aProc;
  139. end;
  140. type
  141. { this type is used by TThread.GetCurrentThread if the thread does not yet
  142. have a value in CurrentThreadVar (Note: the main thread is also created as
  143. a TExternalThread) }
  144. TExternalThread = class(TThread)
  145. protected
  146. { dummy method to remove the warning }
  147. procedure Execute; override;
  148. public
  149. constructor Create;
  150. destructor Destroy; override;
  151. end;
  152. procedure TExternalThread.Execute;
  153. begin
  154. { empty }
  155. end;
  156. constructor TExternalThread.Create;
  157. begin
  158. FExternalThread := True;
  159. { the parameter is unimportant if FExternalThread is True }
  160. inherited Create(False);
  161. with ExternalThreads.LockList do
  162. try
  163. Add(Self);
  164. finally
  165. ExternalThreads.UnlockList;
  166. end;
  167. end;
  168. destructor TExternalThread.Destroy;
  169. begin
  170. inherited;
  171. if not ExternalThreadsCleanup then
  172. with ExternalThreads.LockList do
  173. try
  174. Extract(Self);
  175. finally
  176. ExternalThreads.UnlockList;
  177. end;
  178. end;
  179. function ThreadProc(ThreadObjPtr: Pointer): PtrInt;
  180. var
  181. FreeThread: Boolean;
  182. Thread: TThread absolute ThreadObjPtr;
  183. begin
  184. { if Suspend checks FSuspended before doing anything, make sure it }
  185. { knows we're currently not suspended (this flag may have been set }
  186. { to true if CreateSuspended was true) }
  187. // Thread.FSuspended:=false;
  188. // wait until AfterConstruction has been called, so we cannot
  189. // free ourselves before TThread.Create has finished
  190. // (since that one may check our VTM in case of $R+, and
  191. // will call the AfterConstruction method in all cases)
  192. // Thread.Suspend;
  193. try
  194. { The thread may be already terminated at this point, e.g. if it was intially
  195. suspended, or if it wasn't ever scheduled for execution for whatever reason.
  196. So bypass user code if terminated. }
  197. if not Thread.Terminated then begin
  198. CurrentThreadVar := Thread;
  199. Thread.Execute;
  200. end;
  201. except
  202. Thread.FFatalException := TObject(AcquireExceptionObject);
  203. end;
  204. FreeThread := Thread.FFreeOnTerminate;
  205. Result := Thread.FReturnValue;
  206. Thread.FFinished := True;
  207. Thread.DoTerminate;
  208. if FreeThread then
  209. Thread.Free;
  210. {$ifdef FPC_HAS_FEATURE_THREADING}
  211. EndThread(Result);
  212. {$endif}
  213. end;
  214. { system-dependent code }
  215. {$i tthread.inc}
  216. constructor TThread.Create(CreateSuspended: Boolean;
  217. const StackSize: SizeUInt);
  218. begin
  219. inherited Create;
  220. {$ifdef FPC_HAS_FEATURE_THREADING}
  221. InterlockedIncrement(ThreadQueueLockCounter);
  222. FThreadQueueLockCounted := true; { Guard against exception in descendant’s Create. }
  223. {$endif}
  224. if FExternalThread then
  225. {$ifdef FPC_HAS_FEATURE_THREADING}
  226. FThreadID := GetCurrentThreadID
  227. {$else}
  228. FThreadID := 0{GetCurrentThreadID}
  229. {$endif}
  230. else
  231. SysCreate(CreateSuspended, StackSize);
  232. end;
  233. destructor TThread.Destroy;
  234. begin
  235. if not FExternalThread then begin
  236. SysDestroy;
  237. {$ifdef FPC_HAS_FEATURE_THREADING}
  238. if FHandle <> TThreadID(0) then
  239. CloseThread(FHandle);
  240. {$endif}
  241. end;
  242. RemoveQueuedEvents(Self);
  243. DoneSynchronizeEvent;
  244. {$ifdef FPC_HAS_FEATURE_THREADING}
  245. if FThreadQueueLockCounted and (InterlockedDecrement(ThreadQueueLockCounter)=0) then
  246. DoneCriticalSection(ThreadQueueLock);
  247. {$endif}
  248. { set CurrentThreadVar to Nil? }
  249. inherited Destroy;
  250. end;
  251. procedure TThread.Start;
  252. begin
  253. { suspend/resume are now deprecated in Delphi (they also don't work
  254. on most platforms in FPC), so a different method was required
  255. to start a thread if it's create with fSuspended=true -> that's
  256. what this method is for. }
  257. Resume;
  258. end;
  259. function TThread.GetSuspended: Boolean;
  260. begin
  261. GetSuspended:=FSuspended;
  262. end;
  263. procedure TThread.Terminate;
  264. begin
  265. FTerminated := True;
  266. TerminatedSet;
  267. end;
  268. procedure TThread.TerminatedSet;
  269. begin
  270. // Empty, must be overridden.
  271. end;
  272. procedure TThread.AfterConstruction;
  273. begin
  274. inherited AfterConstruction;
  275. // enable for all platforms once http://bugs.freepascal.org/view.php?id=16884
  276. // is fixed for all platforms (in case the fix for non-unix platforms also
  277. // requires this field at least)
  278. {$if defined(unix) or defined(windows) or defined(os2) or defined(hasamiga) or defined(wasi) }
  279. if not FExternalThread and not FInitialSuspended then
  280. Resume;
  281. {$endif}
  282. end;
  283. procedure ExecuteThreadQueueEntry(aEntry: TThread.PThreadQueueEntry);
  284. begin
  285. if Assigned(aEntry^.Method) then
  286. aEntry^.Method()
  287. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  288. else
  289. if Assigned(aEntry^.ThreadProc) then
  290. aEntry^.ThreadProc
  291. {$endif}
  292. end;
  293. procedure ThreadQueueAppend(aEntry: TThread.PThreadQueueEntry; aQueueIfMain: Boolean);
  294. var
  295. thd: TThread;
  296. issync: Boolean;
  297. begin
  298. { do we really need a synchronized call? }
  299. {$ifdef FPC_HAS_FEATURE_THREADING}
  300. if (GetCurrentThreadID = MainThreadID) and (not aQueueIfMain or not IsMultiThread) then
  301. {$endif}
  302. begin
  303. try
  304. ExecuteThreadQueueEntry(aEntry);
  305. finally
  306. if not Assigned(aEntry^.SyncEvent) then
  307. Dispose(aEntry);
  308. end;
  309. {$ifdef FPC_HAS_FEATURE_THREADING}
  310. end else begin
  311. { store thread and whether we're dealing with a synchronized event; the
  312. event record itself might already be freed after the ThreadQueueLock is
  313. released (in case of a Queue() call; for a Synchronize() call the record
  314. will stay valid, thus accessing SyncEvent later on (if issync is true) is
  315. okay) }
  316. thd := aEntry^.Thread;
  317. issync := Assigned(aEntry^.SyncEvent);
  318. System.EnterCriticalSection(ThreadQueueLock);
  319. try
  320. { add the entry to the thread queue }
  321. if Assigned(ThreadQueueTail) then begin
  322. ThreadQueueTail^.Next := aEntry;
  323. end else
  324. ThreadQueueHead := aEntry;
  325. ThreadQueueTail := aEntry;
  326. finally
  327. System.LeaveCriticalSection(ThreadQueueLock);
  328. end;
  329. { ensure that the main thread knows that something awaits }
  330. RtlEventSetEvent(SynchronizeTimeoutEvent);
  331. if assigned(WakeMainThread) then
  332. WakeMainThread(thd);
  333. { is this a Synchronize or Queue entry? }
  334. if issync then begin
  335. RtlEventWaitFor(aEntry^.SyncEvent);
  336. if Assigned(aEntry^.Exception) then
  337. raise aEntry^.Exception;
  338. end;
  339. {$endif def FPC_HAS_FEATURE_THREADING}
  340. end;
  341. end;
  342. procedure TThread.InitSynchronizeEvent;
  343. begin
  344. if Assigned(FSynchronizeEntry) then
  345. Exit;
  346. New(FSynchronizeEntry);
  347. FillChar(FSynchronizeEntry^, SizeOf(TThreadQueueEntry), 0);
  348. FSynchronizeEntry^.Thread := Self;
  349. {$ifdef FPC_HAS_FEATURE_THREADING}
  350. FSynchronizeEntry^.SyncEvent := RtlEventCreate;
  351. {$else}
  352. FSynchronizeEntry^.SyncEvent := nil{RtlEventCreate};
  353. {$endif}
  354. end;
  355. procedure TThread.DoneSynchronizeEvent;
  356. begin
  357. if not Assigned(FSynchronizeEntry) then
  358. Exit;
  359. {$ifdef FPC_HAS_FEATURE_THREADING}
  360. RtlEventDestroy(FSynchronizeEntry^.SyncEvent);
  361. {$endif}
  362. Dispose(FSynchronizeEntry);
  363. FSynchronizeEntry := Nil;
  364. end;
  365. class function TThread.CurrentIsMain : Boolean;
  366. begin
  367. Result:=TThread.Current.ThreadID=MainThreadID;
  368. end;
  369. class procedure TThread.Synchronize(AThread: TThread; AMethod: TThreadMethod);
  370. var
  371. syncentry: PThreadQueueEntry;
  372. thread: TThread;
  373. begin
  374. {$ifdef FPC_HAS_FEATURE_THREADING}
  375. if Assigned(AThread) and (AThread.ThreadID = GetCurrentThreadID) then
  376. {$else}
  377. if Assigned(AThread) then
  378. {$endif}
  379. thread := AThread
  380. else if Assigned(CurrentThreadVar) then
  381. thread := CurrentThreadVar
  382. else begin
  383. thread := Nil;
  384. { use a local synchronize event }
  385. New(syncentry);
  386. FillChar(syncentry^, SizeOf(TThreadQueueEntry), 0);
  387. {$ifdef FPC_HAS_FEATURE_THREADING}
  388. syncentry^.SyncEvent := RtlEventCreate;
  389. {$else}
  390. syncentry^.SyncEvent := nil{RtlEventCreate};
  391. {$endif}
  392. end;
  393. if Assigned(thread) then begin
  394. { the Synchronize event is instantiated on demand }
  395. thread.InitSynchronizeEvent;
  396. syncentry := thread.FSynchronizeEntry;
  397. end;
  398. syncentry^.Exception := Nil;
  399. syncentry^.Method := AMethod;
  400. try
  401. ThreadQueueAppend(syncentry, False);
  402. finally
  403. syncentry^.Method := Nil;
  404. syncentry^.Next := Nil;
  405. if not Assigned(thread) then begin
  406. { clean up again }
  407. {$ifdef FPC_HAS_FEATURE_THREADING}
  408. RtlEventDestroy(syncentry^.SyncEvent);
  409. {$endif}
  410. Dispose(syncentry);
  411. end;
  412. end;
  413. end;
  414. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  415. class procedure TThread.Synchronize(AThread: TThread; AProcedure: TThreadProcedure);
  416. var
  417. syncentry: PThreadQueueEntry;
  418. thread: TThread;
  419. begin
  420. {$ifdef FPC_HAS_FEATURE_THREADING}
  421. if Assigned(AThread) and (AThread.ThreadID = GetCurrentThreadID) then
  422. {$else}
  423. if Assigned(AThread) then
  424. {$endif}
  425. thread := AThread
  426. else if Assigned(CurrentThreadVar) then
  427. thread := CurrentThreadVar
  428. else begin
  429. thread := Nil;
  430. { use a local synchronize event }
  431. New(syncentry);
  432. FillChar(syncentry^, SizeOf(TThreadQueueEntry), 0);
  433. {$ifdef FPC_HAS_FEATURE_THREADING}
  434. syncentry^.SyncEvent := RtlEventCreate;
  435. {$else}
  436. syncentry^.SyncEvent := nil{RtlEventCreate};
  437. {$endif}
  438. end;
  439. if Assigned(thread) then begin
  440. { the Synchronize event is instantiated on demand }
  441. thread.InitSynchronizeEvent;
  442. syncentry := thread.FSynchronizeEntry;
  443. end;
  444. syncentry^.Exception := Nil;
  445. syncentry^.ThreadProc := AProcedure;
  446. try
  447. ThreadQueueAppend(syncentry, False);
  448. finally
  449. syncentry^.ThreadProc := Nil;
  450. syncentry^.Next := Nil;
  451. if not Assigned(thread) then begin
  452. { clean up again }
  453. {$ifdef FPC_HAS_FEATURE_THREADING}
  454. RtlEventDestroy(syncentry^.SyncEvent);
  455. {$endif}
  456. Dispose(syncentry);
  457. end;
  458. end;
  459. end;
  460. {$endif}
  461. procedure TThread.Synchronize(AMethod: TThreadMethod);
  462. begin
  463. TThread.Synchronize(self,AMethod);
  464. end;
  465. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  466. procedure TThread.Synchronize(AProcedure: TThreadProcedure);
  467. begin
  468. TThread.Synchronize(self,AProcedure);
  469. end;
  470. {$endif}
  471. Function PopThreadQueueHead : TThread.PThreadQueueEntry;
  472. var
  473. lPrev : TThread.PThreadQueueEntry;
  474. lNow : TDateTime;
  475. begin
  476. lPrev:=Nil;
  477. Result:=ThreadQueueHead;
  478. if (Result<>Nil) then
  479. begin
  480. {$ifdef FPC_HAS_FEATURE_THREADING}
  481. System.EnterCriticalSection(ThreadQueueLock);
  482. try
  483. {$endif}
  484. Result:=ThreadQueueHead;
  485. lNow:=Now;
  486. While Assigned(Result) and (Result^.ExecuteAfter<>0) and (Result^.ExecuteAfter>lNow) do
  487. begin
  488. lPrev:=Result;
  489. Result:=Result^.Next;
  490. end;
  491. if Result<>Nil then
  492. begin
  493. if Assigned(lPrev) then
  494. lPrev^.Next:=Result^.Next
  495. else
  496. ThreadQueueHead:=Result^.Next;
  497. // if Result^.Next is Nil, it means we popped the last
  498. if Not Assigned(Result^.Next) then
  499. ThreadQueueTail := lPrev;
  500. end;
  501. {$ifdef FPC_HAS_FEATURE_THREADING}
  502. finally
  503. System.LeaveCriticalSection(ThreadQueueLock);
  504. end;
  505. {$endif}
  506. end;
  507. end;
  508. function CheckSynchronize(timeout : longint=0) : boolean;
  509. { assumes being called from GUI thread }
  510. var
  511. ExceptObj: TObject;
  512. tmpentry: TThread.PThreadQueueEntry;
  513. begin
  514. result:=false;
  515. { first sanity check }
  516. if Not IsMultiThread then
  517. Exit
  518. {$ifdef FPC_HAS_FEATURE_THREADING}
  519. { second sanity check }
  520. else if GetCurrentThreadID<>MainThreadID then
  521. raise EThread.CreateFmt(SCheckSynchronizeError,[GetCurrentThreadID]);
  522. if timeout>0 then
  523. RtlEventWaitFor(SynchronizeTimeoutEvent,timeout)
  524. else
  525. RtlEventResetEvent(SynchronizeTimeoutEvent);
  526. tmpentry := PopThreadQueueHead;
  527. while Assigned(tmpentry) do
  528. begin
  529. { at least one method is handled, so return true }
  530. result := true;
  531. { step 2: execute the method }
  532. exceptobj := Nil;
  533. try
  534. ExecuteThreadQueueEntry(tmpentry);
  535. except
  536. exceptobj := TObject(AcquireExceptionObject);
  537. end;
  538. { step 3: error handling and cleanup }
  539. if Assigned(tmpentry^.SyncEvent) then
  540. begin
  541. { for Synchronize entries we pass back the Exception and trigger
  542. the event that Synchronize waits in }
  543. tmpentry^.Exception := exceptobj;
  544. RtlEventSetEvent(tmpentry^.SyncEvent)
  545. end
  546. else
  547. begin
  548. { for Queue entries we dispose the entry and raise the exception }
  549. Dispose(tmpentry);
  550. if Assigned(exceptobj) then
  551. raise exceptobj;
  552. end;
  553. tmpentry := PopThreadQueueHead;
  554. end
  555. {$endif};
  556. end;
  557. class function TThread.GetCurrentThread: TThread;
  558. begin
  559. { if this is the first time GetCurrentThread is called for an external thread
  560. we need to create a corresponding TExternalThread instance }
  561. Result := CurrentThreadVar;
  562. if not Assigned(Result) then begin
  563. Result := TExternalThread.Create;
  564. CurrentThreadVar := Result;
  565. end;
  566. end;
  567. class function TThread.GetIsSingleProcessor: Boolean;
  568. begin
  569. Result := FProcessorCount <= 1;
  570. end;
  571. procedure TThread.Queue(aMethod: TThreadMethod);
  572. begin
  573. Queue(Self, aMethod);
  574. end;
  575. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  576. procedure TThread.Queue(aProcedure: TThreadProcedure);
  577. begin
  578. Queue(Self, aProcedure);
  579. end;
  580. {$endif}
  581. class procedure TThread.Queue(aThread: TThread; aMethod: TThreadMethod); static;
  582. begin
  583. InternalQueue(aThread, aMethod, False, 0);
  584. end;
  585. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  586. class procedure TThread.Queue(aThread: TThread; AProcedure: TThreadProcedure);
  587. begin
  588. InternalQueue(aThread, aProcedure, False, 0);
  589. end;
  590. {$endif}
  591. class procedure TThread.InternalQueue(aThread: TThread; aMethod: TThreadMethod; aQueueIfMain: Boolean; aExecuteAfter: TDateTime); static;
  592. var
  593. queueentry: PThreadQueueEntry;
  594. begin
  595. New(queueentry);
  596. FillChar(queueentry^, SizeOf(TThreadQueueEntry), 0);
  597. queueentry^.Thread := aThread;
  598. queueentry^.Method := aMethod;
  599. queueentry^.ExecuteAfter:=aExecuteAfter;
  600. { the queueentry is freed by CheckSynchronize (or by RemoveQueuedEvents) }
  601. ThreadQueueAppend(queueentry, aQueueIfMain);
  602. end;
  603. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  604. class procedure TThread.InternalQueue(aThread: TThread; aProcedure: TThreadProcedure; aQueueIfMain: Boolean; aExecuteAfter: TDateTime); static;
  605. var
  606. queueentry: PThreadQueueEntry;
  607. begin
  608. New(queueentry);
  609. FillChar(queueentry^, SizeOf(TThreadQueueEntry), 0);
  610. queueentry^.Thread := aThread;
  611. queueentry^.ThreadProc := aProcedure;
  612. queueentry^.ExecuteAfter:=aExecuteAfter;
  613. { the queueentry is freed by CheckSynchronize (or by RemoveQueuedEvents) }
  614. ThreadQueueAppend(queueentry, aQueueIfMain);
  615. end;
  616. {$endif}
  617. procedure TThread.ForceQueue(aMethod: TThreadMethod);
  618. begin
  619. ForceQueue(Self, aMethod);
  620. end;
  621. class procedure TThread.ForceQueue(aThread: TThread; aMethod: TThreadMethod; aDelay : Integer = 0); static;
  622. var
  623. lEnd : TDateTime;
  624. begin
  625. if aDelay<>0 then
  626. lEnd:=Now+aDelay*(1/MSecsPerDay)
  627. else
  628. lEnd:=0;
  629. InternalQueue(aThread, aMethod, True, lEnd);
  630. end;
  631. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  632. class procedure TThread.ForceQueue(aThread: TThread; aMethod: TThreadProcedure; aDelay : Integer = 0); static;
  633. var
  634. lEnd : TDateTime;
  635. begin
  636. if aDelay<>0 then
  637. lEnd:=Now+aDelay*(1/MSecsPerDay)
  638. else
  639. lEnd:=0;
  640. InternalQueue(aThread, aMethod, True, lEnd);
  641. end;
  642. {$endif}
  643. class procedure TThread.RemoveQueuedEvents(aThread: TThread; aMethod: TThreadMethod);
  644. var
  645. entry, tmpentry, lastentry: PThreadQueueEntry;
  646. begin
  647. { anything to do at all? }
  648. if not Assigned(aThread) and not Assigned(aMethod) then
  649. Exit;
  650. {$ifdef FPC_HAS_FEATURE_THREADING}
  651. System.EnterCriticalSection(ThreadQueueLock);
  652. try
  653. {$endif}
  654. lastentry := Nil;
  655. entry := ThreadQueueHead;
  656. while Assigned(entry) do begin
  657. if
  658. { only entries not added by Synchronize }
  659. not Assigned(entry^.SyncEvent)
  660. { check for the thread }
  661. and (not Assigned(aThread) or (entry^.Thread = aThread))
  662. { check for the method }
  663. and (not Assigned(aMethod) or
  664. (
  665. (TMethod(entry^.Method).Code = TMethod(aMethod).Code) and
  666. (TMethod(entry^.Method).Data = TMethod(aMethod).Data)
  667. ))
  668. then begin
  669. { ok, we need to remove this entry }
  670. tmpentry := entry;
  671. if Assigned(lastentry) then
  672. lastentry^.Next := entry^.Next;
  673. entry := entry^.Next;
  674. if ThreadQueueHead = tmpentry then
  675. ThreadQueueHead := entry;
  676. if ThreadQueueTail = tmpentry then
  677. ThreadQueueTail := lastentry;
  678. { only dispose events added by Queue }
  679. if not Assigned(tmpentry^.SyncEvent) then
  680. Dispose(tmpentry);
  681. end else begin
  682. { leave this entry }
  683. lastentry := entry;
  684. entry := entry^.Next;
  685. end;
  686. end;
  687. {$ifdef FPC_HAS_FEATURE_THREADING}
  688. finally
  689. System.LeaveCriticalSection(ThreadQueueLock);
  690. end;
  691. {$endif}
  692. end;
  693. class procedure TThread.RemoveQueuedEvents(aMethod: TThreadMethod);
  694. begin
  695. RemoveQueuedEvents(Nil, aMethod);
  696. end;
  697. class procedure TThread.RemoveQueuedEvents(aThread: TThread);
  698. begin
  699. RemoveQueuedEvents(aThread, Nil);
  700. end;
  701. class function TThread.CheckTerminated: Boolean;
  702. begin
  703. { this method only works with threads created by TThread, so we can make a
  704. shortcut here }
  705. if not Assigned(CurrentThreadVar) then
  706. raise EThreadExternalException.Create(SThreadExternal);
  707. Result := CurrentThreadVar.FTerminated;
  708. end;
  709. class procedure TThread.SetReturnValue(aValue: Integer);
  710. begin
  711. { this method only works with threads created by TThread, so we can make a
  712. shortcut here }
  713. if not Assigned(CurrentThreadVar) then
  714. raise EThreadExternalException.Create(SThreadExternal);
  715. CurrentThreadVar.FReturnValue := aValue;
  716. end;
  717. class function TThread.CreateAnonymousThread(aProc: TProcedure): TThread;
  718. begin
  719. if not Assigned(aProc) then
  720. raise Exception.Create(SNoProcGiven);
  721. Result := TAnonymousThread.Create(aProc);
  722. end;
  723. {$ifdef FPC_HAS_REFERENCE_PROCEDURE}
  724. class function TThread.CreateAnonymousThread(aProc: TThreadProcedure): TThread;
  725. begin
  726. if not Assigned(aProc) then
  727. raise Exception.Create(SNoProcGiven);
  728. Result := TAnonymousThread.Create(aProc);
  729. end;
  730. {$ENDIF}
  731. class function TThread.CreateAnonymousThread(aProc: TThreadMethod): TThread;
  732. begin
  733. if not Assigned(aProc) then
  734. raise Exception.Create(SNoProcGiven);
  735. Result := TAnonymousThread.Create(aProc);
  736. end;
  737. class procedure TThread.NameThreadForDebugging(aThreadName: UnicodeString; aThreadID: TThreadID);
  738. begin
  739. {$ifdef FPC_HAS_FEATURE_THREADING}
  740. SetThreadDebugName(aThreadID, aThreadName);
  741. {$endif}
  742. end;
  743. class procedure TThread.NameThreadForDebugging(aThreadName: AnsiString; aThreadID: TThreadID);
  744. begin
  745. {$ifdef FPC_HAS_FEATURE_THREADING}
  746. SetThreadDebugName(aThreadID, aThreadName);
  747. {$endif}
  748. end;
  749. class procedure TThread.Yield;
  750. begin
  751. {$ifdef FPC_HAS_FEATURE_THREADING}
  752. ThreadSwitch;
  753. {$endif}
  754. end;
  755. class procedure TThread.Sleep(aMilliseconds: Cardinal);
  756. begin
  757. {$IFDEF FPC_DOTTEDUNITS}System.{$ENDIF}SysUtils.Sleep(aMilliseconds);
  758. end;
  759. class procedure TThread.SpinWait(aIterations: LongWord);
  760. var
  761. i: LongWord;
  762. begin
  763. { yes, it's just a simple busy wait to burn some cpu cycles... and as the job
  764. of this loop is to burn CPU cycles we switch off any optimizations that
  765. could interfere with this (e.g. loop unrolling) }
  766. { Do *NOT* do $PUSH, $OPTIMIZATIONS OFF, <code>, $POP because optimization is
  767. not a local switch, which means $PUSH/POP doesn't affect it, so that turns
  768. off *ALL* optimizations for code below this point. Thanks to this we shipped
  769. large parts of the classes unit with optimizations off between 2012-12-27
  770. and 2014-06-06.
  771. Instead, use a global var for the spinlock, because that is always handled
  772. as volatile, so the access won't be optimized away by the compiler. (KB) }
  773. for i:=1 to aIterations do
  774. begin
  775. Inc(SpinWaitDummy); // SpinWaitDummy *MUST* be global
  776. end;
  777. end;
  778. {$ifndef HAS_TTHREAD_GETSYSTEMTIMES}
  779. class function TThread.GetSystemTimes(out aSystemTimes: TSystemTimes) : Boolean;
  780. begin
  781. { by default we just return a zeroed out record }
  782. FillChar(aSystemTimes, SizeOf(aSystemTimes), 0);
  783. Result:=False;
  784. end;
  785. {$endif}
  786. class function TThread.GetCPUUsage(var Previous: TSystemTimes): Integer;
  787. var
  788. Act : TSystemTimes;
  789. Load,Idle: QWord;
  790. begin
  791. Result:=0;
  792. if not GetSystemTimes(Act) then
  793. exit;
  794. Load:=(Act.UserTime-Previous.UserTime) +
  795. (Act.KernelTime-Previous.KernelTime) +
  796. (Act.NiceTime-Previous.NiceTime);
  797. Idle:=Act.IdleTime-Previous.IdleTime;
  798. Previous:=Act;
  799. if (Load<>0) and (Load>Idle) then
  800. Result:=100*Trunc(1-(Idle/Load));
  801. end;
  802. class function TThread.GetTickCount: LongWord;
  803. begin
  804. Result := {$IFDEF FPC_DOTTEDUNITS}System.{$ENDIF}SysUtils.GetTickCount;
  805. end;
  806. class function TThread.GetTickCount64: QWord;
  807. begin
  808. Result := {$IFDEF FPC_DOTTEDUNITS}System.{$ENDIF}SysUtils.GetTickCount64;
  809. end;
  810. { TSimpleThread allows objects to create a threading method without defining
  811. a new thread class }
  812. Type
  813. TSimpleThread = class(TThread)
  814. private
  815. FExecuteMethod: TThreadExecuteHandler;
  816. protected
  817. procedure Execute; override;
  818. public
  819. constructor Create(ExecuteMethod: TThreadExecuteHandler; AOnterminate : TNotifyEvent);
  820. end;
  821. TSimpleStatusThread = class(TThread)
  822. private
  823. FExecuteMethod: TThreadExecuteStatusHandler;
  824. FStatus : String;
  825. FOnStatus : TThreadStatusNotifyEvent;
  826. protected
  827. procedure Execute; override;
  828. Procedure DoStatus;
  829. Procedure SetStatus(Const AStatus : String);
  830. public
  831. constructor Create(ExecuteMethod: TThreadExecuteStatusHandler; AOnStatus : TThreadStatusNotifyEvent; AOnterminate : TNotifyEvent);
  832. end;
  833. TSimpleProcThread = class(TThread)
  834. private
  835. FExecuteMethod: TThreadExecuteCallBack;
  836. FCallOnTerminate : TNotifyCallBack;
  837. FData : Pointer;
  838. protected
  839. Procedure TerminateCallBack(Sender : TObject);
  840. procedure Execute; override;
  841. public
  842. constructor Create(ExecuteMethod: TThreadExecuteCallBack; AData : Pointer; AOnterminate : TNotifyCallBack);
  843. end;
  844. TSimpleStatusProcThread = class(TThread)
  845. private
  846. FExecuteMethod: TThreadExecuteStatusCallBack;
  847. FCallOnTerminate : TNotifyCallBack;
  848. FStatus : String;
  849. FOnStatus : TThreadStatusNotifyCallBack;
  850. FData : Pointer;
  851. protected
  852. procedure Execute; override;
  853. Procedure DoStatus;
  854. Procedure SetStatus(Const AStatus : String);
  855. Procedure TerminateCallBack(Sender : TObject);
  856. public
  857. constructor Create(ExecuteMethod: TThreadExecuteStatusCallBack; AData : Pointer; AOnStatus : TThreadStatusNotifyCallBack; AOnterminate : TNotifyCallBack);
  858. end;
  859. { TSimpleThread }
  860. constructor TSimpleThread.Create(ExecuteMethod: TThreadExecuteHandler; AOnTerminate: TNotifyEvent);
  861. begin
  862. FExecuteMethod := ExecuteMethod;
  863. OnTerminate := AOnTerminate;
  864. inherited Create(False);
  865. end;
  866. procedure TSimpleThread.Execute;
  867. begin
  868. FreeOnTerminate := True;
  869. FExecuteMethod;
  870. end;
  871. { TSimpleStatusThread }
  872. constructor TSimpleStatusThread.Create(ExecuteMethod: TThreadExecuteStatusHandler;AOnStatus : TThreadStatusNotifyEvent; AOnTerminate: TNotifyEvent);
  873. begin
  874. FExecuteMethod := ExecuteMethod;
  875. OnTerminate := AOnTerminate;
  876. FOnStatus:=AOnStatus;
  877. FStatus:='';
  878. inherited Create(False);
  879. end;
  880. procedure TSimpleStatusThread.Execute;
  881. begin
  882. FreeOnTerminate := True;
  883. FExecuteMethod(@SetStatus);
  884. end;
  885. procedure TSimpleStatusThread.SetStatus(Const AStatus : String);
  886. begin
  887. If (AStatus=FStatus) then
  888. exit;
  889. FStatus:=AStatus;
  890. If Assigned(FOnStatus) then
  891. Synchronize(@DoStatus);
  892. end;
  893. procedure TSimpleStatusThread.DoStatus;
  894. begin
  895. FOnStatus(Self,FStatus);
  896. end;
  897. { TSimpleProcThread }
  898. constructor TSimpleProcThread.Create(ExecuteMethod: TThreadExecuteCallBack; AData : Pointer; AOnTerminate: TNotifyCallBack);
  899. begin
  900. FExecuteMethod := ExecuteMethod;
  901. FCallOnTerminate := AOnTerminate;
  902. FData:=AData;
  903. If Assigned(FCallOnTerminate) then
  904. OnTerminate:=@TerminateCallBack;
  905. inherited Create(False);
  906. end;
  907. procedure TSimpleProcThread.Execute;
  908. begin
  909. FreeOnTerminate := True;
  910. FExecuteMethod(FData);
  911. end;
  912. procedure TSimpleProcThread.TerminateCallBack(Sender : TObject);
  913. begin
  914. if Assigned(FCallOnTerminate) then
  915. FCallOnTerminate(Sender,FData);
  916. end;
  917. { TSimpleStatusProcThread }
  918. constructor TSimpleStatusProcThread.Create(ExecuteMethod: TThreadExecuteStatusCallback; AData : Pointer; AOnStatus : TThreadStatusNotifyCallBack; AOnTerminate: TNotifyCallBack);
  919. begin
  920. FExecuteMethod := ExecuteMethod;
  921. FCallOnTerminate := AOnTerminate;
  922. FData:=AData;
  923. If Assigned(FCallOnTerminate) then
  924. OnTerminate:=@TerminateCallBack;
  925. FOnStatus:=AOnStatus;
  926. FStatus:='';
  927. inherited Create(False);
  928. end;
  929. procedure TSimpleStatusProcThread.Execute;
  930. begin
  931. FreeOnTerminate := True;
  932. FExecuteMethod(FData,@SetStatus);
  933. end;
  934. procedure TSimpleStatusProcThread.SetStatus(Const AStatus : String);
  935. begin
  936. If (AStatus=FStatus) then
  937. exit;
  938. FStatus:=AStatus;
  939. If Assigned(FOnStatus) then
  940. Synchronize(@DoStatus);
  941. end;
  942. procedure TSimpleStatusProcThread.DoStatus;
  943. begin
  944. FOnStatus(Self,FData,FStatus);
  945. end;
  946. procedure TSimpleStatusProcThread.TerminateCallBack(Sender : TObject);
  947. begin
  948. if Assigned(FCallOnTerminate) then
  949. FCallOnTerminate(Sender,FData);
  950. end;
  951. class function TThread.ExecuteInThread(AMethod: TThreadExecuteHandler; AOnTerminate: TNotifyEvent): TThread;
  952. begin
  953. Result:=TSimpleThread.Create(AMethod,AOnTerminate);
  954. end;
  955. class function TThread.ExecuteInThread(AMethod: TThreadExecuteCallback; AData: Pointer; AOnTerminate: TNotifyCallBack): TThread;
  956. begin
  957. Result:=TSimpleProcThread.Create(AMethod,AData,AOnTerminate);
  958. end;
  959. class function TThread.ExecuteInThread(AMethod: TThreadExecuteStatusHandler; AOnStatus: TThreadStatusNotifyEvent;
  960. AOnTerminate: TNotifyEvent): TThread;
  961. begin
  962. If Not Assigned(AOnStatus) then
  963. Raise EThread.Create(SErrStatusCallBackRequired);
  964. Result:=TSimpleStatusThread.Create(AMethod,AOnStatus,AOnTerminate);
  965. end;
  966. class function TThread.ExecuteInThread(AMethod: TThreadExecuteStatusCallback; AOnStatus: TThreadStatusNotifyCallback;
  967. AData: Pointer; AOnTerminate: TNotifyCallBack): TThread;
  968. begin
  969. If Not Assigned(AOnStatus) then
  970. Raise EThread.Create(SErrStatusCallBackRequired);
  971. Result:=TSimpleStatusProcThread.Create(AMethod,AData,AOnStatus,AOnTerminate);
  972. end;
  973. { TPersistent implementation }
  974. {$i persist.inc }
  975. {$i sllist.inc}
  976. {$i resref.inc}
  977. { TComponent implementation }
  978. {$i compon.inc}
  979. { TBasicAction implementation }
  980. {$i action.inc}
  981. { TDataModule implementation }
  982. {$i dm.inc}
  983. { Class and component registration routines }
  984. {$I cregist.inc}
  985. { Interface related stuff }
  986. {$I intf.inc}
  987. {**********************************************************************
  988. * Miscellaneous procedures and functions *
  989. **********************************************************************}
  990. function ExtractStrings(Separators, WhiteSpace: TSysCharSet; Content: PAnsiChar; Strings: TStrings; AddEmptyStrings : Boolean = False): Integer;
  991. var
  992. b, c : PAnsiChar;
  993. procedure SkipWhitespace;
  994. begin
  995. while (c^ in Whitespace) do
  996. inc (c);
  997. end;
  998. procedure AddString;
  999. var
  1000. l : integer;
  1001. s : string;
  1002. begin
  1003. l := c-b;
  1004. if (l > 0) or AddEmptyStrings then
  1005. begin
  1006. if assigned(Strings) then
  1007. begin
  1008. setlength(s, l);
  1009. if l>0 then
  1010. move (b^, s[1],l*SizeOf(AnsiChar));
  1011. Strings.Add (s);
  1012. end;
  1013. inc (result);
  1014. end;
  1015. end;
  1016. var
  1017. quoted : AnsiChar;
  1018. begin
  1019. result := 0;
  1020. c := Content;
  1021. Quoted := #0;
  1022. Separators := Separators + [#13, #10] - ['''','"'];
  1023. SkipWhitespace;
  1024. b := c;
  1025. while (c^ <> #0) do
  1026. begin
  1027. if (c^ = Quoted) then
  1028. begin
  1029. if ((c+1)^ = Quoted) then
  1030. inc (c)
  1031. else
  1032. Quoted := #0
  1033. end
  1034. else if (Quoted = #0) and (c^ in ['''','"']) then
  1035. Quoted := c^;
  1036. if (Quoted = #0) and (c^ in Separators) then
  1037. begin
  1038. AddString;
  1039. inc (c);
  1040. SkipWhitespace;
  1041. b := c;
  1042. end
  1043. else
  1044. inc (c);
  1045. end;
  1046. if (c <> b) then
  1047. AddString;
  1048. end;
  1049. { Point and rectangle constructors }
  1050. function Point(AX, AY: Integer): TPoint;
  1051. begin
  1052. with Result do
  1053. begin
  1054. X := AX;
  1055. Y := AY;
  1056. end;
  1057. end;
  1058. function SmallPoint(AX, AY: SmallInt): TSmallPoint;
  1059. begin
  1060. with Result do
  1061. begin
  1062. X := AX;
  1063. Y := AY;
  1064. end;
  1065. end;
  1066. function Rect(ALeft, ATop, ARight, ABottom: Integer): TRect;
  1067. begin
  1068. with Result do
  1069. begin
  1070. Left := ALeft;
  1071. Top := ATop;
  1072. Right := ARight;
  1073. Bottom := ABottom;
  1074. end;
  1075. end;
  1076. function Bounds(ALeft, ATop, AWidth, AHeight: Integer): TRect;
  1077. begin
  1078. with Result do
  1079. begin
  1080. Left := ALeft;
  1081. Top := ATop;
  1082. Right := ALeft + AWidth;
  1083. Bottom := ATop + AHeight;
  1084. end;
  1085. end;
  1086. function PointsEqual(const P1, P2: TPoint): Boolean; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1087. begin
  1088. { lazy, but should work }
  1089. result:=QWord(P1)=QWord(P2);
  1090. end;
  1091. function PointsEqual(const P1, P2: TSmallPoint): Boolean; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1092. begin
  1093. { lazy, but should work }
  1094. result:=DWord(P1)=DWord(P2);
  1095. end;
  1096. function InvalidPoint(X, Y: Integer): Boolean;
  1097. begin
  1098. result:=(X=-1) and (Y=-1);
  1099. end;
  1100. function InvalidPoint(const At: TPoint): Boolean;
  1101. begin
  1102. result:=(At.x=-1) and (At.y=-1);
  1103. end;
  1104. function InvalidPoint(const At: TSmallPoint): Boolean;
  1105. begin
  1106. result:=(At.x=-1) and (At.y=-1);
  1107. end;
  1108. { Object filing routines }
  1109. var
  1110. IntConstList: TThreadList;
  1111. type
  1112. TIntConst = class
  1113. IntegerType: PTypeInfo; // The integer type RTTI pointer
  1114. IdentToIntFn: TIdentToInt; // Identifier to Integer conversion
  1115. IntToIdentFn: TIntToIdent; // Integer to Identifier conversion
  1116. constructor Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt;
  1117. AIntToIdent: TIntToIdent);
  1118. end;
  1119. constructor TIntConst.Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt;
  1120. AIntToIdent: TIntToIdent);
  1121. begin
  1122. IntegerType := AIntegerType;
  1123. IdentToIntFn := AIdentToInt;
  1124. IntToIdentFn := AIntToIdent;
  1125. end;
  1126. procedure RegisterIntegerConsts(IntegerType: Pointer; IdentToIntFn: TIdentToInt;
  1127. IntToIdentFn: TIntToIdent);
  1128. begin
  1129. IntConstList.Add(TIntConst.Create(IntegerType, IdentToIntFn, IntToIdentFn));
  1130. end;
  1131. function FindIntToIdent(AIntegerType: Pointer): TIntToIdent;
  1132. var
  1133. i: Integer;
  1134. begin
  1135. with IntConstList.LockList do
  1136. try
  1137. for i := 0 to Count - 1 do
  1138. if TIntConst(Items[i]).IntegerType = AIntegerType then
  1139. exit(TIntConst(Items[i]).IntToIdentFn);
  1140. Result := nil;
  1141. finally
  1142. IntConstList.UnlockList;
  1143. end;
  1144. end;
  1145. function FindIdentToInt(AIntegerType: Pointer): TIdentToInt;
  1146. var
  1147. i: Integer;
  1148. begin
  1149. with IntConstList.LockList do
  1150. try
  1151. for i := 0 to Count - 1 do
  1152. with TIntConst(Items[I]) do
  1153. if TIntConst(Items[I]).IntegerType = AIntegerType then
  1154. exit(IdentToIntFn);
  1155. Result := nil;
  1156. finally
  1157. IntConstList.UnlockList;
  1158. end;
  1159. end;
  1160. function IdentToInt(const Ident: String; out Int: LongInt;
  1161. const Map: array of TIdentMapEntry): Boolean;
  1162. var
  1163. i: Integer;
  1164. begin
  1165. for i := Low(Map) to High(Map) do
  1166. if CompareText(Map[i].Name, Ident) = 0 then
  1167. begin
  1168. Int := Map[i].Value;
  1169. exit(True);
  1170. end;
  1171. Result := False;
  1172. end;
  1173. function IntToIdent(Int: LongInt; var Ident: String;
  1174. const Map: array of TIdentMapEntry): Boolean;
  1175. var
  1176. i: Integer;
  1177. begin
  1178. for i := Low(Map) to High(Map) do
  1179. if Map[i].Value = Int then
  1180. begin
  1181. Ident := Map[i].Name;
  1182. exit(True);
  1183. end;
  1184. Result := False;
  1185. end;
  1186. function GlobalIdentToInt(const Ident: String; var Int: LongInt):boolean;
  1187. var
  1188. i : Integer;
  1189. begin
  1190. with IntConstList.LockList do
  1191. try
  1192. for i := 0 to Count - 1 do
  1193. if TIntConst(Items[I]).IdentToIntFn(Ident, Int) then
  1194. Exit(True);
  1195. Result := false;
  1196. finally
  1197. IntConstList.UnlockList;
  1198. end;
  1199. end;
  1200. { TPropFixup }
  1201. // Tainted. TPropFixup is being removed.
  1202. Type
  1203. TInitHandler = Class(TObject)
  1204. AHandler : TInitComponentHandler;
  1205. AClass : TComponentClass;
  1206. end;
  1207. {$ifndef i8086}
  1208. type
  1209. TCodePtrList = TList;
  1210. {$endif i8086}
  1211. Var
  1212. InitHandlerList : TList;
  1213. FindGlobalComponentList : TCodePtrList;
  1214. procedure RegisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent);
  1215. begin
  1216. if not(assigned(FindGlobalComponentList)) then
  1217. FindGlobalComponentList:=TCodePtrList.Create;
  1218. if FindGlobalComponentList.IndexOf(CodePointer(AFindGlobalComponent))<0 then
  1219. FindGlobalComponentList.Add(CodePointer(AFindGlobalComponent));
  1220. end;
  1221. procedure UnregisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent);
  1222. begin
  1223. if assigned(FindGlobalComponentList) then
  1224. FindGlobalComponentList.Remove(CodePointer(AFindGlobalComponent));
  1225. end;
  1226. function FindGlobalComponent(const Name: string): TComponent;
  1227. var
  1228. i : sizeint;
  1229. begin
  1230. FindGlobalComponent:=nil;
  1231. if assigned(FindGlobalComponentList) then
  1232. begin
  1233. for i:=FindGlobalComponentList.Count-1 downto 0 do
  1234. begin
  1235. FindGlobalComponent:=TFindGlobalComponent(FindGlobalComponentList[i])(name);
  1236. if assigned(FindGlobalComponent) then
  1237. break;
  1238. end;
  1239. end;
  1240. end;
  1241. function IsUniqueGlobalComponentName(const aName: string): Boolean;
  1242. begin
  1243. if Assigned(IsUniqueGlobalComponentNameProc) then
  1244. Result:=IsUniqueGlobalComponentNameProc(aName)
  1245. else
  1246. Result:=Not Assigned(FindGlobalComponent(aName));
  1247. end;
  1248. procedure RegisterInitComponentHandler(ComponentClass: TComponentClass; Handler: TInitComponentHandler);
  1249. Var
  1250. I : Integer;
  1251. H: TInitHandler;
  1252. begin
  1253. If (InitHandlerList=Nil) then
  1254. InitHandlerList:=TList.Create;
  1255. H:=TInitHandler.Create;
  1256. H.Aclass:=ComponentClass;
  1257. H.AHandler:=Handler;
  1258. try
  1259. With InitHandlerList do
  1260. begin
  1261. I:=0;
  1262. While (I<Count) and not H.AClass.InheritsFrom(TInitHandler(Items[I]).AClass) do
  1263. Inc(I);
  1264. { override? }
  1265. if (I<Count) and (TInitHandler(Items[I]).AClass=H.AClass) then
  1266. begin
  1267. TInitHandler(Items[I]).AHandler:=Handler;
  1268. H.Free;
  1269. end
  1270. else
  1271. InitHandlerList.Insert(I,H);
  1272. end;
  1273. except
  1274. H.Free;
  1275. raise;
  1276. end;
  1277. end;
  1278. { all targets should at least include the sysres.inc dummy in the system unit to compile this }
  1279. function CreateComponentfromRes(const res : string;Inst : THandle;var Component : TComponent) : Boolean;
  1280. var
  1281. ResStream : TResourceStream;
  1282. ResID : TFPResourceHandle;
  1283. begin
  1284. if Inst=0 then
  1285. Inst:=HInstance;
  1286. ResId:=System.FindResource(Inst, Res, RT_RCDATA);
  1287. result:=ResID<>0;
  1288. try
  1289. if Result then
  1290. begin
  1291. ResStream:=TResourceStream.Create(Inst,Res,RT_RCDATA);
  1292. try
  1293. Component:=ResStream.ReadComponent(Component);
  1294. finally
  1295. ResStream.Free;
  1296. end;
  1297. end;
  1298. except
  1299. on EResNotFound do
  1300. result:=false;
  1301. end;
  1302. end;
  1303. function DefaultInitHandler(Instance: TComponent; RootAncestor: TClass): Boolean;
  1304. function doinit(_class : TClass) : boolean;
  1305. begin
  1306. result:=false;
  1307. if (_class.ClassType=TComponent) or (_class.ClassType=RootAncestor) then
  1308. exit;
  1309. result:=doinit(_class.ClassParent);
  1310. result:=CreateComponentfromRes(_class.ClassName,0,Instance) or result;
  1311. end;
  1312. begin
  1313. {$ifdef FPC_HAS_FEATURE_THREADING}
  1314. GlobalNameSpace.BeginWrite;
  1315. try
  1316. {$endif}
  1317. result:=doinit(Instance.ClassType);
  1318. if Result then
  1319. Instance.ReadDeltaState;
  1320. {$ifdef FPC_HAS_FEATURE_THREADING}
  1321. finally
  1322. GlobalNameSpace.EndWrite;
  1323. end;
  1324. {$endif}
  1325. end;
  1326. function InitInheritedComponent(Instance: TComponent; RootAncestor: TClass): Boolean;
  1327. Var
  1328. I : Integer;
  1329. begin
  1330. if not Assigned(InitHandlerList) then begin
  1331. Result := True;
  1332. Exit;
  1333. end;
  1334. Result:=False;
  1335. With InitHandlerList do
  1336. begin
  1337. I:=0;
  1338. // Instance is the normally the lowest one, so that one should be used when searching.
  1339. While Not result and (I<Count) do
  1340. begin
  1341. If (Instance.InheritsFrom(TInitHandler(Items[i]).AClass)) then
  1342. Result:=TInitHandler(Items[i]).AHandler(Instance,RootAncestor);
  1343. Inc(I);
  1344. end;
  1345. end;
  1346. end;
  1347. function InitComponentRes(const ResName: String; Instance: TComponent): Boolean;
  1348. begin
  1349. Result:=ReadComponentRes(ResName,Instance)=Instance;
  1350. end;
  1351. function SysReadComponentRes(HInstance : THandle; const ResName: String; Instance: TComponent): TComponent;
  1352. Var
  1353. H : TFPResourceHandle;
  1354. begin
  1355. { Windows unit also has a FindResource function, use the one from
  1356. system unit here. }
  1357. H:=system.FindResource(HInstance,ResName,RT_RCDATA);
  1358. if (PtrInt(H)=0) then
  1359. Result:=Nil
  1360. else
  1361. With TResourceStream.Create(HInstance,ResName,RT_RCDATA) do
  1362. try
  1363. Result:=ReadComponent(Instance);
  1364. Finally
  1365. Free;
  1366. end;
  1367. end;
  1368. function ReadComponentRes(const ResName: String; Instance: TComponent): TComponent;
  1369. begin
  1370. Result:=SysReadComponentRes(Hinstance,Resname,Instance);
  1371. end;
  1372. function ReadComponentResEx(HInstance: THandle; const ResName: String): TComponent;
  1373. begin
  1374. Result:=SysReadComponentRes(Hinstance,ResName,Nil);
  1375. end;
  1376. function ReadComponentResFile(const FileName: String; Instance: TComponent): TComponent;
  1377. var
  1378. FileStream: TStream;
  1379. begin
  1380. FileStream := TFileStream.Create(FileName, fmOpenRead {!!!:or fmShareDenyWrite});
  1381. try
  1382. Result := FileStream.ReadComponentRes(Instance);
  1383. finally
  1384. FileStream.Free;
  1385. end;
  1386. end;
  1387. procedure WriteComponentResFile(const FileName: String; Instance: TComponent);
  1388. var
  1389. FileStream: TStream;
  1390. begin
  1391. FileStream := TFileStream.Create(FileName, fmCreate);
  1392. try
  1393. FileStream.WriteComponentRes(Instance.ClassName, Instance);
  1394. finally
  1395. FileStream.Free;
  1396. end;
  1397. end;
  1398. function ReadComponentDeltaRes(Instance: TComponent; const DeltaCandidates: array of string; const Proc: TGetStreamProc): TComponent;
  1399. var
  1400. H:TFPResourceHandle;
  1401. HInst: THandle;
  1402. RootName, Delta, ResName: string;
  1403. S: TStream;
  1404. begin
  1405. S:=nil;
  1406. if (Instance=Nil) or (Proc=Nil) then
  1407. Raise EArgumentNilException.Create(SArgumentNil);
  1408. HInst:=HInstance;
  1409. Result:=Instance;
  1410. RootName:=Instance.ClassType.ClassName;
  1411. for Delta in DeltaCandidates do
  1412. begin
  1413. ResName:=RootName+'_'+Delta;
  1414. H:=System.FindResource(HInst,ResName,RT_RCDATA);
  1415. if PtrInt(H)<>0 then
  1416. try
  1417. S:=TResourceStream.Create(HInst,ResName,RT_RCDATA);
  1418. Proc(S);
  1419. Exit;
  1420. finally
  1421. S.Free;
  1422. end;
  1423. end;
  1424. end;
  1425. Function FindNestedComponent(Root : TComponent; APath : String; CStyle : Boolean = True) : TComponent;
  1426. Function GetNextName : String; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE}
  1427. Var
  1428. P : Integer;
  1429. CM : Boolean;
  1430. begin
  1431. P:=Pos('.',APath);
  1432. CM:=False;
  1433. If (P=0) then
  1434. begin
  1435. If CStyle then
  1436. begin
  1437. P:=Pos('->',APath);
  1438. CM:=P<>0;
  1439. end;
  1440. If (P=0) Then
  1441. P:=Length(APath)+1;
  1442. end;
  1443. Result:=Copy(APath,1,P-1);
  1444. Delete(APath,1,P+Ord(CM));
  1445. end;
  1446. Var
  1447. C : TComponent;
  1448. S : String;
  1449. begin
  1450. If (APath='') then
  1451. Result:=Nil
  1452. else
  1453. begin
  1454. Result:=Root;
  1455. While (APath<>'') And (Result<>Nil) do
  1456. begin
  1457. C:=Result;
  1458. S:=Uppercase(GetNextName);
  1459. Result:=C.FindComponent(S);
  1460. If (Result=Nil) And (S='OWNER') then
  1461. Result:=C;
  1462. end;
  1463. end;
  1464. end;
  1465. {$ifdef FPC_HAS_FEATURE_THREADING}
  1466. threadvar
  1467. {$else}
  1468. var
  1469. {$endif}
  1470. GlobalLoaded, GlobalLists: TFpList;
  1471. procedure BeginGlobalLoading;
  1472. begin
  1473. if not Assigned(GlobalLists) then
  1474. GlobalLists := TFpList.Create;
  1475. GlobalLists.Add(GlobalLoaded);
  1476. GlobalLoaded := TFpList.Create;
  1477. end;
  1478. { Notify all global components that they have been loaded completely }
  1479. procedure NotifyGlobalLoading;
  1480. var
  1481. i: Integer;
  1482. begin
  1483. for i := 0 to GlobalLoaded.Count - 1 do
  1484. TComponent(GlobalLoaded[i]).Loaded;
  1485. end;
  1486. procedure EndGlobalLoading;
  1487. begin
  1488. { Free the memory occupied by BeginGlobalLoading }
  1489. GlobalLoaded.Free;
  1490. GlobalLoaded := TFpList(GlobalLists.Last);
  1491. GlobalLists.Delete(GlobalLists.Count - 1);
  1492. if GlobalLists.Count = 0 then
  1493. begin
  1494. GlobalLists.Free;
  1495. GlobalLists := nil;
  1496. end;
  1497. end;
  1498. function CollectionsEqual(C1, C2: TCollection): Boolean;
  1499. begin
  1500. // !!!: Implement this
  1501. CollectionsEqual:=false;
  1502. end;
  1503. function CollectionsEqual(C1, C2: TCollection; Owner1, Owner2: TComponent): Boolean;
  1504. procedure stream_collection(s : tstream;c : tcollection;o : tcomponent);
  1505. var
  1506. w : twriter;
  1507. begin
  1508. w:=twriter.create(s,4096);
  1509. try
  1510. w.root:=o;
  1511. w.flookuproot:=o;
  1512. w.writecollection(c);
  1513. finally
  1514. w.free;
  1515. end;
  1516. end;
  1517. var
  1518. s1,s2 : tmemorystream;
  1519. begin
  1520. result:=false;
  1521. if (c1.classtype<>c2.classtype) or
  1522. (c1.count<>c2.count) then
  1523. exit;
  1524. if c1.count = 0 then
  1525. begin
  1526. result:= true;
  1527. exit;
  1528. end;
  1529. s1:=tmemorystream.create;
  1530. try
  1531. s2:=tmemorystream.create;
  1532. try
  1533. stream_collection(s1,c1,owner1);
  1534. stream_collection(s2,c2,owner2);
  1535. result:=(s1.size=s2.size) and (CompareByte(s1.memory^,s2.memory^,s1.size)=0);
  1536. finally
  1537. s2.free;
  1538. end;
  1539. finally
  1540. s1.free;
  1541. end;
  1542. end;
  1543. { Object conversion routines }
  1544. type
  1545. CharToOrdFuncty = Function(var charpo: Pointer): Cardinal;
  1546. function CharToOrd(var P: Pointer): Cardinal;
  1547. begin
  1548. result:= ord(PAnsiChar(P)^);
  1549. inc(PAnsiChar(P));
  1550. end;
  1551. function WideCharToOrd(var P: Pointer): Cardinal;
  1552. begin
  1553. result:= ord(pwidechar(P)^);
  1554. inc(pwidechar(P));
  1555. end;
  1556. function Utf8ToOrd(var P:Pointer): Cardinal;
  1557. begin
  1558. // Should also check for illegal utf8 combinations
  1559. Result := Ord(PAnsiChar(P)^);
  1560. Inc(P);
  1561. if (Result and $80) <> 0 then
  1562. if (Ord(Result) and %11100000) = %11000000 then begin
  1563. Result := ((Result and %00011111) shl 6)
  1564. or (ord(PAnsiChar(P)^) and %00111111);
  1565. Inc(P);
  1566. end else if (Ord(Result) and %11110000) = %11100000 then begin
  1567. Result := ((Result and %00011111) shl 12)
  1568. or ((ord(PAnsiChar(P)^) and %00111111) shl 6)
  1569. or (ord((PAnsiChar(P)+1)^) and %00111111);
  1570. Inc(P,2);
  1571. end else begin
  1572. Result := ((ord(Result) and %00011111) shl 18)
  1573. or ((ord(PAnsiChar(P)^) and %00111111) shl 12)
  1574. or ((ord((PAnsiChar(P)+1)^) and %00111111) shl 6)
  1575. or (ord((PAnsiChar(P)+2)^) and %00111111);
  1576. Inc(P,3);
  1577. end;
  1578. end;
  1579. procedure ObjectBinaryToText(Input, Output: TStream; Encoding: TObjectTextEncoding);
  1580. var
  1581. Version: TBinaryObjectReader.TBOVersion;
  1582. procedure OutStr(s: RawByteString);
  1583. begin
  1584. if Length(s) > 0 then
  1585. Output.Write(s[1], Length(s));
  1586. end;
  1587. procedure OutLn(s: RawByteString);
  1588. begin
  1589. OutStr(s + LineEnding);
  1590. end;
  1591. procedure Outchars(P, LastP : Pointer; CharToOrdFunc: CharToOrdFuncty;
  1592. UseBytes: boolean = false);
  1593. var
  1594. res, NewStr: RawByteString;
  1595. w: Cardinal;
  1596. InString, NewInString: Boolean;
  1597. begin
  1598. if p = nil then begin
  1599. res:= '''''';
  1600. end
  1601. else
  1602. begin
  1603. res := '';
  1604. InString := False;
  1605. while P < LastP do
  1606. begin
  1607. NewInString := InString;
  1608. w := CharToOrdfunc(P);
  1609. if w = ord('''') then
  1610. begin //quote AnsiChar
  1611. if not InString then
  1612. NewInString := True;
  1613. NewStr := '''''';
  1614. end
  1615. else if (Ord(w) >= 32) and ((Ord(w) < 127) or (UseBytes and (Ord(w)<256))) then
  1616. begin //printable ascii or bytes
  1617. if not InString then
  1618. NewInString := True;
  1619. NewStr := AnsiChar(w);
  1620. end
  1621. else
  1622. begin //ascii control chars, non ascii
  1623. if InString then
  1624. NewInString := False;
  1625. NewStr := '#' + IntToStr(w);
  1626. end;
  1627. if NewInString <> InString then
  1628. begin
  1629. NewStr := '''' + NewStr;
  1630. InString := NewInString;
  1631. end;
  1632. res := res + NewStr;
  1633. end;
  1634. if InString then
  1635. res := res + '''';
  1636. end;
  1637. OutStr(res);
  1638. end;
  1639. procedure OutString(s: RawByteString);
  1640. begin
  1641. OutChars(Pointer(S),PAnsiChar(S)+Length(S),@CharToOrd,Encoding=oteLFM);
  1642. end;
  1643. procedure OutWString(W: WideString);
  1644. begin
  1645. OutChars(Pointer(W),pwidechar(W)+Length(W),@WideCharToOrd);
  1646. end;
  1647. procedure OutUString(W: UnicodeString);
  1648. begin
  1649. OutChars(Pointer(W),pwidechar(W)+Length(W),@WideCharToOrd);
  1650. end;
  1651. procedure OutUtf8Str(s: RawByteString);
  1652. begin
  1653. if Encoding=oteLFM then
  1654. OutChars(Pointer(S),PAnsiChar(S)+Length(S),@CharToOrd)
  1655. else
  1656. OutChars(Pointer(S),PAnsiChar(S)+Length(S),@Utf8ToOrd);
  1657. end;
  1658. function ReadWord : word; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1659. begin
  1660. Result:=Input.ReadWord;
  1661. Result:=LEtoN(Result);
  1662. end;
  1663. function ReadDWord : longword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1664. begin
  1665. Result:=Input.ReadDWord;
  1666. Result:=LEtoN(Result);
  1667. end;
  1668. function ReadQWord : qword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1669. begin
  1670. Input.ReadBuffer(Result,sizeof(Result));
  1671. Result:=LEtoN(Result);
  1672. end;
  1673. {$ifndef FPUNONE}
  1674. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1675. function ExtendedToDouble(e : pointer) : double;
  1676. var mant : qword;
  1677. exp : smallint;
  1678. sign : boolean;
  1679. d : qword;
  1680. begin
  1681. move(pbyte(e)[0],mant,8); //mantissa : bytes 0..7
  1682. move(pbyte(e)[8],exp,2); //exponent and sign: bytes 8..9
  1683. mant:=LEtoN(mant);
  1684. exp:=LetoN(word(exp));
  1685. sign:=(exp and $8000)<>0;
  1686. if sign then exp:=exp and $7FFF;
  1687. case exp of
  1688. 0 : mant:=0; //if denormalized, value is too small for double,
  1689. //so it's always zero
  1690. $7FFF : exp:=2047 //either infinity or NaN
  1691. else
  1692. begin
  1693. dec(exp,16383-1023);
  1694. if (exp>=-51) and (exp<=0) then //can be denormalized
  1695. begin
  1696. mant:=mant shr (-exp);
  1697. exp:=0;
  1698. end
  1699. else
  1700. if (exp<-51) or (exp>2046) then //exponent too large.
  1701. begin
  1702. Result:=0;
  1703. exit;
  1704. end
  1705. else //normalized value
  1706. mant:=mant shl 1; //hide most significant bit
  1707. end;
  1708. end;
  1709. d:=word(exp);
  1710. d:=d shl 52;
  1711. mant:=mant shr 12;
  1712. d:=d or mant;
  1713. if sign then d:=d or $8000000000000000;
  1714. Result:=pdouble(@d)^;
  1715. end;
  1716. {$ENDIF}
  1717. {$endif}
  1718. function ReadInt(ValueType: TValueType): Int64;
  1719. begin
  1720. case ValueType of
  1721. vaInt8: Result := ShortInt(Input.ReadByte);
  1722. vaInt16: Result := SmallInt(ReadWord);
  1723. vaInt32: Result := LongInt(ReadDWord);
  1724. vaInt64: Result := Int64(ReadQWord);
  1725. end;
  1726. end;
  1727. function ReadInt: Int64;
  1728. begin
  1729. Result := ReadInt(TValueType(Input.ReadByte));
  1730. end;
  1731. {$ifndef FPUNONE}
  1732. function ReadExtended : extended;
  1733. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1734. var ext : array[0..9] of byte;
  1735. {$ENDIF}
  1736. begin
  1737. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1738. Input.ReadBuffer(ext[0],10);
  1739. Result:=ExtendedToDouble(@(ext[0]));
  1740. {$ELSE}
  1741. Input.ReadBuffer(Result,sizeof(Result));
  1742. {$ENDIF}
  1743. end;
  1744. {$endif}
  1745. function ReadSStr: RawByteString;
  1746. var
  1747. len: Byte;
  1748. begin
  1749. len := Input.ReadByte;
  1750. SetLength(Result, len);
  1751. if (len > 0) then
  1752. Input.ReadBuffer(Result[1], len);
  1753. end;
  1754. function ReadLStr: RawByteString;
  1755. var
  1756. len: DWord;
  1757. begin
  1758. len := ReadDWord;
  1759. SetLength(Result, len);
  1760. if (len > 0) then
  1761. Input.ReadBuffer(Result[1], len);
  1762. end;
  1763. function ReadWStr: WideString;
  1764. var
  1765. len: DWord;
  1766. {$IFDEF ENDIAN_BIG}
  1767. i : integer;
  1768. {$ENDIF}
  1769. begin
  1770. len := ReadDWord;
  1771. SetLength(Result, len);
  1772. if (len > 0) then
  1773. begin
  1774. Input.ReadBuffer(Pointer(@Result[1])^, len*2);
  1775. {$IFDEF ENDIAN_BIG}
  1776. for i:=1 to len do
  1777. Result[i]:=widechar(SwapEndian(word(Result[i])));
  1778. {$ENDIF}
  1779. end;
  1780. end;
  1781. function ReadUStr: UnicodeString;
  1782. var
  1783. len: DWord;
  1784. {$IFDEF ENDIAN_BIG}
  1785. i : integer;
  1786. {$ENDIF}
  1787. begin
  1788. len := ReadDWord;
  1789. SetLength(Result, len);
  1790. if (len > 0) then
  1791. begin
  1792. Input.ReadBuffer(Pointer(@Result[1])^, len*2);
  1793. {$IFDEF ENDIAN_BIG}
  1794. for i:=1 to len do
  1795. Result[i]:=widechar(SwapEndian(word(Result[i])));
  1796. {$ENDIF}
  1797. end;
  1798. end;
  1799. procedure ReadPropList(indent: RawByteString);
  1800. procedure ProcessValue(ValueType: TValueType; Indent: RawByteString);
  1801. procedure ProcessBinary;
  1802. var
  1803. ToDo, DoNow, i: LongInt;
  1804. lbuf: array[0..31] of Byte;
  1805. s: RawByteString;
  1806. begin
  1807. ToDo := ReadDWord;
  1808. OutLn('{');
  1809. while ToDo > 0 do begin
  1810. DoNow := ToDo;
  1811. if DoNow > 32 then DoNow := 32;
  1812. Dec(ToDo, DoNow);
  1813. s := Indent + ' ';
  1814. Input.ReadBuffer(lbuf, DoNow);
  1815. for i := 0 to DoNow - 1 do
  1816. s := s + IntToHex(lbuf[i], 2);
  1817. OutLn(s);
  1818. end;
  1819. OutLn(indent + '}');
  1820. end;
  1821. var
  1822. s: RawByteString;
  1823. { len: LongInt; }
  1824. IsFirst: Boolean;
  1825. {$ifndef FPUNONE}
  1826. ext: Extended;
  1827. {$endif}
  1828. begin
  1829. case ValueType of
  1830. vaList: begin
  1831. OutStr('(');
  1832. IsFirst := True;
  1833. while True do begin
  1834. ValueType := TValueType(Input.ReadByte);
  1835. if ValueType = vaNull then break;
  1836. if IsFirst then begin
  1837. OutLn('');
  1838. IsFirst := False;
  1839. end;
  1840. OutStr(Indent + ' ');
  1841. ProcessValue(ValueType, Indent + ' ');
  1842. end;
  1843. OutLn(Indent + ')');
  1844. end;
  1845. vaInt8: OutLn(IntToStr(ShortInt(Input.ReadByte)));
  1846. vaInt16: OutLn( IntToStr(SmallInt(ReadWord)));
  1847. vaInt32: OutLn(IntToStr(LongInt(ReadDWord)));
  1848. vaInt64: OutLn(IntToStr(Int64(ReadQWord)));
  1849. {$ifndef FPUNONE}
  1850. vaExtended: begin
  1851. ext:=ReadExtended;
  1852. Str(ext,S);// Do not use localized strings.
  1853. OutLn(S);
  1854. end;
  1855. {$endif}
  1856. vaString: begin
  1857. OutString(ReadSStr);
  1858. OutLn('');
  1859. end;
  1860. vaIdent: OutLn(ReadSStr);
  1861. vaFalse: OutLn('False');
  1862. vaTrue: OutLn('True');
  1863. vaBinary: ProcessBinary;
  1864. vaSet: begin
  1865. OutStr('[');
  1866. IsFirst := True;
  1867. while True do begin
  1868. s := ReadSStr;
  1869. if Length(s) = 0 then break;
  1870. if not IsFirst then OutStr(', ');
  1871. IsFirst := False;
  1872. OutStr(s);
  1873. end;
  1874. OutLn(']');
  1875. end;
  1876. vaLString:
  1877. begin
  1878. OutString(ReadLStr);
  1879. OutLn('');
  1880. end;
  1881. vaWString:
  1882. begin
  1883. OutWString(ReadWStr);
  1884. OutLn('');
  1885. end;
  1886. vaUString:
  1887. begin
  1888. OutWString(ReadWStr);
  1889. OutLn('');
  1890. end;
  1891. vaNil:
  1892. OutLn('nil');
  1893. vaCollection: begin
  1894. OutStr('<');
  1895. while Input.ReadByte <> 0 do begin
  1896. OutLn(Indent);
  1897. Input.Seek(-1, soFromCurrent);
  1898. OutStr(indent + ' item');
  1899. ValueType := TValueType(Input.ReadByte);
  1900. if ValueType <> vaList then
  1901. OutStr('[' + IntToStr(ReadInt(ValueType)) + ']');
  1902. OutLn('');
  1903. ReadPropList(indent + ' ');
  1904. OutStr(indent + ' end');
  1905. end;
  1906. OutLn('>');
  1907. end;
  1908. {vaSingle: begin OutLn('!!Single!!'); exit end;
  1909. vaCurrency: begin OutLn('!!Currency!!'); exit end;
  1910. vaDate: begin OutLn('!!Date!!'); exit end;}
  1911. vaUTF8String: begin
  1912. OutUtf8Str(ReadLStr);
  1913. OutLn('');
  1914. end;
  1915. else
  1916. Raise EReadError.CreateFmt(SErrInvalidPropertyType,[Ord(ValueType)]);
  1917. end;
  1918. end;
  1919. begin
  1920. while Input.ReadByte <> 0 do begin
  1921. Input.Seek(-1, soFromCurrent);
  1922. OutStr(indent + ReadSStr + ' = ');
  1923. ProcessValue(TValueType(Input.ReadByte), Indent);
  1924. end;
  1925. end;
  1926. procedure ReadObject(indent: RawByteString);
  1927. var
  1928. b: Byte;
  1929. ObjUnitName, ObjClassName, ObjName: RawByteString;
  1930. ChildPos: LongInt;
  1931. ValueType: TValueType;
  1932. p: SizeInt;
  1933. begin
  1934. // Check for FilerFlags
  1935. b := Input.ReadByte;
  1936. if (b and $f0) = $f0 then begin
  1937. if (b and 2) <> 0 then ChildPos := ReadInt;
  1938. end else begin
  1939. b := 0;
  1940. Input.Seek(-1, soFromCurrent);
  1941. end;
  1942. ObjUnitName:='';
  1943. if Version=TBinaryObjectReader.TBOVersion.boVersion1 then
  1944. begin
  1945. ValueType := TValueType(Input.ReadByte);
  1946. if ValueType=vaString then
  1947. ObjClassName := ReadSStr
  1948. else
  1949. ObjClassName := ReadLStr;
  1950. p:=Pos(TBinaryObjectReader.UnitnameSeparator,ObjClassName);
  1951. if p>0 then
  1952. begin
  1953. ObjUnitName:=copy(ObjClassName,1,p-1);
  1954. System.Delete(ObjClassName,1,p);
  1955. end;
  1956. end else
  1957. ObjClassName := ReadSStr;
  1958. ObjName := ReadSStr;
  1959. OutStr(Indent);
  1960. if (b and 1) <> 0 then
  1961. OutStr('inherited')
  1962. else if (b and 4) <> 0 then
  1963. OutStr('inline')
  1964. else
  1965. OutStr('object');
  1966. OutStr(' ');
  1967. if ObjName <> '' then
  1968. OutStr(ObjName + ': ');
  1969. if Version=TBinaryObjectReader.TBOVersion.boVersion1 then
  1970. begin
  1971. OutStr(ObjUnitName);
  1972. OutStr('/');
  1973. end;
  1974. OutStr(ObjClassName);
  1975. if (b and 2) <> 0 then
  1976. OutStr('[' + IntToStr(ChildPos) + ']');
  1977. OutLn('');
  1978. ReadPropList(indent + ' ');
  1979. while Input.ReadByte <> 0 do begin
  1980. Input.Seek(-1, soFromCurrent);
  1981. ReadObject(indent + ' ');
  1982. end;
  1983. OutLn(indent + 'end');
  1984. end;
  1985. var
  1986. Signature: DWord;
  1987. begin
  1988. Signature:=Input.ReadDWord;
  1989. if Signature = DWord(unaligned(FilerSignature1)) then
  1990. Version:=TBinaryObjectReader.TBOVersion.boVersion1
  1991. else if Signature = DWord(unaligned(FilerSignature)) then
  1992. Version:=TBinaryObjectReader.TBOVersion.boVersion0
  1993. else
  1994. raise EReadError.Create('Illegal stream image' {###SInvalidImage});
  1995. ReadObject('');
  1996. end;
  1997. procedure ObjectBinaryToText(Input, Output: TStream);
  1998. begin
  1999. ObjectBinaryToText(Input,Output,oteDFM);
  2000. end;
  2001. procedure ObjectTextToBinary(Input, Output: TStream);
  2002. var
  2003. Fmt : TStreamOriginalFormat;
  2004. begin
  2005. ObjectTextToBinary(Input,Output,Fmt);
  2006. end;
  2007. procedure ObjectTextToBinary(Input, Output: TStream; var Format: TStreamOriginalFormat);
  2008. var
  2009. parser: TParser;
  2010. Version: TBinaryObjectReader.TBOVersion;
  2011. StartPos: Int64;
  2012. procedure WriteWord(w : word); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  2013. begin
  2014. w:=NtoLE(w);
  2015. Output.WriteWord(w);
  2016. end;
  2017. procedure WriteDWord(lw : longword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  2018. begin
  2019. lw:=NtoLE(lw);
  2020. Output.WriteDWord(lw);
  2021. end;
  2022. procedure WriteQWord(qw : qword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  2023. begin
  2024. qw:=NtoLE(qw);
  2025. Output.WriteBuffer(qw,sizeof(qword));
  2026. end;
  2027. {$ifndef FPUNONE}
  2028. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  2029. procedure DoubleToExtended(d : double; e : pointer);
  2030. var mant : qword;
  2031. exp : smallint;
  2032. sign : boolean;
  2033. begin
  2034. mant:=(qword(d) and $000FFFFFFFFFFFFF) shl 12;
  2035. exp :=(qword(d) shr 52) and $7FF;
  2036. sign:=(qword(d) and $8000000000000000)<>0;
  2037. case exp of
  2038. 0 : begin
  2039. if mant<>0 then //denormalized value: hidden bit is 0. normalize it
  2040. begin
  2041. exp:=16383-1022;
  2042. while (mant and $8000000000000000)=0 do
  2043. begin
  2044. dec(exp);
  2045. mant:=mant shl 1;
  2046. end;
  2047. dec(exp); //don't shift, most significant bit is not hidden in extended
  2048. end;
  2049. end;
  2050. 2047 : exp:=$7FFF //either infinity or NaN
  2051. else
  2052. begin
  2053. inc(exp,16383-1023);
  2054. mant:=(mant shr 1) or $8000000000000000; //unhide hidden bit
  2055. end;
  2056. end;
  2057. if sign then exp:=exp or $8000;
  2058. mant:=NtoLE(mant);
  2059. exp:=NtoLE(word(exp));
  2060. move(mant,pbyte(e)[0],8); //mantissa : bytes 0..7
  2061. move(exp,pbyte(e)[8],2); //exponent and sign: bytes 8..9
  2062. end;
  2063. {$ENDIF}
  2064. procedure WriteExtended(const e : extended);
  2065. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  2066. var ext : array[0..9] of byte;
  2067. {$ENDIF}
  2068. begin
  2069. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  2070. DoubleToExtended(e,@(ext[0]));
  2071. Output.WriteBuffer(ext[0],10);
  2072. {$ELSE}
  2073. Output.WriteBuffer(e,sizeof(e));
  2074. {$ENDIF}
  2075. end;
  2076. {$endif}
  2077. procedure WriteSString(const s: RawByteString);
  2078. var size : byte;
  2079. begin
  2080. if length(s)>255 then size:=255
  2081. else size:=length(s);
  2082. Output.WriteByte(size);
  2083. if Length(s) > 0 then
  2084. Output.WriteBuffer(s[1], size);
  2085. end;
  2086. procedure WriteLString(Const s: RawByteString);
  2087. begin
  2088. WriteDWord(Length(s));
  2089. if Length(s) > 0 then
  2090. Output.WriteBuffer(s[1], Length(s));
  2091. end;
  2092. procedure WriteSorLString(Const s: String);
  2093. begin
  2094. if length(s)<256 then
  2095. begin
  2096. Output.WriteByte(Ord(vaString));
  2097. WriteSString(s);
  2098. end else begin
  2099. Output.WriteByte(Ord(vaLString));
  2100. WriteSString(s);
  2101. end;
  2102. end;
  2103. procedure WriteWString(Const s: WideString);
  2104. var len : longword;
  2105. {$IFDEF ENDIAN_BIG}
  2106. i : integer;
  2107. ws : widestring;
  2108. {$ENDIF}
  2109. begin
  2110. len:=Length(s);
  2111. WriteDWord(len);
  2112. if len > 0 then
  2113. begin
  2114. {$IFDEF ENDIAN_BIG}
  2115. setlength(ws,len);
  2116. for i:=1 to len do
  2117. ws[i]:=widechar(SwapEndian(word(s[i])));
  2118. Output.WriteBuffer(ws[1], len*sizeof(widechar));
  2119. {$ELSE}
  2120. Output.WriteBuffer(s[1], len*sizeof(widechar));
  2121. {$ENDIF}
  2122. end;
  2123. end;
  2124. procedure WriteInteger(value: Int64);
  2125. begin
  2126. if (value >= -128) and (value <= 127) then begin
  2127. Output.WriteByte(Ord(vaInt8));
  2128. Output.WriteByte(byte(value));
  2129. end else if (value >= -32768) and (value <= 32767) then begin
  2130. Output.WriteByte(Ord(vaInt16));
  2131. WriteWord(word(value));
  2132. end else if (value >= -2147483648) and (value <= 2147483647) then begin
  2133. Output.WriteByte(Ord(vaInt32));
  2134. WriteDWord(longword(value));
  2135. end else begin
  2136. Output.WriteByte(ord(vaInt64));
  2137. WriteQWord(qword(value));
  2138. end;
  2139. end;
  2140. procedure ProcessWideString(const left : widestring);
  2141. var ws : widestring;
  2142. begin
  2143. ws:=left+parser.TokenWideString;
  2144. while parser.NextToken = '+' do
  2145. begin
  2146. parser.NextToken; // Get next string fragment
  2147. if not (parser.Token in [toString,toWString]) then
  2148. parser.CheckToken(toWString);
  2149. ws:=ws+parser.TokenWideString;
  2150. end;
  2151. Output.WriteByte(Ord(vaWstring));
  2152. WriteWString(ws);
  2153. end;
  2154. procedure ProcessProperty; forward;
  2155. procedure ProcessValue;
  2156. var
  2157. {$ifndef FPUNONE}
  2158. flt: Extended;
  2159. {$endif}
  2160. s: RawByteString;
  2161. stream: TMemoryStream;
  2162. begin
  2163. case parser.Token of
  2164. toInteger:
  2165. begin
  2166. WriteInteger(parser.TokenInt);
  2167. parser.NextToken;
  2168. end;
  2169. {$ifndef FPUNONE}
  2170. toFloat:
  2171. begin
  2172. Output.WriteByte(Ord(vaExtended));
  2173. flt := Parser.TokenFloat;
  2174. WriteExtended(flt);
  2175. parser.NextToken;
  2176. end;
  2177. {$endif}
  2178. toString:
  2179. begin
  2180. s := parser.TokenString;
  2181. while parser.NextToken = '+' do
  2182. begin
  2183. parser.NextToken; // Get next string fragment
  2184. case parser.Token of
  2185. toString : s:=s+parser.TokenString;
  2186. toWString : begin
  2187. ProcessWideString(WideString(s));
  2188. exit;
  2189. end
  2190. else parser.CheckToken(toString);
  2191. end;
  2192. end;
  2193. if (length(S)>255) then
  2194. begin
  2195. Output.WriteByte(Ord(vaLString));
  2196. WriteLString(S);
  2197. end
  2198. else
  2199. begin
  2200. Output.WriteByte(Ord(vaString));
  2201. WriteSString(s);
  2202. end;
  2203. end;
  2204. toWString:
  2205. ProcessWideString('');
  2206. toSymbol:
  2207. begin
  2208. if CompareText(parser.TokenString, 'True') = 0 then
  2209. Output.WriteByte(Ord(vaTrue))
  2210. else if CompareText(parser.TokenString, 'False') = 0 then
  2211. Output.WriteByte(Ord(vaFalse))
  2212. else if CompareText(parser.TokenString, 'nil') = 0 then
  2213. Output.WriteByte(Ord(vaNil))
  2214. else
  2215. begin
  2216. Output.WriteByte(Ord(vaIdent));
  2217. WriteSString(parser.TokenComponentIdent);
  2218. end;
  2219. Parser.NextToken;
  2220. end;
  2221. // Set
  2222. '[':
  2223. begin
  2224. parser.NextToken;
  2225. Output.WriteByte(Ord(vaSet));
  2226. if parser.Token <> ']' then
  2227. while True do
  2228. begin
  2229. parser.CheckToken(toSymbol);
  2230. WriteSString(parser.TokenString);
  2231. parser.NextToken;
  2232. if parser.Token = ']' then
  2233. break;
  2234. parser.CheckToken(',');
  2235. parser.NextToken;
  2236. end;
  2237. Output.WriteByte(0);
  2238. parser.NextToken;
  2239. end;
  2240. // List
  2241. '(':
  2242. begin
  2243. parser.NextToken;
  2244. Output.WriteByte(Ord(vaList));
  2245. while parser.Token <> ')' do
  2246. ProcessValue;
  2247. Output.WriteByte(0);
  2248. parser.NextToken;
  2249. end;
  2250. // Collection
  2251. '<':
  2252. begin
  2253. parser.NextToken;
  2254. Output.WriteByte(Ord(vaCollection));
  2255. while parser.Token <> '>' do
  2256. begin
  2257. parser.CheckTokenSymbol('item');
  2258. parser.NextToken;
  2259. // ConvertOrder
  2260. Output.WriteByte(Ord(vaList));
  2261. while not parser.TokenSymbolIs('end') do
  2262. ProcessProperty;
  2263. parser.NextToken; // Skip 'end'
  2264. Output.WriteByte(0);
  2265. end;
  2266. Output.WriteByte(0);
  2267. parser.NextToken;
  2268. end;
  2269. // Binary data
  2270. '{':
  2271. begin
  2272. Output.WriteByte(Ord(vaBinary));
  2273. stream := TMemoryStream.Create;
  2274. try
  2275. parser.HexToBinary(stream);
  2276. WriteDWord(stream.Size);
  2277. Output.WriteBuffer(Stream.Memory^, stream.Size);
  2278. finally
  2279. stream.Free;
  2280. end;
  2281. parser.NextToken;
  2282. end;
  2283. else
  2284. parser.Error(SInvalidProperty);
  2285. end;
  2286. end;
  2287. procedure ProcessProperty;
  2288. var
  2289. name: RawByteString;
  2290. begin
  2291. // Get name of property
  2292. parser.CheckToken(toSymbol);
  2293. name := parser.TokenString;
  2294. while True do begin
  2295. parser.NextToken;
  2296. if parser.Token <> '.' then break;
  2297. parser.NextToken;
  2298. parser.CheckToken(toSymbol);
  2299. name := name + '.' + parser.TokenString;
  2300. end;
  2301. WriteSString(name);
  2302. parser.CheckToken('=');
  2303. parser.NextToken;
  2304. ProcessValue;
  2305. end;
  2306. procedure ProcessObject(Root: boolean);
  2307. var
  2308. Flags: Byte;
  2309. ObjectName, ObjUnitName, ObjClassName: RawByteString;
  2310. ChildPos: Integer;
  2311. begin
  2312. if parser.TokenSymbolIs('OBJECT') then
  2313. Flags :=0 { IsInherited := False }
  2314. else begin
  2315. if parser.TokenSymbolIs('INHERITED') then
  2316. Flags := 1 { IsInherited := True; }
  2317. else begin
  2318. parser.CheckTokenSymbol('INLINE');
  2319. Flags := 4;
  2320. end;
  2321. end;
  2322. parser.NextToken;
  2323. parser.CheckToken(toSymbol);
  2324. ObjectName := '';
  2325. ObjUnitName := '';
  2326. ObjClassName := parser.TokenString;
  2327. parser.NextToken;
  2328. if parser.Token = '/' then begin
  2329. ObjUnitName := ObjClassName;
  2330. parser.NextToken;
  2331. parser.CheckToken(toSymbol);
  2332. ObjClassName := parser.TokenString;
  2333. parser.NextToken;
  2334. end else if parser.Token = ':' then begin
  2335. parser.NextToken;
  2336. parser.CheckToken(toSymbol);
  2337. ObjectName := ObjClassName;
  2338. ObjClassName := parser.TokenString;
  2339. parser.NextToken;
  2340. if parser.Token = '/' then begin
  2341. ObjUnitName := ObjClassName;
  2342. parser.NextToken;
  2343. parser.CheckToken(toSymbol);
  2344. ObjClassName := parser.TokenString;
  2345. parser.NextToken;
  2346. end;
  2347. if parser.Token = '[' then begin
  2348. parser.NextToken;
  2349. ChildPos := parser.TokenInt;
  2350. parser.NextToken;
  2351. parser.CheckToken(']');
  2352. parser.NextToken;
  2353. Flags := Flags or 2;
  2354. end;
  2355. end;
  2356. if Root then
  2357. begin
  2358. if (ObjUnitName<>'') then
  2359. Version:=TBinaryObjectReader.TBOVersion.boVersion1;
  2360. if Version=TBinaryObjectReader.TBOVersion.boVersion1 then
  2361. Output.WriteBuffer(FilerSignature1[1], length(FilerSignature1))
  2362. else
  2363. Output.WriteBuffer(FilerSignature[1], length(FilerSignature));
  2364. end;
  2365. if Flags <> 0 then begin
  2366. Output.WriteByte($f0 or Flags);
  2367. if (Flags and 2) <> 0 then
  2368. WriteInteger(ChildPos);
  2369. end;
  2370. if Version=TBinaryObjectReader.TBOVersion.boVersion1 then
  2371. WriteSorLString(ObjUnitName+TBinaryObjectReader.UnitnameSeparator+ObjClassName)
  2372. else
  2373. WriteSString(ObjClassName);
  2374. WriteSString(ObjectName);
  2375. // Convert property list
  2376. while not (parser.TokenSymbolIs('END') or
  2377. parser.TokenSymbolIs('OBJECT') or
  2378. parser.TokenSymbolIs('INHERITED') or
  2379. parser.TokenSymbolIs('INLINE')) do
  2380. ProcessProperty;
  2381. Output.WriteByte(0); // Terminate property list
  2382. // Convert child objects
  2383. while not parser.TokenSymbolIs('END') do ProcessObject(false);
  2384. parser.NextToken; // Skip end token
  2385. Output.WriteByte(0); // Terminate property list
  2386. end;
  2387. const
  2388. signature: PAnsiChar = 'TPF0';
  2389. begin
  2390. Version:=TBinaryObjectReader.TBOVersion.boVersion0;
  2391. parser := TParser.Create(Input);
  2392. try
  2393. StartPos:=Output.Position;
  2394. ProcessObject(true);
  2395. finally
  2396. parser.Free;
  2397. end;
  2398. end;
  2399. procedure ObjectResourceToText(Input, Output: TStream);
  2400. begin
  2401. Input.ReadResHeader;
  2402. ObjectBinaryToText(Input, Output);
  2403. end;
  2404. procedure ObjectTextToResource(Input, Output: TStream);
  2405. var
  2406. StartPos, FixupInfo: LongInt;
  2407. parser: TParser;
  2408. name: String;
  2409. begin
  2410. // Get form type name
  2411. StartPos := Input.Position;
  2412. parser := TParser.Create(Input);
  2413. try
  2414. if not parser.TokenSymbolIs('OBJECT') then parser.CheckTokenSymbol('INHERITED');
  2415. parser.NextToken;
  2416. parser.CheckToken(toSymbol);
  2417. parser.NextToken;
  2418. parser.CheckToken(':');
  2419. parser.NextToken;
  2420. parser.CheckToken(toSymbol);
  2421. name := parser.TokenString;
  2422. finally
  2423. parser.Free;
  2424. Input.Position := StartPos;
  2425. end;
  2426. name := UpperCase(name);
  2427. Output.WriteResourceHeader(name,FixupInfo); // Write resource header
  2428. ObjectTextToBinary(Input, Output); // Convert the stuff!
  2429. Output.FixupResourceHeader(FixupInfo); // Insert real resource data size
  2430. end;
  2431. function TestStreamFormat(const Stream: TStream): TStreamOriginalFormat;
  2432. const
  2433. StartChars = [#9, #10, #13, #11, 'o', 'O','i','I',' '];
  2434. var
  2435. aPos: Int64;
  2436. Sig: Packed Array[0..3] of byte;
  2437. IntSig : Longint absolute sig;
  2438. begin
  2439. Result:=sofUnknown;
  2440. aPos:=Stream.Position;
  2441. IntSig:=0;
  2442. Stream.Read(Sig,SizeOf(Sig));
  2443. Stream.Seek(aPos,soBeginning);
  2444. if (Sig[0]=$FF) or (IntSig=LongInt(FilerSignature)) or (IntSig=LongInt(FilerSignature1)) or (IntSig=0) then
  2445. Result:=sofBinary
  2446. else if (AnsiChar(Sig[0]) in StartChars) then
  2447. Result:=sofText
  2448. else if (Sig[0]=$EF) and (Sig[1]=$BB) and (Sig[2]=$BF) then
  2449. Result:=sofUTF8Text;
  2450. end;
  2451. { Utility routines }
  2452. Function IfThen(AValue: Boolean; const ATrue: TStringList; const AFalse: TStringList = nil): TStringList; overload;
  2453. begin
  2454. if avalue then
  2455. result:=atrue
  2456. else
  2457. result:=afalse;
  2458. end;
  2459. function LineStart(Buffer, BufPos: PAnsiChar): PAnsiChar;
  2460. begin
  2461. Result := BufPos;
  2462. while Result > Buffer do begin
  2463. Dec(Result);
  2464. if Result[0] = #10 then break;
  2465. end;
  2466. end;
  2467. procedure CommonInit;
  2468. begin
  2469. {$ifdef FPC_HAS_FEATURE_THREADING}
  2470. SynchronizeTimeoutEvent:=RtlEventCreate;
  2471. InterlockedIncrement(ThreadQueueLockCounter);
  2472. InitCriticalSection(ThreadQueueLock);
  2473. MainThreadID:=GetCurrentThreadID;
  2474. {$else}
  2475. MainThreadID:=0{GetCurrentThreadID};
  2476. {$endif}
  2477. ExternalThreads := TThreadList.Create;
  2478. {$ifdef FPC_HAS_FEATURE_THREADING}
  2479. InitCriticalsection(ResolveSection);
  2480. TThread.FProcessorCount := CPUCount;
  2481. {$else}
  2482. TThread.FProcessorCount := 1{CPUCount};
  2483. {$endif}
  2484. InitHandlerList:=Nil;
  2485. FindGlobalComponentList:=nil;
  2486. IntConstList := TThreadList.Create;
  2487. ClassList := TThreadList.Create;
  2488. ClassAliasList := nil;
  2489. { on unix this maps to a simple rw synchornizer }
  2490. GlobalNameSpace := TMultiReadExclusiveWriteSynchronizer.Create;
  2491. RegisterInitComponentHandler(TComponent,@DefaultInitHandler);
  2492. end;
  2493. procedure CommonCleanup;
  2494. var
  2495. i: Integer;
  2496. tmpentry: TThread.PThreadQueueEntry;
  2497. begin
  2498. {$ifdef FPC_HAS_FEATURE_THREADING}
  2499. GlobalNameSpace.BeginWrite;
  2500. {$endif}
  2501. with IntConstList.LockList do
  2502. try
  2503. for i := 0 to Count - 1 do
  2504. TIntConst(Items[I]).Free;
  2505. finally
  2506. IntConstList.UnlockList;
  2507. end;
  2508. IntConstList.Free;
  2509. ClassList.Free;
  2510. ClassAliasList.Free;
  2511. RemoveFixupReferences(nil, '');
  2512. {$ifdef FPC_HAS_FEATURE_THREADING}
  2513. DoneCriticalsection(ResolveSection);
  2514. {$endif}
  2515. GlobalLists.Free;
  2516. ComponentPages.Free;
  2517. FreeAndNil(NeedResolving);
  2518. {$ifdef FPC_HAS_FEATURE_THREADING}
  2519. GlobalNameSpace.EndWrite;
  2520. {$endif}
  2521. { GlobalNameSpace is an interface so this is enough }
  2522. GlobalNameSpace:=nil;
  2523. if (InitHandlerList<>Nil) then
  2524. for i := 0 to InitHandlerList.Count - 1 do
  2525. TInitHandler(InitHandlerList.Items[I]).Free;
  2526. InitHandlerList.Free;
  2527. InitHandlerList:=Nil;
  2528. FindGlobalComponentList.Free;
  2529. FindGlobalComponentList:=nil;
  2530. ExternalThreadsCleanup:=True;
  2531. with ExternalThreads.LockList do
  2532. try
  2533. for i := 0 to Count - 1 do
  2534. TThread(Items[i]).Free;
  2535. finally
  2536. ExternalThreads.UnlockList;
  2537. end;
  2538. FreeAndNil(ExternalThreads);
  2539. {$ifdef FPC_HAS_FEATURE_THREADING}
  2540. RtlEventDestroy(SynchronizeTimeoutEvent);
  2541. try
  2542. System.EnterCriticalSection(ThreadQueueLock);
  2543. {$endif}
  2544. { clean up the queue, but keep in mind that the entries used for Synchronize
  2545. are owned by the corresponding TThread }
  2546. while Assigned(ThreadQueueHead) do begin
  2547. tmpentry := ThreadQueueHead;
  2548. ThreadQueueHead := tmpentry^.Next;
  2549. if not Assigned(tmpentry^.SyncEvent) then
  2550. Dispose(tmpentry);
  2551. end;
  2552. { We also need to reset ThreadQueueTail }
  2553. ThreadQueueTail := nil;
  2554. {$ifdef FPC_HAS_FEATURE_THREADING}
  2555. finally
  2556. System.LeaveCriticalSection(ThreadQueueLock);
  2557. end;
  2558. if InterlockedDecrement(ThreadQueueLockCounter)=0 then
  2559. DoneCriticalSection(ThreadQueueLock);
  2560. {$endif}
  2561. end;
  2562. { TFiler implementation }
  2563. {$i filer.inc}
  2564. { TReader implementation }
  2565. {$i reader.inc}
  2566. { TWriter implementations }
  2567. {$i writer.inc}
  2568. {$i twriter.inc}
  2569. constructor ComponentPlatformsAttribute.Create(const aPlatforms: TPlatformIds);
  2570. begin
  2571. FPlatForms:=aPlatForms;
  2572. end;