Skip to content

Commit

Permalink
List alignment algorithm
Browse files Browse the repository at this point in the history
Добавлен в проект выравниватель списков IN и других упорядоченных данных.
Вызывается комбинацией Ctrl+Shift+A (если внешний выравниватель не задан).
Интегрировать код выравнивателя пришлось из-за бага wxWidgets.
Ошибочное поведение появляется при вызове внешних утилит,
если им передаётся большой объём текста (более 6 кб).
Выравниватель может зациклиться на произвольных наборах данных.
Используйте с осторожностью.
Выравниватель имеет диалог настройки работы:
При выборе первого пункта диалога все переводы строк остаются как есть.
При выборе второго пункта первая строка будет образцом длинны
и под неё будут подгонятся все прочие строки.
Первый вариант используется для выравнивания insert команд.
Второй для списков IN.
Третий параметр используется, если иногда встречаются короткие строки алгоритм пытается найти выше строку которая больше или равна
текущей.
Например эти строки будут смотреться лучше:
int rs = 0;
int ls = 0;
int type = 0;
int up_item = -1;
bool br = false;
private:
int align = LEFT;
int maxlen = 0;
wxString it;
  • Loading branch information
lsv committed May 22, 2023
1 parent 2fbed7a commit c197ea4
Show file tree
Hide file tree
Showing 7 changed files with 580 additions and 2 deletions.
48 changes: 46 additions & 2 deletions ctl/ctlSQLBox.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
#include "utils/sysProcess.h"
#include <wx/clipbrd.h>
#include <wx/aui/aui.h>

#include "utils/align/AlignWrap.h"
wxString ctlSQLBox::sqlKeywords;
static const wxString s_leftBrace(_T("([{"));
static const wxString s_rightBrace(_T(")]}"));
Expand Down Expand Up @@ -952,6 +952,50 @@ wxString ctlSQLBox::ExternalFormat(int typecmd)
}
if (formatCmd.IsEmpty())
{
if (typecmd == 1) {
//internal align
AlignWrap a;
wxString lineEnd;
switch (GetEOLMode())
{
case wxSTC_EOL_LF:
lineEnd = wxT("\n");
break;
case wxSTC_EOL_CRLF:
lineEnd = wxT("\r\n");
break;
case wxSTC_EOL_CR:
lineEnd = wxT("\r");
break;
}
wxArrayString choiceCmpOpts;
wxArrayInt choiceSelectOpts;
choiceCmpOpts.Add("All line (use all EOL)");
choiceCmpOpts.Add("First line pattern (ignore all but the first EOL)");
choiceCmpOpts.Add("Try looking for patterns above");
wxMultiChoiceDialog dialog(this,
wxT("A multi-choice convenience dialog"),
wxT("Please select several align options"),
choiceCmpOpts);
dialog.SetSelections(choiceSelectOpts);
int cfg = 0;
if (dialog.ShowModal() == wxID_OK) {
choiceSelectOpts = dialog.GetSelections();

for (size_t n = 0; n < choiceSelectOpts.GetCount(); n++) {
if (choiceSelectOpts[n] == 0) cfg |= AlignWrap::ALL_LINES;
if (choiceSelectOpts[n] == 1 ) cfg |= AlignWrap::FIRST_LINE ;
if (choiceSelectOpts[n] == 2) cfg |= AlignWrap::FIND_UP_LONG_LINE;

}
if (CHKCFGPARAM(cfg, AlignWrap::ALL_LINES) && CHKCFGPARAM(cfg, AlignWrap::FIRST_LINE)) cfg -= AlignWrap::FIRST_LINE;
}
else return _("Cancel");


processOutput=a.build(processInput, cfg, lineEnd);
goto theend;
}
return _("You need to setup a "+msgword+"ing command");
}

Expand Down Expand Up @@ -1007,7 +1051,7 @@ wxString ctlSQLBox::ExternalFormat(int typecmd)
{
return _("" + msgword + "ing command error: Output is empty.");
}

theend:
if (isSelected)
ReplaceSelection(processOutput);
else
Expand Down
39 changes: 39 additions & 0 deletions include/utils/align/AlignWrap.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#pragma once
#include "Item.h"

class AlignWrap {
public:
enum cfg
{
// Выравнивание списка строк можно использовать вместе с FIND_UP_LONG_LINE
// например insert команды с одинаковым перечнем элементов
ALL_LINES = 1,
// выравнивание по длинне первой строки
// все переводы строк начиная со второй строки игнорируются
// удобно для выравнивания списков IN
FIRST_LINE= 2,
// вспомогательный флаг применяется если встречаются случайные короткие строки
// и при помощи этого флага ищутся более длинные строки обработанные ранее
FIND_UP_LONG_LINE=4
};
AlignWrap() {}
#define CHKCFGPARAM(val,par) ((val & par)==par)

wxString build(wxString & strsrc, int config,wxString linesep);
void Resize(int idx, int newSize);
wxString range_print(int s, int e);
private:

int range_size(int s, int e);
int range_size(int s);
Item parseItem(int &pos, bool &breakline);
int chkspace(int &pos, bool& br);
int find(int s, int e, Item& k);
//
int parserows = 0;

std::vector <Item> list;

wxString str, lnsep;
int cfg = 0;
};
48 changes: 48 additions & 0 deletions include/utils/align/Item.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#pragma once
#include <wx/wx.h>
class Item {
public:
enum align
{
LEFT = 0,
RIGHT
};
enum type
{
SPACE = 0,
NUM,
WORD,
LITERAL,
ANCHOR,
COMMENT
};

Item(const wxString &str, int type_item, int align_type=LEFT) {
it = str;
type = type_item;
align = align_type;
}
bool operator==(const Item& rh);
bool operator!=(const Item& rh);
wxString print();
wxString println();
const wxString getValue() { return it; }
const wxString getComment() { return comment; }
const int getMaxSize();
const int getParent() { return up_item; }
void setMaxSize(int newSize);
const void add_space(int align, int count_space) { if (align == Item::align::LEFT) rs += count_space; else ls+= count_space;}
const void setParent(int idxPar) { up_item = idxPar; };
const void setComment(wxString c) { comment = c; };
int rs = 0;
int ls = 0;
int type = 0;
int up_item = -1;
bool br = false;
private:
int align = LEFT;
int maxlen = 0;
wxString it;
wxString comment;

};
4 changes: 4 additions & 0 deletions pgAdmin3.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,8 @@
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</PrecompiledHeader>
</ClCompile>
<ClCompile Include="utils\align\AlignWrap.cpp" />
<ClCompile Include="utils\align\Item.cpp" />
<ClCompile Include="utils\csvfiles.cpp" />
<ClCompile Include="utils\diff_match_patch.cc">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
Expand Down Expand Up @@ -1570,6 +1572,8 @@
<ClInclude Include="include\schema\pgPublication.h" />
<ClInclude Include="include\schema\pgSubscription.h" />
<ClInclude Include="include\svnversion.h" />
<ClInclude Include="include\utils\align\AlignWrap.h" />
<ClInclude Include="include\utils\align\Item.h" />
<ClInclude Include="include\utils\json\jsonreader.h" />
<ClInclude Include="include\utils\json\jsonval.h" />
<ClInclude Include="include\utils\json\jsonwriter.h" />
Expand Down
12 changes: 12 additions & 0 deletions pgAdmin3.vcxproj.filters
Original file line number Diff line number Diff line change
Expand Up @@ -1668,6 +1668,12 @@
<ClCompile Include="ctl\ctlGitPanel.cpp">
<Filter>ctl</Filter>
</ClCompile>
<ClCompile Include="utils\align\AlignWrap.cpp">
<Filter>utils</Filter>
</ClCompile>
<ClCompile Include="utils\align\Item.cpp">
<Filter>utils</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="agent\module.mk">
Expand Down Expand Up @@ -3587,6 +3593,12 @@
<ClInclude Include="include\ctl\ctlGitPanel.h">
<Filter>include\ctl</Filter>
</ClInclude>
<ClInclude Include="include\utils\align\AlignWrap.h">
<Filter>include\utils</Filter>
</ClInclude>
<ClInclude Include="include\utils\align\Item.h">
<Filter>include\utils</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<png2c Include="include\images\aggregate-sm.png">
Expand Down

0 comments on commit c197ea4

Please sign in to comment.