Fix #7982 - roo javascript completion
[roobuilder] / src / Palete / LanguageClientVala.vala
1
2 namespace Palete {
3         public class LanguageClientVala : LanguageClient {
4                 int countdown = 0;
5                 protected bool initialized = false;
6                 bool sent_shutdown = false;
7                 uint change_queue_id = 0;
8                 
9                         
10                 private bool _closed = false;
11                 private bool closed {
12                         get { return this._closed ; } 
13                         set {
14                                 GLib.debug("closed has been set? to %s" , value ? "TRUE" : "FALSE" );
15                                 this._closed = value;
16                         }
17                 }
18                 private GLib.SubprocessLauncher launcher = null;
19                 private GLib.Subprocess? subprocess = null;
20                 private IOStream? subprocess_stream = null;
21             public Jsonrpc.Client? jsonrpc_client = null;
22                 
23                 Gee.ArrayList<JsRender.JsRender> open_files;
24                 private JsRender.JsRender? _change_queue_file = null;
25                 private string change_queue_file_source = "";
26                 
27                 JsRender.JsRender? change_queue_file {
28                         set {
29                                 this.change_queue_file_source = value == null ? "" : value.toSource();
30                                 this._change_queue_file = value;
31                         } 
32                         get {
33                                 return this._change_queue_file;
34                         } 
35                 }
36                 void startServer()
37                 {
38                         this.initProcess("/usr/bin/vala-language-server");
39                 }
40                 
41                 
42                 public LanguageClientVala(Project.Project project)
43                 {
44                         // extend versions will proably call initialize to start and connect to server.
45                         base(project);
46                         this.open_files = new   Gee.ArrayList<JsRender.JsRender>();
47                         this.change_queue_id = GLib.Timeout.add_seconds(1, () => {
48                                 if (this.change_queue_file == null) {
49                                         return true;
50                                 }
51                                 this.countdown--;
52                                 if (this.countdown < 0){
53                                         this.document_change_force(this.change_queue_file,  this.change_queue_file_source);
54                                         this.change_queue_file = null;
55                                            
56                                 }
57                                 return true;
58                         });
59                         this.startServer();
60
61                 }
62                 
63                  
64                 public bool initProcess(string process_path)
65                 {
66                         this.onClose();
67                         this.log(LanguageClientAction.LAUNCH, process_path);
68                         GLib.debug("Launching %s", process_path);
69                         this.launcher = new GLib.SubprocessLauncher (SubprocessFlags.STDIN_PIPE | SubprocessFlags.STDOUT_PIPE);
70                         this.launcher.set_environ(GLib.Environ.get());
71                         try {
72
73                                 
74                                 this.subprocess = launcher.spawnv ({ process_path });
75                                 
76                                 this.subprocess.wait_async.begin( null, ( obj,res ) => {
77                                         try {
78                                                 this.subprocess.wait_async.end(res);
79                                         } catch (GLib.Error e) {
80                                                 this.log(LanguageClientAction.ERROR_START, e.message);
81                                                 GLib.debug("subprocess startup error %s", e.message);           
82                                         }
83                                         this.log(LanguageClientAction.EXIT, "process ended");
84                                         GLib.debug("Subprocess ended %s", process_path);
85                                         this.onClose();
86
87                                 });
88                                 var input_stream = this.subprocess.get_stdout_pipe ();
89                                 var output_stream = this.subprocess.get_stdin_pipe ();
90  
91                                 if (input_stream is GLib.UnixInputStream && output_stream is GLib.UnixOutputStream) {
92                                         // set nonblocking
93                                         if (!GLib.Unix.set_fd_nonblocking(((GLib.UnixInputStream)input_stream).fd, true)
94                                          || !GLib.Unix.set_fd_nonblocking (((GLib.UnixOutputStream)output_stream).fd, true)) 
95                                          {
96                                                 GLib.debug("could not set pipes to nonblocking");
97                                                 this.onClose();
98                                             return false;
99                                     }
100                             }
101                             this.subprocess_stream = new GLib.SimpleIOStream (input_stream, output_stream);
102                         this.accept_io_stream ( this.subprocess_stream);
103                         } catch (GLib.Error e) {
104                                 this.log(LanguageClientAction.ERROR_START, e.message);
105                                 GLib.debug("subprocess startup error %s", e.message);   
106                                 this.onClose();
107                                 return false;
108                 }
109             return true;
110         }
111         bool in_close = false;
112                 public override void client_accepted (Jsonrpc.Client client) 
113                 {
114                         if (this.jsonrpc_client == null) {
115                                 this.jsonrpc_client = client;
116                                 
117                                 GLib.debug("client accepted connection - calling init server");
118                                 this.log(LanguageClientAction.ACCEPT, "client accepted");
119
120                                 this.jsonrpc_client.notification.connect((method, paramz) => {
121                                         this.onNotification(method, paramz);
122                                 });
123                                  
124                                 this.jsonrpc_client.failed.connect(() => {
125                                         this.log(LanguageClientAction.ERROR_RPC, "client failed");
126                                         this.onClose();
127                                         
128                                         GLib.debug("language server server has failed");
129                                 });
130
131                                 this.initialize_server ();
132                         } 
133                                          
134                          
135                 }
136                 
137                 
138                 public override   void  initialize_server()   {
139                         try {
140                                 Variant? return_value;
141                                     this.jsonrpc_client.call (
142                                     "initialize",
143                                     this.buildDict (
144                                         processId: new Variant.int32 ((int32) Posix.getpid ()),
145                                         rootPath: new Variant.string (this.project.path),
146                                         rootUri: new Variant.string (File.new_for_path (this.project.path).get_uri ())
147                                     ),
148                                     null,
149                                     out return_value
150                                 );
151                                 GLib.debug ("LS replied with %s", Json.to_string (Json.gvariant_serialize (return_value), true));
152                                 this.initialized = true;
153                                 return;
154                         } catch (GLib.Error e) {
155                                 GLib.debug ("LS replied with error %s", e.message);
156                                 this.onClose();
157                         }
158                         
159                 }
160                 void onClose()
161                 {
162                         if (this.in_close) {
163                                 return;
164                         }
165                         if (this.launcher == null) {
166                                 return;
167                         }
168                         this.in_close = true;
169                         GLib.debug("onClose called");
170                         
171                         if (this.jsonrpc_client != null) {
172                                 try {
173                                         this.jsonrpc_client.close();
174                                 } catch (GLib.Error e) {
175                                         GLib.debug("rpc Error close error %s", e.message);      
176                                 }               
177                         }
178                         if (this.subprocess_stream != null) {
179                                 try {
180                                         this.subprocess_stream.close();
181                                 } catch (GLib.Error e) {
182                                         GLib.debug("stream Error close  %s", e.message);        
183                                 }               
184                         }
185                         if (this.subprocess != null) {
186                                 this.subprocess.force_exit();
187                         }
188                         if (this.launcher != null) {
189                                 this.launcher.close();
190                         }
191                         
192                         this.launcher = null;
193                         this.subprocess = null;
194                         this.jsonrpc_client = null;
195                         this.closed = true;             
196                         this.in_close = false;
197                 }
198         
199         
200                 public bool isReady()
201                 {
202                         if (this.closed) {
203                                 this.log(LanguageClientAction.RESTART,"closed is set - restarting");
204                                 GLib.debug("server stopped = restarting");
205                                 this.initialized = false;
206                                 this.closed = false;
207                                 this.startServer();
208                                 foreach(var f in this.open_files) {
209                                         this.document_open(f);
210                                 }
211                                 return false; // can't do an operation yet?
212                                  
213                         }
214                         
215                         if (!this.initialized) {
216                                 GLib.debug("Server has not been initialized");
217                                 return false;
218                         }
219                         if (this.sent_shutdown) {
220                                 GLib.debug("Server has been started its shutting down process");
221                                 return false;
222                         }
223                         // restart server..
224
225                         
226                         
227                         return true;
228                 }
229         
230                 public void onNotification(string method, Variant? return_value)
231                 {
232                         switch (method) {
233                                 case "textDocument/publishDiagnostics":
234                                         this.onDiagnostic(return_value);
235                                         return;
236                                 default: 
237                                         break;
238                                  
239                         }
240                         GLib.debug("got notification %s : %s",  method , Json.to_string (Json.gvariant_serialize (return_value), true));
241                         
242                 }
243                 
244                 /***
245                 
246                 */
247                 public void onDiagnostic(Variant? return_value) 
248                 {
249
250                         var dg = Json.gobject_deserialize (typeof (Lsp.Diagnostics), Json.gvariant_serialize (return_value)) as Lsp.Diagnostics; 
251                         this.log(LanguageClientAction.DIAG, dg.filename);
252                         var f = this.project.getByPath(dg.filename);
253                         if (f == null) {
254                                 //GLib.debug("no file %s", dg.uri);
255                                 this.project.updateErrorsforFile(null);
256                                 return;
257                         }
258                         foreach(var v in f.errorsByType.values) {
259                                 v.remove_all();
260                         }
261                         foreach(var diag in dg.diagnostics) {
262                                 var ce = new CompileError.new_from_diagnostic(f, diag);
263                                 if (!f.errorsByType.has_key(ce.category)) {
264                                         f.errorsByType.set(ce.category, new  GLib.ListStore(typeof(CompileError)));
265                                 }
266                                 f.errorsByType.get(ce.category).append(ce);
267                         }
268                         f.project.updateErrorsforFile(f);
269                         
270                 }
271                 
272                 public override void document_open (JsRender.JsRender file)  
273                 {
274                         if (!this.isReady()) {
275                                 return;
276                         }
277                         if (!this.open_files.contains(file)) {
278                                 this.open_files.add(file);
279                         }
280                         
281                         GLib.debug ("LS sent open");                     
282                         try {
283                                 this.jsonrpc_client.send_notification (
284                                         "textDocument/didOpen",
285                                         this.buildDict (
286                                                 textDocument : this.buildDict (
287                                                         uri: new Variant.string (file.to_url()),
288                                                         languageId :  new Variant.string (file.language_id()),
289                                                         version :  new GLib.Variant.uint64 ( (uint64) file.version),
290                                                         text : new Variant.string (file.toSource())
291                                                 )
292                                         ),
293                                         null
294                                 );
295                                 this.log(LanguageClientAction.OPEN, file.path);
296                         } catch( GLib.Error  e) {
297                                 this.log(LanguageClientAction.ERROR_RPC, e.message);
298                                 this.onClose();
299                                 GLib.debug ("LS sent open err %s", e.message);
300                         }
301
302                 }
303                 
304                 public override  void document_save (JsRender.JsRender file)  
305         {
306                         if (!this.isReady()) {
307                                 return;
308                         }
309                         this.change_queue_file = null;
310                         GLib.debug ("LS send save");
311                          try {
312                                   this.jsonrpc_client.send_notification  (
313                                         "textDocument/didChange",
314                                         this.buildDict (  
315                                                 textDocument : this.buildDict (    ///TextDocumentItem;
316                                                         uri: new GLib.Variant.string (file.to_url()),
317                                                         version :  new GLib.Variant.uint64 ( (uint64) file.version)
318                                                 )
319                                         ),
320                                         null 
321                                 );
322                                 this.log(LanguageClientAction.SAVE, file.path);
323                         } catch( GLib.Error  e) {
324                                 this.log(LanguageClientAction.ERROR_RPC, e.message);
325                                 GLib.debug ("LS   save err %s", e.message);
326                                 this.onClose();
327                         }
328
329          
330         }
331                 public override  void document_close (JsRender.JsRender file) 
332         {
333                         if (!this.isReady()) {
334                                 return;
335                         }
336                         this.change_queue_file = null;
337                         
338                         if (this.open_files.contains(file)) {
339                                 this.open_files.remove(file);
340                         }
341                         this.log(LanguageClientAction.CLOSE, file.path);
342                         GLib.debug ("LS send close");
343                         try {
344                                   this.jsonrpc_client.send_notification  (
345                                         "textDocument/didChange",
346                                         this.buildDict (  
347                                                 textDocument : this.buildDict (    ///TextDocumentItem;
348                                                         uri: new GLib.Variant.string (file.to_url())
349                                                         
350                                                 )
351                                         ),
352                                         null  
353                                 );
354                         } catch( GLib.Error  e) {
355                                 this.log(LanguageClientAction.ERROR_RPC, e.message);
356                                 GLib.debug ("LS close err %s", e.message);
357                                 this.onClose();
358                         }
359
360          
361         }
362         
363          
364                 public override void document_change (JsRender.JsRender file )    
365                 {
366                         if (this.change_queue_file != null && this.change_queue_file.path != file.path) {
367                                 this.document_change_force(this.change_queue_file, this.change_queue_file_source);
368                         }
369                         
370                         this.countdown = 3;
371                         this.change_queue_file = file;
372                          
373                         
374
375                 }
376         
377
378                 public override void document_change_force (JsRender.JsRender file, string contents)  
379         {
380                         if (!this.isReady()) {
381                                 return;
382                         }
383                              
384                         
385                         GLib.debug ("LS send change");
386                         var ar = new Json.Array();
387                         var obj = new Json.Object();
388                         obj.set_string_member("text", contents);
389                         ar.add_object_element(obj);
390                         var node = new Json.Node(Json.NodeType.ARRAY);
391                         node.set_array(ar);
392                         this.log(LanguageClientAction.CHANGE, file.path);
393                          try {
394                                 this.jsonrpc_client.send_notification (
395                                         "textDocument/didChange",
396                                         this.buildDict (  
397                                                 textDocument : this.buildDict (    ///TextDocumentItem;
398                                                         uri: new GLib.Variant.string (file.to_url()),
399                                                         version :  new GLib.Variant.uint64 ( (uint64) file.version) 
400                                                 ),
401                                                 contentChanges : Json.gvariant_deserialize (node, null)
402                                                 
403                                         ),
404                                         null 
405                                 );
406                         } catch( GLib.Error  e) {
407                                 this.log(LanguageClientAction.ERROR_RPC, e.message);
408                                 GLib.debug ("LS change err %s", e.message);
409                                 this.onClose();
410                         }
411
412          
413         }
414         // called by close window (on last window)...
415                 public override  void exit () throws GLib.Error 
416                 {
417                         if (!this.isReady()) {
418                         
419                                 return;
420                         }
421                         this.log(LanguageClientAction.TERM, "SEND exit");
422                  
423                           this.jsonrpc_client.send_notification (
424                                 "exit",
425                                 null,
426                                 null 
427                         );
428                         this.onClose();
429
430                 }
431                 // not used currently..
432                 public override async void shutdown () throws GLib.Error 
433                 {
434                         if (!this.isReady()) {
435                                 return;
436                         }
437                         this.log(LanguageClientAction.TERM, "SEND shutodwn");
438                         this.sent_shutdown  = true;
439                         Variant? return_value;
440                         yield this.jsonrpc_client.call_async (
441                                 "shutdown",
442                                 null,
443                                 null,
444                                 out return_value
445                         );
446                         GLib.debug ("LS replied with %s", Json.to_string (Json.gvariant_serialize (return_value), true));               
447                 }
448                 //public async  ??/symbol (string symbol) throws GLib.Error {
449                 
450                 // and now for the important styff..
451                 
452                 /*
453                 
454                 @triggerType 1 = typing or ctl-spac, 2 = tiggercharactres?  3= inside completion?
455                 */
456                  public override async Lsp.CompletionList?  completion(JsRender.JsRender file, int line, int offset , int triggerType = 1) throws GLib.Error 
457                  {
458                         /* partial_result_token ,  work_done_token   context = null) */
459                         GLib.debug("%s get completion %s @ %d:%d", this.get_type().name(),  file.relpath, line, offset);
460                         
461                         var ret = new Lsp.CompletionList();     
462                         
463                     if (!this.isReady()) {
464                         GLib.debug("completion - language server not ready");
465                                 return ret;
466                         }
467                         // make sure completion has the latest info..
468                         //if (this.change_queue_file != null && this.change_queue_file.path != file.path) {
469                         //      this.document_change_real(this.change_queue_file, this.change_queue_file_source);
470                         //      this.change_queue_file != null;
471                         //}
472                         this.log(LanguageClientAction.COMPLETE, "SEND complete  %s @ %d:%d".printf(file.relpath, line, offset) );
473                         
474                         Variant? return_value;
475                         
476                         var args = this.buildDict (  
477                                         context : this.buildDict (    ///CompletionContext;
478                                                 triggerKind: new GLib.Variant.int32 (triggerType) 
479                                         //      triggerCharacter :  new GLib.Variant.string ("")
480                                         ),
481                                         textDocument : this.buildDict (    ///TextDocumentItem;
482                                                 uri: new GLib.Variant.string (file.to_url()),
483                                                 version :  new GLib.Variant.uint64 ( (uint64) file.version) 
484                                         ), 
485                                         position :  this.buildDict ( 
486                                                 line :  new GLib.Variant.uint64 ( (uint) line) ,
487                                                 character :  new GLib.Variant.uint64 ( uint.max(0,  (offset -1))) 
488                                         )
489                                 );
490                          
491                         GLib.debug ("textDocument/completion send with %s", Json.to_string (Json.gvariant_serialize (args), true));                                     
492                         
493                         yield this.jsonrpc_client.call_async (
494                                 "textDocument/completion",
495                                 args,
496                                 null,
497                                 out return_value
498                         );
499                         
500                         
501                         //GLib.debug ("LS replied with %s", Json.to_string (Json.gvariant_serialize (return_value), true));                                     
502                         var json = Json.gvariant_serialize (return_value);
503
504
505                         if (json.get_node_type() == Json.NodeType.OBJECT) {
506                                 ret = Json.gobject_deserialize (typeof (Lsp.CompletionList), json) as Lsp.CompletionList; 
507                                 this.log(LanguageClientAction.COMPLETE_REPLY, "GOT complete  %d items".printf(ret.items.size) );
508                                 GLib.debug ("LS replied with Object");
509                                 return ret;
510                         }  
511
512                         if (json.get_node_type() != Json.NodeType.ARRAY) {
513                                 GLib.debug ("LS replied with %s", Json.to_string (Json.gvariant_serialize (return_value), true));                                       
514                                 this.log(LanguageClientAction.ERROR_REPLY, "GOT something else??");
515                                 return ret;
516                         
517                         }
518                         var ar = json.get_array();                      
519                         
520                         for(var i = 0; i < ar.get_length(); i++ ) {
521                                 var add= Json.gobject_deserialize ( typeof (Lsp.CompletionItem),  ar.get_element(i)) as Lsp.CompletionItem;
522                                 ret.items.add( add);
523                                          
524                         }
525                         this.log(LanguageClientAction.COMPLETE_REPLY, "GOT array %d items".printf(ret.items.size) );
526                         GLib.debug ("LS replied with Array");
527                         return ret;
528                 
529
530                 }
531                 //CompletionListInfo.itmems.parse_varient  or CompletionListInfo.parsevarient
532                 public override async Gee.ArrayList<Lsp.DocumentSymbol> syntax (JsRender.JsRender file) throws GLib.Error 
533                  {
534                         /* partial_result_token ,  work_done_token   context = null) */
535                         GLib.debug("get syntax %s", file.relpath);
536                         var ret = new Gee.ArrayList<Lsp.DocumentSymbol>();      
537                         //ret = null;
538                     if (!this.isReady()) {
539                                 return ret;
540                         }
541                         Variant? return_value;
542                         yield this.jsonrpc_client.call_async (
543                                 "textDocument/documentSymbol",
544                                 this.buildDict (  
545                                          
546                                         textDocument : this.buildDict (    ///TextDocumentItem;
547                                                 uri: new GLib.Variant.string (file.to_url()),
548                                                 version :  new GLib.Variant.uint64 ( (uint64) file.version) 
549                                         ) 
550                                          
551                                 ),
552                                 null,
553                                 out return_value
554                         );
555                         
556                         
557                         GLib.debug ("LS replied with %s", Json.to_string (Json.gvariant_serialize (return_value), true));                                       
558                         var json = Json.gvariant_serialize (return_value);
559                          
560                          
561
562                         var ar = json.get_array();
563                         for(var i = 0; i < ar.get_length(); i++ ) {
564                                 var add= Json.gobject_deserialize ( typeof (Lsp.DocumentSymbol),  ar.get_element(i)) as Lsp.DocumentSymbol;
565                                 ret.add( add);
566                                          
567                         }
568                                 return ret ;
569                         
570                 
571
572                 }
573                 
574         }
575         
576 }