Debian Codegraph @

CodeFormatter/codeformatter.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2008 by Eran Ifrah
5 // file name : codeformatter.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 #include "codeformatter.h"
26
27 #include "JSON.h"
28 #include "StringUtils.h"
29 #include "asyncprocess.h"
30 #include "clEditorConfig.h"
31 #include "clEditorStateLocker.h"
32 #include "clFileSystemEvent.h"
33 #include "clFilesCollector.h"
34 #include "clKeyboardManager.h"
35 #include "clSFTPManager.hpp"
36 #include "clSTCLineKeeper.h"
37 #include "clWorkspaceManager.h"
38 #include "codeformatterdlg.h"
39 #include "codelite_events.h"
40 #include "editor_config.h"
41 #include "event_notifier.h"
42 #include "file_logger.h"
43 #include "fileutils.h"
44 #include "globals.h"
45 #include "macros.h"
46 #include "precompiled_header.h"
47 #include "procutils.h"
48 #include "workspace.h"
49
50 #include <algorithm>
51 #include <thread>
52 #include <wx/app.h> //wxInitialize/wxUnInitialize
53 #include <wx/ffile.h>
54 #include <wx/filename.h>
55 #include <wx/log.h>
56 #include <wx/menu.h>
57 #include <wx/msgdlg.h>
58 #include <wx/progdlg.h>
59 #include <wx/xrc/xmlres.h>
60
61 namespace
62 {
63
64 int ID_TOOL_SOURCE_CODE_FORMATTER = ::wxNewId();
65
66 //------------------------------------------------------------------------
67 CodeFormatter* theFormatter = NULL;
68
69 JSONItem json_get_formatter_object(JSON* root, const wxString& formatter_name)
70 {
71 auto json = root->toElement();
72 if(!json.hasNamedObject("tools")) {
73 return JSONItem{ nullptr };
74 }
75 auto servers = json["tools"];
76 int count = servers.arraySize();
77 for(int i = 0; i < count; ++i) {
78 auto tool = servers[i];
79 if(tool["name"].toString() != formatter_name) {
80 continue;
81 }
82 return tool;
83 }
84 return JSONItem{ nullptr };
85 }
86
87 thread_local std::unordered_map<wxString, size_t> ignore_map;
88 bool dec_save_count_if_needed(const wxString& filepath)
89 {
90 if(ignore_map.count(filepath) == 0) {
91 return false;
92 }
93
94 // we caused this event, reduce the file reference count
95 // and return
96 ignore_map[filepath] -= 1;
97 if(ignore_map[filepath] == 0) {
98 ignore_map.erase(filepath);
99 }
100 return true;
101 }
102
103 void inc_save_count(const wxString& filepath)
104 {
105 if(ignore_map.count(filepath)) {
106 ignore_map[filepath] += 1;
107 } else {
108 ignore_map[filepath] = 1;
109 }
110 }
111 } // namespace
112
113 // Allocate the code formatter on the heap, it will be freed by
114 // the application
115 CL_PLUGIN_API IPlugin* CreatePlugin(IManager* manager)
116 {
117 if(theFormatter == 0) {
118 theFormatter = new CodeFormatter(manager);
119 }
120 return theFormatter;
121 }
122
123 CL_PLUGIN_API PluginInfo* GetPluginInfo()
124 {
125 static PluginInfo info;
126 info.SetAuthor("Eran Ifrah");
127 info.SetName("Source Code Formatter");
128 info.SetDescription(_("Source Code Formatter (Supports C/C++/Obj-C/JavaScript/PHP files)"));
129 info.SetVersion("v2.0");
130 return &info;
131 }
132
133 CL_PLUGIN_API int GetPluginInterfaceVersion() { return PLUGIN_INTERFACE_VERSION; }
134
135 CodeFormatter::CodeFormatter(IManager* manager)
136 : IPlugin(manager)
137 {
138 m_manager.Load();
139 m_remoteHelper.reset(new CodeLiteRemoteHelper);
140
141 m_longName = _("Source Code Formatter");
142 m_shortName = _("Source Code Formatter");
143
144 m_mgr->GetTheApp()->Bind(wxEVT_MENU, &CodeFormatter::OnFormatProject, this, ID_TOOL_SOURCE_CODE_FORMATTER);
145 m_mgr->GetTheApp()->Bind(wxEVT_MENU, &CodeFormatter::OnFormatFiles, this, XRCID("format_files"));
146
147 EventNotifier::Get()->Bind(wxEVT_FORMAT_STRING, &CodeFormatter::OnFormatString, this);
148 EventNotifier::Get()->Bind(wxEVT_FORMAT_FILE, &CodeFormatter::OnFormatFile, this);
149 EventNotifier::Get()->Bind(wxEVT_FILE_SAVED, &CodeFormatter::OnFileSaved, this);
150 EventNotifier::Get()->Bind(wxEVT_CONTEXT_MENU_FOLDER, &CodeFormatter::OnContextMenu, this);
151 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_LOADED, &CodeFormatter::OnWorkspaceLoaded, this);
152 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_CLOSED, &CodeFormatter::OnWorkspaceClosed, this);
153
154 Bind(wxEVT_FORMAT_INPLACE_COMPELTED, &CodeFormatter::OnInplaceFormatCompleted, this);
155 Bind(wxEVT_FORMAT_COMPELTED, &CodeFormatter::OnFormatCompleted, this);
156
157 clKeyboardManager::Get()->AddAccelerator(
158 _("Source Code Formatter"),
159 { { "format_source", _("Format Current Source"), "Ctrl-I" }, { "formatter_options", _("Options...") } });
160 }
161
162 CodeFormatter::~CodeFormatter() {}
163
164 void CodeFormatter::CreateToolBar(clToolBarGeneric* toolbar)
165 {
166 clBitmapList* images = toolbar->GetBitmapsCreateIfNeeded();
167 toolbar->AddSpacer();
168 toolbar->AddTool(XRCID("format_source"), _("Format Source"), images->Add("format"), _("Format Source Code"));
169 toolbar->AddTool(XRCID("formatter_options"), _("Format Options"), images->Add("cog"),
170 _("Source Code Formatter Options..."));
171 // Connect the events to us
172
173 // format the current editor
174 m_mgr->GetTheApp()->Bind(wxEVT_MENU, &CodeFormatter::OnFormatEditor, this, XRCID("format_source"));
175 m_mgr->GetTheApp()->Bind(wxEVT_UPDATE_UI, &CodeFormatter::OnFormatEditorUI, this, XRCID("format_source"));
176 // open the settings dialog
177 m_mgr->GetTheApp()->Bind(wxEVT_MENU, &CodeFormatter::OnSettings, this, XRCID("formatter_options"));
178 m_mgr->GetTheApp()->Bind(wxEVT_UPDATE_UI, &CodeFormatter::OnSettingsUI, this, XRCID("formatter_options"));
179 }
180
181 void CodeFormatter::CreatePluginMenu(wxMenu* pluginsMenu)
182 {
183 wxMenu* menu = new wxMenu();
184 wxMenuItem* item(NULL);
185 item = new wxMenuItem(menu, XRCID("format_source"), _("Format Current Source"), _("Format Current Source"),
186 wxITEM_NORMAL);
187 menu->Append(item);
188 menu->AppendSeparator();
189 item = new wxMenuItem(menu, XRCID("formatter_options"), _("Options..."), wxEmptyString, wxITEM_NORMAL);
190 menu->Append(item);
191 pluginsMenu->Append(wxID_ANY, _("Source Code Formatter"), menu);
192 }
193
194 void CodeFormatter::OnFormatEditor(wxCommandEvent& e)
195 {
196 IEditor* editor{ nullptr };
197 const wxString& fileToFormat = e.GetString();
198
199 // If we got a file name in the event, use it instead of the active editor
200 if(!fileToFormat.empty()) {
201 editor = m_mgr->FindEditor(fileToFormat);
202 } else {
203 editor = m_mgr->GetActiveEditor();
204 }
205
206 // get the editor that requires formatting
207 CHECK_PTR_RET(editor);
208 DoFormatEditor(editor);
209 }
210 std::shared_ptr<GenericFormatter> CodeFormatter::FindFormatter(const wxString& filepath, const wxString& content) const
211 {
212 if(wxFileName(filepath).GetExt().IsEmpty()) {
213 // detect by content
214 if(!content.empty()) {
215 // we got content, use it
216 return m_manager.GetFormatterByContent(content);
217 } else if(wxFileName::FileExists(filepath)) {
218 // No content provided, but the file is a local file
219 // read the content and try again
220 wxString buffer;
221 if(FileUtils::ReadBufferFromFile(filepath, buffer, 4000)) {
222 return m_manager.GetFormatterByContent(content);
223 }
224 }
225 } else {
226 // extension
227 return m_manager.GetFormatter(filepath);
228 }
229
230 // if we reached here, we could not determine the proper formatter to use
231 return nullptr;
232 }
233
234 bool CodeFormatter::DoFormatEditor(IEditor* editor)
235 {
236 // sanity
237 CHECK_PTR_RET_FALSE(editor);
238 bool is_remote = editor->IsRemoteFile();
239 auto f = FindFormatter(editor->GetRemotePathOrLocal(), editor->GetEditorText());
240 if(!f) {
241 return false;
242 }
243
244 wxString output;
245 wxString file_path = editor->GetRemotePathOrLocal();
246
247 // save the file formatting it
248 if(editor->IsEditorModified()) {
249 editor->Save();
250 inc_save_count(file_path);
251 }
252
253 if(is_remote) {
254 return f->FormatRemoteFile(file_path, this);
255 } else {
256 return f->FormatFile(file_path, this);
257 }
258 }
259
260 bool CodeFormatter::DoFormatString(const wxString& content, const wxString& fileName, wxString* output)
261 {
262 if(content.empty()) {
263 return false;
264 }
265
266 auto formatter = FindFormatter(fileName, content);
267 if(!formatter) {
268 clDEBUG() << "Could not find suitable formatter for file:" << fileName << endl;
269 return false;
270 }
271 return formatter->FormatString(content, fileName, output);
272 }
273
274 void CodeFormatter::ReloadCurrentEditor()
275 {
276 // reload the current editor
277 wxCommandEvent reload_event{ wxEVT_CMD_RELOAD_EXTERNALLY_MODIFIED_NOPROMPT };
278 EventNotifier::Get()->ProcessEvent(reload_event);
279 }
280
281 bool CodeFormatter::DoFormatFile(const wxString& fileName, bool is_remote_format)
282 {
283 auto f = FindFormatter(fileName);
284 if(!f) {
285 clDEBUG() << "Could not find suitable formatter for file:" << fileName << endl;
286 return false;
287 }
288
289 if(is_remote_format) {
290 return f->FormatRemoteFile(fileName, this);
291 } else {
292 return f->FormatFile(fileName, this);
293 }
294 }
295
296 void CodeFormatter::OnSettings(wxCommandEvent& e)
297 {
298 wxUnusedVar(e);
299
300 CodeFormatterDlg dlg(EventNotifier::Get()->TopFrame(), m_manager);
301 if(dlg.ShowModal() == wxID_OK) {
302 // save the changes to the file system
303 m_manager.Save();
304 } else {
305 // reload all changes from the file system
306 m_manager.Load();
307 }
308 }
309
310 void CodeFormatter::OnFormatEditorUI(wxUpdateUIEvent& e)
311 {
312 CHECK_CL_SHUTDOWN();
313 e.Enable(m_mgr->GetActiveEditor() != NULL);
314 }
315
316 void CodeFormatter::OnSettingsUI(wxUpdateUIEvent& e) { e.Enable(true); }
317
318 void CodeFormatter::OnContextMenu(clContextMenuEvent& event)
319 {
320 event.Skip();
321 event.GetMenu()->Append(XRCID("format_files"), _("Source Code Formatter"));
322 m_selectedFolder = event.GetPath();
323 }
324
325 void CodeFormatter::HookPopupMenu(wxMenu* menu, MenuType type)
326 {
327 wxUnusedVar(type);
328 wxUnusedVar(menu);
329
330 if(type == MenuTypeFileView_Project) {
331 // Project context menu
332 menu->Prepend(ID_TOOL_SOURCE_CODE_FORMATTER, _("Source Code Formatter"));
333 }
334 }
335
336 void CodeFormatter::UnPlug()
337 {
338 m_mgr->GetTheApp()->Unbind(wxEVT_MENU, &CodeFormatter::OnFormatEditor, this, XRCID("format_source"));
339 m_mgr->GetTheApp()->Unbind(wxEVT_UPDATE_UI, &CodeFormatter::OnFormatEditorUI, this, XRCID("format_source"));
340 m_mgr->GetTheApp()->Unbind(wxEVT_MENU, &CodeFormatter::OnSettings, this, XRCID("formatter_options"));
341 m_mgr->GetTheApp()->Unbind(wxEVT_UPDATE_UI, &CodeFormatter::OnSettingsUI, this, XRCID("formatter_options"));
342
343 m_mgr->GetTheApp()->Unbind(wxEVT_MENU, &CodeFormatter::OnFormatProject, this, ID_TOOL_SOURCE_CODE_FORMATTER);
344 m_mgr->GetTheApp()->Unbind(wxEVT_MENU, &CodeFormatter::OnFormatFiles, this, XRCID("format_files"));
345
346 EventNotifier::Get()->Unbind(wxEVT_FORMAT_STRING, &CodeFormatter::OnFormatString, this);
347 EventNotifier::Get()->Unbind(wxEVT_FORMAT_FILE, &CodeFormatter::OnFormatFile, this);
348 EventNotifier::Get()->Unbind(wxEVT_FILE_SAVED, &CodeFormatter::OnFileSaved, this);
349 EventNotifier::Get()->Unbind(wxEVT_CONTEXT_MENU_FOLDER, &CodeFormatter::OnContextMenu, this);
350
351 Unbind(wxEVT_FORMAT_INPLACE_COMPELTED, &CodeFormatter::OnInplaceFormatCompleted, this);
352 Unbind(wxEVT_FORMAT_COMPELTED, &CodeFormatter::OnFormatCompleted, this);
353 }
354
355 IManager* CodeFormatter::GetManager() { return m_mgr; }
356
357 void CodeFormatter::OnFormatString(clSourceFormatEvent& e)
358 {
359 wxString output;
360 if(DoFormatString(e.GetInputString(), e.GetFileName(), &output)) {
361 e.SetFormattedString(output);
362 } else {
363 e.SetFormattedString(wxEmptyString);
364 }
365 }
366
367 void CodeFormatter::OnFormatFile(clSourceFormatEvent& e)
368 {
369 e.Skip(false);
370 if(!DoFormatFile(e.GetFileName(), false)) {
371 // let someone else handle this
372 e.Skip();
373 }
374 }
375
376 void CodeFormatter::OnFormatFiles(wxCommandEvent& event)
377 {
378 wxUnusedVar(event);
379 clGetManager()->SetStatusMessage(_("Code Formatter: scanning for files..."));
380 std::thread thr(
381 [=](const wxString& rootFolder, CodeFormatter* formatter) {
382 clFilesScanner fs;
383 std::vector<wxFileName> files;
384 fs.Scan(rootFolder, files, "*", "*.o;*.obj;*.dll;*.a;*.exe;*.dylib;*.db", "build-*;.codelite;.git;.svn");
385
386 std::vector<wxString> arrfiles;
387 arrfiles.reserve(files.size());
388 for(const wxFileName& f : files) {
389 if(m_manager.CanFormat(f.GetFullName())) {
390 arrfiles.push_back(f.GetFullPath());
391 }
392 }
393 formatter->CallAfter(&CodeFormatter::OnScanFilesCompleted, arrfiles);
394 },
395 m_selectedFolder, this);
396 thr.detach();
397 }
398
399 void CodeFormatter::OnFormatProject(wxCommandEvent& event)
400 {
401 wxUnusedVar(event);
402 TreeItemInfo selectedItem = m_mgr->GetSelectedTreeItemInfo(TreeFileView);
403 if(selectedItem.m_itemType != ProjectItem::TypeProject) {
404 return;
405 }
406
407 ProjectPtr pProj = clCxxWorkspaceST::Get()->GetProject(selectedItem.m_text);
408 CHECK_PTR_RET(pProj);
409
410 const Project::FilesMap_t& allFiles = pProj->GetFiles();
411
412 std::vector<wxString> filesToFormat;
413 filesToFormat.reserve(allFiles.size());
414
415 for(const auto& vt : allFiles) {
416 if(m_manager.CanFormat(vt.second->GetFilename())) {
417 filesToFormat.push_back(vt.second->GetFilename());
418 }
419 }
420 BatchFormat(filesToFormat, false);
421 }
422
423 void CodeFormatter::BatchFormat(const std::vector<wxString>& files, bool silent)
424 {
425 if(files.empty()) {
426 if(!silent) {
427 ::wxMessageBox(_("Project contains no supported files"));
428 }
429 return;
430 }
431
432 if(!silent) {
433 wxString msg;
434 msg << _("You are about to beautify ") << files.size() << _(" files\nContinue?");
435 if(wxYES != ::wxMessageBox(msg, _("Source Code Formatter"), wxYES_NO | wxCANCEL | wxCENTER)) {
436 return;
437 }
438 }
439
440 for(size_t i = 0; i < files.size(); ++i) {
441 wxString msg;
442 msg << "Formatting file: " << (i + 1) << "/" << files.size() << " " << files[i];
443 if(!silent) {
444 clGetManager()->SetStatusMessage(msg, 1);
445 wxSafeYield();
446 }
447 DoFormatFile(files[i], false);
448 }
449
450 if(!silent) {
451 clGetManager()->SetStatusMessage(wxString() << _("Successfully formatted ") << files.size() << _(" files"), 3);
452 wxSafeYield();
453 }
454 EventNotifier::Get()->PostReloadExternallyModifiedEvent(false);
455 }
456
457 void CodeFormatter::OnScanFilesCompleted(const std::vector<wxString>& files) { BatchFormat(files, false); }
458
459 void CodeFormatter::OnWorkspaceLoaded(clWorkspaceEvent& e)
460 {
461 e.Skip();
462 m_remoteHelper->ProcessEvent(e);
463 auto config = m_remoteHelper->GetPluginConfig("Source Code Formatter");
464
465 // reset the remote commands from the previous workspace
466 m_manager.ClearRemoteCommands();
467
468 if(!config) {
469 return;
470 }
471
472 wxArrayString all_tools;
473 m_manager.GetAllNames(&all_tools);
474
475 // update the formatters with the remote command template
476 // note: we do not replace macros here since some of them
477 // might change per activation (e.g. $(CurrentFileRelPath))
478 for(size_t i = 0; i < all_tools.size(); ++i) {
479 const wxString& tool_name = all_tools[i];
480 auto json = json_get_formatter_object(config, tool_name);
481 if(!json.isOk() || (m_manager.GetFormatterByName(tool_name) == nullptr)) {
482 continue;
483 }
484
485 wxString cmd = json["command"].toString();
486 wxString wd = json["working_directory"].toString();
487
488 wxString remote_cmd;
489 if(m_remoteHelper->BuildRemoteCommand(cmd, {}, wd, &remote_cmd)) {
490 m_manager.GetFormatterByName(tool_name)->SetRemoteCommand(remote_cmd);
491 }
492 }
493 }
494
495 void CodeFormatter::OnWorkspaceClosed(clWorkspaceEvent& e)
496 {
497 e.Skip();
498 m_remoteHelper->ProcessEvent(e);
499 }
500
501 void CodeFormatter::OnFileSaved(clCommandEvent& e)
502 {
503 // keep track on files that caused "OnSave" because of this method
504 const wxString& filepath = e.GetFileName();
505 e.Skip();
506
507 // Check that we can handle this file
508 auto f = FindFormatter(e.GetFileName());
509 CHECK_PTR_RET(f);
510
511 // Find the editor and format it
512 auto editor = clGetManager()->FindEditor(filepath);
513 CHECK_PTR_RET(editor);
514
515 // is format required?
516 if(!f->IsFormatOnSave()) {
517 return;
518 }
519
520 // did we cause the OnSave event?
521 if(dec_save_count_if_needed(filepath)) {
522 return;
523 }
524
525 if(!DoFormatEditor(editor)) {
526 return;
527 }
528 }
529
530 void CodeFormatter::OnFormatCompleted(clSourceFormatEvent& event)
531 {
532 event.Skip();
533 const wxString& filepath = event.GetFileName();
534 auto editor = clGetManager()->FindEditor(filepath);
535
536 if(editor) {
537 editor->GetCtrl()->BeginUndoAction();
538 clEditorStateLocker locker{ editor->GetCtrl() };
539 editor->GetCtrl()->SetText(event.GetFormattedString());
540 editor->GetCtrl()->EndUndoAction();
541 m_mgr->SetStatusMessage(_("Done"), 0);
542
543 if(editor->IsEditorModified() /* it should be.. */) {
544 // need to set the editor back to "saved" status
545 editor->Save();
546 inc_save_count(filepath);
547 }
548 } else {
549 // no editor is opened, update the file content
550 if(wxFileExists(filepath)) {
551 FileUtils::WriteFileContent(filepath, event.GetFormattedString());
552 }
553 }
554 }
555
556 void CodeFormatter::OnInplaceFormatCompleted(clSourceFormatEvent& event)
557 {
558 event.Skip();
559 const wxString& filepath = event.GetFileName();
560 auto editor = clGetManager()->FindEditor(filepath);
561
562 if(editor) {
563 // need to update the file itself
564 editor->ReloadFromDisk(true);
565 }
566
567 // since the file was modified outside of the IDE, we need to notify CodeLite
568 // we do this by firing a wxEVT_FILE_MODIFIED_EXTERNALLY event
569 clFileSystemEvent event_modified{ wxEVT_FILE_MODIFIED_EXTERNALLY };
570 event_modified.SetPath(filepath);
571 event_modified.SetIsRemoteFile(!wxFileName::FileExists(filepath));
572 EventNotifier::Get()->AddPendingEvent(event_modified);
573 }