Plutonergy

Importstyler.py [protected]

May 7th, 2021 (edited)
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.10 KB | None | 0 0
  1. -----BEGIN PGP SIGNED MESSAGE-----
  2. Hash: SHA512
  3.  
  4. from PyQt5               import QtWidgets
  5. from PyQt5.QtCore        import Qt
  6. from PyQt5.QtWidgets     import QLabel, QPlainTextEdit, QPushButton, QSpinBox
  7. from PyQt5.QtWidgets     import QTextEdit
  8. from pygments            import highlight
  9. from pygments.formatters import HtmlFormatter
  10. from pygments.lexers     import get_lexer_by_name
  11. import copy
  12. import sys
  13.  
  14. cutvalue = 80
  15.  
  16. class StairWarLabel(QtWidgets.QLabel):
  17.     def __init__(self, place, main):
  18.         super().__init__(place)
  19.         self.setStyleSheet('background-color: rgba(50,50,150,175);color: rgba(255, 212, 42, 255)')
  20.         self.main = main
  21.         self.mode = 1
  22.         self.show()
  23.  
  24.     def change_mode(self):
  25.         if self.mode + 1 in self.modedict:
  26.             self.mode += 1
  27.         else:
  28.             self.mode = 1
  29.  
  30.     def process_stairs(self):
  31.         lefttext = self.main.lefttext.toPlainText()
  32.         if len(lefttext) == 0:
  33.             return
  34.  
  35.  
  36.         self.modedict = {1: "", 2: "", 3: "", 4: "", 5: "", 6: ""}
  37.         tmpdict = {}
  38.         longest = -1
  39.         heads = []
  40.         contents = lefttext.split('\n')
  41.  
  42.         for i in contents:
  43.             if i.find('=') == -1:
  44.                 continue
  45.             while i.find('  ') > -1:
  46.                 i = i.replace('  ', ' ')
  47.  
  48.             i = i.replace('\t', "")
  49.  
  50.             i = self.main.string_stripper(i)
  51.             minilist = i.split('=')
  52.             if len(minilist) != 2:
  53.                 return
  54.  
  55.             minilist[0] = self.main.string_stripper(minilist[0])
  56.             minilist[1] = self.main.string_stripper(minilist[1])
  57.  
  58.             if len(minilist[0]) > longest:
  59.                 longest = len(minilist[0])
  60.  
  61.             heads.append(minilist[0])
  62.             tmpdict.update({minilist[0]: minilist[1]})
  63.  
  64.         heads.sort(key=str.casefold)
  65.         lenheads = copy.copy(heads)
  66.         reverse_lenheads = copy.copy(heads)
  67.         lenheads.sort(key=len)
  68.         reverse_lenheads.sort(key=len, reverse=True)
  69.         for count, i in enumerate(heads):
  70.             self.modedict[1] += f'{i} = {tmpdict[i]}\n'
  71.             self.modedict[2] += f'{i}{" " * (longest - len(i))} = {tmpdict[i]}\n'
  72.  
  73.             ii = lenheads[count]
  74.             self.modedict[3] += f'{ii}{" " * (longest - len(ii))} = {tmpdict[ii]}\n'
  75.             self.modedict[4] += f'{ii} = {tmpdict[ii]}\n'
  76.  
  77.             iii = reverse_lenheads[count]
  78.             self.modedict[5] += f'{iii}{" " * (longest - len(iii))} = {tmpdict[iii]}\n'
  79.             self.modedict[6] += f'{iii} = {tmpdict[iii]}\n'
  80.  
  81.         self.change_mode()
  82.         self.main.righttext.setText(self.main.format_text(self.modedict[self.mode]))
  83.         if self.mode == 1:
  84.             self.main.setWindowTitle("Alphabetically sorted")
  85.         elif self.mode == 2:
  86.             self.main.setWindowTitle("Alphabetically sorted extra space")
  87.         elif self.mode == 3:
  88.             self.main.setWindowTitle("String lengths")
  89.         elif self.mode == 4:
  90.             self.main.setWindowTitle("String lengths extra space")
  91.         elif self.mode == 5:
  92.             self.main.setWindowTitle("String lengths reversed")
  93.         elif self.mode == 6:
  94.             self.main.setWindowTitle("String lengths extra space reversed")
  95.  
  96.     def mousePressEvent(self, ev):
  97.         self.main.u_turn = True
  98.         if ev.button() == 1:
  99.             self.process_stairs()
  100.  
  101.         self.main.u_turn = False
  102.  
  103. class SortLabel(StairWarLabel):
  104.     def sort_only(self):
  105.         lefttext = self.main.lefttext.toPlainText()
  106.         contents = lefttext.split('\n')
  107.  
  108.         self.modedict = {1: "", 2: "", 3: "", 4: ""}
  109.  
  110.         finallist = []
  111.         for i in contents:
  112.  
  113.             while i.find('  ') > -1:
  114.                 i = i.replace('  ', ' ')
  115.  
  116.             i = i.replace('\t', "")
  117.  
  118.             i = self.main.string_stripper(i)
  119.             finallist.append(i)
  120.  
  121.         self.change_mode()
  122.  
  123.         if self.mode == 1:
  124.             finallist.sort()
  125.             self.main.setWindowTitle("Alphabetically sorted")
  126.         elif self.mode == 2:
  127.             finallist.sort(reverse=True)
  128.             self.main.setWindowTitle("Alphabetically reversed")
  129.         elif self.mode == 3:
  130.             finallist.sort(key=len)
  131.             self.main.setWindowTitle("Alphabetically string lengts")
  132.         elif self.mode == 4:
  133.             finallist.sort(key=len, reverse=True)
  134.             self.main.setWindowTitle("Alphabetically string lengts reversed")
  135.  
  136.         self.modedict[self.mode] = '\n'.join(finallist)
  137.         self.main.righttext.setText(self.main.format_text(self.modedict[self.mode]))
  138.  
  139.     def mousePressEvent(self, ev):
  140.         self.main.u_turn = True
  141.         if ev.button() == 1:
  142.             self.sort_only()
  143.         self.main.u_turn = False
  144.  
  145. class CompareLabel(QtWidgets.QLabel):
  146.     def __init__(self, place, main):
  147.         super().__init__(place)
  148.         self.setStyleSheet('background-color: rgba(50,150,50,175);color: rgba(255, 212, 42, 255)')
  149.         self.main = main
  150.         self.show()
  151.  
  152.     def mousePressEvent(self, ev):
  153.         if ev.button() == 1:
  154.             if self.main.lines == True:
  155.                 self.main.lines = False
  156.                 self.main.u_turn = True
  157.                 self.main.lefttext.setText(self.main.format_text(self.main.backup_left))
  158.                 self.main.righttext.setText(self.main.format_text(self.main.backup_right))
  159.                 self.main.u_turn = False
  160.             else:
  161.                 self.main.lines = True
  162.                 self.main.compare_sides()
  163.  
  164. class Styler(QtWidgets.QMainWindow):
  165.     def __init__(self):
  166.         super(Styler, self).__init__()
  167.         self.setWindowTitle('I can grow my own banans!')
  168.         self.setFixedSize(1920,1080)
  169.         self.setStyleSheet('background-color: gray;color: white')
  170.         self.move(800,300)
  171.         self.lefttext = QTextEdit(self)
  172.         self.righttext = QTextEdit(self)
  173.  
  174.         self.lefttext_scrollbar = self.lefttext.verticalScrollBar()
  175.         self.righttext_scrollbar = self.righttext.verticalScrollBar()
  176.         self.lefttext_scrollbar.hide()
  177.         self.righttext_scrollbar.hide()
  178.  
  179.         self.spinbox = QSpinBox(self)
  180.  
  181.         self.lefttext.setStyleSheet('background-color: rgba(36, 30, 37, 255);color: rgba(255, 212, 42, 255)')
  182.         self.righttext.setStyleSheet('background-color: rgba(26, 20, 27, 255);color: rgba(255, 212, 42, 255)')
  183.         self.spinbox.setStyleSheet('background-color: brown;color: rgba(255, 212, 42, 255)')
  184.  
  185.         self.spinbox.setButtonSymbols(2)
  186.         self.spinbox.setAlignment(Qt.AlignCenter)
  187.         self.spinbox.setGeometry(int(self.width() * 0.5) - 30, self.height() - 65, 60, 30)
  188.         self.spinbox.setValue(cutvalue)
  189.  
  190.         self.comparelabel = CompareLabel(self, self)
  191.         self.comparelabel.setGeometry(int(self.width() * 0.5) - 30, self.spinbox.geometry().top() - 40, 60, 30)
  192.  
  193.         self.stairwaylabel = StairWarLabel(self, self)
  194.         self.stairwaylabel.setGeometry(int(self.width() * 0.5) - 30, self.comparelabel.geometry().top() - 40, 60, 30)
  195.  
  196.         self.sortonlylabel = SortLabel(self, self)
  197.         self.sortonlylabel.setStyleSheet('background-color: rgba(150,50,50,175);color: rgba(255, 212, 42, 255)')
  198.         self.sortonlylabel.setGeometry(int(self.width() * 0.5) - 30, self.stairwaylabel.geometry().top() - 40, 60, 30)
  199.  
  200.         self.lefttext.setFixedSize(int(self.width() * 0.5) -20, self.height() - 10)
  201.         self.righttext.setFixedSize(int(self.width() * 0.5) -20, self.height() - 10)
  202.         self.lefttext.move(5,5)
  203.         self.righttext.move(int(self.width() * 0.5) + 15, 5)
  204.         self.lefttext.textChanged.connect(self.style_text)
  205.         self.lines = False
  206.  
  207.         self.show()
  208.  
  209.     def style_text(self):
  210.         if 'u_turn' in dir(self) and self.u_turn == True:
  211.             return
  212.  
  213.         self.lines = False
  214.         self.final = ""
  215.         self.sort_dict = {}
  216.  
  217.         text = self.lefttext.toPlainText()
  218.         new_text = self.format_text(text)
  219.         self.u_turn = True
  220.         self.lefttext.setText(new_text)
  221.         self.u_turn = False
  222.  
  223.         text_list = text.split('\n')
  224.  
  225.         caught = self.add_possible_strings(text_list)
  226.         caught = self.sort_imports_accordingly(caught)
  227.         self.sort_froms_accordingly(caught)
  228.         self.put_together()
  229.         formated_text = self.format_text(self.final)
  230.         self.righttext.setText(formated_text)
  231.  
  232.     def compare_sides(self):
  233.         def count_errors(list_one, list_two):
  234.             list_one = list_one.split()
  235.             list_two = list_two.split()
  236.             rows_of_errors = []
  237.             for count in range(len(list_one)):
  238.                 if count+1 > len(list_two):
  239.                     break
  240.                 if list_one[count] != list_two[count]:
  241.                     rows_of_errors.append(count-3)
  242.             return rows_of_errors
  243.  
  244.         def do_this(text, rows_of_errors):
  245.             splitlist = text.split('\n')
  246.             for c in range(len(splitlist) - 1, -1, -1):
  247.                 if c not in rows_of_errors:
  248.                     splitlist[c] = '\t' + splitlist[c]
  249.                 else:
  250.                     splitlist[c] = '->\t' + splitlist[c]
  251.  
  252.             splitlist.insert(0, ' ')
  253.             splitlist.insert(0, ' ')
  254.             splitlist.insert(0, f'I find {len(rows_of_errors)} unaligned rows!')
  255.             rv = '\n'.join(splitlist)
  256.             return rv
  257.  
  258.         self.backup_left = self.lefttext.toPlainText()
  259.         self.backup_right = self.righttext.toPlainText()
  260.  
  261.         left = copy.copy(self.backup_left)
  262.         right = copy.copy(self.backup_right)
  263.  
  264.         rows_of_errors = count_errors(left, right)
  265.  
  266.         left = do_this(left, rows_of_errors)
  267.         right = do_this(right, rows_of_errors)
  268.  
  269.         self.u_turn = True
  270.         self.lefttext.setText(self.format_text(left))
  271.         self.righttext.setText(self.format_text(right))
  272.         self.u_turn = False
  273.  
  274.     def format_text(self, orgstring):
  275.         lexer = get_lexer_by_name("python", stripall=True)
  276.         formatter = HtmlFormatter(cssclass="source", full=True, linenos=self.lines)
  277.         new_text = highlight(orgstring, lexer, formatter)
  278.  
  279.         return new_text
  280.  
  281.     def add_possible_strings(self, text_list):
  282.         caught = []
  283.         self.top = []
  284.         self.bottom = []
  285.  
  286.         primary_work_done = False
  287.         for count, i in enumerate(text_list):
  288.             i = i.strip()
  289.             if len(i) > len('import ') and i[0:len('import ')] == 'import ' or i[0:len('from ')] == 'from ':
  290.                 caught.append(i)
  291.             else:
  292.                 if len(i) > 2 and i[0:3] == '"""':
  293.                     pass
  294.                 elif len(i) > 2 and i[0:3] == "'''":
  295.                     pass
  296.                 elif len(i) > 0 and i[0] == '#':
  297.                     pass
  298.                 else:
  299.                     primary_work_done = True
  300.  
  301.                 if primary_work_done == True:
  302.                     self.bottom.append(text_list[count].rstrip('\n').rstrip())
  303.                 else:
  304.                     self.top.append(text_list[count].rstrip('\n').rstrip())
  305.  
  306.         return caught
  307.  
  308.     def put_together(self):
  309.         self.final += '\n'.join(self.top)
  310.  
  311.         if 'from' in self.sort_dict:
  312.             x = self.sort_dict['from']
  313.             froms = {k: v for k, v in sorted(x.items(), key=lambda item: item[0])}
  314.  
  315.             max = -1
  316.             for i in froms:
  317.                 if len(i) >= max:
  318.                     max = len(i)+1
  319.  
  320.             for eachfrom in froms:
  321.                 string = 'from ' + eachfrom + (" " * (max - len(eachfrom)))
  322.                 for count, imports in enumerate(froms[eachfrom]):
  323.                     if count == 0:
  324.                         string += f'import {imports}, '
  325.                     else:
  326.                         if len(string) + len(imports) > self.spinbox.value():
  327.                             self.final += string.rstrip(', ') + '\n'
  328.                             string = 'from ' + eachfrom + (" " * (max - len(eachfrom))) + 'import '
  329.  
  330.                         string += imports + ', '
  331.  
  332.                     if count+1 == len(froms[eachfrom]):
  333.                         self.final += string.rstrip(', ') + '\n'
  334.  
  335.  
  336.         if 'import' in self.sort_dict:
  337.             for i in self.sort_dict['import']:
  338.                 self.final += f'import {i}\n'
  339.  
  340.         self.final += '\n'.join(self.bottom)
  341.  
  342.     def string_stripper(self, string):
  343.         string = string.strip()
  344.         string = string.rstrip('\n')
  345.         return string
  346.  
  347.     def sort_froms_accordingly(self, list_with_strings):
  348.         for c in range(len(list_with_strings)-1,-1,-1):
  349.             if list_with_strings[c][0:len('from ')] == 'from ':
  350.                 if 'from' not in self.sort_dict:
  351.                     self.sort_dict.update({'from': { }})
  352.  
  353.                 string = list_with_strings[c][len('from '):]
  354.                 wrong_froms = string.split()
  355.                 froms = []
  356.  
  357.                 for i in wrong_froms:
  358.                     tmp = i.split(',')
  359.                     for ii in tmp:
  360.                         froms.append(ii)
  361.  
  362.                 current = froms[0]
  363.                 current = self.string_stripper(current)
  364.  
  365.                 froms.pop(0) # pops 'current'
  366.                 froms.pop(0) # pops 'import'
  367.  
  368.                 if current not in self.sort_dict['from']:
  369.                     self.sort_dict['from'].update({current: []})
  370.  
  371.                 for eachstring in froms:
  372.                     eachstring = self.string_stripper(eachstring)
  373.                     if eachstring not in self.sort_dict['from'][current] and eachstring != "":
  374.                         self.sort_dict['from'][current].append(eachstring)
  375.  
  376.                 self.sort_dict['from'][current].sort()
  377.                 list_with_strings.pop(c)
  378.  
  379.         return list_with_strings
  380.  
  381.  
  382.     def sort_imports_accordingly(self, list_with_strings):
  383.         for c in range(len(list_with_strings)-1,-1,-1):
  384.             if list_with_strings[c][0:len('import ')] == 'import ':
  385.                 if 'import' not in self.sort_dict:
  386.                     self.sort_dict.update({'import': []})
  387.  
  388.                 string = list_with_strings[c][len('import '):]
  389.                 imports = string.split(',')
  390.  
  391.                 for eachstring in imports:
  392.                     eachstring = self.string_stripper(eachstring)
  393.                     if eachstring not in self.sort_dict['import'] and eachstring != "":
  394.                         self.sort_dict['import'].append(eachstring)
  395.  
  396.                 list_with_strings.pop(c)
  397.  
  398.         if 'import' in self.sort_dict:
  399.             self.sort_dict['import'].sort()
  400.  
  401.         return list_with_strings
  402.  
  403.  
  404. app = QtWidgets.QApplication(sys.argv)
  405. window = Styler()
  406. app.exec_()
  407. -----BEGIN PGP SIGNATURE-----
  408.  
  409. iQEzBAEBCgAdFiEE71LbRNiQBA9vGos59HRz1BzsWMwFAmCU0KEACgkQ9HRz1Bzs
  410. WMyUDggAkySxtyBzNtBwzfOyN2ANhwVqqgB4gfncccouMLqjCJq+Sef6YXFQrZfz
  411. tuaiCPDONLFCUJ/j/7x4g7cXMRihCIF9D42q8s9ISBL9xFjPTa6BPLHsdbmEbeY6
  412. SjzVN4JB8QcTdp5WwN/4MOn4jLXWWY7dT1cVuMQb13uyAiYk/4zn35eKOsMwisXb
  413. BjuVA+QTKYEDHZ4/c645nAHnIE+Y4LqSoS4pz0dxnpBNOhDuzs/t1XdH46L5EDji
  414. y6PZR9V7Pfk5CDC/Yqxpzhv9oZN42CergRFyE+MxpMYYbXzdubGZpl3Ikeq2Ywpk
  415. DBkfmz9kHWTNufKsmYt2WZSpc7C1cg==
  416. =0kRA
  417. -----END PGP SIGNATURE-----
  418.  
Add Comment
Please, Sign In to add comment