Debian Codegraph @

Rust/RustPlugin.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2021 Eran Ifrah
5 // file name : RustPlugin.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 #include "RustPlugin.hpp"
27
28 #include "CargoToml.hpp"
29 #include "CompilerLocatorRustc.hpp"
30 #include "NewFileSystemWorkspaceDialog.h"
31 #include "Platform.hpp"
32 #include "RustWorkspace.hpp"
33 #include "asyncprocess.h"
34 #include "build_settings_config.h"
35 #include "clFileSystemWorkspace.hpp"
36 #include "clFileSystemWorkspaceConfig.hpp"
37 #include "clFilesCollector.h"
38 #include "clRustLocator.hpp"
39 #include "clWorkspaceManager.h"
40 #include "cl_standard_paths.h"
41 #include "environmentconfig.h"
42 #include "event_notifier.h"
43 #include "file_logger.h"
44 #include "globals.h"
45 #include "macros.h"
46 #include "wxmd5.h"
47
48 #include <wx/dir.h>
49 #include <wx/msgdlg.h>
50 #include <wx/stdpaths.h>
51 #include <wx/utils.h>
52
53 static RustPlugin* thePlugin = NULL;
54 // Define the plugin entry point
55 CL_PLUGIN_API IPlugin* CreatePlugin(IManager* manager)
56 {
57 if(thePlugin == 0) {
58 thePlugin = new RustPlugin(manager);
59 }
60 return thePlugin;
61 }
62
63 CL_PLUGIN_API PluginInfo* GetPluginInfo()
64 {
65 static PluginInfo info;
66 info.SetAuthor(wxT("Eran Ifrah"));
67 info.SetName("Rust");
68 info.SetDescription(_("Rust plugin for CodeLite IDE"));
69 info.SetVersion("v1.0");
70 return &info;
71 }
72
73 CL_PLUGIN_API int GetPluginInterfaceVersion() { return PLUGIN_INTERFACE_VERSION; }
74
75 RustPlugin::RustPlugin(IManager* manager)
76 : IPlugin(manager)
77 {
78 m_longName = _("Rust plugin for CodeLite IDE");
79 m_shortName = "Rust";
80 EventNotifier::Get()->Bind(wxEVT_CONTEXT_MENU_FOLDER, &RustPlugin::OnFolderContextMenu, this);
81 EventNotifier::Get()->Bind(wxEVT_FS_NEW_WORKSPACE_FILE_CREATED, &RustPlugin::OnRustWorkspaceFileCreated, this);
82 EventNotifier::Get()->Bind(wxEVT_CMD_CREATE_NEW_WORKSPACE, &RustPlugin::OnNewWorkspace, this);
83 EventNotifier::Get()->Bind(wxEVT_BUILD_OUTPUT_HOTSPOT_CLICKED, &RustPlugin::OnBuildErrorLineClicked, this);
84 EventNotifier::Get()->Bind(wxEVT_BUILD_ENDED, &RustPlugin::OnBuildEnded, this);
85 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_LOADED, &RustPlugin::OnWorkspaceLoaded, this);
86 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_CLOSED, &RustPlugin::OnWorkspaceClosed, this);
87 clWorkspaceManager::Get().RegisterWorkspace(new RustWorkspace());
88 AddRustcCompilerIfMissing(); // make sure we got the rustc compiler if missing
89 }
90
91 RustPlugin::~RustPlugin() {}
92
93 void RustPlugin::CreateToolBar(clToolBarGeneric* toolbar) { wxUnusedVar(toolbar); }
94
95 void RustPlugin::CreatePluginMenu(wxMenu* pluginsMenu) { wxUnusedVar(pluginsMenu); }
96
97 void RustPlugin::HookPopupMenu(wxMenu* menu, MenuType type)
98 {
99 wxUnusedVar(menu);
100 wxUnusedVar(type);
101 }
102
103 void RustPlugin::UnPlug()
104 {
105 EventNotifier::Get()->Unbind(wxEVT_CONTEXT_MENU_FOLDER, &RustPlugin::OnFolderContextMenu, this);
106 EventNotifier::Get()->Unbind(wxEVT_FS_NEW_WORKSPACE_FILE_CREATED, &RustPlugin::OnRustWorkspaceFileCreated, this);
107 EventNotifier::Get()->Unbind(wxEVT_CMD_CREATE_NEW_WORKSPACE, &RustPlugin::OnNewWorkspace, this);
108 EventNotifier::Get()->Unbind(wxEVT_BUILD_OUTPUT_HOTSPOT_CLICKED, &RustPlugin::OnBuildErrorLineClicked, this);
109 EventNotifier::Get()->Unbind(wxEVT_BUILD_ENDED, &RustPlugin::OnBuildEnded, this);
110 EventNotifier::Get()->Unbind(wxEVT_WORKSPACE_LOADED, &RustPlugin::OnWorkspaceLoaded, this);
111 EventNotifier::Get()->Unbind(wxEVT_WORKSPACE_CLOSED, &RustPlugin::OnWorkspaceClosed, this);
112 }
113
114 void RustPlugin::OnFolderContextMenu(clContextMenuEvent& event) { event.Skip(); }
115
116 void RustPlugin::OnRustWorkspaceFileCreated(clFileSystemEvent& event)
117 {
118 event.Skip();
119 wxFileName workspaceFile(event.GetPath());
120 wxFileName fnCargoToml(workspaceFile);
121 fnCargoToml.SetFullName("Cargo.toml");
122 if(fnCargoToml.FileExists()) {
123 CargoToml cargoToml;
124 const wxString& name = cargoToml.Load(fnCargoToml).GetName();
125
126 // update the build commands
127 clFileSystemWorkspaceSettings settings;
128 if(!settings.Load(workspaceFile)) {
129 clWARNING() << "Failed to load file:" << workspaceFile << endl;
130 return;
131 }
132
133 wxString cargo_exe = "cargo";
134 #ifdef __WXMSW__
135 clRustLocator rust_locator;
136 if(rust_locator.Locate()) {
137 cargo_exe = rust_locator.GetRustTool("cargo");
138 ::WrapWithQuotes(cargo_exe);
139 }
140 #endif
141
142 auto debug = settings.GetConfig("Debug");
143 if(debug) {
144 clDEBUG() << "Setting project preferences..." << endl;
145 debug->SetBuildTargets({ { "build", cargo_exe + " build --color always" },
146 { "clean", cargo_exe + " clean --color always" },
147 { "tests", cargo_exe + " test --color always" },
148 { "clippy", cargo_exe + " clippy --color always" } });
149 wxFileName target_exe(workspaceFile.GetPath() + "/target/debug/" + name);
150 #ifdef __WXMSW__
151 target_exe.SetExt("exe");
152 #endif
153 debug->SetExecutable(target_exe.GetFullPath());
154 debug->SetFileExtensions(debug->GetFileExtensions() + ";*.rs;*.toml");
155 debug->SetCompiler("rustc");
156 // set the environment variable to point to rust-gdb
157 wxString env_str;
158 #if !defined(__WXMSW__)
159 // use rust-gdb
160 wxFileName rust_gdb = GetRustTool("rust-gdb");
161 if(rust_gdb.IsOk()) {
162 env_str << "GDB=" << rust_gdb.GetFullPath() << "\n";
163 env_str << "PATH=" << rust_gdb.GetPath() << clPATH_SEPARATOR << "$PATH"
164 << "\n";
165 }
166 #else
167 // use gdb batch file wrapper
168 wxFileName gdb_python_module_directory(clStandardPaths::Get().GetUserDataDir(), wxEmptyString);
169 gdb_python_module_directory.AppendDir("gdb_printers");
170 gdb_python_module_directory.AppendDir("rustlib");
171 gdb_python_module_directory.AppendDir("etc");
172
173 wxFileName gdb_exe = GetRustTool("gdb");
174 if(gdb_exe.FileExists()) {
175 env_str << "RUST_GDB=" << gdb_exe.GetFullPath() << "\n";
176 env_str << "PATH=" << gdb_exe.GetPath() << clPATH_SEPARATOR << "$PATH\n";
177 } else {
178 env_str << "RUST_GDB=gdb\n";
179 }
180
181 // copy the rust-gdb.bat script into our local folder and replace any place-holders
182 wxFileName rust_gdb_script(clStandardPaths::Get().GetBinFolder(), "rust-gdb.bat");
183 wxString rust_gdb_script_content;
184 FileUtils::ReadFileContent(rust_gdb_script, rust_gdb_script_content);
185 rust_gdb_script_content.Replace("%SCRIPTS_PATH%", gdb_python_module_directory.GetPath());
186 rust_gdb_script.SetPath(clStandardPaths::Get().GetUserDataDir());
187 FileUtils::WriteFileContent(rust_gdb_script, rust_gdb_script_content);
188
189 debug->SetDebuggerPath(rust_gdb_script.GetFullPath());
190 // build the startup commands
191 wxString gdbinit_content = R"gdbinit(
192 python
193 import sys
194 sys.path.insert(0, '%GDB_PYTHON_MODULE_DIRECTORY%')
195 import gdb_load_rust_pretty_printers
196 end
197 )gdbinit";
198 gdbinit_content.Trim().Trim(false);
199 wxString fixed_path = gdb_python_module_directory.GetPath();
200 fixed_path.Replace("\\", "/");
201 gdbinit_content.Replace("%GDB_PYTHON_MODULE_DIRECTORY%", fixed_path);
202 debug->SetDebuggerCommands(gdbinit_content);
203 #endif
204 if(!env_str.empty()) {
205 debug->SetEnvironment(env_str);
206 }
207 AddRustcCompilerIfMissing();
208 debug->SetCompiler("rustc");
209 }
210 settings.Save(workspaceFile);
211 }
212 }
213
214 void RustPlugin::OnNewWorkspace(clCommandEvent& e)
215 {
216 e.Skip();
217 if(e.GetString() == "Rust") {
218 e.Skip(false);
219 // Prompt the user for the folder to run 'cargo new'
220 NewFileSystemWorkspaceDialog dlg(EventNotifier::Get()->TopFrame(), false /* do not auto update the name */);
221 dlg.SetLabel(_("Select the folder to run 'cargo new'"));
222 if(dlg.ShowModal() != wxID_OK) {
223 return;
224 }
225
226 EnvSetter env;
227 wxString cargo_exe;
228 if(!ThePlatform->Which("cargo", &cargo_exe)) {
229 wxMessageBox(_("Could not locate cargo in your PATH"), "CodeLite", wxICON_ERROR | wxCENTRE);
230 return;
231 }
232
233 ::WrapWithQuotes(cargo_exe);
234
235 wxString command;
236 command << cargo_exe << " new " << dlg.GetWorkspaceName();
237 IProcess::Ptr_t process(::CreateSyncProcess(command, IProcessCreateDefault | IProcessCreateWithHiddenConsole,
238 dlg.GetWorkspacePath()));
239 if(!process) {
240 clWARNING() << "failed to execute:" << command << endl;
241 return;
242 }
243
244 wxString output;
245 process->WaitForTerminate(output);
246 wxFileName cargoToml(dlg.GetWorkspacePath(), "Cargo.toml");
247 cargoToml.AppendDir(dlg.GetWorkspaceName());
248 if(cargoToml.FileExists()) {
249 // we successfully created a new cargo workspace, now, load it (using the standard file system
250 // workspace)
251 clFileSystemWorkspace::Get().New(cargoToml.GetPath(), cargoToml.GetDirs().Last());
252 }
253 }
254 }
255
256 wxString RustPlugin::GetRustTool(const wxString& toolname) const
257 {
258 clRustLocator locator;
259 if(!locator.Locate()) {
260 return wxEmptyString;
261 }
262 return locator.GetRustTool(toolname);
263 }
264
265 void RustPlugin::OnBuildErrorLineClicked(clBuildEvent& event)
266 {
267 if(!clFileSystemWorkspace::Get().IsOpen()) {
268 event.Skip();
269 return;
270 }
271
272 clDEBUG() << "User requested to open file:" << event.GetFileName() << endl;
273 clDEBUG() << "Line number:" << event.GetLineNumber() << endl;
274
275 if(!FileExtManager::IsFileType(event.GetFileName(), FileExtManager::TypeRust)) {
276 event.Skip();
277 return;
278 }
279
280 event.Skip(false);
281 clDEBUG() << "Rust file clicked:" << event.GetFileName() << endl;
282
283 // build the file path:
284 // the compiler report the file in relative path to the `Cargo.toml` file
285 if(!m_cargoTomlFile.FileExists()) {
286 event.Skip(true); // let others handle this
287 return;
288 }
289
290 wxString strfile = m_cargoTomlFile.GetPath();
291 strfile << wxFILE_SEP_PATH << event.GetFileName();
292 wxFileName fnFile(strfile);
293 if(!fnFile.FileExists()) {
294 event.Skip(true); // let others handle this
295 return;
296 }
297
298 int line_number = event.GetLineNumber();
299 auto cb = [=](IEditor* editor) {
300 editor->GetCtrl()->ClearSelections();
301 // compilers report line numbers starting from `1`
302 // our editor sees line numbers starting from `0`
303 editor->CenterLine(line_number - 1, wxNOT_FOUND);
304 editor->SetActive();
305 };
306 clGetManager()->OpenFileAndAsyncExecute(fnFile.GetFullPath(), std::move(cb));
307 }
308
309 void RustPlugin::AddRustcCompilerIfMissing()
310 {
311 // Create new "rustc" compiler and place compiler patterns to use
312 clDEBUG() << "Searching for rustc compiler..." << endl;
313 if(BuildSettingsConfigST::Get()->IsCompilerExist("rustc")) {
314 clDEBUG() << "Compiler rustc already exists" << endl;
315 return;
316 }
317
318 CompilerLocatorRustc locator;
319 locator.Locate(); // it never fails
320 BuildSettingsConfigST::Get()->SetCompiler(*locator.GetCompilers().begin());
321 BuildSettingsConfigST::Get()->Flush();
322 clDEBUG() << "Successfully added new compiler 'rustc'" << endl;
323 }
324
325 void RustPlugin::OnBuildEnded(clBuildEvent& event)
326 {
327 event.Skip();
328 if(!clFileSystemWorkspace::Get().IsOpen()) {
329 return;
330 }
331
332 wxFileName fnCargoToml(clFileSystemWorkspace::Get().GetFileName());
333 fnCargoToml.SetFullName("Cargo.toml");
334 wxString cargo_toml = fnCargoToml.GetFullPath();
335 if(!wxFileName::FileExists(cargo_toml)) {
336 return;
337 }
338
339 wxString new_digest = wxMD5::GetDigest(fnCargoToml);
340 wxString old_digest;
341 if(m_cargoTomlDigest.count(cargo_toml)) {
342 old_digest = m_cargoTomlDigest[cargo_toml];
343 }
344
345 if(new_digest != old_digest) {
346 // restart is required
347 clLanguageServerEvent restart_event(wxEVT_LSP_RESTART_ALL);
348 EventNotifier::Get()->ProcessEvent(restart_event);
349 }
350 m_cargoTomlDigest[cargo_toml] = new_digest;
351 }
352
353 void RustPlugin::OnWorkspaceLoaded(clWorkspaceEvent& event)
354 {
355 event.Skip();
356 if(!clFileSystemWorkspace::Get().IsOpen()) {
357 return;
358 }
359
360 wxFileName workspaceFile = clFileSystemWorkspace::Get().GetFileName();
361 wxFileName cargo_toml{ workspaceFile.GetPath(), "Cargo.toml" };
362
363 if(cargo_toml.FileExists()) {
364 m_cargoTomlFile = cargo_toml;
365 } else {
366 // try the parent folder
367 cargo_toml.RemoveLastDir();
368 if(cargo_toml.FileExists()) {
369 m_cargoTomlFile = cargo_toml;
370 } else {
371 // We might placed our Cargo.toml in one of the children folers (1 level below)
372 // check them
373 wxArrayString dirs;
374 wxDir::GetAllFiles(workspaceFile.GetPath(), &dirs, wxEmptyString, wxDIR_DIRS | wxDIR_NO_FOLLOW);
375 for(const auto& dir : dirs) {
376 cargo_toml = wxFileName(workspaceFile.GetPath(), "Cargo.toml");
377 cargo_toml.AppendDir(dir);
378 if(cargo_toml.FileExists()) {
379 m_cargoTomlFile = cargo_toml;
380 break;
381 }
382 }
383 }
384 }
385 clDEBUG() << "Cargo.toml file found:" << m_cargoTomlFile << endl;
386 }
387
388 void RustPlugin::OnWorkspaceClosed(clWorkspaceEvent& event)
389 {
390 event.Skip();
391 m_cargoTomlFile.Clear();
392 }