Compare commits

..

8 Commits

Author SHA1 Message Date
N0\A
aa2c23537c wayland removed 2025-11-07 09:31:14 +01:00
N0\A
69b0fb3226 . 2025-11-07 09:30:27 +01:00
N0\A
1814054cc2 supercopy update 2025-11-07 09:24:13 +01:00
N0\A
3b39ed1806 wayland try 1 2025-11-06 15:11:57 +01:00
N0\A
754acac08a quit fix + don't show menu when hidden 2025-11-06 11:03:21 +01:00
N0\A
e0ade52eb5 Merge branch 'main' of https://git.krzak.org/N0VA/CLARA 2025-11-02 18:16:13 +01:00
N0\A
0b115bfe27 better gitignore 2025-11-02 18:16:07 +01:00
N0\A
9fa55dc02e should work without js 2025-11-02 14:27:29 +01:00
5 changed files with 316 additions and 55 deletions

5
.gitignore vendored
View File

@@ -9,5 +9,6 @@ __pycache__/
*.pyc.*
*.pyo.*
# SUPERCOPY
copy.md
SUPERCOPY.py
copy.md
.vscode

View File

@@ -1,37 +1,257 @@
files = [
"core/app_launcher.py",
"core/config.py",
"core/discord_presence.py",
"core/dukto.py",
"core/file_search.py",
"core/headers.py",
"core/http_share.py",
"core/updater.py",
"core/web_search.py",
"strings/en.json",
"strings/personality_en.json",
"windows/app_launcher.py",
"windows/calculator.py",
"windows/file_search.py",
"windows/main_window.py",
"windows/text_viewer.py",
"windows/web_results.py",
"main.py",
"README.md",
"requirements.txt"
]
import os
import sys
import fnmatch
codeblock = "```"
def get_language(file_path):
"""Detect programming language based on file extension."""
extension_map = {
'.html': 'html', '.htm': 'html', '.css': 'css', '.js': 'javascript',
'.mjs': 'javascript', '.cjs': 'javascript', '.py': 'python',
'.pyc': 'python', '.pyo': 'python', '.md': 'markdown',
'.markdown': 'markdown', '.txt': 'text', '.json': 'json',
'.geojson': 'json', '.xml': 'xml', '.php': 'php', '.phtml': 'php',
'.sql': 'sql', '.sh': 'bash', '.bash': 'bash', '.zsh': 'bash',
'.fish': 'fish', '.yml': 'yaml', '.yaml': 'yaml', '.toml': 'toml',
'.ini': 'ini', '.cfg': 'ini', '.conf': 'ini', '.config': 'ini',
'.log': 'text', '.bat': 'batch', '.cmd': 'batch', '.ps1': 'powershell',
'.psm1': 'powershell', '.psd1': 'powershell', '.rb': 'ruby',
'.gemspec': 'ruby', '.go': 'go', '.java': 'java', '.class': 'java',
'.c': 'c', '.h': 'cpp', '.cpp': 'cpp', '.cc': 'cpp', '.cxx': 'cpp',
'.c++': 'cpp', '.hpp': 'cpp', '.hh': 'cpp', '.hxx': 'cpp',
'.cs': 'csharp', '.csx': 'csharp', '.swift': 'swift', '.kt': 'kotlin',
'.kts': 'kotlin', '.rs': 'rust', '.ts': 'typescript', '.tsx': 'typescript',
'.mts': 'typescript', '.cts': 'typescript', '.jsx': 'javascript',
'.vue': 'vue', '.scss': 'scss', '.sass': 'sass', '.less': 'less',
'.styl': 'stylus', '.stylus': 'stylus', '.graphql': 'graphql',
'.gql': 'graphql', '.dockerfile': 'dockerfile', '.dockerignore': 'dockerignore',
'.editorconfig': 'ini', '.gitignore': 'gitignore', '.gitattributes': 'gitattributes',
'.gitmodules': 'gitmodules', '.prettierrc': 'json', '.eslintrc': 'json',
'.babelrc': 'json', '.npmignore': 'gitignore', '.lock': 'text',
'.env': 'env', '.env.local': 'env', '.env.development': 'env',
'.env.production': 'env', '.env.test': 'env',
}
ext = os.path.splitext(file_path)[1].lower()
return extension_map.get(ext, '')
copy = ""
def should_exclude(file_path, root_dir):
"""Determine if a file should be excluded from copying."""
abs_path = os.path.abspath(file_path)
rel_path = os.path.relpath(abs_path, root_dir)
rel_path_forward = rel_path.replace(os.sep, '/')
basename = os.path.basename(file_path)
# Exclude specific files
exclude_files = {'.pyc'}
if rel_path_forward in exclude_files or basename in exclude_files:
return True
# Exclude image files
image_extensions = {
'.png', '.jpg', '.jpeg', '.gif', '.svg', '.bmp', '.ico',
'.tiff', '.tif', '.webp', '.heic', '.heif', '.avif',
'.jfif', '.pjpeg', '.pjp', '.tga', '.psd', '.raw',
'.cr2', '.nef', '.orf', '.sr2', '.arw', '.dng', '.rw2',
'.raf', '.3fr', '.kdc', '.mef', '.mrw', '.pef', '.srw',
'.x3f', '.r3d', '.fff', '.iiq', '.erf', '.nrw'
}
ext = os.path.splitext(file_path)[1].lower()
if ext in image_extensions:
return True
return False
for file in files:
with open(file, "r", encoding="utf-8") as f:
lines = f.readlines()
copy += f"### {file}\n\n"
copy += f"{codeblock}python\n"
copy += "".join(lines)
copy += f"\n{codeblock}\n\n"
def load_gitignore_patterns(root_dir):
"""Load patterns from .gitignore file."""
patterns = []
gitignore_path = os.path.join(root_dir, '.gitignore')
if os.path.isfile(gitignore_path):
try:
with open(gitignore_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
# Skip empty lines and comments
if line and not line.startswith('#'):
# Remove trailing backslash for escaped #
if line.startswith(r'\#'):
line = line[1:]
patterns.append(line)
except Exception as e:
print(f"Warning: Could not read .gitignore: {e}")
return patterns
with open("copy.md", "w", encoding="utf-8") as f:
f.write(copy)
def is_ignored(path, patterns, root_dir):
"""Check if path matches any gitignore pattern (simplified)."""
if not patterns:
return False
# Get relative path with forward slashes
rel_path = os.path.relpath(path, root_dir).replace(os.sep, '/')
# For directories, also check with trailing slash
if os.path.isdir(path):
rel_path_with_slash = rel_path + '/'
else:
rel_path_with_slash = rel_path
for pattern in patterns:
# Skip negation patterns (too complex for this script)
if pattern.startswith('!'):
continue
# Directory pattern (ending with /)
if pattern.endswith('/'):
if not os.path.isdir(path):
continue
pattern = pattern.rstrip('/')
# Match directory name or anything inside it
if fnmatch.fnmatch(rel_path, pattern) or fnmatch.fnmatch(rel_path_with_slash, pattern + '/*'):
return True
continue
# Absolute pattern (starting with /) - match from root only
if pattern.startswith('/'):
pattern = pattern.lstrip('/')
if fnmatch.fnmatch(rel_path, pattern):
return True
continue
# Pattern without slash - matches at any level
if '/' not in pattern:
# Check basename
basename = os.path.basename(rel_path)
if fnmatch.fnmatch(basename, pattern):
return True
else:
# Pattern with slash - relative path match
if fnmatch.fnmatch(rel_path, pattern):
return True
return False
def get_files_from_directory(directory, recursive=False, root_dir=None, gitignore_patterns=None):
"""Get all files from a directory, optionally recursively."""
if root_dir is None:
root_dir = os.getcwd()
if gitignore_patterns is None:
gitignore_patterns = []
files_list = []
abs_directory = os.path.abspath(directory)
if not os.path.exists(abs_directory):
print(f"Warning: Directory '{directory}' not found.")
return files_list
# Skip if directory itself is ignored
if is_ignored(abs_directory, gitignore_patterns, root_dir):
return files_list
if recursive:
for dirpath, dirnames, filenames in os.walk(abs_directory):
# Filter directories: exclude hidden and gitignored
dirnames[:] = [
d for d in dirnames
if not d.startswith('.') and not is_ignored(os.path.join(dirpath, d), gitignore_patterns, root_dir)
]
# Filter files
for filename in filenames:
if filename.startswith('.'):
continue
full_path = os.path.join(dirpath, filename)
if (os.path.isfile(full_path) and
not should_exclude(full_path, root_dir) and
not is_ignored(full_path, gitignore_patterns, root_dir)):
files_list.append(full_path)
else:
for filename in os.listdir(abs_directory):
if filename.startswith('.'):
continue
full_path = os.path.join(abs_directory, filename)
# Skip directories in non-recursive mode
if os.path.isdir(full_path):
continue
if (os.path.isfile(full_path) and
not should_exclude(full_path, root_dir) and
not is_ignored(full_path, gitignore_patterns, root_dir)):
files_list.append(full_path)
return files_list
def main():
"""Main execution function."""
root_dir = os.getcwd()
script_path = os.path.abspath(__file__)
output_file = "copy.md"
codeblock = "```"
# Load .gitignore patterns
gitignore_patterns = load_gitignore_patterns(root_dir)
if gitignore_patterns:
print(f"Loaded {len(gitignore_patterns)} patterns from .gitignore")
def is_output_file(path):
return os.path.abspath(path) == os.path.abspath(output_file)
# Directories to process: (path, recursive)
directories = [
("./", False), # Root directory
("assets/", True), # Archive directory (with subdirectories)
("core/", True), # Legacy directory
("strings/", True), # Maybe directory
("windows/", True)
]
all_files = []
for directory, recursive in directories:
files = get_files_from_directory(directory, recursive, root_dir, gitignore_patterns)
files = [f for f in files if not is_output_file(f) and os.path.abspath(f) != script_path]
all_files.extend(files)
# Remove duplicates and sort
all_files = sorted(set(all_files))
markdown_content = "# Main website\n\n"
file_count = 0
for file_path in all_files:
try:
rel_path = os.path.relpath(file_path, root_dir)
language = get_language(file_path)
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
markdown_content += f"### {rel_path.replace(os.sep, '/')}\n\n"
markdown_content += f"{codeblock}{language}\n" if language else f"{codeblock}\n"
markdown_content += content
markdown_content += f"\n{codeblock}\n\n"
file_count += 1
except UnicodeDecodeError:
print(f"Warning: Could not read {file_path} as text. Skipping.")
except Exception as e:
print(f"Error processing {file_path}: {e}")
markdown_content += f"<!-- Processed {file_count} files -->\n"
try:
with open(output_file, "w", encoding="utf-8") as f:
f.write(markdown_content)
print(f"Successfully created {output_file} with {file_count} files.")
except Exception as e:
print(f"Error writing to {output_file}: {e}")
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -41,8 +41,47 @@ class FileShareHandler(BaseHTTPRequestHandler):
raise RuntimeError(f"HTML template not found at {template_path}")
return cls.html_template
def _generate_shared_text_html(self, text: str) -> str:
if not text:
return ""
escaped_text = html.escape(text)
return f'''<h2>Shared Text</h2>
<p>Select the text below and copy it to your clipboard.</p>
<textarea class="share-text" readonly="readonly">{escaped_text}</textarea>'''
def _generate_shared_files_html(self, files: List[str]) -> str:
"""Generate HTML for shared files section."""
if not files:
return ""
rows = ""
for i, filepath in enumerate(files):
try:
path = Path(filepath)
if path.exists() and path.is_file():
name = html.escape(path.name)
size = format_size(path.stat().st_size)
rows += f'''<tr>
<td>{name}</td>
<td>{size}</td>
<td><a class="button" href="/download/{i}">Download</a></td>
</tr>'''
except Exception:
continue
if not rows:
return ""
return f'''<h2>Shared Files</h2>
<p>Click a button to download the corresponding file.</p>
<table class="file-list" cellpadding="0" cellspacing="0">
<tr><th>Filename</th><th>Size</th><th>Action</th></tr>
{rows}
</table>'''
def _get_base_html(self, hostname: str, url: str, total_size_info: str,
no_content_display: str, initial_data_json: str) -> str:
no_content_display: str, shared_text_html: str, shared_files_html: str) -> str:
template = self.load_html_template()
replacements = {
@@ -51,7 +90,8 @@ class FileShareHandler(BaseHTTPRequestHandler):
'{{URL}}': html.escape(url),
'{{TOTAL_SIZE_INFO}}': total_size_info,
'{{NO_CONTENT_DISPLAY}}': no_content_display,
'{{INITIAL_DATA_JSON}}': initial_data_json
'{{SHARED_TEXT_HTML}}': shared_text_html,
'{{SHARED_FILES_HTML}}': shared_files_html
}
result = template
@@ -106,19 +146,20 @@ class FileShareHandler(BaseHTTPRequestHandler):
if total_size_bytes > 0:
total_size_info = format_size(total_size_bytes)
initial_data_dict = self._get_api_data_dict()
json_string = json.dumps(initial_data_dict)
initial_data_json = json.dumps(json_string)
url = f"http://{self._get_local_ip()}:{self.server.server_address[1]}/" #type: ignore
no_content_display = 'none' if has_content else 'block'
# Generate HTML server-side
shared_text_html = self._generate_shared_text_html(self.shared_text or "")
shared_files_html = self._generate_shared_files_html(self.shared_files)
html_content = self._get_base_html(
hostname=hostname,
url=url,
total_size_info=total_size_info,
no_content_display=no_content_display,
initial_data_json=initial_data_json
shared_text_html=shared_text_html,
shared_files_html=shared_files_html
).encode('utf-8')
self.send_response(200)
@@ -245,6 +286,8 @@ class FileShareServer:
for f in files:
if f not in current_files:
self.shared_files.append(f)
FileShareHandler.shared_files = self.shared_files
def share_text(self, text: str) -> str:
self.shared_text = text

View File

@@ -147,8 +147,12 @@
</div>
<div class="main clearfix">
<div class="left-col">
<div class="section" id="shared-text-container"></div>
<div class="section" id="shared-files-container"></div>
<div class="section" id="shared-text-container">
{{SHARED_TEXT_HTML}}
</div>
<div class="section" id="shared-files-container">
{{SHARED_FILES_HTML}}
</div>
</div>
<div class="right-col">
<div class="section">
@@ -167,7 +171,6 @@
<p>Powered by <a href="https://github.com/n0va-bot/CLARA" target="_blank">CLARA</a>, your friendly desktop assistant.</p>
</div>
</div>
<script type="text/javascript">var initialDataJSON = {{INITIAL_DATA_JSON}};</script>
<script type="text/javascript">
(function() {
var lastData = '';
@@ -232,14 +235,7 @@
xhr.send(null);
}
if (typeof initialDataJSON !== 'undefined' && initialDataJSON) {
lastData = initialDataJSON;
try {
var initialData = JSON.parse(initialDataJSON);
updateContent(initialData);
} catch (e) {}
}
// Refresh data every 5 seconds
setInterval(fetchData, 5000);
})();
</script>

View File

@@ -154,7 +154,7 @@ class MainWindow(QtWidgets.QMainWindow):
right_menu.addAction(s["restart"], self.restart_application)
right_menu.addAction(s["toggle_visibility"], self.toggle_visible)
right_menu.addSeparator()
if self.no_quit:
if not self.no_quit:
right_menu.addAction(s["quit"], QtWidgets.QApplication.quit)
self.tray.setContextMenu(right_menu)
@@ -213,7 +213,8 @@ class MainWindow(QtWidgets.QMainWindow):
hotkey_str = self.config.get("hotkey", "super")
def on_activate():
self.show_menu_signal.emit()
if self.isVisible():
self.show_menu_signal.emit()
key_map = {
"super": "cmd",