File: codeformatter.cpp

package info (click to toggle)
codelite 6.1.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 48,992 kB
  • ctags: 43,502
  • sloc: cpp: 334,263; ansic: 18,441; xml: 4,713; yacc: 2,653; lex: 2,449; python: 1,188; sh: 385; makefile: 40
file content (559 lines) | stat: -rw-r--r-- 20,695 bytes parent folder | download
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : codeformatter.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include "precompiled_header.h"
#include "globals.h"
#include "editor_config.h"
#include "event_notifier.h"
#include "codeformatter.h"
#include <wx/xrc/xmlres.h>
#include <wx/app.h> //wxInitialize/wxUnInitialize
#include "wx/ffile.h"
#include "formatoptions.h"
#include "wx/log.h"
#include "codeformatterdlg.h"
#include "wx/menu.h"
#include "file_logger.h"
#include "asyncprocess.h"
#include "json_node.h"
#include <wx/ffile.h>
#include <wx/filename.h>
#include "file_logger.h"
#include "procutils.h"
#include "clSTCLineKeeper.h"

extern "C" EXPORT char* STDCALL AStyleMain(const char* pSourceIn,
                                           const char* pOptions,
                                           void(STDCALL* fpError)(int, const char*),
                                           char*(STDCALL* fpAlloc)(unsigned long));

//------------------------------------------------------------------------
// Astyle functions required by AStyleLib
// Error handler for the Artistic Style formatter
void STDCALL ASErrorHandler(int errorNumber, const char* errorMessage)
{
    wxString errStr;
    errStr << _U(errorMessage) << wxT(" (error ") << errorNumber << wxT(")");
    CL_DEBUG(errStr.c_str());
}

// Allocate memory for the Artistic Style formatter
char* STDCALL ASMemoryAlloc(unsigned long memoryNeeded)
{
    // error condition is checked after return from AStyleMain
    char* buffer = new char[memoryNeeded];
    return buffer;
}
//------------------------------------------------------------------------
static CodeFormatter* theFormatter = NULL;

// Allocate the code formatter on the heap, it will be freed by
// the application
extern "C" EXPORT IPlugin* CreatePlugin(IManager* manager)
{
    if(theFormatter == 0) {
        theFormatter = new CodeFormatter(manager);
    }
    return theFormatter;
}

extern "C" EXPORT PluginInfo GetPluginInfo()
{
    PluginInfo info;
    info.SetAuthor(wxT("Eran Ifrah"));
    info.SetName(wxT("CodeFormatter"));
    info.SetDescription(_("Source Code Formatter based on the open source AStyle tool"));
    info.SetVersion(wxT("v1.0"));
    return info;
}

extern "C" EXPORT int GetPluginInterfaceVersion() { return PLUGIN_INTERFACE_VERSION; }

CodeFormatter::CodeFormatter(IManager* manager)
    : IPlugin(manager)
{
    m_longName = _("Source Code Formatter (AStyle)");
    m_shortName = wxT("CodeFormatter");

    EventNotifier::Get()->Connect(
        wxEVT_FORMAT_STRING, clSourceFormatEventHandler(CodeFormatter::OnFormatString), NULL, this);
    EventNotifier::Get()->Connect(
        wxEVT_FORMAT_FILE, clSourceFormatEventHandler(CodeFormatter::OnFormatFile), NULL, this);
}

CodeFormatter::~CodeFormatter()
{
    EventNotifier::Get()->Connect(
        wxEVT_FORMAT_STRING, clSourceFormatEventHandler(CodeFormatter::OnFormatString), NULL, this);
    EventNotifier::Get()->Connect(
        wxEVT_FORMAT_FILE, clSourceFormatEventHandler(CodeFormatter::OnFormatFile), NULL, this);
}

clToolBar* CodeFormatter::CreateToolBar(wxWindow* parent)
{
    clToolBar* tb(NULL);
    if(m_mgr->AllowToolbar()) {
        // support both toolbars icon size
        int size = m_mgr->GetToolbarIconSize();

        tb = new clToolBar(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, clTB_DEFAULT_STYLE);
        tb->SetToolBitmapSize(wxSize(size, size));

        BitmapLoader* bmpLoader = m_mgr->GetStdIcons();
        if(size == 24) {
            tb->AddTool(XRCID("format_source"),
                        _("Format Source"),
                        bmpLoader->LoadBitmap(wxT("toolbars/24/codeformatter/code-format")),
                        _("Format Source Code"));
            tb->AddTool(XRCID("formatter_options"),
                        _("Format Options"),
                        bmpLoader->LoadBitmap(wxT("toolbars/24/codeformatter/code-format-options")),
                        _("Source Code Formatter Options..."));
        } else {
            // 16
            tb->AddTool(XRCID("format_source"),
                        _("Format Source"),
                        bmpLoader->LoadBitmap(wxT("toolbars/16/codeformatter/code-format")),
                        _("Format Source Code"));
            tb->AddTool(XRCID("formatter_options"),
                        _("Format Options"),
                        bmpLoader->LoadBitmap(wxT("toolbars/16/codeformatter/code-format-options")),
                        _("Source Code Formatter Options..."));
        }

#if defined(__WXMAC__)
        tb->AddSeparator();
#endif
        tb->Realize();
    }

    // Connect the events to us
    m_mgr->GetTheApp()->Connect(XRCID("format_source"),
                                wxEVT_COMMAND_MENU_SELECTED,
                                wxCommandEventHandler(CodeFormatter::OnFormat),
                                NULL,
                                (wxEvtHandler*)this);
    m_mgr->GetTheApp()->Connect(XRCID("formatter_options"),
                                wxEVT_COMMAND_MENU_SELECTED,
                                wxCommandEventHandler(CodeFormatter::OnFormatOptions),
                                NULL,
                                (wxEvtHandler*)this);
    m_mgr->GetTheApp()->Connect(XRCID("format_source"),
                                wxEVT_UPDATE_UI,
                                wxUpdateUIEventHandler(CodeFormatter::OnFormatUI),
                                NULL,
                                (wxEvtHandler*)this);
    m_mgr->GetTheApp()->Connect(XRCID("formatter_options"),
                                wxEVT_UPDATE_UI,
                                wxUpdateUIEventHandler(CodeFormatter::OnFormatOptionsUI),
                                NULL,
                                (wxEvtHandler*)this);
    return tb;
}

void CodeFormatter::CreatePluginMenu(wxMenu* pluginsMenu)
{
    wxMenu* menu = new wxMenu();
    wxMenuItem* item(NULL);
    item = new wxMenuItem(
        menu, XRCID("format_source"), _("Format Current Source"), _("Format Current Source"), wxITEM_NORMAL);
    menu->Append(item);
    menu->AppendSeparator();
    item = new wxMenuItem(menu, XRCID("formatter_options"), _("Options..."), wxEmptyString, wxITEM_NORMAL);
    menu->Append(item);
    pluginsMenu->Append(wxID_ANY, _("Source Code Formatter"), menu);
}

void CodeFormatter::OnFormat(wxCommandEvent& e)
{
    IEditor* editor(NULL);
    wxString fileToFormat = e.GetString();

    // If we got a file name in the event, use it instead of the active editor
    if(fileToFormat.IsEmpty() == false) {
        editor = m_mgr->FindEditor(fileToFormat);

    } else {
        editor = m_mgr->GetActiveEditor();
    }

    // get the editor that requires formatting
    if(!editor)
        return;

    // Notify about indentation about to start
    wxCommandEvent evt(wxEVT_CODEFORMATTER_INDENT_STARTING);
    evt.SetString(editor->GetFileName().GetFullPath());
    EventNotifier::Get()->ProcessEvent(evt);

    m_mgr->SetStatusMessage(
        wxString::Format(wxT("%s: %s..."), _("Formatting"), editor->GetFileName().GetFullPath().c_str()), 0);
    DoFormatFile(editor);
    m_mgr->SetStatusMessage(_("Done"), 0);
}

void CodeFormatter::DoFormatFile(IEditor* editor)
{
    int curpos = editor->GetCurrentPosition();

    // execute the formatter
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &fmtroptions);

    // We allow ClangFormat to work only when the source file is known to be
    // a C/C++ source file or JavaScript (these are the types of files that clang-format can handle properly)
    if(fmtroptions.GetEngine() == kFormatEngineClangFormat &&
       (FileExtManager::IsCxxFile(editor->GetFileName()) || FileExtManager::IsJavascriptFile(editor->GetFileName()))) {

        int from = wxNOT_FOUND, length = wxNOT_FOUND;
        wxString formattedOutput;
        if(editor->GetSelectionStart() != wxNOT_FOUND) {
            // we got a selection, only format it
            from = editor->GetSelectionStart();
            length = editor->GetSelectionEnd() - from;
            if(length <= 0) {
                from = wxNOT_FOUND;
                length = wxNOT_FOUND;
            }
        }

        // Make sure we format the editor string and _not_ the file (there might be some newly added lines
        // the could be missing ...)
        ClangFormat(editor->GetSTC()->GetText(), formattedOutput, curpos, from, length);

        clSTCLineKeeper lk(editor);
        editor->SetEditorText(formattedOutput);
        editor->SetCaretAt(curpos);

    } else {
        // AStyle
        wxString options = fmtroptions.AstyleOptionsAsString();

        // determine indentation method and amount
        bool useTabs = m_mgr->GetEditorSettings()->GetIndentUsesTabs();
        int tabWidth = m_mgr->GetEditorSettings()->GetTabWidth();
        int indentWidth = m_mgr->GetEditorSettings()->GetIndentWidth();
        options << (useTabs && tabWidth == indentWidth ? wxT(" -t") : wxT(" -s")) << indentWidth;

        wxString output;
        wxString inputString;
        bool formatSelectionOnly(editor->GetSelection().IsEmpty() == false);

        if(formatSelectionOnly) {
            // get the lines contained in the selection
            int selStart = editor->GetSelectionStart();
            int selEnd = editor->GetSelectionEnd();
            int lineNumber = editor->LineFromPos(selStart);

            selStart = editor->PosFromLine(lineNumber);
            selEnd = editor->LineEnd(editor->LineFromPos(selEnd));

            editor->SelectText(selStart, selEnd - selStart);
            inputString = editor->GetSelection();

        } else {
            inputString = editor->GetEditorText();
        }

        AstyleFormat(inputString, options, output);
        if(output.IsEmpty() == false) {

            // append new-line
            wxString eol;
            if(editor->GetEOL() == 0) { // CRLF
                eol = wxT("\r\n");
            } else if(editor->GetEOL() == 1) { // CR
                eol = wxT("\r");
            } else {
                eol = wxT("\n");
            }

            if(!formatSelectionOnly)
                output << eol;

            if(formatSelectionOnly) {
                // format the text (add the indentation)
                output = editor->FormatTextKeepIndent(
                    output, editor->GetSelectionStart(), Format_Text_Indent_Prev_Line | Format_Text_Save_Empty_Lines);
                editor->ReplaceSelection(output);

            } else {
                clSTCLineKeeper lk(editor);
                editor->SetEditorText(output);
                editor->SetCaretAt(curpos);
            }
        }
    }

    // Notify that a file was indented
    wxCommandEvent evt(wxEVT_CODEFORMATTER_INDENT_COMPLETED);
    evt.SetString(editor->GetFileName().GetFullPath());
    EventNotifier::Get()->AddPendingEvent(evt);
}

void CodeFormatter::AstyleFormat(const wxString& input, const wxString& options, wxString& output)
{
    char* textOut = AStyleMain(_C(input), _C(options), ASErrorHandler, ASMemoryAlloc);
    if(textOut) {
        output = _U(textOut);
        output.Trim();
        delete[] textOut;
    }
}

void CodeFormatter::OnFormatOptions(wxCommandEvent& e)
{
    wxUnusedVar(e);
    // load options from settings file
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &fmtroptions);

    wxString sampleFile;
    wxString content;
    sampleFile << m_mgr->GetStartupDirectory() << wxT("/astyle.sample");
    ReadFileWithConversion(sampleFile, content);

    CodeFormatterDlg dlg(NULL, m_mgr, this, fmtroptions, content);
    dlg.ShowModal();
}

void CodeFormatter::OnFormatUI(wxUpdateUIEvent& e)
{
    CHECK_CL_SHUTDOWN();
    e.Enable(m_mgr->GetActiveEditor() != NULL);
}

void CodeFormatter::OnFormatOptionsUI(wxUpdateUIEvent& e) { e.Enable(true); }

void CodeFormatter::HookPopupMenu(wxMenu* menu, MenuType type)
{
    wxUnusedVar(type);
    wxUnusedVar(menu);
}

void CodeFormatter::UnPlug()
{
    m_mgr->GetTheApp()->Disconnect(XRCID("format_source"),
                                   wxEVT_COMMAND_MENU_SELECTED,
                                   wxCommandEventHandler(CodeFormatter::OnFormat),
                                   NULL,
                                   (wxEvtHandler*)this);
    m_mgr->GetTheApp()->Disconnect(XRCID("formatter_options"),
                                   wxEVT_COMMAND_MENU_SELECTED,
                                   wxCommandEventHandler(CodeFormatter::OnFormatOptions),
                                   NULL,
                                   (wxEvtHandler*)this);
    m_mgr->GetTheApp()->Disconnect(XRCID("format_source"),
                                   wxEVT_UPDATE_UI,
                                   wxUpdateUIEventHandler(CodeFormatter::OnFormatUI),
                                   NULL,
                                   (wxEvtHandler*)this);
    m_mgr->GetTheApp()->Disconnect(XRCID("formatter_options"),
                                   wxEVT_UPDATE_UI,
                                   wxUpdateUIEventHandler(CodeFormatter::OnFormatOptionsUI),
                                   NULL,
                                   (wxEvtHandler*)this);
}

IManager* CodeFormatter::GetManager() { return m_mgr; }

void CodeFormatter::OnFormatString(clSourceFormatEvent& e)
{
    wxString str = e.GetInputString();
    if(str.IsEmpty()) {
        e.SetFormattedString(str);
        return;
    }

    // execute the formatter
    FormatOptions fmtroptions;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &fmtroptions);

    wxString output;
    if(fmtroptions.GetEngine() == kFormatEngineAStyle) {
        wxString options = fmtroptions.AstyleOptionsAsString();

        // determine indentation method and amount
        bool useTabs = m_mgr->GetEditorSettings()->GetIndentUsesTabs();
        int tabWidth = m_mgr->GetEditorSettings()->GetTabWidth();
        int indentWidth = m_mgr->GetEditorSettings()->GetIndentWidth();
        options << (useTabs && tabWidth == indentWidth ? wxT(" -t") : wxT(" -s")) << indentWidth;

        AstyleFormat(str, options, output);
        output << DoGetGlobalEOLString();

    } else if(fmtroptions.GetEngine() == kFormatEngineClangFormat) {
        ClangPreviewFormat(str, output, fmtroptions);

    } else {
        // ??
    }
    e.SetFormattedString(output);
}

int CodeFormatter::DoGetGlobalEOL() const
{
    OptionsConfigPtr options = m_mgr->GetEditorSettings();
    if(options->GetEolMode() == wxT("Unix (LF)")) {
        return 2;
    } else if(options->GetEolMode() == wxT("Mac (CR)")) {
        return 1;
    } else if(options->GetEolMode() == wxT("Windows (CRLF)")) {
        return 0;
    } else {
// set the EOL by the hosting OS
#if defined(__WXMAC__)
        return 2;
#elif defined(__WXGTK__)
        return 2;
#else
        return 0;
#endif
    }
}
wxString CodeFormatter::DoGetGlobalEOLString() const
{
    switch(DoGetGlobalEOL()) {
    case 0:
        return wxT("\r\n");
    case 1:
        return wxT("\r");
    case 2:
    default:
        return wxT("\n");
    }
}

void CodeFormatter::OnFormatFile(clSourceFormatEvent& e) { wxUnusedVar(e); }

bool CodeFormatter::ClangFormat(const wxString& content,
                                wxString& formattedOutput,
                                int& cursorPosition,
                                int startOffset,
                                int length)
{
    // Write the content into a temporary file
    wxFileName fn(wxStandardPaths::Get().GetTempDir(), "code-formatter-tmp.cpp");
    wxFFile fp(fn.GetFullPath(), "w+b");
    if(fp.IsOpened()) {
        fp.Write(content, wxConvUTF8);
        fp.Close();
    }

    FormatOptions options;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &options);
    bool res = DoClangFormat(fn, formattedOutput, cursorPosition, startOffset, length, options);
    {
        // Delete the temporary file
        wxLogNull nl;
        ::wxRemoveFile(fn.GetFullPath());
    }
    return res;
}

bool CodeFormatter::ClangFormat(const wxFileName& filename,
                                wxString& formattedOutput,
                                int& cursorPosition,
                                int startOffset,
                                int length)
{
    FormatOptions options;
    m_mgr->GetConfigTool()->ReadObject(wxT("FormatterOptions"), &options);
    return DoClangFormat(filename, formattedOutput, cursorPosition, startOffset, length, options);
}

bool CodeFormatter::ClangPreviewFormat(const wxString& content, wxString& formattedOutput, const FormatOptions& options)
{
    int startOffset, length, cursorPosition;
    startOffset = length = cursorPosition = wxNOT_FOUND;

    wxFileName fn(wxStandardPaths::Get().GetTempDir(), "code-formatter-tmp.cpp");
    wxFFile fp(fn.GetFullPath(), "w+b");
    if(fp.IsOpened()) {
        fp.Write(content, wxConvUTF8);
        fp.Close();
    }
    bool res = DoClangFormat(fn, formattedOutput, cursorPosition, startOffset, length, options);
    {
        // Delete the temporary file
        wxLogNull nl;
        ::wxRemoveFile(fn.GetFullPath());
    }
    return res;
}

bool CodeFormatter::DoClangFormat(const wxFileName& filename,
                                  wxString& formattedOutput,
                                  int& cursorPosition,
                                  int startOffset,
                                  int length,
                                  const FormatOptions& options)
{
    // clang-format
    // Build the command line to run

    if(options.GetClangFormatExe().IsEmpty()) {
        return false;
    }

    wxString command, file;

    command << options.GetClangFormatExe();
    file = filename.GetFullPath();
    ::WrapWithQuotes(command);
    ::WrapWithQuotes(file);

    command << options.ClangFormatOptionsAsString();
    if(cursorPosition != wxNOT_FOUND) {
        command << " -cursor=" << cursorPosition;
    }

    if(startOffset != wxNOT_FOUND && length != wxNOT_FOUND) {
        command << " -offset=" << startOffset << " -length=" << length;
    }
    command << " " << file;

    // Wrap the command in the local shell
    ::WrapInShell(command);

    // Log the command
    CL_DEBUG("CodeForamtter: running:\n%s\n", command);

    // Execute clang-format and reand the output
    formattedOutput.Clear();
    IProcess::Ptr_t clangFormatProc(
        ::CreateSyncProcess(command, IProcessCreateDefault | IProcessCreateWithHiddenConsole));
    CHECK_PTR_RET_FALSE(clangFormatProc);
    clangFormatProc->WaitForTerminate(formattedOutput);
    CL_DEBUG("clang-format returned with:\n%s\n", formattedOutput);

    // The first line contains the cursor position
    if(cursorPosition != wxNOT_FOUND) {
        wxString metadata = formattedOutput.BeforeFirst('\n');
        JSONRoot root(metadata);
        cursorPosition = root.toElement().namedObject("cursor").toInt(wxNOT_FOUND);
        formattedOutput = formattedOutput.AfterFirst('\n');
    }
    return true;
}