SafePDF 1.0.11__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- SafePDF/__init__.py +10 -0
- SafePDF/ctrl/__init__.py +0 -0
- SafePDF/ctrl/language_manager.py +69 -0
- SafePDF/ctrl/safe_pdf_controller.py +469 -0
- SafePDF/logger/__init__.py +0 -0
- SafePDF/logger/logging_config.py +94 -0
- SafePDF/ops/__init__.py +0 -0
- SafePDF/ops/license_manager.py +247 -0
- SafePDF/ops/pdf2docx.py +157 -0
- SafePDF/ops/pdf2jpeg.py +116 -0
- SafePDF/ops/pdf_compress.py +282 -0
- SafePDF/ops/pdf_merge.py +104 -0
- SafePDF/ops/pdf_operations.py +563 -0
- SafePDF/ops/pdf_rotate.py +102 -0
- SafePDF/ops/pdf_split.py +178 -0
- SafePDF/ops/updates.py +308 -0
- SafePDF/safe_pdf_app.py +121 -0
- SafePDF/test/__init__.py +0 -0
- SafePDF/test/test_compression.py +79 -0
- SafePDF/test/test_pro_dialog.py +45 -0
- SafePDF/text/de/help_content.txt +58 -0
- SafePDF/text/de/pro_features.txt +9 -0
- SafePDF/text/de/ui.json +260 -0
- SafePDF/text/de/welcome_content.txt +24 -0
- SafePDF/text/en/help_content.txt +42 -0
- SafePDF/text/en/pro_features.txt +8 -0
- SafePDF/text/en/ui.json +260 -0
- SafePDF/text/en/welcome_content.txt +25 -0
- SafePDF/text/tr/help_content.txt +53 -0
- SafePDF/text/tr/pro_features.txt +8 -0
- SafePDF/text/tr/ui.json +260 -0
- SafePDF/text/tr/welcome_content.txt +24 -0
- SafePDF/ui/__init__.py +11 -0
- SafePDF/ui/common_elements.py +40 -0
- SafePDF/ui/help_ui.py +233 -0
- SafePDF/ui/language_elements.py +9 -0
- SafePDF/ui/operation_settings.py +377 -0
- SafePDF/ui/safe_pdf_ui.py +3497 -0
- SafePDF/ui/settings_ui.py +394 -0
- SafePDF/ui/tabs_manager.py +235 -0
- SafePDF/ui/update_ui.py +717 -0
- SafePDF/version.txt +34 -0
- safepdf-1.0.11.dist-info/METADATA +162 -0
- safepdf-1.0.11.dist-info/RECORD +48 -0
- safepdf-1.0.11.dist-info/WHEEL +5 -0
- safepdf-1.0.11.dist-info/entry_points.txt +2 -0
- safepdf-1.0.11.dist-info/licenses/LICENSE +674 -0
- safepdf-1.0.11.dist-info/top_level.txt +1 -0
SafePDF/ops/pdf_split.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PDF Split Module for SafePDF
|
|
3
|
+
Handles PDF splitting operations
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from os import path as os_path
|
|
7
|
+
from typing import List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
from PyPDF2 import PdfReader, PdfWriter
|
|
11
|
+
except ImportError:
|
|
12
|
+
PdfReader = PdfWriter = None
|
|
13
|
+
|
|
14
|
+
from SafePDF.logger.logging_config import get_logger
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PDFSplitter:
|
|
18
|
+
"""Class handling PDF split operations"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, progress_callback=None, language_manager=None, atomic_write_file=None):
|
|
21
|
+
"""
|
|
22
|
+
Initialize PDF splitter
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
progress_callback: Function to call for progress updates (0-100)
|
|
26
|
+
language_manager: Language manager for localization
|
|
27
|
+
atomic_write_file: Function for atomic file writing
|
|
28
|
+
"""
|
|
29
|
+
self.progress_callback = progress_callback
|
|
30
|
+
self.language_manager = language_manager
|
|
31
|
+
self._atomic_write_file = atomic_write_file
|
|
32
|
+
self._cancel_requested = False
|
|
33
|
+
self.logger = get_logger("SafePDF.PDFSplit")
|
|
34
|
+
|
|
35
|
+
def update_progress(self, value):
|
|
36
|
+
"""Update progress if callback is available"""
|
|
37
|
+
if self.progress_callback:
|
|
38
|
+
self.progress_callback(value)
|
|
39
|
+
|
|
40
|
+
def request_cancel(self):
|
|
41
|
+
"""Request cancellation of a running operation."""
|
|
42
|
+
self._cancel_requested = True
|
|
43
|
+
|
|
44
|
+
def split_pdf(
|
|
45
|
+
self, input_path: str, output_dir: str, method: str = "pages", page_range: Optional[str] = None
|
|
46
|
+
) -> Tuple[bool, str]:
|
|
47
|
+
"""
|
|
48
|
+
Split PDF into multiple files
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
input_path: Input PDF file path
|
|
52
|
+
output_dir: Directory to save split files
|
|
53
|
+
method: Split method ("pages" for each page, "range" for specific range)
|
|
54
|
+
page_range: Page range if method is "range" (e.g., "1-5,7,10-12")
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
Tuple of (success, message)
|
|
58
|
+
"""
|
|
59
|
+
try:
|
|
60
|
+
if not PdfReader or not PdfWriter:
|
|
61
|
+
return False, self.language_manager.get(
|
|
62
|
+
"op_pypdf_unavailable", "PyPDF2/pypdf not available"
|
|
63
|
+
) if self.language_manager else "PyPDF2/pypdf not available"
|
|
64
|
+
|
|
65
|
+
self.update_progress(10)
|
|
66
|
+
|
|
67
|
+
with open(input_path, "rb") as input_file:
|
|
68
|
+
reader = PdfReader(input_file)
|
|
69
|
+
total_pages = len(reader.pages)
|
|
70
|
+
|
|
71
|
+
self.update_progress(20)
|
|
72
|
+
|
|
73
|
+
if method == "pages":
|
|
74
|
+
# Split each page into separate file
|
|
75
|
+
for i, page in enumerate(reader.pages):
|
|
76
|
+
if self._cancel_requested:
|
|
77
|
+
return False, self.language_manager.get(
|
|
78
|
+
"op_cancelled", "Operation cancelled by user"
|
|
79
|
+
) if self.language_manager else "Operation cancelled by user"
|
|
80
|
+
writer = PdfWriter()
|
|
81
|
+
writer.add_page(page)
|
|
82
|
+
|
|
83
|
+
output_filename = f"page_{i + 1}.pdf"
|
|
84
|
+
output_path = os_path.join(output_dir, output_filename)
|
|
85
|
+
|
|
86
|
+
def _write_page(tmpf):
|
|
87
|
+
writer.write(tmpf)
|
|
88
|
+
|
|
89
|
+
if self._atomic_write_file:
|
|
90
|
+
self._atomic_write_file(output_path, _write_page)
|
|
91
|
+
else:
|
|
92
|
+
with open(output_path, "wb") as f:
|
|
93
|
+
_write_page(f)
|
|
94
|
+
|
|
95
|
+
self.update_progress(20 + (70 * i // total_pages))
|
|
96
|
+
|
|
97
|
+
self.update_progress(100)
|
|
98
|
+
success_msg = (
|
|
99
|
+
self.language_manager.get("op_split_pages", "PDF split into {total_pages} files")
|
|
100
|
+
if self.language_manager
|
|
101
|
+
else "PDF split into {total_pages} files"
|
|
102
|
+
)
|
|
103
|
+
return True, success_msg.format(total_pages=total_pages)
|
|
104
|
+
|
|
105
|
+
elif method == "range" and page_range:
|
|
106
|
+
# Parse page range and create files
|
|
107
|
+
ranges = self._parse_page_range(page_range, total_pages)
|
|
108
|
+
|
|
109
|
+
for i, (start, end) in enumerate(ranges):
|
|
110
|
+
if self._cancel_requested:
|
|
111
|
+
return False, self.language_manager.get(
|
|
112
|
+
"op_cancelled", "Operation cancelled by user"
|
|
113
|
+
) if self.language_manager else "Operation cancelled by user"
|
|
114
|
+
writer = PdfWriter()
|
|
115
|
+
for page_num in range(start - 1, end):
|
|
116
|
+
if 0 <= page_num < total_pages:
|
|
117
|
+
writer.add_page(reader.pages[page_num])
|
|
118
|
+
|
|
119
|
+
output_filename = f"pages_{start}-{end}.pdf"
|
|
120
|
+
output_path = os_path.join(output_dir, output_filename)
|
|
121
|
+
|
|
122
|
+
def _write_range(tmpf):
|
|
123
|
+
writer.write(tmpf)
|
|
124
|
+
|
|
125
|
+
if self._atomic_write_file:
|
|
126
|
+
self._atomic_write_file(output_path, _write_range)
|
|
127
|
+
else:
|
|
128
|
+
with open(output_path, "wb") as f:
|
|
129
|
+
_write_range(f)
|
|
130
|
+
|
|
131
|
+
self.update_progress(20 + (70 * i // len(ranges)))
|
|
132
|
+
|
|
133
|
+
self.update_progress(100)
|
|
134
|
+
success_msg = (
|
|
135
|
+
self.language_manager.get(
|
|
136
|
+
"op_split_ranges", "PDF split into {num_ranges} files based on ranges"
|
|
137
|
+
)
|
|
138
|
+
if self.language_manager
|
|
139
|
+
else "PDF split into {num_ranges} files based on ranges"
|
|
140
|
+
)
|
|
141
|
+
return True, success_msg.format(num_ranges=len(ranges))
|
|
142
|
+
|
|
143
|
+
return False, "Invalid split method or parameters"
|
|
144
|
+
|
|
145
|
+
except Exception as e:
|
|
146
|
+
error_msg = (
|
|
147
|
+
self.language_manager.get("op_split_failed", "Split failed: {error}")
|
|
148
|
+
if self.language_manager
|
|
149
|
+
else "Split failed: {error}"
|
|
150
|
+
)
|
|
151
|
+
return False, error_msg.format(error=str(e))
|
|
152
|
+
|
|
153
|
+
def _parse_page_range(self, page_range: str, total_pages: int) -> List[Tuple[int, int]]:
|
|
154
|
+
"""
|
|
155
|
+
Parse page range string into list of (start, end) tuples
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
page_range: Range string like "1-5,7,10-12"
|
|
159
|
+
total_pages: Total number of pages in PDF
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
List of (start, end) tuples
|
|
163
|
+
"""
|
|
164
|
+
ranges = []
|
|
165
|
+
parts = page_range.split(",")
|
|
166
|
+
|
|
167
|
+
for part in parts:
|
|
168
|
+
part = part.strip()
|
|
169
|
+
if "-" in part:
|
|
170
|
+
start, end = part.split("-", 1)
|
|
171
|
+
start = max(1, min(int(start.strip()), total_pages))
|
|
172
|
+
end = max(start, min(int(end.strip()), total_pages))
|
|
173
|
+
ranges.append((start, end))
|
|
174
|
+
else:
|
|
175
|
+
page_num = max(1, min(int(part.strip()), total_pages))
|
|
176
|
+
ranges.append((page_num, page_num))
|
|
177
|
+
|
|
178
|
+
return ranges
|
SafePDF/ops/updates.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SafePDF Updates Module - GitHub Releases and Signed Keys
|
|
3
|
+
by mcagriaksoy - 2025
|
|
4
|
+
|
|
5
|
+
This module handles checking for updates from GitHub Releases,
|
|
6
|
+
downloading and verifying releases using GPG signatures.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import platform
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from urllib.error import URLError
|
|
14
|
+
from urllib.request import urlopen
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import gnupg
|
|
18
|
+
from github import Github
|
|
19
|
+
except ImportError as e:
|
|
20
|
+
print(f"Missing required libraries for updates: {e}")
|
|
21
|
+
print("Please install with: pip install requests PyGitHub python-gnupg")
|
|
22
|
+
sys.exit(1)
|
|
23
|
+
|
|
24
|
+
from SafePDF.logger.logging_config import get_logger
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class SafePDFUpdates:
|
|
28
|
+
"""Handles GitHub releases, updates, and GPG signature verification"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, repo_owner="mcagriaksoy", repo_name="SafePDF"):
|
|
31
|
+
self.repo_owner = repo_owner
|
|
32
|
+
self.repo_name = repo_name
|
|
33
|
+
self.github = Github() # Uses anonymous access for public repos
|
|
34
|
+
self.repo = self.github.get_repo(f"{repo_owner}/{repo_name}")
|
|
35
|
+
self.logger = get_logger("SafePDF.Updates")
|
|
36
|
+
|
|
37
|
+
# Initialize GPG
|
|
38
|
+
try:
|
|
39
|
+
self.gpg = gnupg.GPG()
|
|
40
|
+
self.gpg_available = True
|
|
41
|
+
except (OSError, FileNotFoundError):
|
|
42
|
+
self.logger.warning("GPG not available - signature verification disabled")
|
|
43
|
+
self.gpg = None
|
|
44
|
+
self.gpg_available = False
|
|
45
|
+
|
|
46
|
+
# Get current version
|
|
47
|
+
self.current_version = self._get_current_version()
|
|
48
|
+
|
|
49
|
+
def _get_current_version(self):
|
|
50
|
+
"""Get current application version"""
|
|
51
|
+
try:
|
|
52
|
+
version_file = Path(__file__).parent.parent / "version.txt"
|
|
53
|
+
if version_file.exists():
|
|
54
|
+
with open(version_file, "r") as f:
|
|
55
|
+
return f.read().strip()
|
|
56
|
+
return "0.0.0"
|
|
57
|
+
except Exception as e:
|
|
58
|
+
self.logger.error(f"Error reading version: {e}")
|
|
59
|
+
return "0.0.0"
|
|
60
|
+
|
|
61
|
+
def check_for_updates(self):
|
|
62
|
+
"""
|
|
63
|
+
Check for available updates on GitHub Releases
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
dict: Update info with keys: 'available', 'latest_version', 'download_url', 'changelog'
|
|
67
|
+
or None if no update available or error
|
|
68
|
+
"""
|
|
69
|
+
try:
|
|
70
|
+
# Get latest release
|
|
71
|
+
latest_release = self.repo.get_latest_release()
|
|
72
|
+
|
|
73
|
+
latest_version = latest_release.tag_name.lstrip("v")
|
|
74
|
+
current_version = self.current_version.lstrip("v")
|
|
75
|
+
|
|
76
|
+
if self._is_newer_version(latest_version, current_version):
|
|
77
|
+
# Find appropriate asset for current platform
|
|
78
|
+
download_url, signature_url = self._get_platform_asset(latest_release)
|
|
79
|
+
|
|
80
|
+
if download_url:
|
|
81
|
+
return {
|
|
82
|
+
"available": True,
|
|
83
|
+
"latest_version": latest_version,
|
|
84
|
+
"download_url": download_url,
|
|
85
|
+
"signature_url": signature_url,
|
|
86
|
+
"changelog": latest_release.body,
|
|
87
|
+
"release_url": latest_release.html_url,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {"available": False}
|
|
91
|
+
|
|
92
|
+
except Exception as e:
|
|
93
|
+
self.logger.error(f"Error checking for updates: {e}")
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
def _is_newer_version(self, latest, current):
|
|
97
|
+
"""Compare version strings"""
|
|
98
|
+
try:
|
|
99
|
+
from packaging import version
|
|
100
|
+
|
|
101
|
+
return version.parse(latest) > version.parse(current)
|
|
102
|
+
except ImportError:
|
|
103
|
+
# Fallback to simple string comparison
|
|
104
|
+
return latest != current
|
|
105
|
+
|
|
106
|
+
def _get_platform_asset(self, release):
|
|
107
|
+
"""
|
|
108
|
+
Get the appropriate asset for the current platform
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
tuple: (download_url, signature_url) or (None, None)
|
|
112
|
+
"""
|
|
113
|
+
system = platform.system().lower()
|
|
114
|
+
platform.machine().lower()
|
|
115
|
+
|
|
116
|
+
# Map platform to asset name patterns
|
|
117
|
+
platform_patterns = {
|
|
118
|
+
"windows": ["windows", "win", ".exe", ".msi"],
|
|
119
|
+
"linux": ["linux", ".deb", ".rpm", ".tar.gz"],
|
|
120
|
+
"darwin": ["macos", "darwin", "osx", ".dmg", ".pkg"],
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
patterns = platform_patterns.get(system, [])
|
|
124
|
+
|
|
125
|
+
download_url = None
|
|
126
|
+
signature_url = None
|
|
127
|
+
|
|
128
|
+
for asset in release.assets:
|
|
129
|
+
name = asset.name.lower()
|
|
130
|
+
|
|
131
|
+
# Check for main binary
|
|
132
|
+
if any(pattern in name for pattern in patterns) and not name.endswith(".sig"):
|
|
133
|
+
download_url = asset.browser_download_url
|
|
134
|
+
|
|
135
|
+
# Check for signature file
|
|
136
|
+
if name.endswith(".sig") or ".sig." in name:
|
|
137
|
+
signature_url = asset.browser_download_url
|
|
138
|
+
|
|
139
|
+
return download_url, signature_url
|
|
140
|
+
|
|
141
|
+
def download_and_verify(self, download_url, signature_url, public_key=None):
|
|
142
|
+
"""
|
|
143
|
+
Download a release and verify its GPG signature
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
download_url: URL to download the release
|
|
147
|
+
signature_url: URL to download the signature
|
|
148
|
+
public_key: ASCII-armored public key for verification
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
tuple: (success, file_path, error_message)
|
|
152
|
+
"""
|
|
153
|
+
if not self.gpg_available:
|
|
154
|
+
return False, None, "GPG not available for signature verification"
|
|
155
|
+
|
|
156
|
+
try:
|
|
157
|
+
# Import public key if provided
|
|
158
|
+
if public_key:
|
|
159
|
+
self.gpg.import_keys(public_key)
|
|
160
|
+
|
|
161
|
+
# Download files
|
|
162
|
+
with tempfile.TemporaryDirectory() as temp_dir:
|
|
163
|
+
# Download the release
|
|
164
|
+
release_path = Path(temp_dir) / "release"
|
|
165
|
+
self._download_file(download_url, release_path)
|
|
166
|
+
|
|
167
|
+
# Download signature
|
|
168
|
+
sig_path = Path(temp_dir) / "release.sig"
|
|
169
|
+
self._download_file(signature_url, sig_path)
|
|
170
|
+
|
|
171
|
+
# Verify signature
|
|
172
|
+
with open(sig_path, "rb") as f:
|
|
173
|
+
signature_data = f.read()
|
|
174
|
+
|
|
175
|
+
with open(release_path, "rb") as f:
|
|
176
|
+
file_data = f.read()
|
|
177
|
+
|
|
178
|
+
verified = self.gpg.verify_data(signature_data, file_data)
|
|
179
|
+
|
|
180
|
+
if verified:
|
|
181
|
+
# Move to permanent location
|
|
182
|
+
final_path = self._get_install_path()
|
|
183
|
+
final_path.parent.mkdir(parents=True, exist_ok=True)
|
|
184
|
+
|
|
185
|
+
# For safety, we'll just verify and return the temp path
|
|
186
|
+
# Actual installation would require admin privileges
|
|
187
|
+
return True, str(release_path), "Signature verified successfully"
|
|
188
|
+
else:
|
|
189
|
+
return False, None, "Signature verification failed"
|
|
190
|
+
|
|
191
|
+
except Exception as e:
|
|
192
|
+
self.logger.error(f"Error downloading/verifying: {e}")
|
|
193
|
+
return False, None, str(e)
|
|
194
|
+
|
|
195
|
+
def _download_file(self, url, dest_path):
|
|
196
|
+
"""Download a file from URL to destination path"""
|
|
197
|
+
try:
|
|
198
|
+
with urlopen(url) as response, open(dest_path, "wb") as out_file:
|
|
199
|
+
out_file.write(response.read())
|
|
200
|
+
except URLError as e:
|
|
201
|
+
raise Exception(f"Failed to download {url}: {e}")
|
|
202
|
+
|
|
203
|
+
def _get_install_path(self):
|
|
204
|
+
"""Get the installation path for updates"""
|
|
205
|
+
if getattr(sys, "frozen", False):
|
|
206
|
+
# Running as executable
|
|
207
|
+
return Path(sys.executable).parent / "SafePDF_new.exe"
|
|
208
|
+
else:
|
|
209
|
+
# Running as script
|
|
210
|
+
return Path(__file__).parent.parent / "SafePDF_new.py"
|
|
211
|
+
|
|
212
|
+
def verify_license_file(self, license_file_path, public_key=None):
|
|
213
|
+
"""
|
|
214
|
+
Verify a pro license file using GPG signature
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
license_file_path: Path to the .license file
|
|
218
|
+
public_key: ASCII-armored public key
|
|
219
|
+
|
|
220
|
+
Returns:
|
|
221
|
+
bool: True if license file is valid and verified
|
|
222
|
+
"""
|
|
223
|
+
if not self.gpg_available:
|
|
224
|
+
self.logger.warning("GPG not available - falling back to simple validation")
|
|
225
|
+
return False # Let controller handle fallback
|
|
226
|
+
|
|
227
|
+
try:
|
|
228
|
+
if not public_key:
|
|
229
|
+
# Use a default public key (in production, this would be embedded)
|
|
230
|
+
public_key = self._get_default_public_key()
|
|
231
|
+
|
|
232
|
+
# Import the public key
|
|
233
|
+
import_result = self.gpg.import_keys(public_key)
|
|
234
|
+
if not import_result.fingerprints:
|
|
235
|
+
return False
|
|
236
|
+
|
|
237
|
+
# For detached signature verification, we need the signed data
|
|
238
|
+
# Assume the signed data is "SafePDF-Pro-License"
|
|
239
|
+
signed_data = b"SafePDF-Pro-License"
|
|
240
|
+
|
|
241
|
+
# Verify the detached signature
|
|
242
|
+
with open(license_file_path, "rb") as f:
|
|
243
|
+
signature_data = f.read()
|
|
244
|
+
|
|
245
|
+
verified = self.gpg.verify_data(signature_data, signed_data)
|
|
246
|
+
|
|
247
|
+
return verified.valid
|
|
248
|
+
|
|
249
|
+
except Exception as e:
|
|
250
|
+
self.logger.error(f"Error verifying license file: {e}")
|
|
251
|
+
return False
|
|
252
|
+
|
|
253
|
+
def _get_default_public_key(self):
|
|
254
|
+
"""Get the default public key for verification"""
|
|
255
|
+
key_dir = Path(__file__).parent.parent / "key"
|
|
256
|
+
|
|
257
|
+
# Try PGP key files first
|
|
258
|
+
for ext in [".asc", ".pgp", ".gpg"]:
|
|
259
|
+
key_file = key_dir / f"public{ext}"
|
|
260
|
+
if key_file.exists():
|
|
261
|
+
try:
|
|
262
|
+
with open(key_file, "r") as f:
|
|
263
|
+
return f.read().strip()
|
|
264
|
+
except Exception as e:
|
|
265
|
+
self.logger.error(f"Error reading PGP key file {key_file}: {e}")
|
|
266
|
+
|
|
267
|
+
# Fall back to PEM file
|
|
268
|
+
pem_file = key_dir / "public.pem"
|
|
269
|
+
if pem_file.exists():
|
|
270
|
+
try:
|
|
271
|
+
with open(pem_file, "r") as f:
|
|
272
|
+
return f.read().strip()
|
|
273
|
+
except Exception as e:
|
|
274
|
+
self.logger.error(f"Error reading PEM key file: {e}")
|
|
275
|
+
|
|
276
|
+
# Fallback to placeholder if no key files found
|
|
277
|
+
return """
|
|
278
|
+
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
|
279
|
+
# This is a placeholder - replace with actual public key
|
|
280
|
+
-----END PGP PUBLIC KEY BLOCK-----
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
def get_release_info(self, version=None):
|
|
284
|
+
"""
|
|
285
|
+
Get information about a specific release
|
|
286
|
+
|
|
287
|
+
Args:
|
|
288
|
+
version: Version tag (optional, defaults to latest)
|
|
289
|
+
|
|
290
|
+
Returns:
|
|
291
|
+
dict: Release information
|
|
292
|
+
"""
|
|
293
|
+
try:
|
|
294
|
+
if version:
|
|
295
|
+
release = self.repo.get_release(version)
|
|
296
|
+
else:
|
|
297
|
+
release = self.repo.get_latest_release()
|
|
298
|
+
|
|
299
|
+
return {
|
|
300
|
+
"version": release.tag_name,
|
|
301
|
+
"name": release.title,
|
|
302
|
+
"description": release.body,
|
|
303
|
+
"published_at": release.published_at,
|
|
304
|
+
"assets": [{"name": asset.name, "url": asset.browser_download_url} for asset in release.assets],
|
|
305
|
+
}
|
|
306
|
+
except Exception as e:
|
|
307
|
+
self.logger.error(f"Error getting release info: {e}")
|
|
308
|
+
return None
|
SafePDF/safe_pdf_app.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SafePDF - A Tkinter-based PDF Manipulation Tool
|
|
3
|
+
|
|
4
|
+
This application provides various PDF operations including:
|
|
5
|
+
- PDF Compression
|
|
6
|
+
- PDF Split/Separate
|
|
7
|
+
- PDF Merge
|
|
8
|
+
- PDF to JPG conversion
|
|
9
|
+
- PDF Rotate
|
|
10
|
+
- PDF Repair
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
# Add parent directory to sys.path so SafePDF package imports work
|
|
17
|
+
# when running this script directly
|
|
18
|
+
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
19
|
+
if parent_dir not in sys.path:
|
|
20
|
+
sys.path.insert(0, parent_dir)
|
|
21
|
+
|
|
22
|
+
import tkinter as tk # noqa: E402
|
|
23
|
+
from ctypes import windll # noqa: E402
|
|
24
|
+
from pathlib import Path # noqa: E402
|
|
25
|
+
|
|
26
|
+
from tkinterdnd2 import TkinterDnD # noqa: E402
|
|
27
|
+
|
|
28
|
+
from SafePDF.ctrl.safe_pdf_controller import SafePDFController # noqa: E402
|
|
29
|
+
from SafePDF.logger.logging_config import get_logger # noqa: E402
|
|
30
|
+
from SafePDF.ui.safe_pdf_ui import SafePDFUI # noqa: E402
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SafePDFApp:
|
|
34
|
+
"""Main application coordinator that manages the UI and controller"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, root):
|
|
37
|
+
self.root = root
|
|
38
|
+
|
|
39
|
+
# Keep a reference to icon image to avoid GC
|
|
40
|
+
self._icon_image = None
|
|
41
|
+
|
|
42
|
+
# Initialize controller with progress callback (language_manager will be set later)
|
|
43
|
+
self.controller = SafePDFController(progress_callback=self.update_progress)
|
|
44
|
+
|
|
45
|
+
# Initialize UI with controller reference
|
|
46
|
+
self.ui = SafePDFUI(root, self.controller)
|
|
47
|
+
|
|
48
|
+
# Now that UI is created, update controller with language_manager from UI
|
|
49
|
+
if hasattr(self.ui, "lang_manager"):
|
|
50
|
+
self.controller.language_manager = self.ui.lang_manager
|
|
51
|
+
# Also update the pdf_ops with the language_manager
|
|
52
|
+
if hasattr(self.controller, "pdf_ops") and self.controller.pdf_ops:
|
|
53
|
+
self.controller.pdf_ops.language_manager = self.ui.lang_manager
|
|
54
|
+
|
|
55
|
+
# Module logger
|
|
56
|
+
self.logger = get_logger("SafePDF.App")
|
|
57
|
+
|
|
58
|
+
# Set application icon and taskbar properties
|
|
59
|
+
self.set_app_icon_and_taskbar()
|
|
60
|
+
|
|
61
|
+
def update_progress(self, value):
|
|
62
|
+
"""Progress callback for PDF operations"""
|
|
63
|
+
if hasattr(self.ui, "update_progress"):
|
|
64
|
+
self.ui.update_progress(value)
|
|
65
|
+
|
|
66
|
+
def set_app_icon_and_taskbar(self):
|
|
67
|
+
"""Set Windows AppUserModelID and application icon so the app shows on taskbar."""
|
|
68
|
+
# Only on Windows: set AppUserModelID for proper taskbar grouping & icon
|
|
69
|
+
if sys.platform == "win32":
|
|
70
|
+
try:
|
|
71
|
+
windll.shell32.SetCurrentProcessExplicitAppUserModelID("com.mca.safepdf")
|
|
72
|
+
except Exception:
|
|
73
|
+
self.logger.debug("Error setting AppUserModelID", exc_info=True)
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
# Find an icon file (check assets folder next to this file)
|
|
77
|
+
base = Path(__file__).parent
|
|
78
|
+
candidates = [
|
|
79
|
+
base / "assets" / "icon.ico",
|
|
80
|
+
base / "assets" / "icon.png",
|
|
81
|
+
Path(sys.argv[0]).with_suffix(".ico"),
|
|
82
|
+
]
|
|
83
|
+
icon_path = None
|
|
84
|
+
for c in candidates:
|
|
85
|
+
if c and c.exists():
|
|
86
|
+
icon_path = c
|
|
87
|
+
break
|
|
88
|
+
|
|
89
|
+
# Apply icon: prefer .ico with iconbitmap on Windows, also set wm_iconphoto for other types
|
|
90
|
+
try:
|
|
91
|
+
if icon_path:
|
|
92
|
+
# .ico on Windows
|
|
93
|
+
if icon_path.suffix.lower() == ".ico" and sys.platform == "win32":
|
|
94
|
+
self.root.iconbitmap(str(icon_path))
|
|
95
|
+
else:
|
|
96
|
+
img = tk.PhotoImage(file=str(icon_path))
|
|
97
|
+
# keep reference to avoid garbage collection
|
|
98
|
+
try:
|
|
99
|
+
self.root._icon_image = img
|
|
100
|
+
except Exception:
|
|
101
|
+
self.logger.error("Error keeping icon image reference", exc_info=True)
|
|
102
|
+
pass
|
|
103
|
+
self.root.wm_iconphoto(False, img)
|
|
104
|
+
except Exception:
|
|
105
|
+
self.logger.error("Error setting application icon", exc_info=True)
|
|
106
|
+
pass
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def main():
|
|
110
|
+
"""Main application entry point"""
|
|
111
|
+
try:
|
|
112
|
+
root = TkinterDnD.Tk() # Use TkinterDnD root for drag-and-drop support
|
|
113
|
+
except Exception:
|
|
114
|
+
root = tk.Tk() # Fallback if tkinterdnd2 is not available
|
|
115
|
+
|
|
116
|
+
SafePDFApp(root)
|
|
117
|
+
root.mainloop()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
if __name__ == "__main__":
|
|
121
|
+
main()
|
SafePDF/test/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Test script for PDF compression functionality
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
from SafePDF.ops.pdf_operations import PDFOperations
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_compression():
|
|
12
|
+
"""Test PDF compression with a sample file"""
|
|
13
|
+
print("Testing PDF compression...")
|
|
14
|
+
|
|
15
|
+
# Look for any PDF files in current directory for testing
|
|
16
|
+
pdf_files = [f for f in os.listdir(".") if f.endswith(".pdf")]
|
|
17
|
+
|
|
18
|
+
if not pdf_files:
|
|
19
|
+
print("No PDF files found in current directory for testing.")
|
|
20
|
+
print("Please add a sample PDF file to test compression.")
|
|
21
|
+
return False
|
|
22
|
+
|
|
23
|
+
test_file = pdf_files[0]
|
|
24
|
+
print(f"Testing with file: {test_file}")
|
|
25
|
+
|
|
26
|
+
# Create PDF operations instance
|
|
27
|
+
pdf_ops = PDFOperations(progress_callback=lambda x: print(f"Progress: {x}%"))
|
|
28
|
+
|
|
29
|
+
# Test validation first
|
|
30
|
+
if not pdf_ops.validate_pdf(test_file):
|
|
31
|
+
print(f"Error: {test_file} is not a valid PDF file")
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
print("PDF validation passed")
|
|
35
|
+
|
|
36
|
+
# Test compression with different qualities
|
|
37
|
+
qualities = ["low", "medium", "high"]
|
|
38
|
+
|
|
39
|
+
for quality in qualities:
|
|
40
|
+
output_file = f"test_compressed_{quality}.pdf"
|
|
41
|
+
try:
|
|
42
|
+
print(f"\nTesting {quality} quality compression...")
|
|
43
|
+
success, message = pdf_ops.compress_pdf(test_file, output_file, quality)
|
|
44
|
+
|
|
45
|
+
if success:
|
|
46
|
+
print(f"✅ {quality} compression: {message}")
|
|
47
|
+
|
|
48
|
+
# Check if file exists and is valid
|
|
49
|
+
if os.path.exists(output_file):
|
|
50
|
+
if pdf_ops.validate_pdf(output_file):
|
|
51
|
+
original_size = os.path.getsize(test_file)
|
|
52
|
+
compressed_size = os.path.getsize(output_file)
|
|
53
|
+
print(f" Original: {original_size} bytes")
|
|
54
|
+
print(f" Compressed: {compressed_size} bytes")
|
|
55
|
+
print(f" Savings: {((original_size - compressed_size) / original_size * 100):.1f}%")
|
|
56
|
+
else:
|
|
57
|
+
print(f"❌ Compressed file {output_file} is corrupted!")
|
|
58
|
+
else:
|
|
59
|
+
print(f"❌ Compressed file {output_file} was not created!")
|
|
60
|
+
else:
|
|
61
|
+
print(f"❌ {quality} compression failed: {message}")
|
|
62
|
+
|
|
63
|
+
except Exception as e:
|
|
64
|
+
print(f"❌ Exception during {quality} compression: {e}")
|
|
65
|
+
|
|
66
|
+
# Cleanup test files
|
|
67
|
+
print("\nCleaning up test files...")
|
|
68
|
+
for quality in qualities:
|
|
69
|
+
output_file = f"test_compressed_{quality}.pdf"
|
|
70
|
+
if os.path.exists(output_file):
|
|
71
|
+
os.remove(output_file)
|
|
72
|
+
print(f"Removed {output_file}")
|
|
73
|
+
|
|
74
|
+
print("\nCompression test completed!")
|
|
75
|
+
return True
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
if __name__ == "__main__":
|
|
79
|
+
test_compression()
|