Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_quick_code_modify.py
- import tkinter as tk
- from tkinter import scrolledtext, messagebox, ttk
- root = tk.Tk()
- root.title("Code Modify")
- root.geometry("1200x640+0+0")
- original_code = ""
- modifier_code = ""
- finalized_code = ""
- # Demo original HTML code
- demo_original_html = """<!DOCTYPE html>
- <html>
- <head>
- <title>Original Page</title>
- <meta charset="UTF-8">
- <style>
- body { font-family: Arial; }
- .header { color: blue; }
- </style>
- </head>
- <body>
- <div class="header">Welcome</div>
- <script>
- function originalFunction() {
- console.log("Original code");
- // More original code here
- return true;
- }
- </script>
- </body>
- </html>"""
- # Demo modifier HTML code
- demo_modifier_html = """<!DOCTYPE html>
- <html>
- <head>
- <!-- Keep existing head content -->
- <link rel="stylesheet" href="new-styles.css">
- </head>
- <body>
- <div class="header">Welcome (Modified)</div>
- <script>
- function newFeature() {
- console.log("Added feature");
- }
- // Keep rest of the original code
- </script>
- </body>
- </html>"""
- # Demo original Python code
- demo_original_py = """# Python Application
- import os
- import sys
- class MyClass:
- def __init__(self, name):
- self.name = name
- def greet(self):
- print(f"Hello, {self.name}")
- def main_function():
- # This is the main logic
- print("Running original main_function")
- instance = MyClass("Original")
- instance.greet()
- def original_function(x, y):
- return (x ** y) / 2
- """
- # Demo finalized Python code
- demo_modifier_py = """# Python Application (Modified)
- # Keep existing imports
- import json # New import
- class MyClass:
- def __init__(self, name, age=0): # Modified constructor
- self.name = name
- self.age = age
- def greet(self):
- print(f"Hello, {self.name}, you are {self.age} years old.") # Modified greet
- def new_method(self): # New method
- print("This is a new method.")
- def main_function():
- # This is the modified main logic
- print("Running MODIFIED main_function")
- instance = MyClass("Modified", 30)
- instance.greet()
- instance.new_method() # Call new method
- # Keep existing main_logic content (if any was meant to be kept below this point)
- """
- def show_code(widget, code):
- widget.delete(1.0, tk.END)
- widget.insert(tk.END, code)
- root.update()
- def load_py_demo():
- load(original_text, demo_original_py)
- load(modifier_text, demo_modifier_py)
- def load_html_demo():
- load(original_text, demo_original_html)
- load(modifier_text, demo_modifier_html)
- def load(widget, text=''):
- global original_code, modifier_code, finalized_code
- if not text:
- msg = "Code processed and merged with original"
- try:
- text = root.clipboard_get()
- except tk.TclError:
- messagebox.showerror("Clipboard Error", "No text in clipboard or clipboard access denied")
- status.config(text="Failed to access clipboard")
- return
- except Exception as e:
- messagebox.showerror("Error", f"An error occurred: {str(e)}")
- status.config(text="Error occurred")
- return
- else:
- msg = "Demo loaded - differences automatically highlighted"
- try:
- text = text.encode('utf-8', errors='ignore').decode('utf-8')
- except:
- text = text.encode('latin-1', errors='ignore').decode('latin-1', errors='ignore')
- text = ''.join(char for char in text if char.isprintable() or char in '\n\r\t')
- if widget == original_text:
- show_code(original_text, text)
- show_code(modifier_text, '')
- show_code(finalized_text, '')
- notebook.select(original_frame)
- original_code = demo_original_html
- status.config(text="Original code loaded from clipboard")
- else:
- if not original_code:
- messagebox.showwarning("Warning", "Please load original code first")
- status.config(text="Load original code first")
- return
- modifier_code = text
- show_code(modifier_text, modifier_code)
- finalized_code = process_modifier_code()
- show_code(finalized_text, finalized_code)
- status.config(text=msg)
- highlight_diffs()
- def process_modifier_code():
- result_lines = []
- original_lines = original_code.splitlines()
- modifier_lines = modifier_code.splitlines()
- def add_line(line):
- result_lines.append(line)
- i = 0
- while i < len(modifier_lines):
- line = modifier_lines[i]
- if first_str_in_str(keep, line.lower()):
- tag = get_word(line, 'content', step=(-1))
- tag_start, tag_end = find_section(original_lines, tag)
- if tag_start != -1:
- if i > 0 and modifier_lines[i-1].strip().startswith(f"<{tag}"):
- add_line(modifier_lines[i-1])
- result_lines.extend(original_lines[tag_start+1:tag_end])
- i += 1
- while i < len(modifier_lines) and f"</{tag}>" not in modifier_lines[i]:
- add_line(modifier_lines[i])
- i += 1
- if i < len(modifier_lines):
- add_line(modifier_lines[i])
- i += 1
- continue
- elif i < len(result_lines):
- if result_lines[i] != result_lines[i-1]:
- add_line(line)
- else:
- add_line(line)
- i += 1
- return "\n".join(result_lines)
- def find_section(lines, section):
- section = section.lower()
- start_tag = f"<{section}>"
- end_tag = f"</{section}>"
- start_idx = -1
- end_idx = -1
- for i, line in enumerate(lines):
- if start_tag in line.lower():
- start_idx = i
- if end_tag in line.lower() and start_idx != -1:
- end_idx = i
- break
- return start_idx, end_idx
- def find_context_in_original(original_code, context):
- if not context:
- return 0
- for i in range(len(original_code) - len(context_lines), -1, -1):
- match = True
- for j in range(len(context_lines)):
- if original_code[i+j].strip() != context_lines[j].strip():
- match = False
- break
- if match:
- return i + len(context_lines)
- return -1
- def highlight_diffs():
- if not modifier_code:
- return
- def mark(widget, s1, s2):
- s2 = [s.strip() for s in s2.splitlines()]
- line_num = 0
- for line in s1.splitlines():
- line_num += 1
- s = line.strip()
- if first_str_in_str(keep, s.lower()):
- pass
- elif s not in s2:
- widget.tag_add("changed", f"{line_num}.0", f"{line_num}.end")
- original_text.tag_remove("changed", "1.0", tk.END)
- modifier_text.tag_remove("changed", "1.0", tk.END)
- finalized_text.tag_remove("changed", "1.0", tk.END)
- original_text.tag_config("changed", background="#ffaaaa")
- modifier_text.tag_config("changed", background="#c8e6c9")
- finalized_text.tag_config("changed", background="#c8e6c9")
- mark(original_text, original_code, finalized_code)
- mark(modifier_text, modifier_code, original_code)
- mark(finalized_text, finalized_code, original_code)
- def export_result():
- if not modifier_code:
- messagebox.showwarning("Warning", "No modifier code to copy")
- status.config(text="No modifier code to copy")
- return
- try:
- root.clipboard_clear()
- root.clipboard_append(modifier_code)
- status.config(text="Finalized code copied to clipboard")
- except Exception as e:
- messagebox.showerror("Error", f"Failed to copy to clipboard: {str(e)}")
- status.config(text="Error copying to clipboard")
- def get_word(text, focus, step=(-1)):
- words = text.split()
- if focus not in words:
- return ''
- index = words.index(focus)
- if 0 <= index + step < len(words):
- return words[index + step]
- return ''
- def first_str_in_str(strings, target):
- for s in strings:
- if target.strip().startswith(s):
- return s
- return None
- keep = ["<!-- keep ", "// keep ", "# keep "]
- button_frame = tk.Frame(root)
- button_frame.pack(fill=tk.X, padx=5, pady=5)
- notebook = ttk.Notebook(root)
- notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
- original_frame = ttk.Frame(notebook)
- original_text = scrolledtext.ScrolledText(original_frame, wrap=tk.WORD, font=('Consolas', 10), bg="#f5f5f5", fg="#aa0000")
- original_text.pack(fill=tk.BOTH, expand=True)
- notebook.add(original_frame, text="Original Code")
- modifier_frame = ttk.Frame(notebook)
- modifier_text = scrolledtext.ScrolledText(modifier_frame, wrap=tk.WORD, font=('Consolas', 10), bg="#fffde7")
- modifier_text.pack(fill=tk.BOTH, expand=True)
- notebook.add(modifier_frame, text="Modifier Code")
- finalized_frame = ttk.Frame(notebook)
- finalized_text = scrolledtext.ScrolledText(finalized_frame, wrap=tk.WORD, font=('Consolas', 10), bg="#f5f5f5")
- finalized_text.pack(fill=tk.BOTH, expand=True)
- notebook.add(finalized_frame, text="Finalized Result")
- status = tk.Label(root, text="Ready...", bd=1, relief=tk.SUNKEN, anchor=tk.W)
- status.pack(fill=tk.X)
- tk.Button(button_frame, text="Load HTML Demo", command=load_html_demo, bg="#e1f5fe").pack(side=tk.LEFT, padx=5)
- tk.Button(button_frame, text="Load PYTHON Demo", command=load_py_demo, bg="#e1f5fe").pack(side=tk.LEFT, padx=5)
- tk.Button(button_frame, text="Paste Original", command=lambda: load(original_text), bg="#fce4ec").pack(side=tk.LEFT, padx=5)
- tk.Button(button_frame, text="Paste Modifier", command=lambda: load(modifier_text), bg="#fffde7").pack(side=tk.LEFT, padx=5)
- tk.Button(button_frame, text="Copy Result", command=export_result, bg="#e8f5e9").pack(side=tk.LEFT, padx=5)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement