writer.pas 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304
  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.Count > 0 then begin
  722. ASSERT(Count >= 1);
  723. i:=Variable.Count;
  724. ss:='';
  725. for j:=0 to Variable.Count - 1 do begin
  726. if ss <> '' then
  727. ss:=ss + ', ';
  728. ss:=ss + JniToPasType(TVarDef(Items[j]).VarType, Items[j].Name, False);
  729. end;
  730. s:=Format('%s[%s]', [s, ss]);
  731. end
  732. else
  733. i:=0;
  734. if ProcType = ptProcedure then begin
  735. ASSERT(Count = i + 1);
  736. if Variable.VarType.DefType = dtProcType then begin
  737. Fps.WriteLn(Format('_RefMethodPtr(_env, TMethod(%s), False);', [s]));
  738. ss:=Format('_RefMethodPtr(_env, TMethod(%s), True);', [s]);
  739. end;
  740. s:=s + ':=' + JniToPasType(TVarDef(Items[i]).VarType, Items[i].Name, False);
  741. end;
  742. end;
  743. if ProcType in [ptFunction, ptConstructor] then
  744. s:='Result:=' + PasToJniType(ReturnType, s);
  745. s:=s + ';';
  746. Fps.WriteLn(s);
  747. if (Variable <> nil) and UseTempObjVar then
  748. Fps.WriteLn(ss);
  749. // Return var/out parameters
  750. if tempvars <> nil then begin
  751. for i:=0 to tempvars.Count - 1 do begin
  752. vd:=TVarDef(tempvars.Objects[i]);
  753. if IsJavaSimpleType(vd.VarType) then
  754. Fps.WriteLn(Format('%s_arr^:=%s;', [tempvars[i], PasToJniType(vd.VarType, tempvars[i])]))
  755. else
  756. Fps.WriteLn(Format('_env^^.SetObjectArrayElement(_env, %s, 0, %s);', [vd.Name, PasToJniType(vd.VarType, tempvars[i])]));
  757. end;
  758. end;
  759. if IsTObject and ( (ProcType = ptDestructor) or (CompareText(Name, 'Free') = 0) ) then
  760. Fps.WriteLn(Format('_env^^.SetLongField(_env, _jobj, %s.ObjFieldId, 0);', [GetTypeInfoVar(d.Parent)]));
  761. if tf then begin
  762. Fps.WriteLn('finally', -1);
  763. if tempvars <> nil then begin
  764. for i:=0 to tempvars.Count - 1 do begin
  765. vd:=TVarDef(tempvars.Objects[i]);
  766. if IsJavaSimpleType(vd.VarType) then
  767. Fps.WriteLn(Format('_env^^.Release%sArrayElements(_env, %s, %s_arr, 0);', [JavaType[TTypeDef(vd.VarType).BasicType], vd.Name, tempvars[i]]));
  768. end;
  769. end;
  770. Fps.DecI;
  771. Fps.WriteLn('end;');
  772. end;
  773. s:='';
  774. if ProcType in [ptFunction, ptConstructor] then begin
  775. s:='0';
  776. if (ReturnType.DefType = dtType) and (TTypeDef(ReturnType).BasicType <= btDouble) then
  777. s:='0'
  778. else
  779. s:=Format('%s(0)', [DefToJniType(ReturnType, err)]);
  780. s:='Result:=' + s + ';';
  781. end;
  782. EHandlerEnd('_env', s);
  783. Fps.DecI;
  784. Fps.WriteLn('end;');
  785. AParent:=d.Parent;
  786. end
  787. else
  788. ClassIdx:=FClasses.IndexOf(GetJavaClassName(AParent, ItemDef));
  789. if ClassIdx < 0 then begin
  790. ci:=TClassInfo.Create;
  791. ci.Def:=AParent;
  792. s:=GetJavaClassName(AParent, ItemDef);
  793. ci.IsCommonClass:=s <> AParent.Name;
  794. ClassIdx:=FClasses.AddObject(s, ci);
  795. end;
  796. TClassInfo(FClasses.Objects[ClassIdx]).Funcs.Add(pi);
  797. pi:=nil;
  798. // Java part
  799. s:=GetJavaProcDeclaration(d) + ';';
  800. if (Parent.DefType = dtUnit) or (ProcType = ptConstructor) then
  801. s:='static ' + s;
  802. if Variable = nil then
  803. Fjs.WriteLn('// ' + GetProcDeclaration(d));
  804. if poPrivate in ProcOpt then
  805. ss:='private'
  806. else
  807. if poProtected in ProcOpt then
  808. ss:='protected'
  809. else
  810. ss:='public';
  811. Fjs.WriteLn(ss + ' native ' + s);
  812. finally
  813. pi.Free;
  814. tempvars.Free;
  815. end;
  816. end;
  817. procedure TWriter.WriteVar(d: TVarDef; AParent: TDef);
  818. var
  819. pd: TProcDef;
  820. vd: TVarDef;
  821. t: TTypeDef;
  822. s: string;
  823. i: integer;
  824. begin
  825. if not d.IsUsed then
  826. exit;
  827. if d.VarType <> nil then begin
  828. case d.DefType of
  829. dtVar:
  830. s:='var';
  831. dtProp:
  832. s:='property';
  833. else
  834. s:='';
  835. end;
  836. s:=Trim(s + ' ' + d.Name);
  837. if d.Count > 0 then
  838. s:=s + '[]';
  839. Fjs.WriteLn(Format('// %s: %s', [s, d.VarType.Name]));
  840. end;
  841. if voRead in d.VarOpt then begin
  842. pd:=TProcDef.Create(nil, dtProc);
  843. try
  844. pd.IsUsed:=True;
  845. pd.Parent:=d.Parent;
  846. pd.ProcType:=ptFunction;
  847. pd.Name:='get' + d.Name;
  848. pd.ReturnType:=d.VarType;
  849. if d.DefType = dtProp then begin
  850. for i:=0 to d.Count - 1 do begin
  851. vd:=TVarDef(d.Items[i]);
  852. with TVarDef.Create(pd, dtParam) do begin
  853. Name:=vd.Name;
  854. VarType:=vd.VarType;
  855. VarOpt:=[voRead];
  856. end;
  857. end;
  858. end;
  859. WriteProc(pd, d, AParent);
  860. finally
  861. pd.Free;
  862. end;
  863. end;
  864. if voWrite in d.VarOpt then begin
  865. pd:=TProcDef.Create(nil, dtProc);
  866. try
  867. pd.IsUsed:=True;
  868. pd.Parent:=d.Parent;
  869. pd.ProcType:=ptProcedure;
  870. pd.Name:='set' + d.Name;
  871. s:='Value';
  872. if d.DefType = dtProp then begin
  873. for i:=0 to d.Count - 1 do begin
  874. vd:=TVarDef(d.Items[i]);
  875. with TVarDef.Create(pd, dtParam) do begin
  876. Name:=vd.Name;
  877. VarType:=vd.VarType;
  878. VarOpt:=[voRead];
  879. end;
  880. end;
  881. // Check if the name of value parameter is unique
  882. i:=0;
  883. while i < d.Count do begin
  884. if AnsiCompareText(s, d.Items[i].Name) = 0 then begin
  885. i:=0;
  886. s:='_' + s;
  887. continue;
  888. end;
  889. Inc(i);
  890. end;
  891. end;
  892. with TVarDef.Create(pd, dtParam) do begin
  893. Name:='_' + s;
  894. AliasName:=s;
  895. VarType:=d.VarType;
  896. VarOpt:=[voRead];
  897. end;
  898. t:=TTypeDef.Create(nil, dtType);
  899. try
  900. t.BasicType:=btVoid;
  901. pd.ReturnType:=t;
  902. WriteProc(pd, d, AParent);
  903. finally
  904. t.Free;
  905. end;
  906. finally
  907. pd.Free;
  908. end;
  909. end;
  910. end;
  911. procedure TWriter.WriteConst(d: TConstDef);
  912. var
  913. s, v: string;
  914. begin
  915. if not d.IsUsed then
  916. exit;
  917. v:=d.Value;
  918. if d.VarType = nil then begin
  919. if Copy(d.Value, 1, 1) = '"' then
  920. s:='String'
  921. else
  922. s:='double';
  923. end
  924. else begin
  925. s:=DefToJavaType(d.VarType);
  926. if d.VarType.DefType = dtType then
  927. case TTypeDef(d.VarType).BasicType of
  928. btLongWord, btInt64:
  929. v:=v + 'L';
  930. btBoolean:
  931. if v = '1' then
  932. v:='true'
  933. else
  934. v:='false';
  935. end;
  936. end;
  937. Fjs.WriteLn(Format('public static final %s %s = %s;', [s, d.Name, v]));
  938. end;
  939. procedure TWriter.WriteEnum(d: TDef);
  940. var
  941. i: integer;
  942. s: string;
  943. begin
  944. if not d.IsUsed then
  945. exit;
  946. RegisterPseudoClass(d);
  947. WriteComment(d, 'enum');
  948. Fjs.WriteLn(Format('public static class %s extends system.Enum {', [d.Name]));
  949. Fjs.IncI;
  950. for i:=0 to d.Count - 1 do begin
  951. s:=Format('public final static int %s = %s;', [d[i].Name, TConstDef(d[i]).Value]);
  952. Fjs.WriteLn(s);
  953. end;
  954. Fjs.WriteLn;
  955. Fjs.WriteLn(Format('public %s(int v) { Value = v; }', [d.Name]));
  956. Fjs.WriteLn(Format('@Override public boolean equals(Object o) { return ((o instanceof %0:s) && Value == ((%0:s)o).Value) || super.equals(o); }', [d.Name]));
  957. Fjs.DecI;
  958. Fjs.WriteLn('}');
  959. Fjs.WriteLn;
  960. end;
  961. procedure TWriter.WriteProcType(d: TProcDef; PreInfo: boolean);
  962. procedure _AccessSimpleArray(vd: TVarDef; VarIndex: integer; DoSet: boolean);
  963. begin
  964. with vd do begin
  965. Fps.WriteLn(Format('_tmp_%s:=_env^^.Get%sArrayElements(_env, _args[%d].L, PJBoolean(nil)^);', [Name, GetJniFuncType(VarType), VarIndex]));
  966. Fps.WriteLn(Format('if _tmp_%s <> nil then', [Name]));
  967. if DoSet then
  968. Fps.WriteLn(Format('_tmp_%s^:=%s;', [Name, PasToJniType(VarType, Name)]), 1)
  969. else
  970. Fps.WriteLn(Format('%s:=%s;', [Name, JniToPasType(VarType, '_tmp_' + Name + '^', False)]), 1);
  971. Fps.WriteLn(Format('_env^^.Release%sArrayElements(_env, _args[%d].L, _tmp_%s, 0);', [GetJniFuncType(VarType), VarIndex, Name]));
  972. end;
  973. end;
  974. var
  975. vd: TVarDef;
  976. i: integer;
  977. s, ss, hclass: string;
  978. err: boolean;
  979. begin
  980. if not d.IsUsed or not (poMethodPtr in d.ProcOpt) then
  981. exit;
  982. if PreInfo then begin
  983. WriteClassInfoVar(d);
  984. // Handler proc
  985. hclass:=GetClassPrefix(d) + 'Class';
  986. Fps.WriteLn;
  987. Fps.WriteLn(Format('type %s = class', [hclass]));
  988. Fps.WriteLn(Format('private %s;', [ GetProcDeclaration(d, 'Handler', True)]), 1);
  989. Fps.WriteLn('end;');
  990. Fps.WriteLn;
  991. Fps.WriteLn(GetProcDeclaration(d, Format('%s.Handler', [hclass]), True) + ';');
  992. Fps.WriteLn('var');
  993. Fps.IncI;
  994. Fps.WriteLn('_env: PJNIEnv;');
  995. Fps.WriteLn('_mpi: _TMethodPtrInfo;');
  996. if d.Count > 0 then begin
  997. Fps.WriteLn(Format('_args: array[0..%d] of jvalue;', [d.Count - 1]));
  998. for i:=0 to d.Count - 1 do begin
  999. vd:=TVarDef(d[i]);
  1000. with vd do
  1001. if IsJavaVarParam(vd) and IsJavaSimpleType(VarType) then
  1002. Fps.WriteLn(Format('_tmp_%s: P%s;', [Name, DefToJniType(VarType, err)]));
  1003. end;
  1004. end;
  1005. Fps.DecI;
  1006. Fps.WriteLn('begin');
  1007. Fps.IncI;
  1008. Fps.WriteLn('CurJavaVM^^.GetEnv(CurJavaVM, @_env, JNI_VERSION_1_6);');
  1009. Fps.WriteLn('_MethodPointersCS.Enter;');
  1010. Fps.WriteLn('try');
  1011. Fps.WriteLn('_mpi:=_TMethodPtrInfo(_MethodPointers[-integer(ptruint(Self)) - 1]);', 1);
  1012. Fps.WriteLn('finally');
  1013. Fps.WriteLn('_MethodPointersCS.Leave;', 1);
  1014. Fps.WriteLn('end;');
  1015. for i:=0 to d.Count - 1 do begin
  1016. vd:=TVarDef(d[i]);
  1017. with vd do begin
  1018. if not IsJavaVarParam(vd) then begin
  1019. s:='L';
  1020. if VarType.DefType = dtType then
  1021. s:=Copy(JNITypeSig[TTypeDef(VarType).BasicType], 1, 1);
  1022. ss:=PasToJniType(VarType, Name);
  1023. end
  1024. else begin
  1025. s:='L';
  1026. if IsJavaSimpleType(VarType) then
  1027. ss:=Format('_env^^.New%sArray(_env, 1)', [GetJniFuncType(VarType)])
  1028. else begin
  1029. if voVar in VarOpt then
  1030. ss:=PasToJniType(VarType, Name)
  1031. else
  1032. ss:='nil';
  1033. ss:=Format('_env^^.NewObjectArray(_env, 1, %s.ClassRef, %s)', [GetTypeInfoVar(VarType), ss]);
  1034. end;
  1035. end;
  1036. Fps.WriteLn(Format('_args[%d].%s:=%s;', [i, s, ss]));
  1037. if IsJavaVarParam(vd) and (voVar in VarOpt) and IsJavaSimpleType(VarType) then
  1038. _AccessSimpleArray(TVarDef(d[i]), i, True);
  1039. end;
  1040. end;
  1041. if d.Count > 0 then
  1042. s:='@_args'
  1043. else
  1044. s:='nil';
  1045. // Calling Java handler
  1046. s:=Format('_env^^.Call%sMethodA(_env, _mpi.Obj, _mpi.MethodId, %s)', [GetJniFuncType(d.ReturnType), s]);
  1047. if d.ProcType = ptFunction then
  1048. s:=Format('Result:=%s', [JniToPasType(d.ReturnType, s, False)]);
  1049. Fps.WriteLn(s + ';');
  1050. // Processing var/out parameters
  1051. for i:=0 to d.Count - 1 do begin
  1052. vd:=TVarDef(d[i]);
  1053. with vd do
  1054. if IsJavaVarParam(vd) then
  1055. if IsJavaSimpleType(VarType) then
  1056. _AccessSimpleArray(TVarDef(d[i]), i, False)
  1057. else begin
  1058. s:=Format('_env^^.GetObjectArrayElement(_env, _args[%d].L, 0)', [i]);
  1059. Fps.WriteLn(Format('%s:=%s;', [Name, JniToPasType(VarType, s, False)]));
  1060. end;
  1061. end;
  1062. Fps.DecI;
  1063. Fps.WriteLn('end;');
  1064. // Get handler proc
  1065. Fps.WriteLn;
  1066. Fps.WriteLn(Format('function %sGetHandler(env: PJNIEnv; jobj: jobject; const ci: _TJavaClassInfo): %s.%s;',
  1067. [GetClassPrefix(d), d.Parent.Name, d.Name]));
  1068. Fps.WriteLn('var mpi: _TMethodPtrInfo;');
  1069. Fps.WriteLn('begin');
  1070. Fps.IncI;
  1071. Fps.WriteLn('Result:=nil;');
  1072. Fps.WriteLn('mpi:=_TMethodPtrInfo(_GetPasObj(env, jobj, ci, False));');
  1073. Fps.WriteLn('if mpi = nil then exit;');
  1074. Fps.WriteLn('if mpi.Index = 0 then');
  1075. Fps.WriteLn('TMethod(Result):=mpi.RealMethod', 1);
  1076. Fps.WriteLn('else');
  1077. Fps.WriteLn('with TMethod(Result) do begin', 1);
  1078. Fps.WriteLn('Data:=pointer(ptruint(-integer(mpi.Index)));', 2);
  1079. Fps.WriteLn(Format('Code:=@%s.Handler;', [hclass]), 2);
  1080. Fps.WriteLn('end;', 1);
  1081. Fps.DecI;
  1082. Fps.WriteLn('end;');
  1083. exit;
  1084. end;
  1085. err:=False;
  1086. WriteComment(d, 'procedural type');
  1087. RegisterPseudoClass(d);
  1088. Fjs.WriteLn(Format('/* Pascal prototype: %s */', [GetProcDeclaration(d, 'Execute')]));
  1089. Fjs.WriteLn(Format('/* Java prototype: %s */', [GetJavaProcDeclaration(d, 'Execute')]));
  1090. Fjs.WriteLn(Format('public static class %s extends %s.system.MethodPtr {', [d.Name, JavaPackage]));
  1091. Fjs.IncI;
  1092. Fjs.WriteLn(Format('private String HandlerSig = "%s";', [GetProcSignature(d)]));
  1093. Fjs.WriteLn(Format('public %s(Object Obj, String MethodName) { Init(Obj, MethodName, HandlerSig); }', [d.Name]));
  1094. Fjs.WriteLn(Format('public %s() { Init(this, "Execute", HandlerSig); }', [d.Name]));
  1095. Fjs.WriteLn(Format('protected %s throws NoSuchMethodException { throw new NoSuchMethodException(); }', [GetJavaProcDeclaration(d, 'Execute')]));
  1096. Fjs.DecI;
  1097. Fjs.WriteLn('}');
  1098. Fjs.WriteLn;
  1099. end;
  1100. procedure TWriter.WriteSet(d: TSetDef);
  1101. begin
  1102. if not d.IsUsed then
  1103. exit;
  1104. if d.ElType = nil then
  1105. raise Exception.Create('No element type.');
  1106. WriteComment(d, '');
  1107. Fjs.WriteLn(Format('/* set of %s */', [d.ElType.Name]));
  1108. if d.Size > 4 then begin
  1109. Fjs.WriteLn('/* Set size more than 32 bits is not supported */');
  1110. exit;
  1111. end;
  1112. RegisterPseudoClass(d);
  1113. Fjs.WriteLn(Format('public static class %s extends %s.system.Set<%s,%s> {', [d.Name, JavaPackage, d.Name, d.ElType.Name]));
  1114. Fjs.IncI;
  1115. Fjs.WriteLn(Format('protected byte Size() { return %d; }', [d.Size]));
  1116. Fjs.WriteLn(Format('protected int Base() { return %d; }', [d.Base]));
  1117. Fjs.WriteLn(Format('protected int ElMax() { return %d; }', [d.ElMax]));
  1118. Fjs.WriteLn(Format('protected int Ord(%s Element) { return Element.Ord(); }', [d.ElType.Name]));
  1119. Fjs.WriteLn(Format('public %s() { }', [d.Name]));
  1120. Fjs.WriteLn(Format('public %s(%s... Elements) { super(Elements); }', [d.Name, d.ElType.Name]));
  1121. Fjs.WriteLn(Format('public %0:s(%0:s... Elements) { super(Elements); }', [d.Name]));
  1122. 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]));
  1123. 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]));
  1124. Fjs.DecI;
  1125. Fjs.WriteLn('}');
  1126. Fjs.WriteLn;
  1127. end;
  1128. procedure TWriter.WriteUnit(u: TUnitDef);
  1129. procedure _ExcludeClasses(AAncestorClass: TClassDef);
  1130. var
  1131. i: integer;
  1132. d: TDef;
  1133. s: string;
  1134. excl: boolean;
  1135. begin
  1136. for i:=0 to u.Count - 1 do begin
  1137. d:=u[i];
  1138. if d.DefType = dtClass then begin
  1139. s:=u.Name + '.' + d.Name;
  1140. if AAncestorClass = nil then begin
  1141. excl:=DoCheckItem(s) = crExclude;
  1142. if not excl then
  1143. with TClassDef(d).AncestorClass do
  1144. excl:=DoCheckItem(Parent.Name + '.' + Name) = crExclude;
  1145. end
  1146. else
  1147. excl:=TClassDef(d).AncestorClass = AAncestorClass;
  1148. if excl then begin
  1149. d.SetNotUsed;
  1150. ExcludeList.Add(s);
  1151. _ExcludeClasses(TClassDef(d));
  1152. end;
  1153. end;
  1154. end;
  1155. end;
  1156. var
  1157. d: TDef;
  1158. i: integer;
  1159. HasSystem: boolean;
  1160. begin
  1161. if u.Processed then
  1162. exit;
  1163. u.Processed:=True;
  1164. if not u.IsUsed then
  1165. exit;
  1166. if AnsiCompareText(u.Name, 'system') <> 0 then
  1167. _ExcludeClasses(nil);
  1168. for i:=0 to High(u.UsedUnits) do
  1169. WriteUnit(u.UsedUnits[i]);
  1170. Fps.WriteLn;
  1171. Fps.WriteLn(Format('{ Unit %s }', [u.Name]));
  1172. u.Name:=LowerCase(u.Name);
  1173. Fjs:=TTextOutStream.Create(IncludeTrailingPathDelimiter(FPkgDir) + u.Name + '.java', fmCreate);
  1174. try
  1175. Fjs.WriteLn(Format('package %s;', [JavaPackage]));
  1176. HasSystem:=False;
  1177. if Length(u.UsedUnits) > 0 then begin
  1178. Fjs.WriteLn;
  1179. for i:=0 to High(u.UsedUnits) do
  1180. if u.UsedUnits[i].IsUsed then begin
  1181. Fjs.WriteLn(Format('import %s.%s.*;', [JavaPackage, LowerCase(u.UsedUnits[i].Name)]));
  1182. if AnsiCompareText(u.UsedUnits[i].Name, 'system') = 0 then
  1183. HasSystem:=True;
  1184. end;
  1185. if not HasSystem then
  1186. Fjs.WriteLn(Format('import %s.system.*;', [JavaPackage]));
  1187. end;
  1188. Fjs.WriteLn;
  1189. Fjs.WriteLn('public class ' + u.Name + ' {');
  1190. Fjs.IncI;
  1191. if u.Name = 'system' then begin
  1192. Fjs.WriteLn('static private boolean _JniLibLoaded = false;');
  1193. Fjs.WriteLn('public static void InitJni() {');
  1194. Fjs.WriteLn('if (!_JniLibLoaded) {', 1);
  1195. Fjs.WriteLn('_JniLibLoaded=true;', 2);
  1196. Fjs.WriteLn(Format('System.loadLibrary("%s");', [LibName]), 2);
  1197. Fjs.WriteLn('}', 1);
  1198. Fjs.WriteLn('}');
  1199. // Support functions
  1200. Fjs.WriteLn('public native static long AllocMemory(int Size);');
  1201. AddNativeMethod(u, '_AllocMemory', 'AllocMemory', '(I)J');
  1202. // Base object
  1203. Fjs.WriteLn;
  1204. Fjs.WriteLn('public static class PascalObject {');
  1205. Fjs.IncI;
  1206. Fjs.WriteLn(Format('static { %s.system.InitJni(); }', [JavaPackage]));
  1207. Fjs.WriteLn('protected long _pasobj = 0;');
  1208. Fjs.WriteLn('@Override public boolean equals(Object o) { return ((o instanceof PascalObject) && _pasobj == ((PascalObject)o)._pasobj); }');
  1209. Fjs.WriteLn('@Override public int hashCode() { return (int)_pasobj; }');
  1210. Fjs.DecI;
  1211. Fjs.WriteLn('}');
  1212. Fjs.WriteLn;
  1213. Fjs.WriteLn('public static long Pointer(PascalObject obj) { return (obj == null) ? 0 : obj._pasobj; }');
  1214. // Record
  1215. Fjs.WriteLn;
  1216. Fjs.WriteLn('public static class Record extends PascalObject {');
  1217. Fjs.IncI;
  1218. Fjs.WriteLn('protected void finalize() { Free(); }');
  1219. Fjs.WriteLn('public Record() { _pasobj = AllocMemory(Size()); }');
  1220. Fjs.WriteLn('public void Free() { _pasobj = 0; }');
  1221. Fjs.WriteLn('public int Size() { return 0; }');
  1222. Fjs.DecI;
  1223. Fjs.WriteLn('}');
  1224. // Method pointer base class
  1225. d:=TClassDef.Create(FThisUnit, dtClass);
  1226. d.Name:='_TMethodPtrInfo';
  1227. d.AliasName:='MethodPtr';
  1228. WriteClassInfoVar(d);
  1229. Fps.WriteLn;
  1230. Fps.WriteLn('procedure _TMethodPtrInfo_Init(env: PJNIEnv; _self, JavaObj: JObject; AMethodName, AMethodSig: jstring);' + JniCaliing);
  1231. Fps.WriteLn('var mpi: _TMethodPtrInfo;');
  1232. Fps.WriteLn('begin');
  1233. Fps.IncI;
  1234. EHandlerStart;
  1235. Fps.WriteLn('mpi:=_TMethodPtrInfo.Create(env, JavaObj, ansistring(_StringFromJString(env, AMethodName)), ansistring(_StringFromJString(env, AMethodSig)));');
  1236. Fps.WriteLn(Format('env^^.SetLongField(env, _self, %s.ObjFieldId, Int64(ptruint(mpi)));', [GetTypeInfoVar(d)]));
  1237. EHandlerEnd('env');
  1238. Fps.DecI;
  1239. Fps.WriteLn('end;');
  1240. AddNativeMethod(d, '_TMethodPtrInfo_Init', 'Init', Format('(Ljava/lang/Object;%s%s)V', [JNITypeSig[btString], JNITypeSig[btString]]));
  1241. Fps.WriteLn;
  1242. Fps.WriteLn('procedure _TMethodPtrInfo_Release(env: PJNIEnv; _self: JObject);' + JniCaliing);
  1243. Fps.WriteLn('begin');
  1244. Fps.IncI;
  1245. EHandlerStart;
  1246. Fps.WriteLn(Format('_TMethodPtrInfo(_GetPasObj(env, _self, %s, True)).Release(env);', [GetTypeInfoVar(d)]));
  1247. EHandlerEnd('env');
  1248. Fps.DecI;
  1249. Fps.WriteLn('end;');
  1250. AddNativeMethod(d, '_TMethodPtrInfo_Release', 'Release', '()V');
  1251. Fjs.WriteLn;
  1252. Fjs.WriteLn('public static class MethodPtr extends PascalObject {');
  1253. Fjs.IncI;
  1254. Fjs.WriteLn('private native void Release();');
  1255. Fjs.WriteLn('protected void finalize() { if (_pasobj != 0) Release(); }');
  1256. Fjs.WriteLn('protected native void Init(Object Obj, String MethodName, String MethodSignature);');
  1257. Fjs.DecI;
  1258. Fjs.WriteLn('}');
  1259. Fjs.WriteLn;
  1260. // Base class for Enum
  1261. Fjs.WriteLn('public static class Enum {');
  1262. Fjs.IncI;
  1263. Fjs.WriteLn('public int Value;');
  1264. Fjs.WriteLn('public int Ord() { return Value; }');
  1265. Fjs.WriteLn('@Override public boolean equals(Object o) { return (o instanceof Integer) && Value == (Integer)o; }');
  1266. Fjs.WriteLn('@Override public int hashCode() { return Value; }');
  1267. Fjs.DecI;
  1268. Fjs.WriteLn('}');
  1269. Fjs.WriteLn;
  1270. // Base class for Set
  1271. Fjs.WriteLn('public static class Set<TS extends Set<?,?>,TE extends Enum> {');
  1272. Fjs.IncI;
  1273. Fjs.WriteLn('protected int Value = 0;');
  1274. Fjs.WriteLn('protected byte Size() { return 0; }');
  1275. Fjs.WriteLn('protected int Base() { return 0; }');
  1276. Fjs.WriteLn('protected int ElMax() { return 0; }');
  1277. Fjs.WriteLn('protected int Ord(TE Element) { return 0; }');
  1278. Fjs.WriteLn('protected int GetMask(TE Element) {');
  1279. Fjs.IncI;
  1280. Fjs.WriteLn('return 1 << (Ord(Element) - Base());');
  1281. Fjs.DecI;
  1282. Fjs.WriteLn('}');
  1283. Fjs.WriteLn('public Set() { }');
  1284. Fjs.WriteLn('public Set(TE... Elements) { Include(Elements); }');
  1285. Fjs.WriteLn('public Set(TS... Elements) { for (TS e : Elements) Include(e); }');
  1286. Fjs.WriteLn('public void Include(TE... Elements) { for (TE e: Elements) Value = Value | GetMask(e); }');
  1287. Fjs.WriteLn('public void Include(TS s) { Value=Value | s.Value; }');
  1288. Fjs.WriteLn('public void Exclude(TE... Elements) { for (TE e: Elements) Value = Value & ~GetMask(e); }');
  1289. Fjs.WriteLn('public void Exclude(TS s) { Value=Value & ~s.Value; }');
  1290. Fjs.WriteLn('public void Assign(TS s) { Value=s.Value; }');
  1291. Fjs.WriteLn('public void Intersect(TS s) { Value=Value & s.Value; }');
  1292. Fjs.WriteLn('public boolean Has(TE Element) { return (Value & GetMask(Element)) != 0; }');
  1293. Fjs.WriteLn('public boolean IsEmpty() { return Value == 0; }');
  1294. Fjs.WriteLn('public boolean equals(TS s) { return Value == s.Value; }');
  1295. Fjs.WriteLn('public boolean equals(TE Element) { return Value == Ord(Element); }');
  1296. Fjs.WriteLn('public boolean equals(int Element) { return Value == Element; }');
  1297. Fjs.DecI;
  1298. Fjs.WriteLn('}');
  1299. Fjs.WriteLn;
  1300. end;
  1301. Fjs.WriteLn(Format('static { %s.system.InitJni(); }', [JavaPackage]));
  1302. Fjs.WriteLn;
  1303. // First pass
  1304. for i:=0 to u.Count - 1 do begin
  1305. d:=u[i];
  1306. if not d.IsUsed then
  1307. continue;
  1308. case d.DefType of
  1309. dtSet, dtEnum:
  1310. WriteClassInfoVar(d);
  1311. dtClass, dtRecord:
  1312. WriteClass(d, True);
  1313. dtProcType:
  1314. WriteProcType(TProcDef(d), True);
  1315. end;
  1316. end;
  1317. // Second pass
  1318. for i:=0 to u.Count - 1 do begin
  1319. d:=u[i];
  1320. if not d.IsUsed then
  1321. continue;
  1322. case d.DefType of
  1323. dtClass, dtRecord:
  1324. WriteClass(d, False);
  1325. dtProc:
  1326. WriteProc(TProcDef(d));
  1327. dtVar, dtProp:
  1328. WriteVar(TVarDef(d));
  1329. dtEnum:
  1330. WriteEnum(d);
  1331. dtProcType:
  1332. WriteProcType(TProcDef(d), False);
  1333. dtSet:
  1334. WriteSet(TSetDef(d));
  1335. dtConst:
  1336. WriteConst(TConstDef(d));
  1337. end;
  1338. end;
  1339. Fjs.DecI;
  1340. Fjs.WriteLn('}');
  1341. finally
  1342. Fjs.Free;
  1343. end;
  1344. end;
  1345. procedure TWriter.WriteOnLoad;
  1346. var
  1347. i, j: integer;
  1348. ci: TClassInfo;
  1349. s, ss, fn: string;
  1350. d: TTypeDef;
  1351. begin
  1352. if FClasses.Count = 0 then
  1353. exit;
  1354. Fps.WriteLn;
  1355. Fps.WriteLn('function JNI_OnLoad(vm: PJavaVM; reserved: pointer): jint;' + JniCaliing);
  1356. Fps.WriteLn('const');
  1357. for i:=0 to FClasses.Count - 1 do begin
  1358. ci:=TClassInfo(FClasses.Objects[i]);
  1359. if ci.Funcs.Count = 0 then
  1360. continue;
  1361. Fps.WriteLn(Format(' _%sNativeMethods: array[0..%d] of JNINativeMethod = (', [GetClassPrefix(ci.Def, FClasses[i]), ci.Funcs.Count - 1]));
  1362. for j:=0 to ci.Funcs.Count - 1 do begin
  1363. with TProcInfo(ci.Funcs[j]) do
  1364. Fps.Write(Format(' (name: ''%s''; signature: ''%s''; fnPtr: @%s)', [Name, JniSignature, JniName]));
  1365. if j < ci.Funcs.Count - 1 then
  1366. Fps.Write(',');
  1367. Fps.WriteLn;
  1368. end;
  1369. Fps.WriteLn(' );');
  1370. end;
  1371. Fps.WriteLn;
  1372. Fps.WriteLn('var');
  1373. Fps.IncI;
  1374. Fps.WriteLn('env: PJNIEnv;');
  1375. Fps.WriteLn;
  1376. Fps.WriteLn('function _Reg(ClassName: PAnsiChar; Methods: PJNINativeMethod; Count: integer; ci: _PJavaClassInfo; const FieldName: ansistring = ''_pasobj''; const FieldSig: ansistring = ''J''): boolean;');
  1377. Fps.WriteLn('var');
  1378. Fps.WriteLn('c: jclass;', 1);
  1379. Fps.WriteLn('begin');
  1380. Fps.IncI;
  1381. Fps.WriteLn('Result:=False;');
  1382. Fps.WriteLn('c:=env^^.FindClass(env, ClassName);');
  1383. Fps.WriteLn('if c = nil then exit;');
  1384. Fps.WriteLn('Result:=(Count = 0) or (env^^.RegisterNatives(env, c, Methods, Count) = 0);');
  1385. Fps.WriteLn('if Result and (ci <> nil) then begin');
  1386. Fps.IncI;
  1387. Fps.WriteLn('ci^.ClassRef:=env^^.NewGlobalRef(env, c);');
  1388. Fps.WriteLn('Result:=ci^.ClassRef <> nil;');
  1389. Fps.WriteLn('if Result and (FieldName <> '''') then begin');
  1390. Fps.WriteLn('ci^.ObjFieldId:=env^^.GetFieldID(env, ci^.ClassRef, PAnsiChar(FieldName), PAnsiChar(FieldSig));', 1);
  1391. Fps.WriteLn('Result:=ci^.ObjFieldId <> nil;', 1);
  1392. Fps.WriteLn('end;');
  1393. Fps.DecI;
  1394. Fps.WriteLn('end;');
  1395. Fps.DecI;
  1396. Fps.WriteLn('end;');
  1397. Fps.WriteLn;
  1398. Fps.WriteLn('begin', -1);
  1399. Fps.WriteLn('Result:=JNI_ERR;');
  1400. Fps.WriteLn('if vm^^.GetEnv(vm, @env, JNI_VERSION_1_6) <> JNI_OK then exit;');
  1401. Fps.WriteLn('CurJavaVM:=vm;');
  1402. d:=TTypeDef.Create(nil, dtType);
  1403. try
  1404. d.BasicType:=btString;
  1405. s:=JNITypeSig[d.BasicType];
  1406. s:=Copy(s, 2, Length(s) - 2);
  1407. Fps.WriteLn(Format('if not _Reg(''%s'', nil, 0, @%s, '''', '''') then exit;',
  1408. [s, GetTypeInfoVar(d)]));
  1409. finally
  1410. d.Free;
  1411. end;
  1412. for i:=0 to FClasses.Count - 1 do begin
  1413. ci:=TClassInfo(FClasses.Objects[i]);
  1414. s:=GetTypeInfoVar(ci.Def);
  1415. if (s = '') or (ci.IsCommonClass) then
  1416. s:='nil'
  1417. else
  1418. s:='@' + s;
  1419. if ci.Funcs.Count = 0 then
  1420. ss:='nil'
  1421. else
  1422. ss:=Format('@_%sNativeMethods', [GetClassPrefix(ci.Def, FClasses[i])]);
  1423. fn:='';
  1424. if ci.Def <> nil then
  1425. if ci.Def.DefType in [dtSet, dtEnum] then
  1426. fn:=', ''Value'', ''I''';
  1427. Fps.WriteLn(Format('if not _Reg(''%s'', %s, %d, %s%s) then exit;',
  1428. [GetJavaClassPath(ci.Def, FClasses[i]), ss, ci.Funcs.Count, s, fn]));
  1429. end;
  1430. Fps.WriteLn('Result:=JNI_VERSION_1_6;');
  1431. Fps.DecI;
  1432. Fps.WriteLn('end;');
  1433. Fps.WriteLn;
  1434. Fps.WriteLn('exports JNI_OnLoad;');
  1435. end;
  1436. function TWriter.JniToPasType(d: TDef; const v: string; CheckNil: boolean): string;
  1437. var
  1438. n: 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. begin
  1449. Result:=Format('_StringFromJString(_env, %s)', [Result]);
  1450. if BasicType <> btWideString then
  1451. Result:=Format('%s(%s)', [d.Name, Result]);
  1452. end;
  1453. btBoolean:
  1454. Result:=Format('LongBool(%s)', [Result]);
  1455. btChar:
  1456. Result:=Format('char(widechar(%s))', [Result]);
  1457. btWideChar:
  1458. Result:=Format('widechar(%s)', [Result]);
  1459. btPointer:
  1460. Result:=Format('pointer(ptruint(%s))', [Result]);
  1461. btGuid:
  1462. Result:=Format('StringToGUID(ansistring(_StringFromJString(_env, %s)))', [Result]);
  1463. else
  1464. Result:=Format('%s(%s)', [d.Name, Result]);
  1465. end;
  1466. dtClass:
  1467. begin
  1468. if CheckNil then
  1469. n:='True'
  1470. else
  1471. n:='False';
  1472. Result:=Format('%s.%s(_GetPasObj(_env, %s, %s, %s))', [d.Parent.Name, d.Name, Result, GetTypeInfoVar(d), n]);
  1473. end;
  1474. dtRecord:
  1475. Result:=Format('%s.%s(_GetPasObj(_env, %s, %s, True)^)', [d.Parent.Name, d.Name, Result, GetTypeInfoVar(d)]);
  1476. dtProcType:
  1477. Result:=Format('%sGetHandler(_env, %s, %s)', [GetClassPrefix(d), Result, GetTypeInfoVar(d)]);
  1478. dtEnum:
  1479. Result:=Format('%s.%s(_GetIntObjValue(_env, %s, %s))', [d.Parent.Name, d.Name, Result, GetTypeInfoVar(d)]);
  1480. dtSet:
  1481. Result:=Format('%s.%s(%s(_GetIntObjValue(_env, %s, %s)))', [d.Parent.Name, d.Name, GetPasIntType(TSetDef(d).Size), Result, GetTypeInfoVar(d)]);
  1482. end;
  1483. end;
  1484. function TWriter.PasToJniType(d: TDef; const v: string): string;
  1485. begin
  1486. Result:=v;
  1487. if d = nil then
  1488. exit;
  1489. case d.DefType of
  1490. dtType:
  1491. with TTypeDef(d) do
  1492. case BasicType of
  1493. btString, btWideString:
  1494. Result:=Format('_StringToJString(_env, _JNIString(%s))', [Result]);
  1495. btBoolean:
  1496. Result:=Format('jboolean(LongBool(%s))', [Result]);
  1497. btChar:
  1498. Result:=Format('jchar(widechar(%s))', [Result]);
  1499. btWideChar:
  1500. Result:=Format('jchar(%s)', [Result]);
  1501. btEnum:
  1502. Result:=Format('jint(%s)', [Result]);
  1503. btPointer:
  1504. Result:=Format('ptruint(pointer(%s))', [Result]);
  1505. btGuid:
  1506. Result:=Format('_StringToJString(_env, _JNIString(GUIDToString(%s)))', [Result]);
  1507. end;
  1508. dtClass:
  1509. Result:=Format('_CreateJavaObj(_env, %s, %s)', [Result, GetTypeInfoVar(d)]);
  1510. dtRecord:
  1511. Result:=Format('_%s_CreateObj(_env, %s)', [GetClassPrefix(d), Result]);
  1512. dtProcType:
  1513. Result:=Format('_CreateMethodPtrObject(_env, TMethod(%s), %s)', [Result, GetTypeInfoVar(d)]);
  1514. dtEnum:
  1515. Result:=Format('_CreateIntObj(_env, longint(%s), %s)', [Result, GetTypeInfoVar(d)]);
  1516. dtSet:
  1517. Result:=Format('_CreateIntObj(_env, %s(%s), %s)', [GetPasIntType(TSetDef(d).Size), Result, GetTypeInfoVar(d)]);
  1518. end;
  1519. end;
  1520. function TWriter.GetTypeInfoVar(ClassDef: TDef): string;
  1521. begin
  1522. if ClassDef.DefType = dtUnit then
  1523. Result:=''
  1524. else
  1525. if ClassDef.DefType = dtType then
  1526. Result:='_Java_' + JavaType[TTypeDef(ClassDef).BasicType] + '_Info'
  1527. else
  1528. Result:='_JNI_' + ClassDef.Parent.Name + '_' + ClassDef.Name + '_Info';
  1529. end;
  1530. function TWriter.GetClassPrefix(ClassDef: TDef; const AClassName: string): string;
  1531. begin
  1532. if AClassName = '' then
  1533. Result:=ClassDef.Name
  1534. else
  1535. Result:=AClassName;
  1536. Result:=Result + '_';
  1537. if ClassDef.DefType <> dtUnit then
  1538. Result:=ClassDef.Parent.Name + '_' + Result;
  1539. Result:='JNI_' + Result;
  1540. end;
  1541. function TWriter.IsJavaSimpleType(d: TDef): boolean;
  1542. begin
  1543. Result:=(d <> nil) and (d.DefType = dtType) and (Length(JNITypeSig[TTypeDef(d).BasicType]) = 1);
  1544. end;
  1545. function TWriter.IsJavaVarParam(ParamDef: TVarDef): boolean;
  1546. begin
  1547. with ParamDef do
  1548. Result:=VarOpt * [voVar, voOut] <> [];
  1549. end;
  1550. function TWriter.GetProcDeclaration(d: TProcDef; const ProcName: string; FullTypeNames: boolean): string;
  1551. var
  1552. s, ss: string;
  1553. j: integer;
  1554. begin
  1555. with d do begin
  1556. if Count > 0 then
  1557. s:='('
  1558. else
  1559. s:='';
  1560. for j:=0 to Count - 1 do
  1561. with TVarDef(Items[j]) do begin
  1562. if j > 0 then
  1563. s:=s + '; ';
  1564. if voVar in VarOpt then
  1565. s:=s + 'var '
  1566. else
  1567. if voOut in VarOpt then
  1568. s:=s + 'out '
  1569. else
  1570. if voConst in VarOpt then
  1571. s:=s + 'const ';
  1572. s:=s + Name + ': ' + GetPasType(VarType, FullTypeNames);
  1573. end;
  1574. if Count > 0 then
  1575. s:=s + ')';
  1576. case ProcType of
  1577. ptConstructor:
  1578. ss:='constructor';
  1579. ptDestructor:
  1580. ss:='destructor';
  1581. ptProcedure:
  1582. ss:='procedure';
  1583. ptFunction:
  1584. ss:='function';
  1585. else
  1586. ss:='';
  1587. end;
  1588. if ProcType in [ptConstructor, ptFunction] then
  1589. s:=s + ': ' + GetPasType(ReturnType, FullTypeNames);
  1590. ss:=ss + ' ';
  1591. if ProcName <> '' then
  1592. ss:=ss + ProcName
  1593. else
  1594. ss:=ss + Name;
  1595. Result:=ss + s;
  1596. end;
  1597. end;
  1598. function TWriter.GetJavaProcDeclaration(d: TProcDef; const ProcName: string): string;
  1599. var
  1600. s: string;
  1601. j: integer;
  1602. vd: TVarDef;
  1603. begin
  1604. with d do begin
  1605. if ProcName <> '' then
  1606. s:=ProcName
  1607. else
  1608. s:=AliasName;
  1609. s:=DefToJavaType(ReturnType) + ' ' + s + '(';
  1610. for j:=0 to Count - 1 do begin
  1611. vd:=TVarDef(Items[j]);
  1612. with vd do begin
  1613. if j > 0 then
  1614. s:=s + ', ';
  1615. s:=s + DefToJavaType(VarType);
  1616. if IsJavaVarParam(vd) then
  1617. s:=s + '[]';
  1618. s:=s + ' ' + AliasName;
  1619. end;
  1620. end;
  1621. s:=s + ')';
  1622. end;
  1623. Result:=s;
  1624. end;
  1625. function TWriter.GetJniFuncType(d: TDef): string;
  1626. begin
  1627. if IsJavaSimpleType(d) then begin
  1628. Result:=JavaType[TTypeDef(d).BasicType];
  1629. Result[1]:=UpCase(Result[1]);
  1630. end
  1631. else
  1632. Result:='Object';
  1633. end;
  1634. function TWriter.GetJavaClassName(cls: TDef; it: TDef): string;
  1635. begin
  1636. Result:=cls.AliasName;
  1637. if (cls.DefType <> dtClass) or ((it <> nil) and not (it.DefType in ReplDefs)) then
  1638. exit;
  1639. with TClassDef(cls) do begin
  1640. if not (HasReplacedItems or ImplementsReplacedItems) then
  1641. exit;
  1642. if ImplementsReplacedItems and not HasReplacedItems then
  1643. exit;
  1644. if it <> nil then
  1645. with TReplDef(it) do begin
  1646. if (it.DefType = dtProc) and (TProcDef(it).ProcType = ptConstructor) then
  1647. exit;
  1648. if IsReplaced or IsReplImpl then
  1649. exit;
  1650. end;
  1651. end;
  1652. Result:='__' + Result;
  1653. end;
  1654. procedure TWriter.RegisterPseudoClass(d: TDef);
  1655. var
  1656. ci: TClassInfo;
  1657. begin
  1658. if FClasses.IndexOf(d.Name) < 0 then begin
  1659. ci:=TClassInfo.Create;
  1660. ci.Def:=d;
  1661. FClasses.AddObject(d.Name, ci);
  1662. end;
  1663. end;
  1664. function TWriter.GetPasIntType(Size: integer): string;
  1665. begin
  1666. case Size of
  1667. 1: Result:='byte';
  1668. 2: Result:='word';
  1669. else
  1670. Result:='cardinal';
  1671. end;
  1672. end;
  1673. function TWriter.GetPasType(d: TDef; FullName: boolean): string;
  1674. begin
  1675. Result:=d.Name;
  1676. if FullName and (d.DefType <> dtType) then
  1677. Result:=d.Parent.Name + '.' + Result;
  1678. end;
  1679. function TWriter.AddCustomProc(ParentDef: TDef; const JniName, Name: string; RetType: TBasicType; const Params: array of TBasicType): TProcDef;
  1680. var
  1681. i: integer;
  1682. vd: TVarDef;
  1683. begin
  1684. Result:=TProcDef.Create(ParentDef, dtProc);
  1685. Result.Name:=JniName;
  1686. Result.AliasName:=Name;
  1687. if RetType = btVoid then
  1688. Result.ProcType:=ptProcedure
  1689. else
  1690. Result.ProcType:=ptFunction;
  1691. for i:=0 to High(Params) do begin
  1692. vd:=TVarDef.Create(Result, dtParam);
  1693. vd.Name:=Format('p%d', [i + 1]);
  1694. vd.VarType:=TTypeDef.Create(vd, dtType);
  1695. TTypeDef(vd.VarType).BasicType:=Params[i];
  1696. end;
  1697. Result.ReturnType:=TTypeDef.Create(ParentDef, dtType);
  1698. TTypeDef(Result.ReturnType).BasicType:=RetType;
  1699. end;
  1700. procedure TWriter.AddNativeMethod(ParentDef: TDef; const JniName, Name, Signature: string);
  1701. var
  1702. i: integer;
  1703. ci: TClassInfo;
  1704. pi: TProcInfo;
  1705. begin
  1706. pi:=TProcInfo.Create;
  1707. pi.Name:=Name;
  1708. pi.JniName:=JniName;
  1709. pi.JniSignature:=Signature;
  1710. i:=FClasses.IndexOf(ParentDef.AliasName);
  1711. if i < 0 then begin
  1712. ci:=TClassInfo.Create;
  1713. ci.Def:=ParentDef;
  1714. i:=FClasses.AddObject(ParentDef.AliasName, ci);
  1715. end;
  1716. TClassInfo(FClasses.Objects[i]).Funcs.Add(pi);
  1717. end;
  1718. function TWriter.GetProcSignature(d: TProcDef): string;
  1719. var
  1720. j: integer;
  1721. vd: TVarDef;
  1722. begin
  1723. Result:='(';
  1724. for j:=0 to d.Count - 1 do begin
  1725. vd:=TVarDef(d[j]);
  1726. with vd do begin
  1727. if IsJavaVarParam(vd) then
  1728. Result:=Result + '[';
  1729. Result:=Result + DefToJniSig(VarType);
  1730. end;
  1731. end;
  1732. Result:=Result + ')' + DefToJniSig(d.ReturnType);
  1733. end;
  1734. procedure TWriter.EHandlerStart;
  1735. begin
  1736. Fps.WriteLn('try');
  1737. Fps.IncI;
  1738. end;
  1739. procedure TWriter.EHandlerEnd(const EnvVarName: string; const ExtraCode: string);
  1740. begin
  1741. Fps.WriteLn('except', -1);
  1742. Fps.WriteLn(Format('_HandleJNIException(%s);', [EnvVarName]));
  1743. if ExtraCode <> '' then
  1744. Fps.WriteLn(ExtraCode);
  1745. Fps.DecI;
  1746. Fps.WriteLn('end;');
  1747. end;
  1748. procedure TWriter.WriteClassInfoVar(d: TDef);
  1749. begin
  1750. Fps.WriteLn;
  1751. Fps.WriteLn(Format('var %s: _TJavaClassInfo;', [GetTypeInfoVar(d)]));
  1752. end;
  1753. procedure TWriter.WriteComment(d: TDef; const AType: string);
  1754. begin
  1755. Fps.WriteLn;
  1756. Fps.WriteLn(Format('{ %s }', [d.Name]));
  1757. Fjs.WriteLn(Format('/* %s %s */', [AType, d.Name]));
  1758. {$ifdef DEBUG}
  1759. Fjs.WriteLn(Format('/* Ref count: %d */', [d.RefCnt]));
  1760. {$endif}
  1761. end;
  1762. {
  1763. procedure TWriter.AddCustomProc(ParentDef: TDef; const JniName, Name: string; RetType: TBasicType; const Params: array of TBasicType);
  1764. var
  1765. i: integer;
  1766. ci: TClassInfo;
  1767. pi: TProcInfo;
  1768. begin
  1769. pi:=TProcInfo.Create;
  1770. pi.Name:=Name;
  1771. pi.JniName:=JniName;
  1772. pi.JniSignature:='(';
  1773. for i:=0 to High(Params) do
  1774. pi.JniSignature:=pi.JniSignature + JNITypeSig[Params[i]];
  1775. pi.JniSignature:=pi.JniSignature + ')';
  1776. pi.JniSignature:=pi.JniSignature + JNITypeSig[RetType];
  1777. i:=FClasses.IndexOf(ParentDef.Name);
  1778. if i < 0 then begin
  1779. ci:=TClassInfo.Create;
  1780. ci.Def:=ParentDef;
  1781. i:=FClasses.AddObject(ParentDef.Name, ci);
  1782. end;
  1783. TClassInfo(FClasses.Objects[i]).Funcs.Add(pi);
  1784. end;
  1785. }
  1786. constructor TWriter.Create;
  1787. var
  1788. i: integer;
  1789. begin
  1790. Units:=TStringList.Create;
  1791. FClasses:=TStringList.Create;
  1792. FClasses.Sorted:=True;
  1793. JavaPackage:='pas';
  1794. IncludeList:=TStringList.Create;
  1795. IncludeList.Duplicates:=dupIgnore;
  1796. ExcludeList:=TStringList.Create;
  1797. ExcludeList.Duplicates:=dupIgnore;
  1798. for i:=Low(ExcludeStd) to High(ExcludeStd) do
  1799. ExcludeList.Add(ExcludeStd[i]);
  1800. for i:=Low(ExcludeDelphi7) to High(ExcludeDelphi7) do
  1801. ExcludeList.Add(ExcludeDelphi7[i]);
  1802. FThisUnit:=TUnitDef.Create(nil, dtUnit);
  1803. end;
  1804. destructor TWriter.Destroy;
  1805. var
  1806. i: integer;
  1807. begin
  1808. for i:=0 to FClasses.Count - 1 do
  1809. FClasses.Objects[i].Free;
  1810. FClasses.Free;
  1811. Units.Free;
  1812. IncludeList.Free;
  1813. ExcludeList.Free;
  1814. FThisUnit.Free;
  1815. inherited Destroy;
  1816. end;
  1817. procedure TWriter.ProcessUnits;
  1818. var
  1819. p: TPPUParser;
  1820. i: integer;
  1821. s, ss: string;
  1822. d: TDef;
  1823. begin
  1824. if Units.Count = 0 then
  1825. raise Exception.Create('No unit name specified.');
  1826. if (OutPath <> '') and not DirectoryExists(OutPath) then
  1827. raise Exception.CreateFmt('Output path "%s" does not exist.', [OutPath]);
  1828. if (JavaOutPath <> '') and not DirectoryExists(JavaOutPath) then
  1829. raise Exception.CreateFmt('Output path "%s" does not exist.', [JavaOutPath]);
  1830. if LibName = '' then
  1831. LibName:=AnsiLowerCase(ChangeFileExt(Units[0], '')) + 'jni';
  1832. for i:=0 to IncludeList.Count - 1 do
  1833. IncludeList[i]:=Trim(IncludeList[i]);
  1834. IncludeList.Sorted:=True;
  1835. for i:=0 to ExcludeList.Count - 1 do
  1836. ExcludeList[i]:=Trim(ExcludeList[i]);
  1837. ExcludeList.Sorted:=True;
  1838. FThisUnit.Name:=LibName;
  1839. FThisUnit.AliasName:='system';
  1840. p:=TPPUParser.Create(SearchPath);
  1841. try
  1842. p.OnCheckItem:=@DoCheckItem;
  1843. for i:=0 to Units.Count - 1 do
  1844. IncludeList.Add(ChangeFileExt(ExtractFileName(Units[i]), ''));
  1845. for i:=0 to Units.Count - 1 do
  1846. p.Parse(ChangeFileExt(ExtractFileName(Units[i]), ''));
  1847. if OutPath <> '' then
  1848. OutPath:=IncludeTrailingPathDelimiter(OutPath);
  1849. if JavaOutPath <> '' then
  1850. JavaOutPath:=IncludeTrailingPathDelimiter(JavaOutPath);
  1851. FPkgDir:=JavaOutPath + StringReplace(JavaPackage, '.', DirectorySeparator, [rfReplaceAll]);
  1852. ForceDirectories(FPkgDir);
  1853. Fps:=TTextOutStream.Create(OutPath + LibName + '.pas', fmCreate);
  1854. Fps.WriteLn('library '+ LibName + ';');
  1855. Fps.WriteLn('{$ifdef fpc} {$mode objfpc} {$H+} {$endif}');
  1856. Fps.WriteLn;
  1857. Fps.WriteLn('uses');
  1858. Fps.WriteLn('{$ifndef FPC} Windows, {$endif} {$ifdef unix} cthreads, {$endif} SysUtils, SyncObjs,', 1);
  1859. s:='';
  1860. for i:=0 to p.Units.Count - 1 do begin
  1861. ProcessRules(p.Units[i]);
  1862. ss:=LowerCase(p.Units[i].Name);
  1863. if (ss ='system') or (ss = 'objpas') or (ss = 'sysutils') or (ss = 'syncobjs') or (ss = 'jni') then
  1864. continue;
  1865. if s <> '' then
  1866. s:=s + ', ';
  1867. s:=s + p.Units[i].Name;
  1868. end;
  1869. Fps.WriteLn(s + ', jni;', 1);
  1870. // Types
  1871. Fps.WriteLn;
  1872. Fps.WriteLn('type');
  1873. Fps.IncI;
  1874. Fps.WriteLn('_JNIString = {$ifdef FPC} unicodestring {$else} widestring {$endif};');
  1875. Fps.WriteLn('{$ifndef FPC} ptruint = cardinal; {$endif}');
  1876. Fps.WriteLn;
  1877. Fps.WriteLn('_TJavaClassInfo = record');
  1878. Fps.WriteLn('ClassRef: JClass;', 1);
  1879. Fps.WriteLn('ObjFieldId: JFieldId;', 1);
  1880. Fps.WriteLn('end;');
  1881. Fps.WriteLn('_PJavaClassInfo = ^_TJavaClassInfo;');
  1882. Fps.DecI;
  1883. Fps.WriteLn;
  1884. d:=TtypeDef.Create(nil, dtType);
  1885. TtypeDef(d).BasicType:=btString;
  1886. Fps.WriteLn(Format('var %s: _TJavaClassInfo;', [GetTypeInfoVar(d)]));
  1887. d.Free;
  1888. // Support functions
  1889. Fps.WriteLn;
  1890. Fps.WriteLn('function _StringFromJString(env: PJNIEnv; s: jstring): _JNIString;');
  1891. Fps.WriteLn('var');
  1892. Fps.WriteLn('p: PJChar;', 1);
  1893. Fps.WriteLn('c: JBoolean;', 1);
  1894. Fps.WriteLn('begin');
  1895. Fps.WriteLn('if s = nil then begin', 1);
  1896. Fps.WriteLn('Result:='''';', 2);
  1897. Fps.WriteLn('exit;', 2);
  1898. Fps.WriteLn('end;', 1);
  1899. Fps.WriteLn('p:=env^^.GetStringChars(env, s, c);', 1);
  1900. Fps.WriteLn('SetString(Result, PWideChar(p), env^^.GetStringLength(env, s));', 1);
  1901. Fps.WriteLn('env^^.ReleaseStringChars(env, s, p);', 1);
  1902. Fps.WriteLn('end;');
  1903. Fps.WriteLn;
  1904. Fps.WriteLn('function _StringToJString(env: PJNIEnv; const s: _JNIString): jstring;');
  1905. Fps.WriteLn('begin');
  1906. Fps.WriteLn('Result:=env^^.NewString(env, PJChar(PWideChar(s)), Length(s));', 1);
  1907. Fps.WriteLn('end;');
  1908. Fps.WriteLn;
  1909. Fps.WriteLn('function _CreateJavaObj(env: PJNIEnv; PasObj: pointer; const ci: _TJavaClassInfo): jobject;');
  1910. Fps.WriteLn('begin');
  1911. Fps.IncI;
  1912. Fps.WriteLn('Result:=nil;');
  1913. Fps.WriteLn('if PasObj = nil then exit;');
  1914. Fps.WriteLn('Result:=env^^.AllocObject(env, ci.ClassRef);');
  1915. Fps.WriteLn('if Result = nil then exit;');
  1916. Fps.WriteLn('env^^.SetLongField(env, Result, ci.ObjFieldId, Int64(ptruint(PasObj)));');
  1917. Fps.DecI;
  1918. Fps.WriteLn('end;');
  1919. Fps.WriteLn;
  1920. Fps.WriteLn('function _GetPasObj(env: PJNIEnv; jobj: jobject; const ci: _TJavaClassInfo; CheckNil: boolean): pointer;');
  1921. Fps.WriteLn('var pasobj: jlong;');
  1922. Fps.WriteLn('begin');
  1923. Fps.IncI;
  1924. Fps.WriteLn('if jobj <> nil then');
  1925. Fps.WriteLn('pasobj:=env^^.GetLongField(env, jobj, ci.ObjFieldId)', 1);
  1926. Fps.WriteLn('else');
  1927. Fps.WriteLn('pasobj:=0;', 1);
  1928. Fps.WriteLn('if CheckNil and (pasobj = 0) then');
  1929. Fps.WriteLn('raise Exception.Create(''Attempt to access a released Pascal object.'');', 1);
  1930. Fps.WriteLn('Result:=pointer(ptruint(pasobj));');
  1931. Fps.DecI;
  1932. Fps.WriteLn('end;');
  1933. Fps.WriteLn;
  1934. Fps.WriteLn('procedure _HandleJNIException(env: PJNIEnv);');
  1935. Fps.WriteLn('begin');
  1936. if p.OnExceptionProc <> nil then begin
  1937. Fps.WriteLn(Format('%s.%s;', [p.OnExceptionProc.Parent.Name, p.OnExceptionProc.Name]), 1);
  1938. p.OnExceptionProc.SetNotUsed;
  1939. end;
  1940. Fps.WriteLn('env^^.ThrowNew(env, env^^.FindClass(env, ''java/lang/Exception''), PAnsiChar(Utf8Encode(Exception(ExceptObject).Message)));', 1);
  1941. Fps.WriteLn('end;');
  1942. Fps.WriteLn;
  1943. Fps.WriteLn('procedure _RaiseVarParamException(const VarName: string);');
  1944. Fps.WriteLn('begin');
  1945. Fps.WriteLn('raise Exception.CreateFmt(''An array with only single element must be passed as parameter "%s".'', [VarName]);', 1);
  1946. Fps.WriteLn('end;');
  1947. Fps.WriteLn;
  1948. Fps.WriteLn('function _AllocMemory(env: PJNIEnv; jobj: jobject; size: jint): jlong;');
  1949. Fps.WriteLn('var p: pointer;');
  1950. Fps.WriteLn('begin');
  1951. Fps.WriteLn('GetMem(p, size);', 1);
  1952. Fps.WriteLn('FillChar(p^, size, 0);', 1);
  1953. Fps.WriteLn('Result:=ptruint(p);', 1);
  1954. Fps.WriteLn('end;');
  1955. // Method pointer support
  1956. Fps.WriteLn;
  1957. Fps.WriteLn('type');
  1958. Fps.IncI;
  1959. Fps.WriteLn('_TMethodPtrInfo = class');
  1960. Fps.IncI;
  1961. Fps.WriteLn('Obj: JObject;');
  1962. Fps.WriteLn('MethodId: JMethodID;');
  1963. Fps.WriteLn('Index, RefCnt: integer;');
  1964. Fps.WriteLn('RealMethod: TMethod;');
  1965. Fps.WriteLn('constructor Create(env: PJNIEnv; JavaObj: JObject; const AMethodName, AMethodSig: ansistring);');
  1966. Fps.WriteLn('procedure Release(env: PJNIEnv);');
  1967. Fps.DecI;
  1968. Fps.WriteLn('end;');
  1969. Fps.DecI;
  1970. Fps.WriteLn;
  1971. Fps.WriteLn('var _MethodPointers: array of _TMethodPtrInfo;');
  1972. Fps.WriteLn('var _MethodPointersCS: TCriticalSection;');
  1973. Fps.WriteLn;
  1974. Fps.WriteLn('constructor _TMethodPtrInfo.Create(env: PJNIEnv; JavaObj: JObject; const AMethodName, AMethodSig: ansistring);');
  1975. Fps.WriteLn('var c: JClass;');
  1976. Fps.WriteLn('begin');
  1977. Fps.IncI;
  1978. Fps.WriteLn('RefCnt:=1;');
  1979. Fps.WriteLn('if (JavaObj = nil) or (AMethodName = '''') then exit;');
  1980. Fps.WriteLn('c:=env^^.GetObjectClass(env, JavaObj);');
  1981. Fps.WriteLn('if c = nil then exit;');
  1982. Fps.WriteLn('MethodId:=env^^.GetMethodID(env, c, PAnsiChar(AMethodName), PAnsiChar(AMethodSig));');
  1983. Fps.WriteLn('if MethodId = nil then raise Exception.CreateFmt(''Method "%s" does not exist or has wrong parameters.'', [AMethodName]);');
  1984. Fps.WriteLn('Obj:=env^^.NewGlobalRef(env, JavaObj);');
  1985. Fps.WriteLn('_MethodPointersCS.Enter;');
  1986. Fps.WriteLn('try');
  1987. Fps.IncI;
  1988. Fps.WriteLn('Index:=Length(_MethodPointers) + 1;');
  1989. Fps.WriteLn(Format('if Index > %d then raise Exception.Create(''Too many method pointers.'');', [MaxMethodPointers]));
  1990. Fps.WriteLn('SetLength(_MethodPointers, Index);');
  1991. Fps.WriteLn('_MethodPointers[Index - 1]:=Self;');
  1992. Fps.WriteLn('finally', -1);
  1993. Fps.WriteLn('_MethodPointersCS.Leave;');
  1994. Fps.DecI;
  1995. Fps.WriteLn('end;');
  1996. Fps.DecI;
  1997. Fps.WriteLn('end;');
  1998. Fps.WriteLn;
  1999. Fps.WriteLn('procedure _TMethodPtrInfo.Release(env: PJNIEnv);');
  2000. Fps.WriteLn('var i: integer;');
  2001. Fps.WriteLn('begin');
  2002. Fps.IncI;
  2003. Fps.WriteLn('i:=InterlockedDecrement(RefCnt);');
  2004. Fps.WriteLn('if i <> 0 then exit;');
  2005. Fps.WriteLn('if Index > 0 then begin');
  2006. Fps.IncI;
  2007. Fps.WriteLn('_MethodPointersCS.Enter;');
  2008. Fps.WriteLn('try');
  2009. Fps.IncI;
  2010. Fps.WriteLn('Dec(Index);');
  2011. Fps.WriteLn('_MethodPointers[Index]:=nil;');
  2012. Fps.WriteLn('Index:=Length(_MethodPointers);');
  2013. Fps.WriteLn('while (Index > 0) and (_MethodPointers[Index] = nil) do Dec(Index);');
  2014. Fps.WriteLn('SetLength(_MethodPointers, Index + 1);');
  2015. Fps.WriteLn('finally', -1);
  2016. Fps.WriteLn('_MethodPointersCS.Leave;');
  2017. Fps.DecI;
  2018. Fps.WriteLn('end;');
  2019. Fps.WriteLn('env^^.DeleteGlobalRef(env, Obj);');
  2020. Fps.DecI;
  2021. Fps.WriteLn('end;');
  2022. Fps.WriteLn('Self.Destroy;');
  2023. Fps.DecI;
  2024. Fps.WriteLn('end;');
  2025. Fps.WriteLn;
  2026. Fps.WriteLn('procedure _RefMethodPtr(env: PJNIEnv; const m: TMethod; AddRef: boolean);');
  2027. Fps.WriteLn('var i: integer;');
  2028. Fps.WriteLn('begin');
  2029. Fps.IncI;
  2030. Fps.WriteLn('i:=-integer(ptruint(m.Data));');
  2031. Fps.WriteLn(Format('if (i < 1) or (i > %d) then exit;', [MaxMethodPointers]));
  2032. Fps.WriteLn('_MethodPointersCS.Enter;');
  2033. Fps.WriteLn('try');
  2034. Fps.IncI;
  2035. Fps.WriteLn('with _MethodPointers[i - 1] do');
  2036. Fps.WriteLn('if AddRef then InterlockedIncrement(RefCnt) else Release(env);', 1);
  2037. Fps.WriteLn('finally', -1);
  2038. Fps.WriteLn('_MethodPointersCS.Leave;');
  2039. Fps.DecI;
  2040. Fps.WriteLn('end;');
  2041. Fps.DecI;
  2042. Fps.WriteLn('end;');
  2043. Fps.WriteLn;
  2044. Fps.WriteLn('function _CreateMethodPtrObject(env: PJNIEnv; const m: TMethod; const ci: _TJavaClassInfo): jobject;');
  2045. Fps.WriteLn('var i: integer;');
  2046. Fps.WriteLn('var mpi: _TMethodPtrInfo;');
  2047. Fps.WriteLn('begin');
  2048. Fps.IncI;
  2049. Fps.WriteLn('_MethodPointersCS.Enter;');
  2050. Fps.WriteLn('try');
  2051. Fps.IncI;
  2052. Fps.WriteLn('i:=-integer(ptruint(m.Data));');
  2053. Fps.WriteLn(Format('if (i > 0) and (i <= %d) then begin', [MaxMethodPointers]));
  2054. Fps.WriteLn('mpi:=_MethodPointers[i - 1];', 1);
  2055. Fps.WriteLn('InterlockedIncrement(mpi.RefCnt);', 1);
  2056. Fps.WriteLn('end');
  2057. Fps.WriteLn('else begin');
  2058. Fps.WriteLn('mpi:=_TMethodPtrInfo.Create(env, nil, '''', '''');', 1);
  2059. Fps.WriteLn('mpi.RealMethod:=m;', 1);
  2060. Fps.WriteLn('end;');
  2061. Fps.WriteLn('finally', -1);
  2062. Fps.WriteLn('_MethodPointersCS.Leave;');
  2063. Fps.DecI;
  2064. Fps.WriteLn('end;');
  2065. Fps.WriteLn('Result:=_CreateJavaObj(env, pointer(mpi), ci);');
  2066. Fps.DecI;
  2067. Fps.WriteLn('end;');
  2068. // Set support
  2069. Fps.WriteLn;
  2070. Fps.WriteLn('function _GetIntObjValue(env: PJNIEnv; jobj: jobject; const ci: _TJavaClassInfo): longint;');
  2071. Fps.WriteLn('begin');
  2072. Fps.IncI;
  2073. Fps.WriteLn('if jobj = nil then raise Exception.Create(''Attempt to access a NULL set.'');');
  2074. Fps.WriteLn('Result:=env^^.GetIntField(env, jobj, ci.ObjFieldId);');
  2075. Fps.DecI;
  2076. Fps.WriteLn('end;');
  2077. Fps.WriteLn;
  2078. Fps.WriteLn('function _CreateIntObj(env: PJNIEnv; Value: longint; const ci: _TJavaClassInfo): jobject;');
  2079. Fps.WriteLn('begin');
  2080. Fps.IncI;
  2081. Fps.WriteLn('Result:=nil;');
  2082. Fps.WriteLn('Result:=env^^.AllocObject(env, ci.ClassRef);');
  2083. Fps.WriteLn('if Result = nil then exit;');
  2084. Fps.WriteLn('env^^.SetIntField(env, Result, ci.ObjFieldId, Value);');
  2085. Fps.DecI;
  2086. Fps.WriteLn('end;');
  2087. // Write units
  2088. for i:=0 to p.Units.Count - 1 do
  2089. with TUnitDef(p.Units[i]) do begin
  2090. WriteUnit(TUnitDef(p.Units[i]));
  2091. end;
  2092. WriteOnLoad;
  2093. Fps.WriteLn;
  2094. Fps.WriteLn('begin');
  2095. Fps.WriteLn('IsMultiThread:=True;', 1);
  2096. Fps.WriteLn('_MethodPointersCS:=TCriticalSection.Create;', 1);
  2097. Fps.WriteLn('end.');
  2098. finally
  2099. Fps.Free;
  2100. p.Free;
  2101. end;
  2102. end;
  2103. end.