summaryrefslogtreecommitdiff
path: root/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeClient.cs
blob: 2bf3b83c7525fc617e298fc03915247431577a3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace GodotTools.IdeConnection
{
    public abstract class GodotIdeClient : GodotIdeBase
    {
        protected GodotIdeMetadata GodotIdeMetadata;

        private readonly FileSystemWatcher fsWatcher;

        protected GodotIdeClient(string projectMetadataDir) : base(projectMetadataDir)
        {
            messageHandlers = InitializeMessageHandlers();

            // FileSystemWatcher requires an existing directory
            if (!File.Exists(projectMetadataDir))
                Directory.CreateDirectory(projectMetadataDir);

            fsWatcher = new FileSystemWatcher(projectMetadataDir, MetaFileName);
        }

        private void OnMetaFileChanged(object sender, FileSystemEventArgs e)
        {
            if (IsDisposed)
                return;

            lock (ConnectionLock)
            {
                if (IsDisposed)
                    return;

                if (!File.Exists(MetaFilePath))
                    return;

                var metadata = ReadMetadataFile();

                if (metadata != null && metadata != GodotIdeMetadata)
                {
                    GodotIdeMetadata = metadata.Value;
                    ConnectToServer();
                }
            }
        }

        private void OnMetaFileDeleted(object sender, FileSystemEventArgs e)
        {
            if (IsDisposed)
                return;

            if (IsConnected)
                DisposeConnection();

            // The file may have been re-created

            lock (ConnectionLock)
            {
                if (IsDisposed)
                    return;

                if (IsConnected || !File.Exists(MetaFilePath))
                    return;

                var metadata = ReadMetadataFile();

                if (metadata != null)
                {
                    GodotIdeMetadata = metadata.Value;
                    ConnectToServer();
                }
            }
        }

        private GodotIdeMetadata? ReadMetadataFile()
        {
            using (var reader = File.OpenText(MetaFilePath))
            {
                string portStr = reader.ReadLine();

                if (portStr == null)
                    return null;

                string editorExecutablePath = reader.ReadLine();

                if (editorExecutablePath == null)
                    return null;

                if (!int.TryParse(portStr, out int port))
                    return null;

                return new GodotIdeMetadata(port, editorExecutablePath);
            }
        }

        private void ConnectToServer()
        {
            var tcpClient = new TcpClient();

            Connection = new GodotIdeConnectionClient(tcpClient, HandleMessage);
            Connection.Logger = Logger;

            try
            {
                Logger.LogInfo("Connecting to Godot Ide Server");

                tcpClient.Connect(IPAddress.Loopback, GodotIdeMetadata.Port);

                Logger.LogInfo("Connection open with Godot Ide Server");

                var clientThread = new Thread(Connection.Start)
                {
                    IsBackground = true,
                    Name = "Godot Ide Connection Client"
                };
                clientThread.Start();
            }
            catch (SocketException e)
            {
                if (e.SocketErrorCode == SocketError.ConnectionRefused)
                    Logger.LogError("The connection to the Godot Ide Server was refused");
                else
                    throw;
            }
        }

        public void Start()
        {
            Logger.LogInfo("Starting Godot Ide Client");

            fsWatcher.Changed += OnMetaFileChanged;
            fsWatcher.Deleted += OnMetaFileDeleted;
            fsWatcher.EnableRaisingEvents = true;

            lock (ConnectionLock)
            {
                if (IsDisposed)
                    return;

                if (!File.Exists(MetaFilePath))
                {
                    Logger.LogInfo("There is no Godot Ide Server running");
                    return;
                }

                var metadata = ReadMetadataFile();

                if (metadata != null)
                {
                    GodotIdeMetadata = metadata.Value;
                    ConnectToServer();
                }
                else
                {
                    Logger.LogError("Failed to read Godot Ide metadata file");
                }
            }
        }

        public bool WriteMessage(Message message)
        {
            return Connection.WriteMessage(message);
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                fsWatcher?.Dispose();
            }
        }

        protected virtual bool HandleMessage(Message message)
        {
            if (messageHandlers.TryGetValue(message.Id, out var action))
            {
                action(message.Arguments);
                return true;
            }

            return false;
        }

        private readonly Dictionary<string, Action<string[]>> messageHandlers;

        private Dictionary<string, Action<string[]>> InitializeMessageHandlers()
        {
            return new Dictionary<string, Action<string[]>>
            {
                ["OpenFile"] = args =>
                {
                    switch (args.Length)
                    {
                        case 1:
                            OpenFile(file: args[0]);
                            return;
                        case 2:
                            OpenFile(file: args[0], line: int.Parse(args[1]));
                            return;
                        case 3:
                            OpenFile(file: args[0], line: int.Parse(args[1]), column: int.Parse(args[2]));
                            return;
                        default:
                            throw new ArgumentException();
                    }
                }
            };
        }

        protected abstract void OpenFile(string file);
        protected abstract void OpenFile(string file, int line);
        protected abstract void OpenFile(string file, int line, int column);
    }
}