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