classes.inc 72 KB

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