classes.inc 74 KB

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