classes.inc 74 KB

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