classes.inc 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962
  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 defined(CPUX86_64) or Defined(CPUI386)}
  776. fpc_x86_pause;
  777. {$ELSEIF defined(CPUARM)}
  778. fpc_arm_yield;
  779. {$ELSEIF defined(CPUAARCH64}
  780. fpc_aarch64_yield;
  781. {$ELSE}
  782. Inc(SpinWaitDummy); // SpinWaitDummy *MUST* be global
  783. {$ENDIF}
  784. end;
  785. end;
  786. {$ifndef HAS_TTHREAD_GETSYSTEMTIMES}
  787. class function TThread.GetSystemTimes(out aSystemTimes: TSystemTimes) : Boolean;
  788. begin
  789. { by default we just return a zeroed out record }
  790. FillChar(aSystemTimes, SizeOf(aSystemTimes), 0);
  791. Result:=False;
  792. end;
  793. {$endif}
  794. class function TThread.GetCPUUsage(var Previous: TSystemTimes): Integer;
  795. var
  796. Act : TSystemTimes;
  797. Load,Idle: QWord;
  798. begin
  799. Result:=0;
  800. if not GetSystemTimes(Act) then
  801. exit;
  802. Load:=(Act.UserTime-Previous.UserTime) +
  803. (Act.KernelTime-Previous.KernelTime) +
  804. (Act.NiceTime-Previous.NiceTime);
  805. Idle:=Act.IdleTime-Previous.IdleTime;
  806. Previous:=Act;
  807. if (Load<>0) and (Load>Idle) then
  808. Result:=100*Trunc(1-(Idle/Load));
  809. end;
  810. class function TThread.GetTickCount: LongWord;
  811. begin
  812. Result := {$IFDEF FPC_DOTTEDUNITS}System.{$ENDIF}SysUtils.GetTickCount;
  813. end;
  814. class function TThread.GetTickCount64: QWord;
  815. begin
  816. Result := {$IFDEF FPC_DOTTEDUNITS}System.{$ENDIF}SysUtils.GetTickCount64;
  817. end;
  818. { TSimpleThread allows objects to create a threading method without defining
  819. a new thread class }
  820. Type
  821. TSimpleThread = class(TThread)
  822. private
  823. FExecuteMethod: TThreadExecuteHandler;
  824. protected
  825. procedure Execute; override;
  826. public
  827. constructor Create(ExecuteMethod: TThreadExecuteHandler; AOnterminate : TNotifyEvent);
  828. end;
  829. TSimpleStatusThread = class(TThread)
  830. private
  831. FExecuteMethod: TThreadExecuteStatusHandler;
  832. FStatus : String;
  833. FOnStatus : TThreadStatusNotifyEvent;
  834. protected
  835. procedure Execute; override;
  836. Procedure DoStatus;
  837. Procedure SetStatus(Const AStatus : String);
  838. public
  839. constructor Create(ExecuteMethod: TThreadExecuteStatusHandler; AOnStatus : TThreadStatusNotifyEvent; AOnterminate : TNotifyEvent);
  840. end;
  841. TSimpleProcThread = class(TThread)
  842. private
  843. FExecuteMethod: TThreadExecuteCallBack;
  844. FCallOnTerminate : TNotifyCallBack;
  845. FData : Pointer;
  846. protected
  847. Procedure TerminateCallBack(Sender : TObject);
  848. procedure Execute; override;
  849. public
  850. constructor Create(ExecuteMethod: TThreadExecuteCallBack; AData : Pointer; AOnterminate : TNotifyCallBack);
  851. end;
  852. TSimpleStatusProcThread = class(TThread)
  853. private
  854. FExecuteMethod: TThreadExecuteStatusCallBack;
  855. FCallOnTerminate : TNotifyCallBack;
  856. FStatus : String;
  857. FOnStatus : TThreadStatusNotifyCallBack;
  858. FData : Pointer;
  859. protected
  860. procedure Execute; override;
  861. Procedure DoStatus;
  862. Procedure SetStatus(Const AStatus : String);
  863. Procedure TerminateCallBack(Sender : TObject);
  864. public
  865. constructor Create(ExecuteMethod: TThreadExecuteStatusCallBack; AData : Pointer; AOnStatus : TThreadStatusNotifyCallBack; AOnterminate : TNotifyCallBack);
  866. end;
  867. { TSimpleThread }
  868. constructor TSimpleThread.Create(ExecuteMethod: TThreadExecuteHandler; AOnTerminate: TNotifyEvent);
  869. begin
  870. FExecuteMethod := ExecuteMethod;
  871. OnTerminate := AOnTerminate;
  872. inherited Create(False);
  873. end;
  874. procedure TSimpleThread.Execute;
  875. begin
  876. FreeOnTerminate := True;
  877. FExecuteMethod;
  878. end;
  879. { TSimpleStatusThread }
  880. constructor TSimpleStatusThread.Create(ExecuteMethod: TThreadExecuteStatusHandler;AOnStatus : TThreadStatusNotifyEvent; AOnTerminate: TNotifyEvent);
  881. begin
  882. FExecuteMethod := ExecuteMethod;
  883. OnTerminate := AOnTerminate;
  884. FOnStatus:=AOnStatus;
  885. FStatus:='';
  886. inherited Create(False);
  887. end;
  888. procedure TSimpleStatusThread.Execute;
  889. begin
  890. FreeOnTerminate := True;
  891. FExecuteMethod(@SetStatus);
  892. end;
  893. procedure TSimpleStatusThread.SetStatus(Const AStatus : String);
  894. begin
  895. If (AStatus=FStatus) then
  896. exit;
  897. FStatus:=AStatus;
  898. If Assigned(FOnStatus) then
  899. Synchronize(@DoStatus);
  900. end;
  901. procedure TSimpleStatusThread.DoStatus;
  902. begin
  903. FOnStatus(Self,FStatus);
  904. end;
  905. { TSimpleProcThread }
  906. constructor TSimpleProcThread.Create(ExecuteMethod: TThreadExecuteCallBack; AData : Pointer; AOnTerminate: TNotifyCallBack);
  907. begin
  908. FExecuteMethod := ExecuteMethod;
  909. FCallOnTerminate := AOnTerminate;
  910. FData:=AData;
  911. If Assigned(FCallOnTerminate) then
  912. OnTerminate:=@TerminateCallBack;
  913. inherited Create(False);
  914. end;
  915. procedure TSimpleProcThread.Execute;
  916. begin
  917. FreeOnTerminate := True;
  918. FExecuteMethod(FData);
  919. end;
  920. procedure TSimpleProcThread.TerminateCallBack(Sender : TObject);
  921. begin
  922. if Assigned(FCallOnTerminate) then
  923. FCallOnTerminate(Sender,FData);
  924. end;
  925. { TSimpleStatusProcThread }
  926. constructor TSimpleStatusProcThread.Create(ExecuteMethod: TThreadExecuteStatusCallback; AData : Pointer; AOnStatus : TThreadStatusNotifyCallBack; AOnTerminate: TNotifyCallBack);
  927. begin
  928. FExecuteMethod := ExecuteMethod;
  929. FCallOnTerminate := AOnTerminate;
  930. FData:=AData;
  931. If Assigned(FCallOnTerminate) then
  932. OnTerminate:=@TerminateCallBack;
  933. FOnStatus:=AOnStatus;
  934. FStatus:='';
  935. inherited Create(False);
  936. end;
  937. procedure TSimpleStatusProcThread.Execute;
  938. begin
  939. FreeOnTerminate := True;
  940. FExecuteMethod(FData,@SetStatus);
  941. end;
  942. procedure TSimpleStatusProcThread.SetStatus(Const AStatus : String);
  943. begin
  944. If (AStatus=FStatus) then
  945. exit;
  946. FStatus:=AStatus;
  947. If Assigned(FOnStatus) then
  948. Synchronize(@DoStatus);
  949. end;
  950. procedure TSimpleStatusProcThread.DoStatus;
  951. begin
  952. FOnStatus(Self,FData,FStatus);
  953. end;
  954. procedure TSimpleStatusProcThread.TerminateCallBack(Sender : TObject);
  955. begin
  956. if Assigned(FCallOnTerminate) then
  957. FCallOnTerminate(Sender,FData);
  958. end;
  959. class function TThread.ExecuteInThread(AMethod: TThreadExecuteHandler; AOnTerminate: TNotifyEvent): TThread;
  960. begin
  961. Result:=TSimpleThread.Create(AMethod,AOnTerminate);
  962. end;
  963. class function TThread.ExecuteInThread(AMethod: TThreadExecuteCallback; AData: Pointer; AOnTerminate: TNotifyCallBack): TThread;
  964. begin
  965. Result:=TSimpleProcThread.Create(AMethod,AData,AOnTerminate);
  966. end;
  967. class function TThread.ExecuteInThread(AMethod: TThreadExecuteStatusHandler; AOnStatus: TThreadStatusNotifyEvent;
  968. AOnTerminate: TNotifyEvent): TThread;
  969. begin
  970. If Not Assigned(AOnStatus) then
  971. Raise EThread.Create(SErrStatusCallBackRequired);
  972. Result:=TSimpleStatusThread.Create(AMethod,AOnStatus,AOnTerminate);
  973. end;
  974. class function TThread.ExecuteInThread(AMethod: TThreadExecuteStatusCallback; AOnStatus: TThreadStatusNotifyCallback;
  975. AData: Pointer; AOnTerminate: TNotifyCallBack): TThread;
  976. begin
  977. If Not Assigned(AOnStatus) then
  978. Raise EThread.Create(SErrStatusCallBackRequired);
  979. Result:=TSimpleStatusProcThread.Create(AMethod,AData,AOnStatus,AOnTerminate);
  980. end;
  981. { TPersistent implementation }
  982. {$i persist.inc }
  983. {$i sllist.inc}
  984. {$i resref.inc}
  985. { TComponent implementation }
  986. {$i compon.inc}
  987. { TBasicAction implementation }
  988. {$i action.inc}
  989. { TDataModule implementation }
  990. {$i dm.inc}
  991. { Class and component registration routines }
  992. {$I cregist.inc}
  993. { Interface related stuff }
  994. {$I intf.inc}
  995. {**********************************************************************
  996. * Miscellaneous procedures and functions *
  997. **********************************************************************}
  998. function ExtractStrings(Separators, WhiteSpace: TSysCharSet; Content: PAnsiChar; Strings: TStrings; AddEmptyStrings : Boolean = False): Integer;
  999. var
  1000. b, c : PAnsiChar;
  1001. procedure SkipWhitespace;
  1002. begin
  1003. while (c^ in Whitespace) do
  1004. inc (c);
  1005. end;
  1006. procedure AddString;
  1007. var
  1008. l : integer;
  1009. s : string;
  1010. begin
  1011. l := c-b;
  1012. if (l > 0) or AddEmptyStrings then
  1013. begin
  1014. if assigned(Strings) then
  1015. begin
  1016. setlength(s, l);
  1017. if l>0 then
  1018. move (b^, s[1],l*SizeOf(AnsiChar));
  1019. Strings.Add (s);
  1020. end;
  1021. inc (result);
  1022. end;
  1023. end;
  1024. var
  1025. quoted : AnsiChar;
  1026. begin
  1027. result := 0;
  1028. c := Content;
  1029. Quoted := #0;
  1030. Separators := Separators + [#13, #10] - ['''','"'];
  1031. SkipWhitespace;
  1032. b := c;
  1033. while (c^ <> #0) do
  1034. begin
  1035. if (c^ = Quoted) then
  1036. begin
  1037. if ((c+1)^ = Quoted) then
  1038. inc (c)
  1039. else
  1040. Quoted := #0
  1041. end
  1042. else if (Quoted = #0) and (c^ in ['''','"']) then
  1043. Quoted := c^;
  1044. if (Quoted = #0) and (c^ in Separators) then
  1045. begin
  1046. AddString;
  1047. inc (c);
  1048. SkipWhitespace;
  1049. b := c;
  1050. end
  1051. else
  1052. inc (c);
  1053. end;
  1054. if (c <> b) then
  1055. AddString;
  1056. end;
  1057. { Point and rectangle constructors }
  1058. function Point(AX, AY: Integer): TPoint;
  1059. begin
  1060. with Result do
  1061. begin
  1062. X := AX;
  1063. Y := AY;
  1064. end;
  1065. end;
  1066. function SmallPoint(AX, AY: SmallInt): TSmallPoint;
  1067. begin
  1068. with Result do
  1069. begin
  1070. X := AX;
  1071. Y := AY;
  1072. end;
  1073. end;
  1074. function Rect(ALeft, ATop, ARight, ABottom: Integer): TRect;
  1075. begin
  1076. with Result do
  1077. begin
  1078. Left := ALeft;
  1079. Top := ATop;
  1080. Right := ARight;
  1081. Bottom := ABottom;
  1082. end;
  1083. end;
  1084. function Bounds(ALeft, ATop, AWidth, AHeight: Integer): TRect;
  1085. begin
  1086. with Result do
  1087. begin
  1088. Left := ALeft;
  1089. Top := ATop;
  1090. Right := ALeft + AWidth;
  1091. Bottom := ATop + AHeight;
  1092. end;
  1093. end;
  1094. function PointsEqual(const P1, P2: TPoint): Boolean; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1095. begin
  1096. { lazy, but should work }
  1097. result:=QWord(P1)=QWord(P2);
  1098. end;
  1099. function PointsEqual(const P1, P2: TSmallPoint): Boolean; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1100. begin
  1101. { lazy, but should work }
  1102. result:=DWord(P1)=DWord(P2);
  1103. end;
  1104. function InvalidPoint(X, Y: Integer): Boolean;
  1105. begin
  1106. result:=(X=-1) and (Y=-1);
  1107. end;
  1108. function InvalidPoint(const At: TPoint): Boolean;
  1109. begin
  1110. result:=(At.x=-1) and (At.y=-1);
  1111. end;
  1112. function InvalidPoint(const At: TSmallPoint): Boolean;
  1113. begin
  1114. result:=(At.x=-1) and (At.y=-1);
  1115. end;
  1116. { Object filing routines }
  1117. var
  1118. IntConstList: TThreadList;
  1119. type
  1120. TIntConst = class
  1121. IntegerType: PTypeInfo; // The integer type RTTI pointer
  1122. IdentToIntFn: TIdentToInt; // Identifier to Integer conversion
  1123. IntToIdentFn: TIntToIdent; // Integer to Identifier conversion
  1124. constructor Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt;
  1125. AIntToIdent: TIntToIdent);
  1126. end;
  1127. constructor TIntConst.Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt;
  1128. AIntToIdent: TIntToIdent);
  1129. begin
  1130. IntegerType := AIntegerType;
  1131. IdentToIntFn := AIdentToInt;
  1132. IntToIdentFn := AIntToIdent;
  1133. end;
  1134. procedure RegisterIntegerConsts(IntegerType: Pointer; IdentToIntFn: TIdentToInt;
  1135. IntToIdentFn: TIntToIdent);
  1136. begin
  1137. IntConstList.Add(TIntConst.Create(IntegerType, IdentToIntFn, IntToIdentFn));
  1138. end;
  1139. function FindIntToIdent(AIntegerType: Pointer): TIntToIdent;
  1140. var
  1141. i: Integer;
  1142. begin
  1143. with IntConstList.LockList do
  1144. try
  1145. for i := 0 to Count - 1 do
  1146. if TIntConst(Items[i]).IntegerType = AIntegerType then
  1147. exit(TIntConst(Items[i]).IntToIdentFn);
  1148. Result := nil;
  1149. finally
  1150. IntConstList.UnlockList;
  1151. end;
  1152. end;
  1153. function FindIdentToInt(AIntegerType: Pointer): TIdentToInt;
  1154. var
  1155. i: Integer;
  1156. begin
  1157. with IntConstList.LockList do
  1158. try
  1159. for i := 0 to Count - 1 do
  1160. with TIntConst(Items[I]) do
  1161. if TIntConst(Items[I]).IntegerType = AIntegerType then
  1162. exit(IdentToIntFn);
  1163. Result := nil;
  1164. finally
  1165. IntConstList.UnlockList;
  1166. end;
  1167. end;
  1168. function IdentToInt(const Ident: String; out Int: LongInt;
  1169. const Map: array of TIdentMapEntry): Boolean;
  1170. var
  1171. i: Integer;
  1172. begin
  1173. for i := Low(Map) to High(Map) do
  1174. if CompareText(Map[i].Name, Ident) = 0 then
  1175. begin
  1176. Int := Map[i].Value;
  1177. exit(True);
  1178. end;
  1179. Result := False;
  1180. end;
  1181. function IntToIdent(Int: LongInt; var Ident: String;
  1182. const Map: array of TIdentMapEntry): Boolean;
  1183. var
  1184. i: Integer;
  1185. begin
  1186. for i := Low(Map) to High(Map) do
  1187. if Map[i].Value = Int then
  1188. begin
  1189. Ident := Map[i].Name;
  1190. exit(True);
  1191. end;
  1192. Result := False;
  1193. end;
  1194. function GlobalIdentToInt(const Ident: String; var Int: LongInt):boolean;
  1195. var
  1196. i : Integer;
  1197. begin
  1198. with IntConstList.LockList do
  1199. try
  1200. for i := 0 to Count - 1 do
  1201. if TIntConst(Items[I]).IdentToIntFn(Ident, Int) then
  1202. Exit(True);
  1203. Result := false;
  1204. finally
  1205. IntConstList.UnlockList;
  1206. end;
  1207. end;
  1208. { TPropFixup }
  1209. // Tainted. TPropFixup is being removed.
  1210. Type
  1211. TInitHandler = Class(TObject)
  1212. AHandler : TInitComponentHandler;
  1213. AClass : TComponentClass;
  1214. end;
  1215. {$ifndef i8086}
  1216. type
  1217. TCodePtrList = TList;
  1218. {$endif i8086}
  1219. Var
  1220. InitHandlerList : TList;
  1221. FindGlobalComponentList : TCodePtrList;
  1222. procedure RegisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent);
  1223. begin
  1224. if not(assigned(FindGlobalComponentList)) then
  1225. FindGlobalComponentList:=TCodePtrList.Create;
  1226. if FindGlobalComponentList.IndexOf(CodePointer(AFindGlobalComponent))<0 then
  1227. FindGlobalComponentList.Add(CodePointer(AFindGlobalComponent));
  1228. end;
  1229. procedure UnregisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent);
  1230. begin
  1231. if assigned(FindGlobalComponentList) then
  1232. FindGlobalComponentList.Remove(CodePointer(AFindGlobalComponent));
  1233. end;
  1234. function FindGlobalComponent(const Name: string): TComponent;
  1235. var
  1236. i : sizeint;
  1237. begin
  1238. FindGlobalComponent:=nil;
  1239. if assigned(FindGlobalComponentList) then
  1240. begin
  1241. for i:=FindGlobalComponentList.Count-1 downto 0 do
  1242. begin
  1243. FindGlobalComponent:=TFindGlobalComponent(FindGlobalComponentList[i])(name);
  1244. if assigned(FindGlobalComponent) then
  1245. break;
  1246. end;
  1247. end;
  1248. end;
  1249. function IsUniqueGlobalComponentName(const aName: string): Boolean;
  1250. begin
  1251. if Assigned(IsUniqueGlobalComponentNameProc) then
  1252. Result:=IsUniqueGlobalComponentNameProc(aName)
  1253. else
  1254. Result:=Not Assigned(FindGlobalComponent(aName));
  1255. end;
  1256. procedure RegisterInitComponentHandler(ComponentClass: TComponentClass; Handler: TInitComponentHandler);
  1257. Var
  1258. I : Integer;
  1259. H: TInitHandler;
  1260. begin
  1261. If (InitHandlerList=Nil) then
  1262. InitHandlerList:=TList.Create;
  1263. H:=TInitHandler.Create;
  1264. H.Aclass:=ComponentClass;
  1265. H.AHandler:=Handler;
  1266. try
  1267. With InitHandlerList do
  1268. begin
  1269. I:=0;
  1270. While (I<Count) and not H.AClass.InheritsFrom(TInitHandler(Items[I]).AClass) do
  1271. Inc(I);
  1272. { override? }
  1273. if (I<Count) and (TInitHandler(Items[I]).AClass=H.AClass) then
  1274. begin
  1275. TInitHandler(Items[I]).AHandler:=Handler;
  1276. H.Free;
  1277. end
  1278. else
  1279. InitHandlerList.Insert(I,H);
  1280. end;
  1281. except
  1282. H.Free;
  1283. raise;
  1284. end;
  1285. end;
  1286. { all targets should at least include the sysres.inc dummy in the system unit to compile this }
  1287. function CreateComponentfromRes(const res : string;Inst : THandle;var Component : TComponent) : Boolean;
  1288. var
  1289. ResStream : TResourceStream;
  1290. ResID : TFPResourceHandle;
  1291. begin
  1292. if Inst=0 then
  1293. Inst:=HInstance;
  1294. ResId:=System.FindResource(Inst, Res, RT_RCDATA);
  1295. result:=ResID<>0;
  1296. try
  1297. if Result then
  1298. begin
  1299. ResStream:=TResourceStream.Create(Inst,Res,RT_RCDATA);
  1300. try
  1301. Component:=ResStream.ReadComponent(Component);
  1302. finally
  1303. ResStream.Free;
  1304. end;
  1305. end;
  1306. except
  1307. on EResNotFound do
  1308. result:=false;
  1309. end;
  1310. end;
  1311. function DefaultInitHandler(Instance: TComponent; RootAncestor: TClass): Boolean;
  1312. function doinit(_class : TClass) : boolean;
  1313. begin
  1314. result:=false;
  1315. if (_class.ClassType=TComponent) or (_class.ClassType=RootAncestor) then
  1316. exit;
  1317. result:=doinit(_class.ClassParent);
  1318. result:=CreateComponentfromRes(_class.ClassName,0,Instance) or result;
  1319. end;
  1320. begin
  1321. {$ifdef FPC_HAS_FEATURE_THREADING}
  1322. GlobalNameSpace.BeginWrite;
  1323. try
  1324. {$endif}
  1325. result:=doinit(Instance.ClassType);
  1326. if Result then
  1327. Instance.ReadDeltaState;
  1328. {$ifdef FPC_HAS_FEATURE_THREADING}
  1329. finally
  1330. GlobalNameSpace.EndWrite;
  1331. end;
  1332. {$endif}
  1333. end;
  1334. function InitInheritedComponent(Instance: TComponent; RootAncestor: TClass): Boolean;
  1335. Var
  1336. I : Integer;
  1337. begin
  1338. if not Assigned(InitHandlerList) then begin
  1339. Result := True;
  1340. Exit;
  1341. end;
  1342. Result:=False;
  1343. With InitHandlerList do
  1344. begin
  1345. I:=0;
  1346. // Instance is the normally the lowest one, so that one should be used when searching.
  1347. While Not result and (I<Count) do
  1348. begin
  1349. If (Instance.InheritsFrom(TInitHandler(Items[i]).AClass)) then
  1350. Result:=TInitHandler(Items[i]).AHandler(Instance,RootAncestor);
  1351. Inc(I);
  1352. end;
  1353. end;
  1354. end;
  1355. function InitComponentRes(const ResName: String; Instance: TComponent): Boolean;
  1356. begin
  1357. Result:=ReadComponentRes(ResName,Instance)=Instance;
  1358. end;
  1359. function SysReadComponentRes(HInstance : THandle; const ResName: String; Instance: TComponent): TComponent;
  1360. Var
  1361. H : TFPResourceHandle;
  1362. begin
  1363. { Windows unit also has a FindResource function, use the one from
  1364. system unit here. }
  1365. H:=system.FindResource(HInstance,ResName,RT_RCDATA);
  1366. if (PtrInt(H)=0) then
  1367. Result:=Nil
  1368. else
  1369. With TResourceStream.Create(HInstance,ResName,RT_RCDATA) do
  1370. try
  1371. Result:=ReadComponent(Instance);
  1372. Finally
  1373. Free;
  1374. end;
  1375. end;
  1376. function ReadComponentRes(const ResName: String; Instance: TComponent): TComponent;
  1377. begin
  1378. Result:=SysReadComponentRes(Hinstance,Resname,Instance);
  1379. end;
  1380. function ReadComponentResEx(HInstance: THandle; const ResName: String): TComponent;
  1381. begin
  1382. Result:=SysReadComponentRes(Hinstance,ResName,Nil);
  1383. end;
  1384. function ReadComponentResFile(const FileName: String; Instance: TComponent): TComponent;
  1385. var
  1386. FileStream: TStream;
  1387. begin
  1388. FileStream := TFileStream.Create(FileName, fmOpenRead {!!!:or fmShareDenyWrite});
  1389. try
  1390. Result := FileStream.ReadComponentRes(Instance);
  1391. finally
  1392. FileStream.Free;
  1393. end;
  1394. end;
  1395. procedure WriteComponentResFile(const FileName: String; Instance: TComponent);
  1396. var
  1397. FileStream: TStream;
  1398. begin
  1399. FileStream := TFileStream.Create(FileName, fmCreate);
  1400. try
  1401. FileStream.WriteComponentRes(Instance.ClassName, Instance);
  1402. finally
  1403. FileStream.Free;
  1404. end;
  1405. end;
  1406. function ReadComponentDeltaRes(Instance: TComponent; const DeltaCandidates: array of string; const Proc: TGetStreamProc): TComponent;
  1407. var
  1408. H:TFPResourceHandle;
  1409. HInst: THandle;
  1410. RootName, Delta, ResName: string;
  1411. S: TStream;
  1412. begin
  1413. S:=nil;
  1414. if (Instance=Nil) or (Proc=Nil) then
  1415. Raise EArgumentNilException.Create(SArgumentNil);
  1416. HInst:=HInstance;
  1417. Result:=Instance;
  1418. RootName:=Instance.ClassType.ClassName;
  1419. for Delta in DeltaCandidates do
  1420. begin
  1421. ResName:=RootName+'_'+Delta;
  1422. H:=System.FindResource(HInst,ResName,RT_RCDATA);
  1423. if PtrInt(H)<>0 then
  1424. try
  1425. S:=TResourceStream.Create(HInst,ResName,RT_RCDATA);
  1426. Proc(S);
  1427. Exit;
  1428. finally
  1429. S.Free;
  1430. end;
  1431. end;
  1432. end;
  1433. Function FindNestedComponent(Root : TComponent; APath : String; CStyle : Boolean = True) : TComponent;
  1434. Function GetNextName : String; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE}
  1435. Var
  1436. P : Integer;
  1437. CM : Boolean;
  1438. begin
  1439. P:=Pos('.',APath);
  1440. CM:=False;
  1441. If (P=0) then
  1442. begin
  1443. If CStyle then
  1444. begin
  1445. P:=Pos('->',APath);
  1446. CM:=P<>0;
  1447. end;
  1448. If (P=0) Then
  1449. P:=Length(APath)+1;
  1450. end;
  1451. Result:=Copy(APath,1,P-1);
  1452. Delete(APath,1,P+Ord(CM));
  1453. end;
  1454. Var
  1455. C : TComponent;
  1456. S : String;
  1457. begin
  1458. If (APath='') then
  1459. Result:=Nil
  1460. else
  1461. begin
  1462. Result:=Root;
  1463. While (APath<>'') And (Result<>Nil) do
  1464. begin
  1465. C:=Result;
  1466. S:=Uppercase(GetNextName);
  1467. Result:=C.FindComponent(S);
  1468. If (Result=Nil) And (S='OWNER') then
  1469. Result:=C;
  1470. end;
  1471. end;
  1472. end;
  1473. {$ifdef FPC_HAS_FEATURE_THREADING}
  1474. threadvar
  1475. {$else}
  1476. var
  1477. {$endif}
  1478. GlobalLoaded, GlobalLists: TFpList;
  1479. procedure BeginGlobalLoading;
  1480. begin
  1481. if not Assigned(GlobalLists) then
  1482. GlobalLists := TFpList.Create;
  1483. GlobalLists.Add(GlobalLoaded);
  1484. GlobalLoaded := TFpList.Create;
  1485. end;
  1486. { Notify all global components that they have been loaded completely }
  1487. procedure NotifyGlobalLoading;
  1488. var
  1489. i: Integer;
  1490. begin
  1491. for i := 0 to GlobalLoaded.Count - 1 do
  1492. TComponent(GlobalLoaded[i]).Loaded;
  1493. end;
  1494. procedure EndGlobalLoading;
  1495. begin
  1496. { Free the memory occupied by BeginGlobalLoading }
  1497. GlobalLoaded.Free;
  1498. GlobalLoaded := TFpList(GlobalLists.Last);
  1499. GlobalLists.Delete(GlobalLists.Count - 1);
  1500. if GlobalLists.Count = 0 then
  1501. begin
  1502. GlobalLists.Free;
  1503. GlobalLists := nil;
  1504. end;
  1505. end;
  1506. function CollectionsEqual(C1, C2: TCollection): Boolean;
  1507. begin
  1508. // !!!: Implement this
  1509. CollectionsEqual:=false;
  1510. end;
  1511. function CollectionsEqual(C1, C2: TCollection; Owner1, Owner2: TComponent): Boolean;
  1512. procedure stream_collection(s : tstream;c : tcollection;o : tcomponent);
  1513. var
  1514. w : twriter;
  1515. begin
  1516. w:=twriter.create(s,4096);
  1517. try
  1518. w.root:=o;
  1519. w.flookuproot:=o;
  1520. w.writecollection(c);
  1521. finally
  1522. w.free;
  1523. end;
  1524. end;
  1525. var
  1526. s1,s2 : tmemorystream;
  1527. begin
  1528. result:=false;
  1529. if (c1.classtype<>c2.classtype) or
  1530. (c1.count<>c2.count) then
  1531. exit;
  1532. if c1.count = 0 then
  1533. begin
  1534. result:= true;
  1535. exit;
  1536. end;
  1537. s1:=tmemorystream.create;
  1538. try
  1539. s2:=tmemorystream.create;
  1540. try
  1541. stream_collection(s1,c1,owner1);
  1542. stream_collection(s2,c2,owner2);
  1543. result:=(s1.size=s2.size) and (CompareByte(s1.memory^,s2.memory^,s1.size)=0);
  1544. finally
  1545. s2.free;
  1546. end;
  1547. finally
  1548. s1.free;
  1549. end;
  1550. end;
  1551. { Object conversion routines }
  1552. type
  1553. CharToOrdFuncty = Function(var charpo: Pointer): Cardinal;
  1554. function CharToOrd(var P: Pointer): Cardinal;
  1555. begin
  1556. result:= ord(PAnsiChar(P)^);
  1557. inc(PAnsiChar(P));
  1558. end;
  1559. function WideCharToOrd(var P: Pointer): Cardinal;
  1560. begin
  1561. result:= ord(pwidechar(P)^);
  1562. inc(pwidechar(P));
  1563. end;
  1564. function Utf8ToOrd(var P:Pointer): Cardinal;
  1565. begin
  1566. // Should also check for illegal utf8 combinations
  1567. Result := Ord(PAnsiChar(P)^);
  1568. Inc(P);
  1569. if (Result and $80) <> 0 then
  1570. if (Ord(Result) and %11100000) = %11000000 then begin
  1571. Result := ((Result and %00011111) shl 6)
  1572. or (ord(PAnsiChar(P)^) and %00111111);
  1573. Inc(P);
  1574. end else if (Ord(Result) and %11110000) = %11100000 then begin
  1575. Result := ((Result and %00011111) shl 12)
  1576. or ((ord(PAnsiChar(P)^) and %00111111) shl 6)
  1577. or (ord((PAnsiChar(P)+1)^) and %00111111);
  1578. Inc(P,2);
  1579. end else begin
  1580. Result := ((ord(Result) and %00011111) shl 18)
  1581. or ((ord(PAnsiChar(P)^) and %00111111) shl 12)
  1582. or ((ord((PAnsiChar(P)+1)^) and %00111111) shl 6)
  1583. or (ord((PAnsiChar(P)+2)^) and %00111111);
  1584. Inc(P,3);
  1585. end;
  1586. end;
  1587. procedure ObjectBinaryToText(Input, Output: TStream; Encoding: TObjectTextEncoding);
  1588. var
  1589. Version: TBinaryObjectReader.TBOVersion;
  1590. procedure OutStr(s: RawByteString);
  1591. begin
  1592. if Length(s) > 0 then
  1593. Output.Write(s[1], Length(s));
  1594. end;
  1595. procedure OutLn(s: RawByteString);
  1596. begin
  1597. OutStr(s + LineEnding);
  1598. end;
  1599. procedure Outchars(P, LastP : Pointer; CharToOrdFunc: CharToOrdFuncty;
  1600. UseBytes: boolean = false);
  1601. var
  1602. res, NewStr: RawByteString;
  1603. w: Cardinal;
  1604. InString, NewInString: Boolean;
  1605. begin
  1606. if p = nil then begin
  1607. res:= '''''';
  1608. end
  1609. else
  1610. begin
  1611. res := '';
  1612. InString := False;
  1613. while P < LastP do
  1614. begin
  1615. NewInString := InString;
  1616. w := CharToOrdfunc(P);
  1617. if w = ord('''') then
  1618. begin //quote AnsiChar
  1619. if not InString then
  1620. NewInString := True;
  1621. NewStr := '''''';
  1622. end
  1623. else if (Ord(w) >= 32) and ((Ord(w) < 127) or (UseBytes and (Ord(w)<256))) then
  1624. begin //printable ascii or bytes
  1625. if not InString then
  1626. NewInString := True;
  1627. NewStr := AnsiChar(w);
  1628. end
  1629. else
  1630. begin //ascii control chars, non ascii
  1631. if InString then
  1632. NewInString := False;
  1633. NewStr := '#' + IntToStr(w);
  1634. end;
  1635. if NewInString <> InString then
  1636. begin
  1637. NewStr := '''' + NewStr;
  1638. InString := NewInString;
  1639. end;
  1640. res := res + NewStr;
  1641. end;
  1642. if InString then
  1643. res := res + '''';
  1644. end;
  1645. OutStr(res);
  1646. end;
  1647. procedure OutString(s: RawByteString);
  1648. begin
  1649. OutChars(Pointer(S),PAnsiChar(S)+Length(S),@CharToOrd,Encoding=oteLFM);
  1650. end;
  1651. procedure OutWString(W: WideString);
  1652. begin
  1653. OutChars(Pointer(W),pwidechar(W)+Length(W),@WideCharToOrd);
  1654. end;
  1655. procedure OutUString(W: UnicodeString);
  1656. begin
  1657. OutChars(Pointer(W),pwidechar(W)+Length(W),@WideCharToOrd);
  1658. end;
  1659. procedure OutUtf8Str(s: RawByteString);
  1660. begin
  1661. if Encoding=oteLFM then
  1662. OutChars(Pointer(S),PAnsiChar(S)+Length(S),@CharToOrd)
  1663. else
  1664. OutChars(Pointer(S),PAnsiChar(S)+Length(S),@Utf8ToOrd);
  1665. end;
  1666. function ReadWord : word; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1667. begin
  1668. Result:=Input.ReadWord;
  1669. Result:=LEtoN(Result);
  1670. end;
  1671. function ReadDWord : longword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1672. begin
  1673. Result:=Input.ReadDWord;
  1674. Result:=LEtoN(Result);
  1675. end;
  1676. function ReadQWord : qword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  1677. begin
  1678. Input.ReadBuffer(Result,sizeof(Result));
  1679. Result:=LEtoN(Result);
  1680. end;
  1681. {$ifndef FPUNONE}
  1682. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1683. function ExtendedToDouble(e : pointer) : double;
  1684. var mant : qword;
  1685. exp : smallint;
  1686. sign : boolean;
  1687. d : qword;
  1688. begin
  1689. move(pbyte(e)[0],mant,8); //mantissa : bytes 0..7
  1690. move(pbyte(e)[8],exp,2); //exponent and sign: bytes 8..9
  1691. mant:=LEtoN(mant);
  1692. exp:=LetoN(word(exp));
  1693. sign:=(exp and $8000)<>0;
  1694. if sign then exp:=exp and $7FFF;
  1695. case exp of
  1696. 0 : mant:=0; //if denormalized, value is too small for double,
  1697. //so it's always zero
  1698. $7FFF : exp:=2047 //either infinity or NaN
  1699. else
  1700. begin
  1701. dec(exp,16383-1023);
  1702. if (exp>=-51) and (exp<=0) then //can be denormalized
  1703. begin
  1704. mant:=mant shr (-exp);
  1705. exp:=0;
  1706. end
  1707. else
  1708. if (exp<-51) or (exp>2046) then //exponent too large.
  1709. begin
  1710. Result:=0;
  1711. exit;
  1712. end
  1713. else //normalized value
  1714. mant:=mant shl 1; //hide most significant bit
  1715. end;
  1716. end;
  1717. d:=word(exp);
  1718. d:=d shl 52;
  1719. mant:=mant shr 12;
  1720. d:=d or mant;
  1721. if sign then d:=d or $8000000000000000;
  1722. Result:=pdouble(@d)^;
  1723. end;
  1724. {$ENDIF}
  1725. {$endif}
  1726. function ReadInt(ValueType: TValueType): Int64;
  1727. begin
  1728. case ValueType of
  1729. vaInt8: Result := ShortInt(Input.ReadByte);
  1730. vaInt16: Result := SmallInt(ReadWord);
  1731. vaInt32: Result := LongInt(ReadDWord);
  1732. vaInt64: Result := Int64(ReadQWord);
  1733. end;
  1734. end;
  1735. function ReadInt: Int64;
  1736. begin
  1737. Result := ReadInt(TValueType(Input.ReadByte));
  1738. end;
  1739. {$ifndef FPUNONE}
  1740. function ReadExtended : extended;
  1741. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1742. var ext : array[0..9] of byte;
  1743. {$ENDIF}
  1744. begin
  1745. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  1746. Input.ReadBuffer(ext[0],10);
  1747. Result:=ExtendedToDouble(@(ext[0]));
  1748. {$ELSE}
  1749. Input.ReadBuffer(Result,sizeof(Result));
  1750. {$ENDIF}
  1751. end;
  1752. {$endif}
  1753. function ReadSStr: RawByteString;
  1754. var
  1755. len: Byte;
  1756. begin
  1757. len := Input.ReadByte;
  1758. SetLength(Result, len);
  1759. if (len > 0) then
  1760. Input.ReadBuffer(Result[1], len);
  1761. end;
  1762. function ReadLStr: RawByteString;
  1763. var
  1764. len: DWord;
  1765. begin
  1766. len := ReadDWord;
  1767. SetLength(Result, len);
  1768. if (len > 0) then
  1769. Input.ReadBuffer(Result[1], len);
  1770. end;
  1771. function ReadWStr: WideString;
  1772. var
  1773. len: DWord;
  1774. {$IFDEF ENDIAN_BIG}
  1775. i : integer;
  1776. {$ENDIF}
  1777. begin
  1778. len := ReadDWord;
  1779. SetLength(Result, len);
  1780. if (len > 0) then
  1781. begin
  1782. Input.ReadBuffer(Pointer(@Result[1])^, len*2);
  1783. {$IFDEF ENDIAN_BIG}
  1784. for i:=1 to len do
  1785. Result[i]:=widechar(SwapEndian(word(Result[i])));
  1786. {$ENDIF}
  1787. end;
  1788. end;
  1789. function ReadUStr: UnicodeString;
  1790. var
  1791. len: DWord;
  1792. {$IFDEF ENDIAN_BIG}
  1793. i : integer;
  1794. {$ENDIF}
  1795. begin
  1796. len := ReadDWord;
  1797. SetLength(Result, len);
  1798. if (len > 0) then
  1799. begin
  1800. Input.ReadBuffer(Pointer(@Result[1])^, len*2);
  1801. {$IFDEF ENDIAN_BIG}
  1802. for i:=1 to len do
  1803. Result[i]:=widechar(SwapEndian(word(Result[i])));
  1804. {$ENDIF}
  1805. end;
  1806. end;
  1807. procedure ReadPropList(indent: RawByteString);
  1808. procedure ProcessValue(ValueType: TValueType; Indent: RawByteString);
  1809. procedure ProcessBinary;
  1810. var
  1811. ToDo, DoNow, i: LongInt;
  1812. lbuf: array[0..31] of Byte;
  1813. s: RawByteString;
  1814. begin
  1815. ToDo := ReadDWord;
  1816. OutLn('{');
  1817. while ToDo > 0 do begin
  1818. DoNow := ToDo;
  1819. if DoNow > 32 then DoNow := 32;
  1820. Dec(ToDo, DoNow);
  1821. s := Indent + ' ';
  1822. Input.ReadBuffer(lbuf, DoNow);
  1823. for i := 0 to DoNow - 1 do
  1824. s := s + IntToHex(lbuf[i], 2);
  1825. OutLn(s);
  1826. end;
  1827. OutLn(indent + '}');
  1828. end;
  1829. var
  1830. s: RawByteString;
  1831. { len: LongInt; }
  1832. IsFirst: Boolean;
  1833. {$ifndef FPUNONE}
  1834. ext: Extended;
  1835. {$endif}
  1836. begin
  1837. case ValueType of
  1838. vaList: begin
  1839. OutStr('(');
  1840. IsFirst := True;
  1841. while True do begin
  1842. ValueType := TValueType(Input.ReadByte);
  1843. if ValueType = vaNull then break;
  1844. if IsFirst then begin
  1845. OutLn('');
  1846. IsFirst := False;
  1847. end;
  1848. OutStr(Indent + ' ');
  1849. ProcessValue(ValueType, Indent + ' ');
  1850. end;
  1851. OutLn(Indent + ')');
  1852. end;
  1853. vaInt8: OutLn(IntToStr(ShortInt(Input.ReadByte)));
  1854. vaInt16: OutLn( IntToStr(SmallInt(ReadWord)));
  1855. vaInt32: OutLn(IntToStr(LongInt(ReadDWord)));
  1856. vaInt64: OutLn(IntToStr(Int64(ReadQWord)));
  1857. {$ifndef FPUNONE}
  1858. vaExtended: begin
  1859. ext:=ReadExtended;
  1860. Str(ext,S);// Do not use localized strings.
  1861. OutLn(S);
  1862. end;
  1863. {$endif}
  1864. vaString: begin
  1865. OutString(ReadSStr);
  1866. OutLn('');
  1867. end;
  1868. vaIdent: OutLn(ReadSStr);
  1869. vaFalse: OutLn('False');
  1870. vaTrue: OutLn('True');
  1871. vaBinary: ProcessBinary;
  1872. vaSet: begin
  1873. OutStr('[');
  1874. IsFirst := True;
  1875. while True do begin
  1876. s := ReadSStr;
  1877. if Length(s) = 0 then break;
  1878. if not IsFirst then OutStr(', ');
  1879. IsFirst := False;
  1880. OutStr(s);
  1881. end;
  1882. OutLn(']');
  1883. end;
  1884. vaLString:
  1885. begin
  1886. OutString(ReadLStr);
  1887. OutLn('');
  1888. end;
  1889. vaWString:
  1890. begin
  1891. OutWString(ReadWStr);
  1892. OutLn('');
  1893. end;
  1894. vaUString:
  1895. begin
  1896. OutWString(ReadWStr);
  1897. OutLn('');
  1898. end;
  1899. vaNil:
  1900. OutLn('nil');
  1901. vaCollection: begin
  1902. OutStr('<');
  1903. while Input.ReadByte <> 0 do begin
  1904. OutLn(Indent);
  1905. Input.Seek(-1, soFromCurrent);
  1906. OutStr(indent + ' item');
  1907. ValueType := TValueType(Input.ReadByte);
  1908. if ValueType <> vaList then
  1909. OutStr('[' + IntToStr(ReadInt(ValueType)) + ']');
  1910. OutLn('');
  1911. ReadPropList(indent + ' ');
  1912. OutStr(indent + ' end');
  1913. end;
  1914. OutLn('>');
  1915. end;
  1916. {vaSingle: begin OutLn('!!Single!!'); exit end;
  1917. vaCurrency: begin OutLn('!!Currency!!'); exit end;
  1918. vaDate: begin OutLn('!!Date!!'); exit end;}
  1919. vaUTF8String: begin
  1920. OutUtf8Str(ReadLStr);
  1921. OutLn('');
  1922. end;
  1923. else
  1924. Raise EReadError.CreateFmt(SErrInvalidPropertyType,[Ord(ValueType)]);
  1925. end;
  1926. end;
  1927. begin
  1928. while Input.ReadByte <> 0 do begin
  1929. Input.Seek(-1, soFromCurrent);
  1930. OutStr(indent + ReadSStr + ' = ');
  1931. ProcessValue(TValueType(Input.ReadByte), Indent);
  1932. end;
  1933. end;
  1934. procedure ReadObject(indent: RawByteString);
  1935. var
  1936. b: Byte;
  1937. ObjUnitName, ObjClassName, ObjName: RawByteString;
  1938. ChildPos: LongInt;
  1939. ValueType: TValueType;
  1940. p: SizeInt;
  1941. begin
  1942. // Check for FilerFlags
  1943. b := Input.ReadByte;
  1944. if (b and $f0) = $f0 then begin
  1945. if (b and 2) <> 0 then ChildPos := ReadInt;
  1946. end else begin
  1947. b := 0;
  1948. Input.Seek(-1, soFromCurrent);
  1949. end;
  1950. ObjUnitName:='';
  1951. if Version=TBinaryObjectReader.TBOVersion.boVersion1 then
  1952. begin
  1953. ValueType := TValueType(Input.ReadByte);
  1954. if ValueType=vaString then
  1955. ObjClassName := ReadSStr
  1956. else
  1957. ObjClassName := ReadLStr;
  1958. p:=Pos(TBinaryObjectReader.UnitnameSeparator,ObjClassName);
  1959. if p>0 then
  1960. begin
  1961. ObjUnitName:=copy(ObjClassName,1,p-1);
  1962. System.Delete(ObjClassName,1,p);
  1963. end;
  1964. end else
  1965. ObjClassName := ReadSStr;
  1966. ObjName := ReadSStr;
  1967. OutStr(Indent);
  1968. if (b and 1) <> 0 then
  1969. OutStr('inherited')
  1970. else if (b and 4) <> 0 then
  1971. OutStr('inline')
  1972. else
  1973. OutStr('object');
  1974. OutStr(' ');
  1975. if ObjName <> '' then
  1976. OutStr(ObjName + ': ');
  1977. if Version=TBinaryObjectReader.TBOVersion.boVersion1 then
  1978. begin
  1979. OutStr(ObjUnitName);
  1980. OutStr('/');
  1981. end;
  1982. OutStr(ObjClassName);
  1983. if (b and 2) <> 0 then
  1984. OutStr('[' + IntToStr(ChildPos) + ']');
  1985. OutLn('');
  1986. ReadPropList(indent + ' ');
  1987. while Input.ReadByte <> 0 do begin
  1988. Input.Seek(-1, soFromCurrent);
  1989. ReadObject(indent + ' ');
  1990. end;
  1991. OutLn(indent + 'end');
  1992. end;
  1993. var
  1994. Signature: DWord;
  1995. begin
  1996. Signature:=Input.ReadDWord;
  1997. if Signature = DWord(unaligned(FilerSignature1)) then
  1998. Version:=TBinaryObjectReader.TBOVersion.boVersion1
  1999. else if Signature = DWord(unaligned(FilerSignature)) then
  2000. Version:=TBinaryObjectReader.TBOVersion.boVersion0
  2001. else
  2002. raise EReadError.Create('Illegal stream image' {###SInvalidImage});
  2003. ReadObject('');
  2004. end;
  2005. procedure ObjectBinaryToText(Input, Output: TStream);
  2006. begin
  2007. ObjectBinaryToText(Input,Output,oteDFM);
  2008. end;
  2009. procedure ObjectTextToBinary(Input, Output: TStream);
  2010. var
  2011. Fmt : TStreamOriginalFormat;
  2012. begin
  2013. ObjectTextToBinary(Input,Output,Fmt);
  2014. end;
  2015. procedure ObjectTextToBinary(Input, Output: TStream; var Format: TStreamOriginalFormat);
  2016. var
  2017. parser: TParser;
  2018. Version: TBinaryObjectReader.TBOVersion;
  2019. StartPos: Int64;
  2020. procedure WriteWord(w : word); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  2021. begin
  2022. w:=NtoLE(w);
  2023. Output.WriteWord(w);
  2024. end;
  2025. procedure WriteDWord(lw : longword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  2026. begin
  2027. lw:=NtoLE(lw);
  2028. Output.WriteDWord(lw);
  2029. end;
  2030. procedure WriteQWord(qw : qword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
  2031. begin
  2032. qw:=NtoLE(qw);
  2033. Output.WriteBuffer(qw,sizeof(qword));
  2034. end;
  2035. {$ifndef FPUNONE}
  2036. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  2037. procedure DoubleToExtended(d : double; e : pointer);
  2038. var mant : qword;
  2039. exp : smallint;
  2040. sign : boolean;
  2041. begin
  2042. mant:=(qword(d) and $000FFFFFFFFFFFFF) shl 12;
  2043. exp :=(qword(d) shr 52) and $7FF;
  2044. sign:=(qword(d) and $8000000000000000)<>0;
  2045. case exp of
  2046. 0 : begin
  2047. if mant<>0 then //denormalized value: hidden bit is 0. normalize it
  2048. begin
  2049. exp:=16383-1022;
  2050. while (mant and $8000000000000000)=0 do
  2051. begin
  2052. dec(exp);
  2053. mant:=mant shl 1;
  2054. end;
  2055. dec(exp); //don't shift, most significant bit is not hidden in extended
  2056. end;
  2057. end;
  2058. 2047 : exp:=$7FFF //either infinity or NaN
  2059. else
  2060. begin
  2061. inc(exp,16383-1023);
  2062. mant:=(mant shr 1) or $8000000000000000; //unhide hidden bit
  2063. end;
  2064. end;
  2065. if sign then exp:=exp or $8000;
  2066. mant:=NtoLE(mant);
  2067. exp:=NtoLE(word(exp));
  2068. move(mant,pbyte(e)[0],8); //mantissa : bytes 0..7
  2069. move(exp,pbyte(e)[8],2); //exponent and sign: bytes 8..9
  2070. end;
  2071. {$ENDIF}
  2072. procedure WriteExtended(const e : extended);
  2073. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  2074. var ext : array[0..9] of byte;
  2075. {$ENDIF}
  2076. begin
  2077. {$IFNDEF FPC_HAS_TYPE_EXTENDED}
  2078. DoubleToExtended(e,@(ext[0]));
  2079. Output.WriteBuffer(ext[0],10);
  2080. {$ELSE}
  2081. Output.WriteBuffer(e,sizeof(e));
  2082. {$ENDIF}
  2083. end;
  2084. {$endif}
  2085. procedure WriteSString(const s: RawByteString);
  2086. var size : byte;
  2087. begin
  2088. if length(s)>255 then size:=255
  2089. else size:=length(s);
  2090. Output.WriteByte(size);
  2091. if Length(s) > 0 then
  2092. Output.WriteBuffer(s[1], size);
  2093. end;
  2094. procedure WriteLString(Const s: RawByteString);
  2095. begin
  2096. WriteDWord(Length(s));
  2097. if Length(s) > 0 then
  2098. Output.WriteBuffer(s[1], Length(s));
  2099. end;
  2100. procedure WriteSorLString(Const s: String);
  2101. begin
  2102. if length(s)<256 then
  2103. begin
  2104. Output.WriteByte(Ord(vaString));
  2105. WriteSString(s);
  2106. end else begin
  2107. Output.WriteByte(Ord(vaLString));
  2108. WriteSString(s);
  2109. end;
  2110. end;
  2111. procedure WriteWString(Const s: WideString);
  2112. var len : longword;
  2113. {$IFDEF ENDIAN_BIG}
  2114. i : integer;
  2115. ws : widestring;
  2116. {$ENDIF}
  2117. begin
  2118. len:=Length(s);
  2119. WriteDWord(len);
  2120. if len > 0 then
  2121. begin
  2122. {$IFDEF ENDIAN_BIG}
  2123. setlength(ws,len);
  2124. for i:=1 to len do
  2125. ws[i]:=widechar(SwapEndian(word(s[i])));
  2126. Output.WriteBuffer(ws[1], len*sizeof(widechar));
  2127. {$ELSE}
  2128. Output.WriteBuffer(s[1], len*sizeof(widechar));
  2129. {$ENDIF}
  2130. end;
  2131. end;
  2132. procedure WriteInteger(value: Int64);
  2133. begin
  2134. if (value >= -128) and (value <= 127) then begin
  2135. Output.WriteByte(Ord(vaInt8));
  2136. Output.WriteByte(byte(value));
  2137. end else if (value >= -32768) and (value <= 32767) then begin
  2138. Output.WriteByte(Ord(vaInt16));
  2139. WriteWord(word(value));
  2140. end else if (value >= -2147483648) and (value <= 2147483647) then begin
  2141. Output.WriteByte(Ord(vaInt32));
  2142. WriteDWord(longword(value));
  2143. end else begin
  2144. Output.WriteByte(ord(vaInt64));
  2145. WriteQWord(qword(value));
  2146. end;
  2147. end;
  2148. procedure ProcessWideString(const left : widestring);
  2149. var ws : widestring;
  2150. begin
  2151. ws:=left+parser.TokenWideString;
  2152. while parser.NextToken = '+' do
  2153. begin
  2154. parser.NextToken; // Get next string fragment
  2155. if not (parser.Token in [toString,toWString]) then
  2156. parser.CheckToken(toWString);
  2157. ws:=ws+parser.TokenWideString;
  2158. end;
  2159. Output.WriteByte(Ord(vaWstring));
  2160. WriteWString(ws);
  2161. end;
  2162. procedure ProcessProperty; forward;
  2163. procedure ProcessValue;
  2164. var
  2165. {$ifndef FPUNONE}
  2166. flt: Extended;
  2167. {$endif}
  2168. s: RawByteString;
  2169. stream: TMemoryStream;
  2170. begin
  2171. case parser.Token of
  2172. toInteger:
  2173. begin
  2174. WriteInteger(parser.TokenInt);
  2175. parser.NextToken;
  2176. end;
  2177. {$ifndef FPUNONE}
  2178. toFloat:
  2179. begin
  2180. Output.WriteByte(Ord(vaExtended));
  2181. flt := Parser.TokenFloat;
  2182. WriteExtended(flt);
  2183. parser.NextToken;
  2184. end;
  2185. {$endif}
  2186. toString:
  2187. begin
  2188. s := parser.TokenString;
  2189. while parser.NextToken = '+' do
  2190. begin
  2191. parser.NextToken; // Get next string fragment
  2192. case parser.Token of
  2193. toString : s:=s+parser.TokenString;
  2194. toWString : begin
  2195. ProcessWideString(WideString(s));
  2196. exit;
  2197. end
  2198. else parser.CheckToken(toString);
  2199. end;
  2200. end;
  2201. if (length(S)>255) then
  2202. begin
  2203. Output.WriteByte(Ord(vaLString));
  2204. WriteLString(S);
  2205. end
  2206. else
  2207. begin
  2208. Output.WriteByte(Ord(vaString));
  2209. WriteSString(s);
  2210. end;
  2211. end;
  2212. toWString:
  2213. ProcessWideString('');
  2214. toSymbol:
  2215. begin
  2216. if CompareText(parser.TokenString, 'True') = 0 then
  2217. Output.WriteByte(Ord(vaTrue))
  2218. else if CompareText(parser.TokenString, 'False') = 0 then
  2219. Output.WriteByte(Ord(vaFalse))
  2220. else if CompareText(parser.TokenString, 'nil') = 0 then
  2221. Output.WriteByte(Ord(vaNil))
  2222. else
  2223. begin
  2224. Output.WriteByte(Ord(vaIdent));
  2225. WriteSString(parser.TokenComponentIdent);
  2226. end;
  2227. Parser.NextToken;
  2228. end;
  2229. // Set
  2230. '[':
  2231. begin
  2232. parser.NextToken;
  2233. Output.WriteByte(Ord(vaSet));
  2234. if parser.Token <> ']' then
  2235. while True do
  2236. begin
  2237. parser.CheckToken(toSymbol);
  2238. WriteSString(parser.TokenString);
  2239. parser.NextToken;
  2240. if parser.Token = ']' then
  2241. break;
  2242. parser.CheckToken(',');
  2243. parser.NextToken;
  2244. end;
  2245. Output.WriteByte(0);
  2246. parser.NextToken;
  2247. end;
  2248. // List
  2249. '(':
  2250. begin
  2251. parser.NextToken;
  2252. Output.WriteByte(Ord(vaList));
  2253. while parser.Token <> ')' do
  2254. ProcessValue;
  2255. Output.WriteByte(0);
  2256. parser.NextToken;
  2257. end;
  2258. // Collection
  2259. '<':
  2260. begin
  2261. parser.NextToken;
  2262. Output.WriteByte(Ord(vaCollection));
  2263. while parser.Token <> '>' do
  2264. begin
  2265. parser.CheckTokenSymbol('item');
  2266. parser.NextToken;
  2267. // ConvertOrder
  2268. Output.WriteByte(Ord(vaList));
  2269. while not parser.TokenSymbolIs('end') do
  2270. ProcessProperty;
  2271. parser.NextToken; // Skip 'end'
  2272. Output.WriteByte(0);
  2273. end;
  2274. Output.WriteByte(0);
  2275. parser.NextToken;
  2276. end;
  2277. // Binary data
  2278. '{':
  2279. begin
  2280. Output.WriteByte(Ord(vaBinary));
  2281. stream := TMemoryStream.Create;
  2282. try
  2283. parser.HexToBinary(stream);
  2284. WriteDWord(stream.Size);
  2285. Output.WriteBuffer(Stream.Memory^, stream.Size);
  2286. finally
  2287. stream.Free;
  2288. end;
  2289. parser.NextToken;
  2290. end;
  2291. else
  2292. parser.Error(SInvalidProperty);
  2293. end;
  2294. end;
  2295. procedure ProcessProperty;
  2296. var
  2297. name: RawByteString;
  2298. begin
  2299. // Get name of property
  2300. parser.CheckToken(toSymbol);
  2301. name := parser.TokenString;
  2302. while True do begin
  2303. parser.NextToken;
  2304. if parser.Token <> '.' then break;
  2305. parser.NextToken;
  2306. parser.CheckToken(toSymbol);
  2307. name := name + '.' + parser.TokenString;
  2308. end;
  2309. WriteSString(name);
  2310. parser.CheckToken('=');
  2311. parser.NextToken;
  2312. ProcessValue;
  2313. end;
  2314. procedure ProcessObject(Root: boolean);
  2315. var
  2316. Flags: Byte;
  2317. ObjectName, ObjUnitName, ObjClassName: RawByteString;
  2318. ChildPos: Integer;
  2319. begin
  2320. if parser.TokenSymbolIs('OBJECT') then
  2321. Flags :=0 { IsInherited := False }
  2322. else begin
  2323. if parser.TokenSymbolIs('INHERITED') then
  2324. Flags := 1 { IsInherited := True; }
  2325. else begin
  2326. parser.CheckTokenSymbol('INLINE');
  2327. Flags := 4;
  2328. end;
  2329. end;
  2330. parser.NextToken;
  2331. parser.CheckToken(toSymbol);
  2332. ObjectName := '';
  2333. ObjUnitName := '';
  2334. ObjClassName := parser.TokenString;
  2335. parser.NextToken;
  2336. if parser.Token = '/' then begin
  2337. ObjUnitName := ObjClassName;
  2338. parser.NextToken;
  2339. parser.CheckToken(toSymbol);
  2340. ObjClassName := parser.TokenString;
  2341. parser.NextToken;
  2342. end else if parser.Token = ':' then begin
  2343. parser.NextToken;
  2344. parser.CheckToken(toSymbol);
  2345. ObjectName := ObjClassName;
  2346. ObjClassName := parser.TokenString;
  2347. parser.NextToken;
  2348. if parser.Token = '/' then begin
  2349. ObjUnitName := ObjClassName;
  2350. parser.NextToken;
  2351. parser.CheckToken(toSymbol);
  2352. ObjClassName := parser.TokenString;
  2353. parser.NextToken;
  2354. end;
  2355. if parser.Token = '[' then begin
  2356. parser.NextToken;
  2357. ChildPos := parser.TokenInt;
  2358. parser.NextToken;
  2359. parser.CheckToken(']');
  2360. parser.NextToken;
  2361. Flags := Flags or 2;
  2362. end;
  2363. end;
  2364. if Root then
  2365. begin
  2366. if (ObjUnitName<>'') then
  2367. Version:=TBinaryObjectReader.TBOVersion.boVersion1;
  2368. if Version=TBinaryObjectReader.TBOVersion.boVersion1 then
  2369. Output.WriteBuffer(FilerSignature1[1], length(FilerSignature1))
  2370. else
  2371. Output.WriteBuffer(FilerSignature[1], length(FilerSignature));
  2372. end;
  2373. if Flags <> 0 then begin
  2374. Output.WriteByte($f0 or Flags);
  2375. if (Flags and 2) <> 0 then
  2376. WriteInteger(ChildPos);
  2377. end;
  2378. if Version=TBinaryObjectReader.TBOVersion.boVersion1 then
  2379. WriteSorLString(ObjUnitName+TBinaryObjectReader.UnitnameSeparator+ObjClassName)
  2380. else
  2381. WriteSString(ObjClassName);
  2382. WriteSString(ObjectName);
  2383. // Convert property list
  2384. while not (parser.TokenSymbolIs('END') or
  2385. parser.TokenSymbolIs('OBJECT') or
  2386. parser.TokenSymbolIs('INHERITED') or
  2387. parser.TokenSymbolIs('INLINE')) do
  2388. ProcessProperty;
  2389. Output.WriteByte(0); // Terminate property list
  2390. // Convert child objects
  2391. while not parser.TokenSymbolIs('END') do ProcessObject(false);
  2392. parser.NextToken; // Skip end token
  2393. Output.WriteByte(0); // Terminate property list
  2394. end;
  2395. const
  2396. signature: PAnsiChar = 'TPF0';
  2397. begin
  2398. Version:=TBinaryObjectReader.TBOVersion.boVersion0;
  2399. parser := TParser.Create(Input);
  2400. try
  2401. StartPos:=Output.Position;
  2402. ProcessObject(true);
  2403. finally
  2404. parser.Free;
  2405. end;
  2406. end;
  2407. procedure ObjectResourceToText(Input, Output: TStream);
  2408. begin
  2409. Input.ReadResHeader;
  2410. ObjectBinaryToText(Input, Output);
  2411. end;
  2412. procedure ObjectTextToResource(Input, Output: TStream);
  2413. var
  2414. StartPos, FixupInfo: LongInt;
  2415. parser: TParser;
  2416. name: String;
  2417. begin
  2418. // Get form type name
  2419. StartPos := Input.Position;
  2420. parser := TParser.Create(Input);
  2421. try
  2422. if not parser.TokenSymbolIs('OBJECT') then parser.CheckTokenSymbol('INHERITED');
  2423. parser.NextToken;
  2424. parser.CheckToken(toSymbol);
  2425. parser.NextToken;
  2426. parser.CheckToken(':');
  2427. parser.NextToken;
  2428. parser.CheckToken(toSymbol);
  2429. name := parser.TokenString;
  2430. finally
  2431. parser.Free;
  2432. Input.Position := StartPos;
  2433. end;
  2434. name := UpperCase(name);
  2435. Output.WriteResourceHeader(name,FixupInfo); // Write resource header
  2436. ObjectTextToBinary(Input, Output); // Convert the stuff!
  2437. Output.FixupResourceHeader(FixupInfo); // Insert real resource data size
  2438. end;
  2439. function TestStreamFormat(const Stream: TStream): TStreamOriginalFormat;
  2440. const
  2441. StartChars = [#9, #10, #13, #11, 'o', 'O','i','I',' '];
  2442. var
  2443. aPos: Int64;
  2444. Sig: Packed Array[0..3] of byte;
  2445. IntSig : Longint absolute sig;
  2446. begin
  2447. Result:=sofUnknown;
  2448. aPos:=Stream.Position;
  2449. IntSig:=0;
  2450. Stream.Read(Sig,SizeOf(Sig));
  2451. Stream.Seek(aPos,soBeginning);
  2452. if (Sig[0]=$FF) or (IntSig=LongInt(FilerSignature)) or (IntSig=LongInt(FilerSignature1)) or (IntSig=0) then
  2453. Result:=sofBinary
  2454. else if (AnsiChar(Sig[0]) in StartChars) then
  2455. Result:=sofText
  2456. else if (Sig[0]=$EF) and (Sig[1]=$BB) and (Sig[2]=$BF) then
  2457. Result:=sofUTF8Text;
  2458. end;
  2459. { Utility routines }
  2460. Function IfThen(AValue: Boolean; const ATrue: TStringList; const AFalse: TStringList = nil): TStringList; overload;
  2461. begin
  2462. if avalue then
  2463. result:=atrue
  2464. else
  2465. result:=afalse;
  2466. end;
  2467. function LineStart(Buffer, BufPos: PAnsiChar): PAnsiChar;
  2468. begin
  2469. Result := BufPos;
  2470. while Result > Buffer do begin
  2471. Dec(Result);
  2472. if Result[0] = #10 then break;
  2473. end;
  2474. end;
  2475. procedure CommonInit;
  2476. begin
  2477. {$ifdef FPC_HAS_FEATURE_THREADING}
  2478. SynchronizeTimeoutEvent:=RtlEventCreate;
  2479. InterlockedIncrement(ThreadQueueLockCounter);
  2480. InitCriticalSection(ThreadQueueLock);
  2481. MainThreadID:=GetCurrentThreadID;
  2482. {$else}
  2483. MainThreadID:=0{GetCurrentThreadID};
  2484. {$endif}
  2485. ExternalThreads := TThreadList.Create;
  2486. {$ifdef FPC_HAS_FEATURE_THREADING}
  2487. InitCriticalsection(ResolveSection);
  2488. TThread.FProcessorCount := CPUCount;
  2489. {$else}
  2490. TThread.FProcessorCount := 1{CPUCount};
  2491. {$endif}
  2492. InitHandlerList:=Nil;
  2493. FindGlobalComponentList:=nil;
  2494. IntConstList := TThreadList.Create;
  2495. ClassList := TThreadList.Create;
  2496. ClassAliasList := nil;
  2497. { on unix this maps to a simple rw synchornizer }
  2498. GlobalNameSpace := TMultiReadExclusiveWriteSynchronizer.Create;
  2499. RegisterInitComponentHandler(TComponent,@DefaultInitHandler);
  2500. end;
  2501. procedure CommonCleanup;
  2502. var
  2503. i: Integer;
  2504. tmpentry: TThread.PThreadQueueEntry;
  2505. begin
  2506. {$ifdef FPC_HAS_FEATURE_THREADING}
  2507. GlobalNameSpace.BeginWrite;
  2508. {$endif}
  2509. with IntConstList.LockList do
  2510. try
  2511. for i := 0 to Count - 1 do
  2512. TIntConst(Items[I]).Free;
  2513. finally
  2514. IntConstList.UnlockList;
  2515. end;
  2516. IntConstList.Free;
  2517. ClassList.Free;
  2518. ClassAliasList.Free;
  2519. RemoveFixupReferences(nil, '');
  2520. {$ifdef FPC_HAS_FEATURE_THREADING}
  2521. DoneCriticalsection(ResolveSection);
  2522. {$endif}
  2523. GlobalLists.Free;
  2524. ComponentPages.Free;
  2525. FreeAndNil(NeedResolving);
  2526. {$ifdef FPC_HAS_FEATURE_THREADING}
  2527. GlobalNameSpace.EndWrite;
  2528. {$endif}
  2529. { GlobalNameSpace is an interface so this is enough }
  2530. GlobalNameSpace:=nil;
  2531. if (InitHandlerList<>Nil) then
  2532. for i := 0 to InitHandlerList.Count - 1 do
  2533. TInitHandler(InitHandlerList.Items[I]).Free;
  2534. InitHandlerList.Free;
  2535. InitHandlerList:=Nil;
  2536. FindGlobalComponentList.Free;
  2537. FindGlobalComponentList:=nil;
  2538. ExternalThreadsCleanup:=True;
  2539. with ExternalThreads.LockList do
  2540. try
  2541. for i := 0 to Count - 1 do
  2542. TThread(Items[i]).Free;
  2543. finally
  2544. ExternalThreads.UnlockList;
  2545. end;
  2546. FreeAndNil(ExternalThreads);
  2547. {$ifdef FPC_HAS_FEATURE_THREADING}
  2548. RtlEventDestroy(SynchronizeTimeoutEvent);
  2549. try
  2550. System.EnterCriticalSection(ThreadQueueLock);
  2551. {$endif}
  2552. { clean up the queue, but keep in mind that the entries used for Synchronize
  2553. are owned by the corresponding TThread }
  2554. while Assigned(ThreadQueueHead) do begin
  2555. tmpentry := ThreadQueueHead;
  2556. ThreadQueueHead := tmpentry^.Next;
  2557. if not Assigned(tmpentry^.SyncEvent) then
  2558. Dispose(tmpentry);
  2559. end;
  2560. { We also need to reset ThreadQueueTail }
  2561. ThreadQueueTail := nil;
  2562. {$ifdef FPC_HAS_FEATURE_THREADING}
  2563. finally
  2564. System.LeaveCriticalSection(ThreadQueueLock);
  2565. end;
  2566. if InterlockedDecrement(ThreadQueueLockCounter)=0 then
  2567. DoneCriticalSection(ThreadQueueLock);
  2568. {$endif}
  2569. end;
  2570. { TFiler implementation }
  2571. {$i filer.inc}
  2572. { TReader implementation }
  2573. {$i reader.inc}
  2574. { TWriter implementations }
  2575. {$i writer.inc}
  2576. {$i twriter.inc}
  2577. constructor ComponentPlatformsAttribute.Create(const aPlatforms: TPlatformIds);
  2578. begin
  2579. FPlatForms:=aPlatForms;
  2580. end;