writer.pas 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246
  1. {
  2. pas2jni - JNI bridge generator for Pascal.
  3. Copyright (c) 2013 by Yury Sidorov.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************}
  16. unit writer;
  17. {$mode objfpc}{$H+}
  18. interface
  19. //{$define DEBUG}
  20. {$ifdef DEBUG}
  21. {$ASSERTIONS ON}
  22. {$endif}
  23. uses
  24. Classes, SysUtils, def, contnrs, PPUParser;
  25. const
  26. MaxMethodPointers = 10000;
  27. type
  28. { TTextOutStream }
  29. TTextOutStream = class(TFileStream)
  30. private
  31. FIndent: integer;
  32. FIndStr: string;
  33. procedure SetIndednt(const AValue: integer);
  34. public
  35. procedure Write(const s: ansistring); overload;
  36. procedure WriteLn(const s: ansistring = ''; ExtraIndent: integer = 0);
  37. procedure IncI;
  38. procedure DecI;
  39. property Indent: integer read FIndent write SetIndednt;
  40. property SIndent: string read FIndStr;
  41. end;
  42. { TWriter }
  43. TWriter = class
  44. private
  45. Fjs, Fps: TTextOutStream;
  46. FClasses: TStringList;
  47. FPkgDir: string;
  48. FUniqueCnt: integer;
  49. FThisUnit: TUnitDef;
  50. function DoCheckItem(const ItemName: string): TCheckItemResult;
  51. procedure ProcessRules(d: TDef; const Prefix: string = '');
  52. function GetUniqueNum: integer;
  53. function DefToJniType(d: TDef; var err: boolean): string;
  54. function DefToJniSig(d: TDef): string;
  55. function DefToJavaType(d: TDef): string;
  56. function GetJavaClassPath(d: TDef; const AClassName: string = ''): string;
  57. function JniToPasType(d: TDef; const v: string; CheckNil: boolean): string;
  58. function PasToJniType(d: TDef; const v: string): string;
  59. function GetTypeInfoVar(ClassDef: TDef): string;
  60. function GetClassPrefix(ClassDef: TDef; const AClassName: string = ''): string;
  61. function IsJavaSimpleType(d: TDef): boolean;
  62. function IsJavaVarParam(ParamDef: TVarDef): boolean;
  63. function GetProcDeclaration(d: TProcDef; const ProcName: string = ''; FullTypeNames: boolean = False): string;
  64. function GetJavaProcDeclaration(d: TProcDef; const ProcName: string = ''): string;
  65. function GetJniFuncType(d: TDef): string;
  66. function GetJavaClassName(cls: TDef; it: TDef): string;
  67. procedure RegisterPseudoClass(d: TDef);
  68. function GetPasIntType(Size: integer): string;
  69. function GetPasType(d: TDef; FullName: boolean): string;
  70. // procedure AddCustomProc(ParentDef: TDef; const JniName, Name: string; RetType: TBasicType; const Params: array of TBasicType);
  71. function AddCustomProc(ParentDef: TDef; const JniName, Name: string; RetType: TBasicType; const Params: array of TBasicType): TProcDef;
  72. procedure AddNativeMethod(ParentDef: TDef; const JniName, Name, Signature: string);
  73. function GetProcSignature(d: TProcDef): string;
  74. procedure EHandlerStart;
  75. procedure EHandlerEnd(const EnvVarName: string; const ExtraCode: string = '');
  76. procedure WriteClassInfoVar(d: TDef);
  77. procedure WriteComment(d: TDef; const AType: string);
  78. procedure WriteClass(d: TDef; PreInfo: boolean);
  79. procedure WriteProc(d: TProcDef; Variable: TVarDef = nil; AParent: TDef = nil);
  80. procedure WriteVar(d: TVarDef; AParent: TDef = nil);
  81. procedure WriteConst(d: TConstDef);
  82. procedure WriteEnum(d: TDef);
  83. procedure WriteProcType(d: TProcDef; PreInfo: boolean);
  84. procedure WriteSet(d: TSetDef);
  85. procedure WriteUnit(u: TUnitDef);
  86. procedure WriteOnLoad;
  87. public
  88. SearchPath: string;
  89. LibName: string;
  90. JavaPackage: string;
  91. Units: TStringList;
  92. OutPath: string;
  93. JavaOutPath: string;
  94. IncludeList: TStringList;
  95. ExcludeList: TStringList;
  96. constructor Create;
  97. destructor Destroy; override;
  98. procedure ProcessUnits;
  99. end;
  100. implementation
  101. const
  102. JNIType: array[TBasicType] of string =
  103. ('', 'jshort', 'jbyte', 'jint', 'jshort', 'jlong', 'jint', 'jlong', 'jfloat', 'jdouble', 'jstring',
  104. 'jstring', 'jboolean', 'jchar', 'jchar', 'jint', 'jlong', 'jstring');
  105. JNITypeSig: array[TBasicType] of string =
  106. ('V', 'S', 'B', 'I', 'S', 'J', 'I', 'J', 'F', 'D', 'Ljava/lang/String;', 'Ljava/lang/String;',
  107. 'Z', 'C', 'C', 'I', 'J', 'Ljava/lang/String;');
  108. JavaType: array[TBasicType] of string =
  109. ('void', 'short', 'byte', 'int', 'short', 'long', 'int', 'long', 'float', 'double', 'String',
  110. 'String', 'boolean', 'char', 'char', 'int', 'long', 'String');
  111. TextIndent = 2;
  112. ExcludeStd: array[1..44] of string = (
  113. 'classes.TStream.ReadComponent', 'classes.TStream.ReadComponentRes', 'classes.TStream.WriteComponent', 'classes.TStream.WriteComponentRes',
  114. 'classes.TStream.WriteDescendent', 'classes.TStream.WriteDescendentRes', 'classes.TStream.WriteResourceHeader', 'classes.TStream.FixupResourceHeader',
  115. 'classes.TStream.ReadResHeader', 'classes.TComponent.WriteState', 'classes.TComponent.ExecuteAction', 'classes.TComponent.UpdateAction',
  116. 'classes.TComponent.GetEnumerator', 'classes.TComponent.VCLComObject', 'classes.TComponent.DesignInfo', 'classes.TComponent.Destroying',
  117. 'classes.TComponent.FreeNotification', 'classes.TComponent.RemoveFreeNotification', 'classes.TComponent.FreeOnRelease', 'classes.TComponent.SetSubComponent',
  118. 'system.TObject.newinstance', 'system.TObject.FreeInstance', 'system.TObject.SafeCallException', 'system.TObject.InitInstance',
  119. 'system.TObject.CleanupInstance', 'system.TObject.ClassInfo', 'system.TObject.AfterConstruction', 'system.TObject.BeforeDestruction',
  120. 'system.TObject.GetInterfaceEntry', 'system.TObject.GetInterfaceTable', 'system.TObject.MethodAddress', 'system.TObject.MethodName',
  121. 'system.TObject.FieldAddress', 'classes.TComponent.ComponentState', 'classes.TComponent.ComponentStyle', 'classes.TList.GetEnumerator',
  122. 'classes.TList.List', 'classes.TList.FPOAttachObserver', 'classes.TList.FPODetachObserver', 'classes.TList.FPONotifyObservers',
  123. 'classes.TPersistent.FPOAttachObserver', 'classes.TPersistent.FPODetachObserver', 'classes.TPersistent.FPONotifyObservers',
  124. 'system.fma'
  125. );
  126. ExcludeDelphi7: array[1..25] of string = (
  127. 'system.TObject.StringMessageTable', 'system.TObject.GetInterfaceEntryByStr', 'system.TObject.UnitName', 'system.TObject.Equals',
  128. 'system.TObject.GetHashCode', 'system.TObject.ToString','classes.TStream.ReadByte', 'classes.TStream.ReadWord',
  129. 'classes.TStream.ReadDWord', 'classes.TStream.ReadQWord', 'classes.TStream.ReadAnsiString', 'classes.TStream.WriteByte',
  130. 'classes.TStream.WriteWord', 'classes.TStream.WriteDWord', 'classes.TStream.WriteQWord', 'classes.TStream.WriteAnsiString',
  131. 'classes.TCollection.Exchange', 'classes.TStrings.Equals', 'classes.TStrings.GetNameValue', 'classes.TStrings.ExtractName',
  132. 'classes.TStrings.TextLineBreakStyle', 'classes.TStrings.StrictDelimiter', 'classes.TStrings.GetEnumerator', 'classes.TStringList.OwnsObjects',
  133. 'classes.TList.AddList'
  134. );
  135. SUnsupportedType = '<unsupported type>';
  136. function JniCaliing: string;
  137. begin
  138. Result:='{$ifdef windows} stdcall {$else} cdecl {$endif};';
  139. end;
  140. { TTextOutStream }
  141. procedure TTextOutStream.SetIndednt(const AValue: integer);
  142. begin
  143. if FIndent = AValue then exit;
  144. FIndent:=AValue;
  145. SetLength(FIndStr, FIndent*TextIndent);
  146. if FIndent > 0 then
  147. FillChar(FIndStr[1], FIndent*TextIndent, ' ');
  148. end;
  149. procedure TTextOutStream.Write(const s: ansistring);
  150. begin
  151. WriteBuffer(PChar(s)^, Length(s));
  152. end;
  153. procedure TTextOutStream.WriteLn(const s: ansistring; ExtraIndent: integer);
  154. begin
  155. if s = '' then
  156. Write(LineEnding)
  157. else begin
  158. Indent:=Indent + ExtraIndent;
  159. try
  160. Write(FIndStr + s + LineEnding);
  161. finally
  162. Indent:=Indent - ExtraIndent;
  163. end;
  164. end;
  165. end;
  166. procedure TTextOutStream.IncI;
  167. begin
  168. Indent:=Indent + 1;
  169. end;
  170. procedure TTextOutStream.DecI;
  171. begin
  172. if Indent > 0 then
  173. Indent:=Indent - 1;
  174. end;
  175. type
  176. { TClassInfo }
  177. TClassInfo = class
  178. public
  179. Def: TDef;
  180. Funcs: TObjectList;
  181. IsCommonClass: boolean;
  182. constructor Create;
  183. destructor Destroy; override;
  184. end;
  185. TProcInfo = class
  186. public
  187. Name: string;
  188. JniName: string;
  189. JniSignature: string;
  190. end;
  191. { TClassInfo }
  192. constructor TClassInfo.Create;
  193. begin
  194. Funcs:=TObjectList.Create(True);
  195. end;
  196. destructor TClassInfo.Destroy;
  197. begin
  198. Funcs.Free;
  199. inherited Destroy;
  200. end;
  201. { TWriter }
  202. function TWriter.DefToJniType(d: TDef; var err: boolean): string;
  203. begin
  204. if d = nil then begin
  205. Result:=SUnsupportedType;
  206. err:=True;
  207. end
  208. else begin
  209. if not d.IsUsed then begin
  210. Result:='<excluded type> ' + d.Name;
  211. err:=True;
  212. end
  213. else
  214. case d.DefType of
  215. dtType:
  216. Result:=JNIType[TTypeDef(d).BasicType];
  217. dtClass, dtRecord, dtEnum:
  218. Result:='jobject';
  219. dtProcType:
  220. if poMethodPtr in TProcDef(d).ProcOpt then
  221. Result:='jobject'
  222. else begin
  223. Result:=SUnsupportedType + ' ' + d.Name;
  224. err:=True;
  225. end;
  226. dtSet:
  227. if TSetDef(d).Size <= 4 then
  228. Result:='jobject'
  229. else begin
  230. Result:=SUnsupportedType + ' ' + d.Name;
  231. err:=True;
  232. end;
  233. else begin
  234. Result:=SUnsupportedType + ' ' + d.Name;
  235. err:=True;
  236. d.SetNotUsed;
  237. end;
  238. end;
  239. end;
  240. end;
  241. function TWriter.DoCheckItem(const ItemName: string): TCheckItemResult;
  242. begin
  243. if IncludeList.IndexOf(ItemName) >= 0 then
  244. Result:=crInclude
  245. else
  246. if ExcludeList.IndexOf(ItemName) >= 0 then
  247. Result:=crExclude
  248. else
  249. Result:=crDefault;
  250. end;
  251. procedure TWriter.ProcessRules(d: TDef; const Prefix: string);
  252. var
  253. i: integer;
  254. s: string;
  255. begin
  256. s:=Prefix + d.Name;
  257. i:=IncludeList.IndexOf(s);
  258. if i >= 0 then begin
  259. i:=ptruint(IncludeList.Objects[i]);
  260. if (i = 0) or (d.Count = i - 1) then
  261. d.IsUsed:=True;
  262. end
  263. else
  264. if ExcludeList.IndexOf(s) >= 0 then begin
  265. d.SetNotUsed;
  266. end;
  267. if not (d.DefType in [dtUnit, dtClass, dtRecord]) then
  268. exit;
  269. s:=s + '.';
  270. for i:=0 to d.Count - 1 do
  271. ProcessRules(d[i], s);
  272. end;
  273. function TWriter.GetUniqueNum: integer;
  274. begin
  275. Inc(FUniqueCnt);
  276. Result:=FUniqueCnt;
  277. end;
  278. function TWriter.DefToJniSig(d: TDef): string;
  279. begin
  280. if d = nil then
  281. Result:=SUnsupportedType
  282. else
  283. case d.DefType of
  284. dtType:
  285. Result:=JNITypeSig[TTypeDef(d).BasicType];
  286. dtClass, dtRecord, dtProcType, dtSet, dtEnum:
  287. Result:='L' + GetJavaClassPath(d) + ';';
  288. else
  289. Result:=SUnsupportedType;
  290. end;
  291. end;
  292. function TWriter.DefToJavaType(d: TDef): string;
  293. begin
  294. if d = nil then
  295. Result:=SUnsupportedType
  296. else
  297. case d.DefType of
  298. dtType:
  299. Result:=JavaType[TTypeDef(d).BasicType];
  300. dtClass, dtRecord, dtProcType, dtSet, dtEnum:
  301. Result:=d.Name;
  302. else
  303. Result:=SUnsupportedType;
  304. end;
  305. end;
  306. function TWriter.GetJavaClassPath(d: TDef; const AClassName: string): string;
  307. var
  308. n: string;
  309. begin
  310. if AClassName = '' then
  311. n:=d.AliasName
  312. else
  313. n:=AClassName;
  314. Result:=StringReplace(JavaPackage, '.', '/', [rfReplaceAll]);
  315. if Result <> '' then
  316. Result:=Result + '/';
  317. if d.DefType = dtUnit then
  318. Result:=Result + n
  319. else
  320. Result:=Result + d.Parent.AliasName + '$' + n;
  321. end;
  322. procedure TWriter.WriteClass(d: TDef; PreInfo: boolean);
  323. var
  324. WrittenItems: TList;
  325. procedure _WriteConstructors(c: TClassDef; Written: TStringList);
  326. var
  327. i, j: integer;
  328. p: TProcDef;
  329. OldRet: TDef;
  330. s: string;
  331. begin
  332. if c = nil then
  333. exit;
  334. for i:=0 to c.Count - 1 do
  335. with c[i] do begin
  336. if (DefType = dtProc) and not c.IsPrivate and (TProcDef(c[i]).ProcType = ptConstructor) then begin
  337. p:=TProcDef(c[i]);
  338. j:=Written.IndexOf(p.Name);
  339. if (j < 0) or (Written.Objects[j] = c) then begin
  340. s:=p.Name + ':';
  341. for j:=0 to p.Count - 1 do
  342. s:=s + DefToJniSig(p[j]);
  343. if Written.IndexOf(s) < 0 then begin
  344. OldRet:=p.ReturnType;
  345. p.ReturnType:=d;
  346. p.Parent:=d;
  347. try
  348. WriteProc(p);
  349. finally
  350. p.ReturnType:=OldRet;
  351. p.Parent:=c;
  352. end;
  353. Written.Add(s);
  354. if not (poOverload in p.ProcOpt) then
  355. Written.AddObject(p.Name, c);
  356. end;
  357. end;
  358. end;
  359. end;
  360. _WriteConstructors(c.AncestorClass, Written);
  361. end;
  362. procedure WriteConstructors;
  363. var
  364. cc: TStringList;
  365. begin
  366. if not TClassDef(d).HasAbstractMethods then begin
  367. // Writing all constructors including parent's
  368. cc:=TStringList.Create;
  369. try
  370. cc.Sorted:=True;
  371. _WriteConstructors(TClassDef(d), cc);
  372. finally
  373. cc.Free;
  374. end;
  375. end;
  376. end;
  377. procedure _WriteReplacedItems(c: TClassDef);
  378. var
  379. i: integer;
  380. p: TReplDef;
  381. begin
  382. c:=c.AncestorClass;
  383. if c = nil then
  384. exit;
  385. if c.HasReplacedItems then begin
  386. for i:=0 to c.Count - 1 do
  387. with c[i] do begin
  388. p:=TReplDef(c[i]);
  389. if (DefType in ReplDefs) and ((p.IsReplaced) or p.IsReplImpl) then begin
  390. if p.ReplacedItem <> nil then
  391. WrittenItems.Add(p.ReplacedItem);
  392. if WrittenItems.IndexOf(p) >= 0 then
  393. continue;
  394. case p.DefType of
  395. dtProc:
  396. WriteProc(TProcDef(p), nil, d);
  397. dtProp, dtField:
  398. WriteVar(TVarDef(p), d);
  399. end;
  400. end;
  401. end;
  402. end;
  403. _WriteReplacedItems(c);
  404. end;
  405. procedure WriteReplacedItems;
  406. begin
  407. _WriteReplacedItems(TClassDef(d));
  408. end;
  409. procedure WriteItems(Regular, Replaced, ReplImpl: boolean);
  410. var
  411. i: integer;
  412. it: TReplDef;
  413. begin
  414. for i:=0 to d.Count - 1 do begin
  415. it:=TReplDef(d[i]);
  416. if not (it.DefType in ReplDefs) then
  417. continue;
  418. if not (it.IsReplImpl or it.IsReplaced) then begin
  419. if not Regular then
  420. continue;
  421. end
  422. else
  423. if (not Replaced and it.IsReplaced) or (not ReplImpl and it.IsReplImpl) then
  424. continue;
  425. if it.ReplacedItem <> nil then
  426. WrittenItems.Add(it.ReplacedItem);
  427. case it.DefType of
  428. dtProc:
  429. if TProcDef(it).ProcType <> ptConstructor then
  430. WriteProc(TProcDef(it));
  431. dtProp, dtField:
  432. WriteVar(TVarDef(it));
  433. end;
  434. end;
  435. end;
  436. procedure WriteTypeCast(const AName: string; SecondPass: boolean);
  437. var
  438. s, ss: string;
  439. begin
  440. if d.DefType <> dtClass then
  441. exit;
  442. with TClassDef(d) do begin
  443. if (AncestorClass = nil) and not (SecondPass and HasReplacedItems) then
  444. // TObject
  445. s:='_pasobj=obj._pasobj'
  446. else
  447. s:='super(obj)';
  448. if HasReplacedItems and not SecondPass then
  449. ss:='protected'
  450. else
  451. ss:='public';
  452. Fjs.WriteLn(Format('%s %s(PascalObject obj) { %s; }', [ss, AName, s]))
  453. end;
  454. end;
  455. var
  456. s, ss, n: string;
  457. RegularClass: boolean;
  458. begin
  459. if PreInfo then begin
  460. WriteClassInfoVar(d);
  461. if d.DefType = dtRecord then begin
  462. s:=d.Parent.Name + '.' + d.Name;
  463. Fps.WriteLn;
  464. Fps.WriteLn(Format('function _%s_CreateObj(env: PJNIEnv; const r: %s): jobject;', [GetClassPrefix(d), s]));
  465. Fps.WriteLn(Format('var pr: ^%s;', [s]));
  466. Fps.WriteLn('begin');
  467. Fps.IncI;
  468. Fps.WriteLn('New(pr); pr^:=r;');
  469. Fps.WriteLn(Format('Result:=_CreateJavaObj(env, pr, %s);', [GetTypeInfoVar(d)]));
  470. Fps.DecI;
  471. Fps.WriteLn('end;');
  472. Fps.WriteLn;
  473. ss:=Format('_%s_Free', [GetClassPrefix(d)]);
  474. Fps.WriteLn(Format('procedure %s(env: PJNIEnv; _self: JObject; r: jlong);', [ss]) + JniCaliing);
  475. Fps.WriteLn(Format('var pr: ^%s;', [s]));
  476. Fps.WriteLn('begin');
  477. Fps.WriteLn('pr:=pointer(ptruint(r));', 1);
  478. Fps.WriteLn('Dispose(pr);', 1);
  479. Fps.WriteLn('end;');
  480. AddNativeMethod(d, ss, 'Release', '(J)V');
  481. end;
  482. exit;
  483. end;
  484. // Java
  485. case d.DefType of
  486. dtClass:
  487. s:='class';
  488. dtRecord:
  489. s:='record';
  490. else
  491. s:='';
  492. end;
  493. WriteComment(d, s);
  494. n:=GetJavaClassName(d, nil);
  495. s:='public static class ' + n + ' extends ';
  496. if d.DefType = dtClass then
  497. with TClassDef(d) do begin
  498. if AncestorClass <> nil then begin
  499. ss:=AncestorClass.Name;
  500. if ImplementsReplacedItems then
  501. ss:='__' + ss;
  502. s:=s + ss;
  503. end
  504. else
  505. s:=s + 'PascalObject';
  506. end
  507. else
  508. s:=s + Format('%s.system.Record', [JavaPackage]);
  509. Fjs.WriteLn(s + ' {');
  510. Fjs.IncI;
  511. if d.DefType = dtRecord then begin
  512. Fjs.WriteLn('private native void Release(long pasobj);');
  513. Fjs.WriteLn(Format('public %s() { }', [d.Name]));
  514. Fjs.WriteLn(Format('public void Free() { Release(_pasobj); super.Free(); }', [d.Name]));
  515. Fjs.WriteLn(Format('public int Size() { return %d; }', [TRecordDef(d).Size]));
  516. end;
  517. WriteTypeCast(n, False);
  518. WrittenItems:=TList.Create;
  519. try
  520. RegularClass:=(d.DefType = dtClass) and not TClassDef(d).HasReplacedItems;
  521. if RegularClass then
  522. WriteConstructors;
  523. // Write regular items
  524. WriteItems(True, False, RegularClass);
  525. if RegularClass and TClassDef(d).ImplementsReplacedItems then
  526. // Write implementation wrappers for replaced mehods
  527. WriteReplacedItems;
  528. Fjs.DecI;
  529. Fjs.WriteLn('}');
  530. Fjs.WriteLn;
  531. if (d.DefType = dtClass) and (TClassDef(d).HasReplacedItems) then begin
  532. // Write replaced items
  533. Fjs.WriteLn(Format('public static class %s extends __%0:s {', [d.AliasName]));
  534. Fjs.IncI;
  535. WriteTypeCast(d.AliasName, True);
  536. WriteConstructors;
  537. WriteItems(False, True, True);
  538. if TClassDef(d).ImplementsReplacedItems then
  539. // Write implementation wrappers for replaced mehods
  540. WriteReplacedItems;
  541. Fjs.DecI;
  542. Fjs.WriteLn('}');
  543. Fjs.WriteLn;
  544. end;
  545. finally
  546. WrittenItems.Free;
  547. end;
  548. end;
  549. procedure TWriter.WriteProc(d: TProcDef; Variable: TVarDef; AParent: TDef);
  550. var
  551. i, j, ClassIdx: integer;
  552. s, ss: string;
  553. err, tf: boolean;
  554. pi: TProcInfo;
  555. ci: TClassInfo;
  556. IsTObject: boolean;
  557. tempvars: TStringList;
  558. vd: TVarDef;
  559. UseTempObjVar: boolean;
  560. ItemDef: TDef;
  561. begin
  562. ASSERT(d.DefType = dtProc);
  563. if d.IsPrivate or not d.IsUsed then
  564. exit;
  565. IsTObject:=(d.Parent.DefType = dtClass) and (TClassDef(d.Parent).AncestorClass = nil);
  566. if (d.ProcType = ptDestructor) and not IsTObject then
  567. exit;
  568. if Variable <> nil then
  569. ItemDef:=Variable
  570. else
  571. ItemDef:=d;
  572. tempvars:=nil;
  573. pi:=TProcInfo.Create;
  574. with d do
  575. try
  576. pi.Name:=Name;
  577. s:=GetClassPrefix(d.Parent) + pi.Name;
  578. pi.JniName:=s;
  579. pi.JniSignature:=GetProcSignature(d);
  580. if AParent = nil then begin
  581. // Checking duplicate name and duplicate params
  582. ClassIdx:=FClasses.IndexOf(GetJavaClassName(d.Parent, ItemDef));
  583. if ClassIdx >= 0 then begin
  584. ci:=TClassInfo(FClasses.Objects[ClassIdx]);
  585. j:=1;
  586. ss:=Copy(pi.JniSignature, 1, Pos(')', pi.JniSignature));
  587. repeat
  588. err:=False;
  589. for i:=0 to ci.Funcs.Count - 1 do
  590. with TProcInfo(ci.Funcs[i]) do
  591. if CompareText(JniName, pi.JniName) = 0 then begin
  592. Inc(j);
  593. pi.JniName:=Format('%s_%d', [s, j]);
  594. err:=True;
  595. break;
  596. end
  597. else
  598. if (CompareText(Name, pi.Name) = 0) and (ss = Copy(JniSignature, 1, Pos(')', JniSignature))) then
  599. // Duplicate params
  600. exit;
  601. until not err;
  602. end;
  603. err:=False;
  604. if ProcType in [ptFunction, ptConstructor] then
  605. s:='function'
  606. else
  607. s:='procedure';
  608. s:=s + ' ' + pi.JniName + '(_env: PJNIEnv; _jobj: jobject';
  609. UseTempObjVar:=(ProcType = ptProcedure) and (Variable <> nil) and (Variable.VarType <> nil) and (Variable.VarType.DefType = dtProcType) and (Variable.Parent.DefType <> dtUnit);
  610. for j:=0 to Count - 1 do begin
  611. vd:=TVarDef(Items[j]);
  612. with vd do begin
  613. s:=s + '; ' + Name + ': ';
  614. if not IsJavaVarParam(vd) then
  615. s:=s + DefToJniType(VarType, err)
  616. else begin
  617. s:=s + 'jarray';
  618. if tempvars = nil then
  619. tempvars:=TStringList.Create;
  620. if VarType = nil then
  621. err:=True
  622. else
  623. Tag:=tempvars.AddObject('__tmp_' + Name, d.Items[j]) + 1;
  624. end;
  625. end;
  626. end;
  627. s:=s + ')';
  628. if ProcType in [ptFunction, ptConstructor] then
  629. s:=s + ': ' + DefToJniType(ReturnType, err);
  630. s:=s + '; ' + JniCaliing;
  631. if err then begin
  632. d.SetNotUsed;
  633. s:='// ' + s;
  634. end;
  635. Fps.WriteLn;
  636. Fps.WriteLn(s);
  637. if err then
  638. exit;
  639. if (tempvars <> nil) or UseTempObjVar then begin
  640. s:='';
  641. Fps.WriteLn('var');
  642. Fps.IncI;
  643. if tempvars <> nil then begin
  644. for i:=0 to tempvars.Count - 1 do begin
  645. vd:=TVarDef(tempvars.Objects[i]);
  646. Fps.WriteLn(Format('%s: %s;', [tempvars[i], GetPasType(vd.VarType, True)]));
  647. if IsJavaSimpleType(vd.VarType) then begin
  648. Fps.WriteLn(Format('%s_arr: P%s;', [tempvars[i], DefToJniType(vd.VarType, err)]));
  649. if s = '' then
  650. s:='__iscopy: JBoolean;';
  651. end;
  652. end;
  653. if s <> '' then
  654. Fps.WriteLn(s);
  655. end;
  656. if UseTempObjVar then
  657. Fps.WriteLn('__objvar: ' + d.Parent.Name + ';');
  658. Fps.DecI;
  659. end;
  660. Fps.WriteLn('begin');
  661. Fps.IncI;
  662. EHandlerStart;
  663. tf:=False;
  664. // Assign var parameter values to local vars
  665. if tempvars <> nil then begin
  666. for i:=0 to tempvars.Count - 1 do begin
  667. vd:=TVarDef(tempvars.Objects[i]);
  668. Fps.WriteLn(Format('if _env^^.GetArrayLength(_env, %s) <> 1 then _RaiseVarParamException(''%s'');', [vd.Name, vd.Name]));
  669. if IsJavaSimpleType(vd.VarType) then begin
  670. Fps.WriteLn(Format('%s_arr:=_env^^.Get%sArrayElements(_env, %s, __iscopy);', [tempvars[i], GetJniFuncType(vd.VarType), vd.Name]));
  671. Fps.WriteLn(Format('if %s_arr = nil then _RaiseVarParamException(''%s'');', [tempvars[i], vd.Name]));
  672. s:=tempvars[i] + '_arr^';
  673. tf:=True;
  674. end
  675. else
  676. s:=Format('_env^^.GetObjectArrayElement(_env, %s, 0)', [vd.Name]);
  677. if voVar in vd.VarOpt then
  678. Fps.WriteLn(tempvars[i] + ':=' + JniToPasType(vd.VarType, s, False) + ';');
  679. end;
  680. end;
  681. if tf then begin
  682. Fps.WriteLn('try');
  683. Fps.IncI;
  684. end;
  685. s:='';
  686. if Parent.DefType = dtUnit then
  687. s:=Parent.Name + '.'
  688. else
  689. if ProcType = ptConstructor then
  690. s:=Parent.Parent.Name + '.' + Parent.Name + '.'
  691. else
  692. s:=JniToPasType(d.Parent, '_jobj', True) + '.';
  693. if Variable = nil then begin
  694. // Regular proc
  695. s:=s + pi.Name;
  696. if Count > 0 then begin
  697. s:=s + '(';
  698. for j:=0 to Count - 1 do begin
  699. vd:=TVarDef(Items[j]);
  700. if vd.Tag <> 0 then
  701. ss:=tempvars[vd.Tag - 1]
  702. else begin
  703. ss:=Items[j].Name;
  704. ss:=JniToPasType(vd.VarType, ss, False);
  705. end;
  706. if j <> 0 then
  707. s:=s + ', ';
  708. s:=s + ss;
  709. end;
  710. s:=s + ')';
  711. end;
  712. end
  713. else begin
  714. // Var access
  715. if UseTempObjVar then begin
  716. System.Delete(s, Length(s), 1);
  717. Fps.WriteLn('__objvar:=' + s + ';');
  718. s:='__objvar.';
  719. end;
  720. s:=s + Variable.Name;
  721. if Variable.IndexType <> nil then begin
  722. ASSERT(Count >= 1);
  723. i:=1;
  724. s:=Format('%s[%s]', [s, JniToPasType(TVarDef(Items[0]).VarType, Items[0].Name, False)]);
  725. end
  726. else
  727. i:=0;
  728. if ProcType = ptProcedure then begin
  729. ASSERT(Count = i + 1);
  730. if Variable.VarType.DefType = dtProcType then begin
  731. Fps.WriteLn(Format('_RefMethodPtr(_env, TMethod(%s), False);', [s]));
  732. ss:=Format('_RefMethodPtr(_env, TMethod(%s), True);', [s]);
  733. end;
  734. s:=s + ':=' + JniToPasType(TVarDef(Items[i]).VarType, Items[i].Name, False);
  735. end;
  736. end;
  737. if ProcType in [ptFunction, ptConstructor] then
  738. s:='Result:=' + PasToJniType(ReturnType, s);
  739. s:=s + ';';
  740. Fps.WriteLn(s);
  741. if (Variable <> nil) and UseTempObjVar then
  742. Fps.WriteLn(ss);
  743. // Return var/out parameters
  744. if tempvars <> nil then begin
  745. for i:=0 to tempvars.Count - 1 do begin
  746. vd:=TVarDef(tempvars.Objects[i]);
  747. if IsJavaSimpleType(vd.VarType) then
  748. Fps.WriteLn(Format('%s_arr^:=%s;', [tempvars[i], PasToJniType(vd.VarType, tempvars[i])]))
  749. else
  750. Fps.WriteLn(Format('_env^^.SetObjectArrayElement(_env, %s, 0, %s);', [vd.Name, PasToJniType(vd.VarType, tempvars[i])]));
  751. end;
  752. end;
  753. if IsTObject and ( (ProcType = ptDestructor) or (CompareText(Name, 'Free') = 0) ) then
  754. Fps.WriteLn(Format('_env^^.SetLongField(_env, _jobj, %s.ObjFieldId, 0);', [GetTypeInfoVar(d.Parent)]));
  755. if tf then begin
  756. Fps.WriteLn('finally', -1);
  757. if tempvars <> nil then begin
  758. for i:=0 to tempvars.Count - 1 do begin
  759. vd:=TVarDef(tempvars.Objects[i]);
  760. if IsJavaSimpleType(vd.VarType) then
  761. Fps.WriteLn(Format('_env^^.Release%sArrayElements(_env, %s, %s_arr, 0);', [JavaType[TTypeDef(vd.VarType).BasicType], vd.Name, tempvars[i]]));
  762. end;
  763. end;
  764. Fps.DecI;
  765. Fps.WriteLn('end;');
  766. end;
  767. s:='';
  768. if ProcType in [ptFunction, ptConstructor] then begin
  769. s:='0';
  770. if (ReturnType.DefType = dtType) and (TTypeDef(ReturnType).BasicType <= btDouble) then
  771. s:='0'
  772. else
  773. s:=Format('%s(0)', [DefToJniType(ReturnType, err)]);
  774. s:='Result:=' + s + ';';
  775. end;
  776. EHandlerEnd('_env', s);
  777. Fps.DecI;
  778. Fps.WriteLn('end;');
  779. AParent:=d.Parent;
  780. end
  781. else
  782. ClassIdx:=FClasses.IndexOf(GetJavaClassName(AParent, ItemDef));
  783. if ClassIdx < 0 then begin
  784. ci:=TClassInfo.Create;
  785. ci.Def:=AParent;
  786. s:=GetJavaClassName(AParent, ItemDef);
  787. ci.IsCommonClass:=s <> AParent.Name;
  788. ClassIdx:=FClasses.AddObject(s, ci);
  789. end;
  790. TClassInfo(FClasses.Objects[ClassIdx]).Funcs.Add(pi);
  791. pi:=nil;
  792. // Java part
  793. s:=GetJavaProcDeclaration(d) + ';';
  794. if (Parent.DefType = dtUnit) or (ProcType = ptConstructor) then
  795. s:='static ' + s;
  796. if Variable = nil then
  797. Fjs.WriteLn('// ' + GetProcDeclaration(d));
  798. if poPrivate in ProcOpt then
  799. ss:='private'
  800. else
  801. if poProtected in ProcOpt then
  802. ss:='protected'
  803. else
  804. ss:='public';
  805. Fjs.WriteLn(ss + ' native ' + s);
  806. finally
  807. pi.Free;
  808. tempvars.Free;
  809. end;
  810. end;
  811. procedure TWriter.WriteVar(d: TVarDef; AParent: TDef);
  812. var
  813. pd: TProcDef;
  814. t: TTypeDef;
  815. s: string;
  816. begin
  817. if not d.IsUsed then
  818. exit;
  819. if d.VarType <> nil then begin
  820. case d.DefType of
  821. dtVar:
  822. s:='var';
  823. dtProp:
  824. s:='property';
  825. else
  826. s:='';
  827. end;
  828. s:=Trim(s + ' ' + d.Name);
  829. if d.IndexType <> nil then
  830. s:=s + '[]';
  831. Fjs.WriteLn(Format('// %s: %s', [s, d.VarType.Name]));
  832. end;
  833. if voRead in d.VarOpt then begin
  834. pd:=TProcDef.Create(nil, dtProc);
  835. try
  836. pd.IsUsed:=True;
  837. pd.Parent:=d.Parent;
  838. pd.ProcType:=ptFunction;
  839. pd.Name:='get' + d.Name;
  840. pd.ReturnType:=d.VarType;
  841. if d.IndexType <> nil then
  842. with TVarDef.Create(pd, dtParam) do begin
  843. Name:='_Index';
  844. AliasName:='Index';
  845. VarType:=d.IndexType;
  846. VarOpt:=[voRead];
  847. end;
  848. WriteProc(pd, d, AParent);
  849. finally
  850. pd.Free;
  851. end;
  852. end;
  853. if voWrite in d.VarOpt then begin
  854. pd:=TProcDef.Create(nil, dtProc);
  855. try
  856. pd.IsUsed:=True;
  857. pd.Parent:=d.Parent;
  858. pd.ProcType:=ptProcedure;
  859. pd.Name:='set' + d.Name;
  860. if d.IndexType <> nil then
  861. with TVarDef.Create(pd, dtParam) do begin
  862. Name:='_Index';
  863. AliasName:='Index';
  864. VarType:=d.IndexType;
  865. VarOpt:=[voRead];
  866. end;
  867. with TVarDef.Create(pd, dtParam) do begin
  868. Name:='_Value';
  869. AliasName:='Value';
  870. VarType:=d.VarType;
  871. VarOpt:=[voRead];
  872. end;
  873. t:=TTypeDef.Create(nil, dtType);
  874. try
  875. t.BasicType:=btVoid;
  876. pd.ReturnType:=t;
  877. WriteProc(pd, d, AParent);
  878. finally
  879. t.Free;
  880. end;
  881. finally
  882. pd.Free;
  883. end;
  884. end;
  885. end;
  886. procedure TWriter.WriteConst(d: TConstDef);
  887. var
  888. s, v: string;
  889. begin
  890. if not d.IsUsed then
  891. exit;
  892. v:=d.Value;
  893. if d.VarType = nil then begin
  894. if Copy(d.Value, 1, 1) = '"' then
  895. s:='String'
  896. else
  897. s:='double';
  898. end
  899. else begin
  900. s:=DefToJavaType(d.VarType);
  901. if d.VarType.DefType = dtType then
  902. case TTypeDef(d.VarType).BasicType of
  903. btLongWord, btInt64:
  904. v:=v + 'L';
  905. btBoolean:
  906. if v = '1' then
  907. v:='true'
  908. else
  909. v:='false';
  910. end;
  911. end;
  912. Fjs.WriteLn(Format('public static final %s %s = %s;', [s, d.Name, v]));
  913. end;
  914. procedure TWriter.WriteEnum(d: TDef);
  915. var
  916. i: integer;
  917. s: string;
  918. begin
  919. if not d.IsUsed then
  920. exit;
  921. RegisterPseudoClass(d);
  922. WriteComment(d, 'enum');
  923. Fjs.WriteLn(Format('public static class %s extends system.Enum {', [d.Name]));
  924. Fjs.IncI;
  925. for i:=0 to d.Count - 1 do begin
  926. s:=Format('public final static int %s = %s;', [d[i].Name, TConstDef(d[i]).Value]);
  927. Fjs.WriteLn(s);
  928. end;
  929. Fjs.WriteLn;
  930. Fjs.WriteLn(Format('public %s(int v) { Value = v; }', [d.Name]));
  931. Fjs.WriteLn(Format('@Override public boolean equals(Object o) { return ((o instanceof %0:s) && Value == ((%0:s)o).Value) || super.equals(o); }', [d.Name]));
  932. Fjs.DecI;
  933. Fjs.WriteLn('}');
  934. Fjs.WriteLn;
  935. end;
  936. procedure TWriter.WriteProcType(d: TProcDef; PreInfo: boolean);
  937. procedure _AccessSimpleArray(vd: TVarDef; VarIndex: integer; DoSet: boolean);
  938. begin
  939. with vd do begin
  940. Fps.WriteLn(Format('_tmp_%s:=_env^^.Get%sArrayElements(_env, _args[%d].L, PJBoolean(nil)^);', [Name, GetJniFuncType(VarType), VarIndex]));
  941. Fps.WriteLn(Format('if _tmp_%s <> nil then', [Name]));
  942. if DoSet then
  943. Fps.WriteLn(Format('_tmp_%s^:=%s;', [Name, PasToJniType(VarType, Name)]), 1)
  944. else
  945. Fps.WriteLn(Format('%s:=%s;', [Name, JniToPasType(VarType, '_tmp_' + Name + '^', False)]), 1);
  946. Fps.WriteLn(Format('_env^^.Release%sArrayElements(_env, _args[%d].L, _tmp_%s, 0);', [GetJniFuncType(VarType), VarIndex, Name]));
  947. end;
  948. end;
  949. var
  950. vd: TVarDef;
  951. i: integer;
  952. s, ss: string;
  953. err: boolean;
  954. begin
  955. if not d.IsUsed or not (poMethodPtr in d.ProcOpt) then
  956. exit;
  957. if PreInfo then begin
  958. WriteClassInfoVar(d);
  959. // Handler proc
  960. Fps.WriteLn;
  961. vd:=TVarDef.Create(nil, dtParam);
  962. try
  963. vd.Name:='_data';
  964. vd.VarType:=TTypeDef.Create(nil, dtType);
  965. with TTypeDef(vd.VarType) do begin
  966. Name:='pointer';
  967. BasicType:=btPointer;
  968. end;
  969. d.Insert(0, vd);
  970. Fps.WriteLn(GetProcDeclaration(d, Format('%sHandler', [GetClassPrefix(d)]), True) + ';');
  971. finally
  972. vd.VarType.Free;
  973. vd.Free;
  974. end;
  975. Fps.WriteLn('var');
  976. Fps.IncI;
  977. Fps.WriteLn('_env: PJNIEnv;');
  978. Fps.WriteLn('_mpi: _TMethodPtrInfo;');
  979. if d.Count > 0 then begin
  980. Fps.WriteLn(Format('_args: array[0..%d] of jvalue;', [d.Count - 1]));
  981. for i:=0 to d.Count - 1 do begin
  982. vd:=TVarDef(d[i]);
  983. with vd do
  984. if IsJavaVarParam(vd) and IsJavaSimpleType(VarType) then
  985. Fps.WriteLn(Format('_tmp_%s: P%s;', [Name, DefToJniType(VarType, err)]));
  986. end;
  987. end;
  988. Fps.DecI;
  989. Fps.WriteLn('begin');
  990. Fps.IncI;
  991. Fps.WriteLn('CurJavaVM^^.GetEnv(CurJavaVM, @_env, JNI_VERSION_1_6);');
  992. Fps.WriteLn('_MethodPointersCS.Enter;');
  993. Fps.WriteLn('try');
  994. Fps.WriteLn('_mpi:=_TMethodPtrInfo(_MethodPointers[-integer(ptruint(_data)) - 1]);', 1);
  995. Fps.WriteLn('finally');
  996. Fps.WriteLn('_MethodPointersCS.Leave;', 1);
  997. Fps.WriteLn('end;');
  998. for i:=0 to d.Count - 1 do begin
  999. vd:=TVarDef(d[i]);
  1000. with vd do begin
  1001. if not IsJavaVarParam(vd) then begin
  1002. s:='L';
  1003. if VarType.DefType = dtType then
  1004. s:=Copy(JNITypeSig[TTypeDef(VarType).BasicType], 1, 1);
  1005. ss:=PasToJniType(VarType, Name);
  1006. end
  1007. else begin
  1008. s:='L';
  1009. if IsJavaSimpleType(VarType) then
  1010. ss:=Format('_env^^.New%sArray(_env, 1)', [GetJniFuncType(VarType)])
  1011. else begin
  1012. if voVar in VarOpt then
  1013. ss:=PasToJniType(VarType, Name)
  1014. else
  1015. ss:='nil';
  1016. ss:=Format('_env^^.NewObjectArray(_env, 1, %s.ClassRef, %s)', [GetTypeInfoVar(VarType), ss]);
  1017. end;
  1018. end;
  1019. Fps.WriteLn(Format('_args[%d].%s:=%s;', [i, s, ss]));
  1020. if IsJavaVarParam(vd) and (voVar in VarOpt) and IsJavaSimpleType(VarType) then
  1021. _AccessSimpleArray(TVarDef(d[i]), i, True);
  1022. end;
  1023. end;
  1024. if d.Count > 0 then
  1025. s:='@_args'
  1026. else
  1027. s:='nil';
  1028. // Calling Java handler
  1029. s:=Format('_env^^.Call%sMethodA(_env, _mpi.Obj, _mpi.MethodId, %s)', [GetJniFuncType(d.ReturnType), s]);
  1030. if d.ProcType = ptFunction then
  1031. s:=Format('Result:=%s', [JniToPasType(d.ReturnType, s, False)]);
  1032. Fps.WriteLn(s + ';');
  1033. // Processing var/out parameters
  1034. for i:=0 to d.Count - 1 do begin
  1035. vd:=TVarDef(d[i]);
  1036. with vd do
  1037. if IsJavaVarParam(vd) then
  1038. if IsJavaSimpleType(VarType) then
  1039. _AccessSimpleArray(TVarDef(d[i]), i, False)
  1040. else begin
  1041. s:=Format('_env^^.GetObjectArrayElement(_env, _args[%d].L, 0)', [i]);
  1042. Fps.WriteLn(Format('%s:=%s;', [Name, JniToPasType(VarType, s, False)]));
  1043. end;
  1044. end;
  1045. Fps.DecI;
  1046. Fps.WriteLn('end;');
  1047. // Get handler proc
  1048. Fps.WriteLn;
  1049. Fps.WriteLn(Format('function %sGetHandler(env: PJNIEnv; jobj: jobject; const ci: _TJavaClassInfo): %s.%s;',
  1050. [GetClassPrefix(d), d.Parent.Name, d.Name]));
  1051. Fps.WriteLn('var mpi: _TMethodPtrInfo;');
  1052. Fps.WriteLn('begin');
  1053. Fps.IncI;
  1054. Fps.WriteLn('Result:=nil;');
  1055. Fps.WriteLn('mpi:=_TMethodPtrInfo(_GetPasObj(env, jobj, ci, False));');
  1056. Fps.WriteLn('if mpi = nil then exit;');
  1057. Fps.WriteLn('if mpi.Index = 0 then');
  1058. Fps.WriteLn('TMethod(Result):=mpi.RealMethod', 1);
  1059. Fps.WriteLn('else');
  1060. Fps.WriteLn('with TMethod(Result) do begin', 1);
  1061. Fps.WriteLn('Data:=pointer(ptruint(-integer(mpi.Index)));', 2);
  1062. Fps.WriteLn(Format('Code:=@%sHandler;', [GetClassPrefix(d)]), 2);
  1063. Fps.WriteLn('end;', 1);
  1064. Fps.DecI;
  1065. Fps.WriteLn('end;');
  1066. exit;
  1067. end;
  1068. err:=False;
  1069. WriteComment(d, 'procedural type');
  1070. RegisterPseudoClass(d);
  1071. Fjs.WriteLn(Format('/* Pascal prototype: %s */', [GetProcDeclaration(d, 'Execute')]));
  1072. Fjs.WriteLn(Format('/* Java prototype: %s */', [GetJavaProcDeclaration(d, 'Execute')]));
  1073. Fjs.WriteLn(Format('public static class %s extends %s.system.MethodPtr {', [d.Name, JavaPackage]));
  1074. Fjs.IncI;
  1075. Fjs.WriteLn(Format('private String HandlerSig = "%s";', [GetProcSignature(d)]));
  1076. Fjs.WriteLn(Format('public %s(Object Obj, String MethodName) { Init(Obj, MethodName, HandlerSig); }', [d.Name]));
  1077. Fjs.WriteLn(Format('public %s() { Init(this, "Execute", HandlerSig); }', [d.Name]));
  1078. Fjs.WriteLn(Format('protected %s throws NoSuchMethodException { throw new NoSuchMethodException(); }', [GetJavaProcDeclaration(d, 'Execute')]));
  1079. Fjs.DecI;
  1080. Fjs.WriteLn('}');
  1081. Fjs.WriteLn;
  1082. end;
  1083. procedure TWriter.WriteSet(d: TSetDef);
  1084. begin
  1085. if not d.IsUsed then
  1086. exit;
  1087. if d.ElType = nil then
  1088. raise Exception.Create('No element type.');
  1089. WriteComment(d, '');
  1090. Fjs.WriteLn(Format('/* set of %s */', [d.ElType.Name]));
  1091. if d.Size > 4 then begin
  1092. Fjs.WriteLn('/* Set size more than 32 bits is not supported */');
  1093. exit;
  1094. end;
  1095. RegisterPseudoClass(d);
  1096. Fjs.WriteLn(Format('public static class %s extends %s.system.Set<%s,%s> {', [d.Name, JavaPackage, d.Name, d.ElType.Name]));
  1097. Fjs.IncI;
  1098. Fjs.WriteLn(Format('protected byte Size() { return %d; }', [d.Size]));
  1099. Fjs.WriteLn(Format('protected int Base() { return %d; }', [d.Base]));
  1100. Fjs.WriteLn(Format('protected int ElMax() { return %d; }', [d.ElMax]));
  1101. Fjs.WriteLn(Format('protected int Ord(%s Element) { return Element.Ord(); }', [d.ElType.Name]));
  1102. Fjs.WriteLn(Format('public %s() { }', [d.Name]));
  1103. Fjs.WriteLn(Format('public %s(%s... Elements) { super(Elements); }', [d.Name, d.ElType.Name]));
  1104. Fjs.WriteLn(Format('public %0:s(%0:s... Elements) { super(Elements); }', [d.Name]));
  1105. Fjs.WriteLn(Format('public static %0:s Exclude(%0:s s1, %0:s s2) { %0:s r = new %0:s(s1); r.Exclude(s2); return r; }', [d.Name]));
  1106. Fjs.WriteLn(Format('public static %0:s Intersect(%0:s s1, %0:s s2) { %0:s r = new %0:s(s1); r.Intersect(s2); return r; }', [d.Name]));
  1107. Fjs.DecI;
  1108. Fjs.WriteLn('}');
  1109. Fjs.WriteLn;
  1110. end;
  1111. procedure TWriter.WriteUnit(u: TUnitDef);
  1112. var
  1113. d: TDef;
  1114. i: integer;
  1115. HasSystem: boolean;
  1116. begin
  1117. if u.Processed then
  1118. exit;
  1119. u.Processed:=True;
  1120. if not u.IsUsed then
  1121. exit;
  1122. for i:=0 to High(u.UsedUnits) do
  1123. WriteUnit(u.UsedUnits[i]);
  1124. Fps.WriteLn;
  1125. Fps.WriteLn(Format('{ Unit %s }', [u.Name]));
  1126. u.Name:=LowerCase(u.Name);
  1127. Fjs:=TTextOutStream.Create(IncludeTrailingPathDelimiter(FPkgDir) + u.Name + '.java', fmCreate);
  1128. try
  1129. Fjs.WriteLn(Format('package %s;', [JavaPackage]));
  1130. HasSystem:=False;
  1131. if Length(u.UsedUnits) > 0 then begin
  1132. Fjs.WriteLn;
  1133. for i:=0 to High(u.UsedUnits) do
  1134. if u.UsedUnits[i].IsUsed then begin
  1135. Fjs.WriteLn(Format('import %s.%s.*;', [JavaPackage, LowerCase(u.UsedUnits[i].Name)]));
  1136. if AnsiCompareText(u.UsedUnits[i].Name, 'system') = 0 then
  1137. HasSystem:=True;
  1138. end;
  1139. if not HasSystem then
  1140. Fjs.WriteLn(Format('import %s.system.*;', [JavaPackage]));
  1141. end;
  1142. Fjs.WriteLn;
  1143. Fjs.WriteLn('public class ' + u.Name + ' {');
  1144. Fjs.IncI;
  1145. if u.Name = 'system' then begin
  1146. Fjs.WriteLn('static private boolean _JniLibLoaded = false;');
  1147. Fjs.WriteLn('public static void InitJni() {');
  1148. Fjs.WriteLn('if (!_JniLibLoaded) {', 1);
  1149. Fjs.WriteLn('_JniLibLoaded=true;', 2);
  1150. Fjs.WriteLn(Format('System.loadLibrary("%s");', [LibName]), 2);
  1151. Fjs.WriteLn('}', 1);
  1152. Fjs.WriteLn('}');
  1153. // Support functions
  1154. Fjs.WriteLn('public native static long AllocMemory(int Size);');
  1155. AddNativeMethod(u, '_AllocMemory', 'AllocMemory', '(I)J');
  1156. // Base object
  1157. Fjs.WriteLn;
  1158. Fjs.WriteLn('public static class PascalObject {');
  1159. Fjs.IncI;
  1160. Fjs.WriteLn(Format('static { %s.system.InitJni(); }', [JavaPackage]));
  1161. Fjs.WriteLn('protected long _pasobj = 0;');
  1162. Fjs.WriteLn('@Override public boolean equals(Object o) { return ((o instanceof PascalObject) && _pasobj == ((PascalObject)o)._pasobj); }');
  1163. Fjs.WriteLn('@Override public int hashCode() { return (int)_pasobj; }');
  1164. Fjs.DecI;
  1165. Fjs.WriteLn('}');
  1166. Fjs.WriteLn;
  1167. Fjs.WriteLn('public static long Pointer(PascalObject obj) { return (obj == null) ? 0 : obj._pasobj; }');
  1168. // Record
  1169. Fjs.WriteLn;
  1170. Fjs.WriteLn('public static class Record extends PascalObject {');
  1171. Fjs.IncI;
  1172. Fjs.WriteLn('protected void finalize() { Free(); }');
  1173. Fjs.WriteLn('public Record() { _pasobj = AllocMemory(Size()); }');
  1174. Fjs.WriteLn('public void Free() { _pasobj = 0; }');
  1175. Fjs.WriteLn('public int Size() { return 0; }');
  1176. Fjs.DecI;
  1177. Fjs.WriteLn('}');
  1178. // Method pointer base class
  1179. d:=TClassDef.Create(FThisUnit, dtClass);
  1180. d.Name:='_TMethodPtrInfo';
  1181. d.AliasName:='MethodPtr';
  1182. WriteClassInfoVar(d);
  1183. Fps.WriteLn;
  1184. Fps.WriteLn('procedure _TMethodPtrInfo_Init(env: PJNIEnv; _self, JavaObj: JObject; AMethodName, AMethodSig: jstring);' + JniCaliing);
  1185. Fps.WriteLn('var mpi: _TMethodPtrInfo;');
  1186. Fps.WriteLn('begin');
  1187. Fps.IncI;
  1188. EHandlerStart;
  1189. Fps.WriteLn('mpi:=_TMethodPtrInfo.Create(env, JavaObj, ansistring(_StringFromJString(env, AMethodName)), ansistring(_StringFromJString(env, AMethodSig)));');
  1190. Fps.WriteLn(Format('env^^.SetLongField(env, _self, %s.ObjFieldId, Int64(ptruint(mpi)));', [GetTypeInfoVar(d)]));
  1191. EHandlerEnd('env');
  1192. Fps.DecI;
  1193. Fps.WriteLn('end;');
  1194. AddNativeMethod(d, '_TMethodPtrInfo_Init', 'Init', Format('(Ljava/lang/Object;%s%s)V', [JNITypeSig[btString], JNITypeSig[btString]]));
  1195. Fps.WriteLn;
  1196. Fps.WriteLn('procedure _TMethodPtrInfo_Release(env: PJNIEnv; _self: JObject);' + JniCaliing);
  1197. Fps.WriteLn('begin');
  1198. Fps.IncI;
  1199. EHandlerStart;
  1200. Fps.WriteLn(Format('_TMethodPtrInfo(_GetPasObj(env, _self, %s, True)).Release(env);', [GetTypeInfoVar(d)]));
  1201. EHandlerEnd('env');
  1202. Fps.DecI;
  1203. Fps.WriteLn('end;');
  1204. AddNativeMethod(d, '_TMethodPtrInfo_Release', 'Release', '()V');
  1205. Fjs.WriteLn;
  1206. Fjs.WriteLn('public static class MethodPtr extends PascalObject {');
  1207. Fjs.IncI;
  1208. Fjs.WriteLn('private native void Release();');
  1209. Fjs.WriteLn('protected void finalize() { if (_pasobj != 0) Release(); }');
  1210. Fjs.WriteLn('protected native void Init(Object Obj, String MethodName, String MethodSignature);');
  1211. Fjs.DecI;
  1212. Fjs.WriteLn('}');
  1213. Fjs.WriteLn;
  1214. // Base class for Enum
  1215. Fjs.WriteLn('public static class Enum {');
  1216. Fjs.IncI;
  1217. Fjs.WriteLn('public int Value;');
  1218. Fjs.WriteLn('public int Ord() { return Value; }');
  1219. Fjs.WriteLn('@Override public boolean equals(Object o) { return (o instanceof Integer) && Value == (Integer)o; }');
  1220. Fjs.WriteLn('@Override public int hashCode() { return Value; }');
  1221. Fjs.DecI;
  1222. Fjs.WriteLn('}');
  1223. Fjs.WriteLn;
  1224. // Base class for Set
  1225. Fjs.WriteLn('public static class Set<TS extends Set<?,?>,TE extends Enum> {');
  1226. Fjs.IncI;
  1227. Fjs.WriteLn('protected int Value = 0;');
  1228. Fjs.WriteLn('protected byte Size() { return 0; }');
  1229. Fjs.WriteLn('protected int Base() { return 0; }');
  1230. Fjs.WriteLn('protected int ElMax() { return 0; }');
  1231. Fjs.WriteLn('protected int Ord(TE Element) { return 0; }');
  1232. Fjs.WriteLn('protected int GetMask(TE Element) {');
  1233. Fjs.IncI;
  1234. Fjs.WriteLn('return 1 << (Ord(Element) - Base());');
  1235. Fjs.DecI;
  1236. Fjs.WriteLn('}');
  1237. Fjs.WriteLn('public Set() { }');
  1238. Fjs.WriteLn('public Set(TE... Elements) { Include(Elements); }');
  1239. Fjs.WriteLn('public Set(TS... Elements) { for (TS e : Elements) Include(e); }');
  1240. Fjs.WriteLn('public void Include(TE... Elements) { for (TE e: Elements) Value = Value | GetMask(e); }');
  1241. Fjs.WriteLn('public void Include(TS s) { Value=Value | s.Value; }');
  1242. Fjs.WriteLn('public void Exclude(TE... Elements) { for (TE e: Elements) Value = Value & ~GetMask(e); }');
  1243. Fjs.WriteLn('public void Exclude(TS s) { Value=Value & ~s.Value; }');
  1244. Fjs.WriteLn('public void Assign(TS s) { Value=s.Value; }');
  1245. Fjs.WriteLn('public void Intersect(TS s) { Value=Value & s.Value; }');
  1246. Fjs.WriteLn('public boolean Has(TE Element) { return (Value & GetMask(Element)) != 0; }');
  1247. Fjs.WriteLn('public boolean IsEmpty() { return Value == 0; }');
  1248. Fjs.WriteLn('public boolean equals(TS s) { return Value == s.Value; }');
  1249. Fjs.WriteLn('public boolean equals(TE Element) { return Value == Ord(Element); }');
  1250. Fjs.WriteLn('public boolean equals(int Element) { return Value == Element; }');
  1251. Fjs.DecI;
  1252. Fjs.WriteLn('}');
  1253. Fjs.WriteLn;
  1254. end;
  1255. Fjs.WriteLn(Format('static { %s.system.InitJni(); }', [JavaPackage]));
  1256. Fjs.WriteLn;
  1257. // First pass
  1258. for i:=0 to u.Count - 1 do begin
  1259. d:=u[i];
  1260. if not d.IsUsed then
  1261. continue;
  1262. case d.DefType of
  1263. dtSet, dtEnum:
  1264. WriteClassInfoVar(d);
  1265. dtClass, dtRecord:
  1266. WriteClass(d, True);
  1267. dtProcType:
  1268. WriteProcType(TProcDef(d), True);
  1269. end;
  1270. end;
  1271. // Second pass
  1272. for i:=0 to u.Count - 1 do begin
  1273. d:=u[i];
  1274. if not d.IsUsed then
  1275. continue;
  1276. case d.DefType of
  1277. dtClass, dtRecord:
  1278. WriteClass(d, False);
  1279. dtProc:
  1280. WriteProc(TProcDef(d));
  1281. dtVar, dtProp:
  1282. WriteVar(TVarDef(d));
  1283. dtEnum:
  1284. WriteEnum(d);
  1285. dtProcType:
  1286. WriteProcType(TProcDef(d), False);
  1287. dtSet:
  1288. WriteSet(TSetDef(d));
  1289. dtConst:
  1290. WriteConst(TConstDef(d));
  1291. end;
  1292. end;
  1293. Fjs.DecI;
  1294. Fjs.WriteLn('}');
  1295. finally
  1296. Fjs.Free;
  1297. end;
  1298. end;
  1299. procedure TWriter.WriteOnLoad;
  1300. var
  1301. i, j: integer;
  1302. ci: TClassInfo;
  1303. s, ss, fn: string;
  1304. d: TTypeDef;
  1305. begin
  1306. if FClasses.Count = 0 then
  1307. exit;
  1308. Fps.WriteLn;
  1309. Fps.WriteLn('function JNI_OnLoad(vm: PJavaVM; reserved: pointer): jint;' + JniCaliing);
  1310. Fps.WriteLn('const');
  1311. for i:=0 to FClasses.Count - 1 do begin
  1312. ci:=TClassInfo(FClasses.Objects[i]);
  1313. if ci.Funcs.Count = 0 then
  1314. continue;
  1315. Fps.WriteLn(Format(' _%sNativeMethods: array[0..%d] of JNINativeMethod = (', [GetClassPrefix(ci.Def, FClasses[i]), ci.Funcs.Count - 1]));
  1316. for j:=0 to ci.Funcs.Count - 1 do begin
  1317. with TProcInfo(ci.Funcs[j]) do
  1318. Fps.Write(Format(' (name: ''%s''; signature: ''%s''; fnPtr: @%s)', [Name, JniSignature, JniName]));
  1319. if j < ci.Funcs.Count - 1 then
  1320. Fps.Write(',');
  1321. Fps.WriteLn;
  1322. end;
  1323. Fps.WriteLn(' );');
  1324. end;
  1325. Fps.WriteLn;
  1326. Fps.WriteLn('var');
  1327. Fps.IncI;
  1328. Fps.WriteLn('env: PJNIEnv;');
  1329. Fps.WriteLn;
  1330. Fps.WriteLn('function _Reg(ClassName: PAnsiChar; Methods: PJNINativeMethod; Count: integer; ci: _PJavaClassInfo; const FieldName: ansistring = ''_pasobj''; const FieldSig: ansistring = ''J''): boolean;');
  1331. Fps.WriteLn('var');
  1332. Fps.WriteLn('c: jclass;', 1);
  1333. Fps.WriteLn('begin');
  1334. Fps.IncI;
  1335. Fps.WriteLn('Result:=False;');
  1336. Fps.WriteLn('c:=env^^.FindClass(env, ClassName);');
  1337. Fps.WriteLn('if c = nil then exit;');
  1338. Fps.WriteLn('Result:=(Count = 0) or (env^^.RegisterNatives(env, c, Methods, Count) = 0);');
  1339. Fps.WriteLn('if Result and (ci <> nil) then begin');
  1340. Fps.IncI;
  1341. Fps.WriteLn('ci^.ClassRef:=env^^.NewGlobalRef(env, c);');
  1342. Fps.WriteLn('Result:=ci^.ClassRef <> nil;');
  1343. Fps.WriteLn('if Result and (FieldName <> '''') then begin');
  1344. Fps.WriteLn('ci^.ObjFieldId:=env^^.GetFieldID(env, ci^.ClassRef, PAnsiChar(FieldName), PAnsiChar(FieldSig));', 1);
  1345. Fps.WriteLn('Result:=ci^.ObjFieldId <> nil;', 1);
  1346. Fps.WriteLn('end;');
  1347. Fps.DecI;
  1348. Fps.WriteLn('end;');
  1349. Fps.DecI;
  1350. Fps.WriteLn('end;');
  1351. Fps.WriteLn;
  1352. Fps.WriteLn('begin', -1);
  1353. Fps.WriteLn('Result:=JNI_ERR;');
  1354. Fps.WriteLn('if vm^^.GetEnv(vm, @env, JNI_VERSION_1_6) <> JNI_OK then exit;');
  1355. Fps.WriteLn('CurJavaVM:=vm;');
  1356. d:=TTypeDef.Create(nil, dtType);
  1357. try
  1358. d.BasicType:=btString;
  1359. s:=JNITypeSig[d.BasicType];
  1360. s:=Copy(s, 2, Length(s) - 2);
  1361. Fps.WriteLn(Format('if not _Reg(''%s'', nil, 0, @%s, '''', '''') then exit;',
  1362. [s, GetTypeInfoVar(d)]));
  1363. finally
  1364. d.Free;
  1365. end;
  1366. for i:=0 to FClasses.Count - 1 do begin
  1367. ci:=TClassInfo(FClasses.Objects[i]);
  1368. s:=GetTypeInfoVar(ci.Def);
  1369. if (s = '') or (ci.IsCommonClass) then
  1370. s:='nil'
  1371. else
  1372. s:='@' + s;
  1373. if ci.Funcs.Count = 0 then
  1374. ss:='nil'
  1375. else
  1376. ss:=Format('@_%sNativeMethods', [GetClassPrefix(ci.Def, FClasses[i])]);
  1377. fn:='';
  1378. if ci.Def <> nil then
  1379. if ci.Def.DefType in [dtSet, dtEnum] then
  1380. fn:=', ''Value'', ''I''';
  1381. Fps.WriteLn(Format('if not _Reg(''%s'', %s, %d, %s%s) then exit;',
  1382. [GetJavaClassPath(ci.Def, FClasses[i]), ss, ci.Funcs.Count, s, fn]));
  1383. end;
  1384. Fps.WriteLn('Result:=JNI_VERSION_1_6;');
  1385. Fps.DecI;
  1386. Fps.WriteLn('end;');
  1387. Fps.WriteLn;
  1388. Fps.WriteLn('exports JNI_OnLoad;');
  1389. end;
  1390. function TWriter.JniToPasType(d: TDef; const v: string; CheckNil: boolean): string;
  1391. var
  1392. n: string;
  1393. begin
  1394. Result:=v;
  1395. if d = nil then
  1396. exit;
  1397. case d.DefType of
  1398. dtType:
  1399. with TTypeDef(d) do
  1400. case BasicType of
  1401. btString, btWideString:
  1402. begin
  1403. Result:=Format('_StringFromJString(_env, %s)', [Result]);
  1404. if BasicType <> btWideString then
  1405. Result:=Format('%s(%s)', [d.Name, Result]);
  1406. end;
  1407. btBoolean:
  1408. Result:=Format('LongBool(%s)', [Result]);
  1409. btChar:
  1410. Result:=Format('char(widechar(%s))', [Result]);
  1411. btWideChar:
  1412. Result:=Format('widechar(%s)', [Result]);
  1413. btPointer:
  1414. Result:=Format('pointer(ptruint(%s))', [Result]);
  1415. btGuid:
  1416. Result:=Format('StringToGUID(ansistring(_StringFromJString(_env, %s)))', [Result]);
  1417. else
  1418. Result:=Format('%s(%s)', [d.Name, Result]);
  1419. end;
  1420. dtClass:
  1421. begin
  1422. if CheckNil then
  1423. n:='True'
  1424. else
  1425. n:='False';
  1426. Result:=Format('%s.%s(_GetPasObj(_env, %s, %s, %s))', [d.Parent.Name, d.Name, Result, GetTypeInfoVar(d), n]);
  1427. end;
  1428. dtRecord:
  1429. Result:=Format('%s.%s(_GetPasObj(_env, %s, %s, True)^)', [d.Parent.Name, d.Name, Result, GetTypeInfoVar(d)]);
  1430. dtProcType:
  1431. Result:=Format('%sGetHandler(_env, %s, %s)', [GetClassPrefix(d), Result, GetTypeInfoVar(d)]);
  1432. dtEnum:
  1433. Result:=Format('%s.%s(_GetIntObjValue(_env, %s, %s))', [d.Parent.Name, d.Name, Result, GetTypeInfoVar(d)]);
  1434. dtSet:
  1435. Result:=Format('%s.%s(%s(_GetIntObjValue(_env, %s, %s)))', [d.Parent.Name, d.Name, GetPasIntType(TSetDef(d).Size), Result, GetTypeInfoVar(d)]);
  1436. end;
  1437. end;
  1438. function TWriter.PasToJniType(d: TDef; const v: string): string;
  1439. begin
  1440. Result:=v;
  1441. if d = nil then
  1442. exit;
  1443. case d.DefType of
  1444. dtType:
  1445. with TTypeDef(d) do
  1446. case BasicType of
  1447. btString, btWideString:
  1448. Result:=Format('_StringToJString(_env, _JNIString(%s))', [Result]);
  1449. btBoolean:
  1450. Result:=Format('jboolean(LongBool(%s))', [Result]);
  1451. btChar:
  1452. Result:=Format('jchar(widechar(%s))', [Result]);
  1453. btWideChar:
  1454. Result:=Format('jchar(%s)', [Result]);
  1455. btEnum:
  1456. Result:=Format('jint(%s)', [Result]);
  1457. btPointer:
  1458. Result:=Format('ptruint(pointer(%s))', [Result]);
  1459. btGuid:
  1460. Result:=Format('_StringToJString(_env, _JNIString(GUIDToString(%s)))', [Result]);
  1461. end;
  1462. dtClass:
  1463. Result:=Format('_CreateJavaObj(_env, %s, %s)', [Result, GetTypeInfoVar(d)]);
  1464. dtRecord:
  1465. Result:=Format('_%s_CreateObj(_env, %s)', [GetClassPrefix(d), Result]);
  1466. dtProcType:
  1467. Result:=Format('_CreateMethodPtrObject(_env, TMethod(%s), %s)', [Result, GetTypeInfoVar(d)]);
  1468. dtEnum:
  1469. Result:=Format('_CreateIntObj(_env, longint(%s), %s)', [Result, GetTypeInfoVar(d)]);
  1470. dtSet:
  1471. Result:=Format('_CreateIntObj(_env, %s(%s), %s)', [GetPasIntType(TSetDef(d).Size), Result, GetTypeInfoVar(d)]);
  1472. end;
  1473. end;
  1474. function TWriter.GetTypeInfoVar(ClassDef: TDef): string;
  1475. begin
  1476. if ClassDef.DefType = dtUnit then
  1477. Result:=''
  1478. else
  1479. if ClassDef.DefType = dtType then
  1480. Result:='_Java_' + JavaType[TTypeDef(ClassDef).BasicType] + '_Info'
  1481. else
  1482. Result:='_JNI_' + ClassDef.Parent.Name + '_' + ClassDef.Name + '_Info';
  1483. end;
  1484. function TWriter.GetClassPrefix(ClassDef: TDef; const AClassName: string): string;
  1485. begin
  1486. if AClassName = '' then
  1487. Result:=ClassDef.Name
  1488. else
  1489. Result:=AClassName;
  1490. Result:=Result + '_';
  1491. if ClassDef.DefType <> dtUnit then
  1492. Result:=ClassDef.Parent.Name + '_' + Result;
  1493. Result:='JNI_' + Result;
  1494. end;
  1495. function TWriter.IsJavaSimpleType(d: TDef): boolean;
  1496. begin
  1497. Result:=(d <> nil) and (d.DefType = dtType) and (Length(JNITypeSig[TTypeDef(d).BasicType]) = 1);
  1498. end;
  1499. function TWriter.IsJavaVarParam(ParamDef: TVarDef): boolean;
  1500. begin
  1501. with ParamDef do
  1502. Result:=VarOpt * [voVar, voOut] <> [];
  1503. end;
  1504. function TWriter.GetProcDeclaration(d: TProcDef; const ProcName: string; FullTypeNames: boolean): string;
  1505. var
  1506. s, ss: string;
  1507. j: integer;
  1508. begin
  1509. with d do begin
  1510. if Count > 0 then
  1511. s:='('
  1512. else
  1513. s:='';
  1514. for j:=0 to Count - 1 do
  1515. with TVarDef(Items[j]) do begin
  1516. if j > 0 then
  1517. s:=s + '; ';
  1518. if voVar in VarOpt then
  1519. s:=s + 'var '
  1520. else
  1521. if voOut in VarOpt then
  1522. s:=s + 'out '
  1523. else
  1524. if voConst in VarOpt then
  1525. s:=s + 'const ';
  1526. s:=s + Name + ': ' + GetPasType(VarType, FullTypeNames);
  1527. end;
  1528. if Count > 0 then
  1529. s:=s + ')';
  1530. case ProcType of
  1531. ptConstructor:
  1532. ss:='constructor';
  1533. ptDestructor:
  1534. ss:='destructor';
  1535. ptProcedure:
  1536. ss:='procedure';
  1537. ptFunction:
  1538. ss:='function';
  1539. else
  1540. ss:='';
  1541. end;
  1542. if ProcType in [ptConstructor, ptFunction] then
  1543. s:=s + ': ' + GetPasType(ReturnType, FullTypeNames);
  1544. ss:=ss + ' ';
  1545. if ProcName <> '' then
  1546. ss:=ss + ProcName
  1547. else
  1548. ss:=ss + Name;
  1549. Result:=ss + s;
  1550. end;
  1551. end;
  1552. function TWriter.GetJavaProcDeclaration(d: TProcDef; const ProcName: string): string;
  1553. var
  1554. s: string;
  1555. j: integer;
  1556. vd: TVarDef;
  1557. begin
  1558. with d do begin
  1559. if ProcName <> '' then
  1560. s:=ProcName
  1561. else
  1562. s:=AliasName;
  1563. s:=DefToJavaType(ReturnType) + ' ' + s + '(';
  1564. for j:=0 to Count - 1 do begin
  1565. vd:=TVarDef(Items[j]);
  1566. with vd do begin
  1567. if j > 0 then
  1568. s:=s + ', ';
  1569. s:=s + DefToJavaType(VarType);
  1570. if IsJavaVarParam(vd) then
  1571. s:=s + '[]';
  1572. s:=s + ' ' + AliasName;
  1573. end;
  1574. end;
  1575. s:=s + ')';
  1576. end;
  1577. Result:=s;
  1578. end;
  1579. function TWriter.GetJniFuncType(d: TDef): string;
  1580. begin
  1581. if IsJavaSimpleType(d) then begin
  1582. Result:=JavaType[TTypeDef(d).BasicType];
  1583. Result[1]:=UpCase(Result[1]);
  1584. end
  1585. else
  1586. Result:='Object';
  1587. end;
  1588. function TWriter.GetJavaClassName(cls: TDef; it: TDef): string;
  1589. begin
  1590. Result:=cls.AliasName;
  1591. if (cls.DefType <> dtClass) or ((it <> nil) and not (it.DefType in ReplDefs)) then
  1592. exit;
  1593. with TClassDef(cls) do begin
  1594. if not (HasReplacedItems or ImplementsReplacedItems) then
  1595. exit;
  1596. if ImplementsReplacedItems and not HasReplacedItems then
  1597. exit;
  1598. if it <> nil then
  1599. with TReplDef(it) do begin
  1600. if (it.DefType = dtProc) and (TProcDef(it).ProcType = ptConstructor) then
  1601. exit;
  1602. if IsReplaced or IsReplImpl then
  1603. exit;
  1604. end;
  1605. end;
  1606. Result:='__' + Result;
  1607. end;
  1608. procedure TWriter.RegisterPseudoClass(d: TDef);
  1609. var
  1610. ci: TClassInfo;
  1611. begin
  1612. if FClasses.IndexOf(d.Name) < 0 then begin
  1613. ci:=TClassInfo.Create;
  1614. ci.Def:=d;
  1615. FClasses.AddObject(d.Name, ci);
  1616. end;
  1617. end;
  1618. function TWriter.GetPasIntType(Size: integer): string;
  1619. begin
  1620. case Size of
  1621. 1: Result:='byte';
  1622. 2: Result:='word';
  1623. else
  1624. Result:='cardinal';
  1625. end;
  1626. end;
  1627. function TWriter.GetPasType(d: TDef; FullName: boolean): string;
  1628. begin
  1629. Result:=d.Name;
  1630. if FullName and (d.DefType <> dtType) then
  1631. Result:=d.Parent.Name + '.' + Result;
  1632. end;
  1633. function TWriter.AddCustomProc(ParentDef: TDef; const JniName, Name: string; RetType: TBasicType; const Params: array of TBasicType): TProcDef;
  1634. var
  1635. i: integer;
  1636. vd: TVarDef;
  1637. begin
  1638. Result:=TProcDef.Create(ParentDef, dtProc);
  1639. Result.Name:=JniName;
  1640. Result.AliasName:=Name;
  1641. if RetType = btVoid then
  1642. Result.ProcType:=ptProcedure
  1643. else
  1644. Result.ProcType:=ptFunction;
  1645. for i:=0 to High(Params) do begin
  1646. vd:=TVarDef.Create(Result, dtParam);
  1647. vd.Name:=Format('p%d', [i + 1]);
  1648. vd.VarType:=TTypeDef.Create(vd, dtType);
  1649. TTypeDef(vd.VarType).BasicType:=Params[i];
  1650. end;
  1651. Result.ReturnType:=TTypeDef.Create(ParentDef, dtType);
  1652. TTypeDef(Result.ReturnType).BasicType:=RetType;
  1653. end;
  1654. procedure TWriter.AddNativeMethod(ParentDef: TDef; const JniName, Name, Signature: string);
  1655. var
  1656. i: integer;
  1657. ci: TClassInfo;
  1658. pi: TProcInfo;
  1659. begin
  1660. pi:=TProcInfo.Create;
  1661. pi.Name:=Name;
  1662. pi.JniName:=JniName;
  1663. pi.JniSignature:=Signature;
  1664. i:=FClasses.IndexOf(ParentDef.AliasName);
  1665. if i < 0 then begin
  1666. ci:=TClassInfo.Create;
  1667. ci.Def:=ParentDef;
  1668. i:=FClasses.AddObject(ParentDef.AliasName, ci);
  1669. end;
  1670. TClassInfo(FClasses.Objects[i]).Funcs.Add(pi);
  1671. end;
  1672. function TWriter.GetProcSignature(d: TProcDef): string;
  1673. var
  1674. j: integer;
  1675. vd: TVarDef;
  1676. begin
  1677. Result:='(';
  1678. for j:=0 to d.Count - 1 do begin
  1679. vd:=TVarDef(d[j]);
  1680. with vd do begin
  1681. if IsJavaVarParam(vd) then
  1682. Result:=Result + '[';
  1683. Result:=Result + DefToJniSig(VarType);
  1684. end;
  1685. end;
  1686. Result:=Result + ')' + DefToJniSig(d.ReturnType);
  1687. end;
  1688. procedure TWriter.EHandlerStart;
  1689. begin
  1690. Fps.WriteLn('try');
  1691. Fps.IncI;
  1692. end;
  1693. procedure TWriter.EHandlerEnd(const EnvVarName: string; const ExtraCode: string);
  1694. begin
  1695. Fps.WriteLn('except', -1);
  1696. Fps.WriteLn(Format('_HandleJNIException(%s);', [EnvVarName]));
  1697. if ExtraCode <> '' then
  1698. Fps.WriteLn(ExtraCode);
  1699. Fps.DecI;
  1700. Fps.WriteLn('end;');
  1701. end;
  1702. procedure TWriter.WriteClassInfoVar(d: TDef);
  1703. begin
  1704. Fps.WriteLn;
  1705. Fps.WriteLn(Format('var %s: _TJavaClassInfo;', [GetTypeInfoVar(d)]));
  1706. end;
  1707. procedure TWriter.WriteComment(d: TDef; const AType: string);
  1708. begin
  1709. Fps.WriteLn;
  1710. Fps.WriteLn(Format('{ %s }', [d.Name]));
  1711. Fjs.WriteLn(Format('/* %s %s */', [AType, d.Name]));
  1712. {$ifdef DEBUG}
  1713. Fjs.WriteLn(Format('/* Ref count: %d */', [d.RefCnt]));
  1714. {$endif}
  1715. end;
  1716. {
  1717. procedure TWriter.AddCustomProc(ParentDef: TDef; const JniName, Name: string; RetType: TBasicType; const Params: array of TBasicType);
  1718. var
  1719. i: integer;
  1720. ci: TClassInfo;
  1721. pi: TProcInfo;
  1722. begin
  1723. pi:=TProcInfo.Create;
  1724. pi.Name:=Name;
  1725. pi.JniName:=JniName;
  1726. pi.JniSignature:='(';
  1727. for i:=0 to High(Params) do
  1728. pi.JniSignature:=pi.JniSignature + JNITypeSig[Params[i]];
  1729. pi.JniSignature:=pi.JniSignature + ')';
  1730. pi.JniSignature:=pi.JniSignature + JNITypeSig[RetType];
  1731. i:=FClasses.IndexOf(ParentDef.Name);
  1732. if i < 0 then begin
  1733. ci:=TClassInfo.Create;
  1734. ci.Def:=ParentDef;
  1735. i:=FClasses.AddObject(ParentDef.Name, ci);
  1736. end;
  1737. TClassInfo(FClasses.Objects[i]).Funcs.Add(pi);
  1738. end;
  1739. }
  1740. constructor TWriter.Create;
  1741. var
  1742. i: integer;
  1743. begin
  1744. Units:=TStringList.Create;
  1745. FClasses:=TStringList.Create;
  1746. FClasses.Sorted:=True;
  1747. JavaPackage:='pas';
  1748. IncludeList:=TStringList.Create;
  1749. IncludeList.Duplicates:=dupIgnore;
  1750. ExcludeList:=TStringList.Create;
  1751. ExcludeList.Duplicates:=dupIgnore;
  1752. for i:=Low(ExcludeStd) to High(ExcludeStd) do
  1753. ExcludeList.Add(ExcludeStd[i]);
  1754. for i:=Low(ExcludeDelphi7) to High(ExcludeDelphi7) do
  1755. ExcludeList.Add(ExcludeDelphi7[i]);
  1756. FThisUnit:=TUnitDef.Create(nil, dtUnit);
  1757. end;
  1758. destructor TWriter.Destroy;
  1759. var
  1760. i: integer;
  1761. begin
  1762. for i:=0 to FClasses.Count - 1 do
  1763. FClasses.Objects[i].Free;
  1764. FClasses.Free;
  1765. Units.Free;
  1766. IncludeList.Free;
  1767. ExcludeList.Free;
  1768. FThisUnit.Free;
  1769. inherited Destroy;
  1770. end;
  1771. procedure TWriter.ProcessUnits;
  1772. var
  1773. p: TPPUParser;
  1774. i: integer;
  1775. s, ss: string;
  1776. d: TDef;
  1777. begin
  1778. if Units.Count = 0 then
  1779. raise Exception.Create('No unit name specified.');
  1780. if (OutPath <> '') and not DirectoryExists(OutPath) then
  1781. raise Exception.CreateFmt('Output path "%s" does not exist.', [OutPath]);
  1782. if (JavaOutPath <> '') and not DirectoryExists(JavaOutPath) then
  1783. raise Exception.CreateFmt('Output path "%s" does not exist.', [JavaOutPath]);
  1784. if LibName = '' then
  1785. LibName:=AnsiLowerCase(ChangeFileExt(Units[0], '')) + 'jni';
  1786. for i:=0 to IncludeList.Count - 1 do
  1787. IncludeList[i]:=Trim(IncludeList[i]);
  1788. IncludeList.Sorted:=True;
  1789. for i:=0 to ExcludeList.Count - 1 do
  1790. ExcludeList[i]:=Trim(ExcludeList[i]);
  1791. ExcludeList.Sorted:=True;
  1792. FThisUnit.Name:=LibName;
  1793. FThisUnit.AliasName:='system';
  1794. p:=TPPUParser.Create(SearchPath);
  1795. try
  1796. p.OnCheckItem:=@DoCheckItem;
  1797. for i:=0 to Units.Count - 1 do
  1798. IncludeList.Add(ChangeFileExt(ExtractFileName(Units[i]), ''));
  1799. for i:=0 to Units.Count - 1 do
  1800. p.Parse(ChangeFileExt(ExtractFileName(Units[i]), ''));
  1801. if OutPath <> '' then
  1802. OutPath:=IncludeTrailingPathDelimiter(OutPath);
  1803. if JavaOutPath <> '' then
  1804. JavaOutPath:=IncludeTrailingPathDelimiter(JavaOutPath);
  1805. FPkgDir:=JavaOutPath + StringReplace(JavaPackage, '.', DirectorySeparator, [rfReplaceAll]);
  1806. ForceDirectories(FPkgDir);
  1807. Fps:=TTextOutStream.Create(OutPath + LibName + '.pas', fmCreate);
  1808. Fps.WriteLn('library '+ LibName + ';');
  1809. Fps.WriteLn('{$ifdef fpc} {$mode objfpc} {$H+} {$endif}');
  1810. Fps.WriteLn;
  1811. Fps.WriteLn('uses');
  1812. Fps.WriteLn('{$ifndef FPC} Windows, {$endif} {$ifdef unix} cthreads, {$endif} SysUtils, SyncObjs,', 1);
  1813. s:='';
  1814. for i:=0 to p.Units.Count - 1 do begin
  1815. ProcessRules(p.Units[i]);
  1816. ss:=LowerCase(p.Units[i].Name);
  1817. if (ss ='system') or (ss = 'objpas') or (ss = 'sysutils') or (ss = 'syncobjs') or (ss = 'jni') then
  1818. continue;
  1819. if s <> '' then
  1820. s:=s + ', ';
  1821. s:=s + p.Units[i].Name;
  1822. end;
  1823. Fps.WriteLn(s + ', jni;', 1);
  1824. // Types
  1825. Fps.WriteLn;
  1826. Fps.WriteLn('type');
  1827. Fps.IncI;
  1828. Fps.WriteLn('_JNIString = {$ifdef FPC} unicodestring {$else} widestring {$endif};');
  1829. Fps.WriteLn('{$ifndef FPC} ptruint = cardinal; {$endif}');
  1830. Fps.WriteLn;
  1831. Fps.WriteLn('_TJavaClassInfo = record');
  1832. Fps.WriteLn('ClassRef: JClass;', 1);
  1833. Fps.WriteLn('ObjFieldId: JFieldId;', 1);
  1834. Fps.WriteLn('end;');
  1835. Fps.WriteLn('_PJavaClassInfo = ^_TJavaClassInfo;');
  1836. Fps.DecI;
  1837. Fps.WriteLn;
  1838. d:=TtypeDef.Create(nil, dtType);
  1839. TtypeDef(d).BasicType:=btString;
  1840. Fps.WriteLn(Format('var %s: _TJavaClassInfo;', [GetTypeInfoVar(d)]));
  1841. d.Free;
  1842. // Support functions
  1843. Fps.WriteLn;
  1844. Fps.WriteLn('function _StringFromJString(env: PJNIEnv; s: jstring): _JNIString;');
  1845. Fps.WriteLn('var');
  1846. Fps.WriteLn('p: PJChar;', 1);
  1847. Fps.WriteLn('c: JBoolean;', 1);
  1848. Fps.WriteLn('begin');
  1849. Fps.WriteLn('if s = nil then begin', 1);
  1850. Fps.WriteLn('Result:='''';', 2);
  1851. Fps.WriteLn('exit;', 2);
  1852. Fps.WriteLn('end;', 1);
  1853. Fps.WriteLn('p:=env^^.GetStringChars(env, s, c);', 1);
  1854. Fps.WriteLn('SetString(Result, PWideChar(p), env^^.GetStringLength(env, s));', 1);
  1855. Fps.WriteLn('env^^.ReleaseStringChars(env, s, p);', 1);
  1856. Fps.WriteLn('end;');
  1857. Fps.WriteLn;
  1858. Fps.WriteLn('function _StringToJString(env: PJNIEnv; const s: _JNIString): jstring;');
  1859. Fps.WriteLn('begin');
  1860. Fps.WriteLn('Result:=env^^.NewString(env, PJChar(PWideChar(s)), Length(s));', 1);
  1861. Fps.WriteLn('end;');
  1862. Fps.WriteLn;
  1863. Fps.WriteLn('function _CreateJavaObj(env: PJNIEnv; PasObj: pointer; const ci: _TJavaClassInfo): jobject;');
  1864. Fps.WriteLn('begin');
  1865. Fps.IncI;
  1866. Fps.WriteLn('Result:=nil;');
  1867. Fps.WriteLn('if PasObj = nil then exit;');
  1868. Fps.WriteLn('Result:=env^^.AllocObject(env, ci.ClassRef);');
  1869. Fps.WriteLn('if Result = nil then exit;');
  1870. Fps.WriteLn('env^^.SetLongField(env, Result, ci.ObjFieldId, Int64(ptruint(PasObj)));');
  1871. Fps.DecI;
  1872. Fps.WriteLn('end;');
  1873. Fps.WriteLn;
  1874. Fps.WriteLn('function _GetPasObj(env: PJNIEnv; jobj: jobject; const ci: _TJavaClassInfo; CheckNil: boolean): pointer;');
  1875. Fps.WriteLn('var pasobj: jlong;');
  1876. Fps.WriteLn('begin');
  1877. Fps.IncI;
  1878. Fps.WriteLn('if jobj <> nil then');
  1879. Fps.WriteLn('pasobj:=env^^.GetLongField(env, jobj, ci.ObjFieldId)', 1);
  1880. Fps.WriteLn('else');
  1881. Fps.WriteLn('pasobj:=0;', 1);
  1882. Fps.WriteLn('if CheckNil and (pasobj = 0) then');
  1883. Fps.WriteLn('raise Exception.Create(''Attempt to access a released Pascal object.'');', 1);
  1884. Fps.WriteLn('Result:=pointer(ptruint(pasobj));');
  1885. Fps.DecI;
  1886. Fps.WriteLn('end;');
  1887. Fps.WriteLn;
  1888. Fps.WriteLn('procedure _HandleJNIException(env: PJNIEnv);');
  1889. Fps.WriteLn('begin');
  1890. Fps.WriteLn('env^^.ThrowNew(env, env^^.FindClass(env, ''java/lang/Exception''), PAnsiChar(Utf8Encode(Exception(ExceptObject).Message)));', 1);
  1891. Fps.WriteLn('end;');
  1892. Fps.WriteLn;
  1893. Fps.WriteLn('procedure _RaiseVarParamException(const VarName: string);');
  1894. Fps.WriteLn('begin');
  1895. Fps.WriteLn('raise Exception.CreateFmt(''An array with only single element must be passed as parameter "%s".'', [VarName]);', 1);
  1896. Fps.WriteLn('end;');
  1897. Fps.WriteLn;
  1898. Fps.WriteLn('function _AllocMemory(env: PJNIEnv; jobj: jobject; size: jint): jlong;');
  1899. Fps.WriteLn('var p: pointer;');
  1900. Fps.WriteLn('begin');
  1901. Fps.WriteLn('GetMem(p, size);', 1);
  1902. Fps.WriteLn('FillChar(p^, size, 0);', 1);
  1903. Fps.WriteLn('Result:=ptruint(p);', 1);
  1904. Fps.WriteLn('end;');
  1905. // Method pointer support
  1906. Fps.WriteLn;
  1907. Fps.WriteLn('type');
  1908. Fps.IncI;
  1909. Fps.WriteLn('_TMethodPtrInfo = class');
  1910. Fps.IncI;
  1911. Fps.WriteLn('Obj: JObject;');
  1912. Fps.WriteLn('MethodId: JMethodID;');
  1913. Fps.WriteLn('Index, RefCnt: integer;');
  1914. Fps.WriteLn('RealMethod: TMethod;');
  1915. Fps.WriteLn('constructor Create(env: PJNIEnv; JavaObj: JObject; const AMethodName, AMethodSig: ansistring);');
  1916. Fps.WriteLn('procedure Release(env: PJNIEnv);');
  1917. Fps.DecI;
  1918. Fps.WriteLn('end;');
  1919. Fps.DecI;
  1920. Fps.WriteLn;
  1921. Fps.WriteLn('var _MethodPointers: array of _TMethodPtrInfo;');
  1922. Fps.WriteLn('var _MethodPointersCS: TCriticalSection;');
  1923. Fps.WriteLn;
  1924. Fps.WriteLn('constructor _TMethodPtrInfo.Create(env: PJNIEnv; JavaObj: JObject; const AMethodName, AMethodSig: ansistring);');
  1925. Fps.WriteLn('var c: JClass;');
  1926. Fps.WriteLn('begin');
  1927. Fps.IncI;
  1928. Fps.WriteLn('RefCnt:=1;');
  1929. Fps.WriteLn('if (JavaObj = nil) or (AMethodName = '''') then exit;');
  1930. Fps.WriteLn('c:=env^^.GetObjectClass(env, JavaObj);');
  1931. Fps.WriteLn('if c = nil then exit;');
  1932. Fps.WriteLn('MethodId:=env^^.GetMethodID(env, c, PAnsiChar(AMethodName), PAnsiChar(AMethodSig));');
  1933. Fps.WriteLn('if MethodId = nil then raise Exception.CreateFmt(''Method "%s" does not exist or has wrong parameters.'', [AMethodName]);');
  1934. Fps.WriteLn('Obj:=env^^.NewGlobalRef(env, JavaObj);');
  1935. Fps.WriteLn('_MethodPointersCS.Enter;');
  1936. Fps.WriteLn('try');
  1937. Fps.IncI;
  1938. Fps.WriteLn('Index:=Length(_MethodPointers) + 1;');
  1939. Fps.WriteLn(Format('if Index > %d then raise Exception.Create(''Too many method pointers.'');', [MaxMethodPointers]));
  1940. Fps.WriteLn('SetLength(_MethodPointers, Index);');
  1941. Fps.WriteLn('_MethodPointers[Index - 1]:=Self;');
  1942. Fps.WriteLn('finally', -1);
  1943. Fps.WriteLn('_MethodPointersCS.Leave;');
  1944. Fps.DecI;
  1945. Fps.WriteLn('end;');
  1946. Fps.DecI;
  1947. Fps.WriteLn('end;');
  1948. Fps.WriteLn;
  1949. Fps.WriteLn('procedure _TMethodPtrInfo.Release(env: PJNIEnv);');
  1950. Fps.WriteLn('var i: integer;');
  1951. Fps.WriteLn('begin');
  1952. Fps.IncI;
  1953. Fps.WriteLn('i:=InterlockedDecrement(RefCnt);');
  1954. Fps.WriteLn('if i <> 0 then exit;');
  1955. Fps.WriteLn('if Index > 0 then begin');
  1956. Fps.IncI;
  1957. Fps.WriteLn('_MethodPointersCS.Enter;');
  1958. Fps.WriteLn('try');
  1959. Fps.IncI;
  1960. Fps.WriteLn('Dec(Index);');
  1961. Fps.WriteLn('_MethodPointers[Index]:=nil;');
  1962. Fps.WriteLn('Index:=Length(_MethodPointers);');
  1963. Fps.WriteLn('while (Index > 0) and (_MethodPointers[Index] = nil) do Dec(Index);');
  1964. Fps.WriteLn('SetLength(_MethodPointers, Index + 1);');
  1965. Fps.WriteLn('finally', -1);
  1966. Fps.WriteLn('_MethodPointersCS.Leave;');
  1967. Fps.DecI;
  1968. Fps.WriteLn('end;');
  1969. Fps.WriteLn('env^^.DeleteGlobalRef(env, Obj);');
  1970. Fps.DecI;
  1971. Fps.WriteLn('end;');
  1972. Fps.WriteLn('Self.Destroy;');
  1973. Fps.DecI;
  1974. Fps.WriteLn('end;');
  1975. Fps.WriteLn;
  1976. Fps.WriteLn('procedure _RefMethodPtr(env: PJNIEnv; const m: TMethod; AddRef: boolean);');
  1977. Fps.WriteLn('var i: integer;');
  1978. Fps.WriteLn('begin');
  1979. Fps.IncI;
  1980. Fps.WriteLn('i:=-integer(ptruint(m.Data));');
  1981. Fps.WriteLn(Format('if (i < 1) or (i > %d) then exit;', [MaxMethodPointers]));
  1982. Fps.WriteLn('_MethodPointersCS.Enter;');
  1983. Fps.WriteLn('try');
  1984. Fps.IncI;
  1985. Fps.WriteLn('with _MethodPointers[i - 1] do');
  1986. Fps.WriteLn('if AddRef then InterlockedIncrement(RefCnt) else Release(env);', 1);
  1987. Fps.WriteLn('finally', -1);
  1988. Fps.WriteLn('_MethodPointersCS.Leave;');
  1989. Fps.DecI;
  1990. Fps.WriteLn('end;');
  1991. Fps.DecI;
  1992. Fps.WriteLn('end;');
  1993. Fps.WriteLn;
  1994. Fps.WriteLn('function _CreateMethodPtrObject(env: PJNIEnv; const m: TMethod; const ci: _TJavaClassInfo): jobject;');
  1995. Fps.WriteLn('var i: integer;');
  1996. Fps.WriteLn('var mpi: _TMethodPtrInfo;');
  1997. Fps.WriteLn('begin');
  1998. Fps.IncI;
  1999. Fps.WriteLn('_MethodPointersCS.Enter;');
  2000. Fps.WriteLn('try');
  2001. Fps.IncI;
  2002. Fps.WriteLn('i:=-integer(ptruint(m.Data));');
  2003. Fps.WriteLn(Format('if (i > 0) and (i <= %d) then begin', [MaxMethodPointers]));
  2004. Fps.WriteLn('mpi:=_MethodPointers[i - 1];', 1);
  2005. Fps.WriteLn('InterlockedIncrement(mpi.RefCnt);', 1);
  2006. Fps.WriteLn('end');
  2007. Fps.WriteLn('else begin');
  2008. Fps.WriteLn('mpi:=_TMethodPtrInfo.Create(env, nil, '''', '''');', 1);
  2009. Fps.WriteLn('mpi.RealMethod:=m;', 1);
  2010. Fps.WriteLn('end;');
  2011. Fps.WriteLn('finally', -1);
  2012. Fps.WriteLn('_MethodPointersCS.Leave;');
  2013. Fps.DecI;
  2014. Fps.WriteLn('end;');
  2015. Fps.WriteLn('Result:=_CreateJavaObj(env, pointer(mpi), ci);');
  2016. Fps.DecI;
  2017. Fps.WriteLn('end;');
  2018. // Set support
  2019. Fps.WriteLn;
  2020. Fps.WriteLn('function _GetIntObjValue(env: PJNIEnv; jobj: jobject; const ci: _TJavaClassInfo): longint;');
  2021. Fps.WriteLn('begin');
  2022. Fps.IncI;
  2023. Fps.WriteLn('if jobj = nil then raise Exception.Create(''Attempt to access a NULL set.'');');
  2024. Fps.WriteLn('Result:=env^^.GetIntField(env, jobj, ci.ObjFieldId);');
  2025. Fps.DecI;
  2026. Fps.WriteLn('end;');
  2027. Fps.WriteLn;
  2028. Fps.WriteLn('function _CreateIntObj(env: PJNIEnv; Value: longint; const ci: _TJavaClassInfo): jobject;');
  2029. Fps.WriteLn('begin');
  2030. Fps.IncI;
  2031. Fps.WriteLn('Result:=nil;');
  2032. Fps.WriteLn('Result:=env^^.AllocObject(env, ci.ClassRef);');
  2033. Fps.WriteLn('if Result = nil then exit;');
  2034. Fps.WriteLn('env^^.SetIntField(env, Result, ci.ObjFieldId, Value);');
  2035. Fps.DecI;
  2036. Fps.WriteLn('end;');
  2037. // Write units
  2038. for i:=0 to p.Units.Count - 1 do
  2039. with TUnitDef(p.Units[i]) do begin
  2040. WriteUnit(TUnitDef(p.Units[i]));
  2041. end;
  2042. WriteOnLoad;
  2043. Fps.WriteLn;
  2044. Fps.WriteLn('begin');
  2045. Fps.WriteLn('IsMultiThread:=True;', 1);
  2046. Fps.WriteLn('_MethodPointersCS:=TCriticalSection.Create;', 1);
  2047. Fps.WriteLn('end.');
  2048. finally
  2049. Fps.Free;
  2050. p.Free;
  2051. end;
  2052. end;
  2053. end.