classes.inc 72 KB

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