-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdensify
More file actions
executable file
·806 lines (699 loc) · 29.7 KB
/
densify
File metadata and controls
executable file
·806 lines (699 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
#!/usr/bin/env python3
#################################################################
### PROJECT:
### Densify
### VERSION:
### v0.4.0
### SCRIPT:
### Densify
### DESCRIPTION:
### GTK4 application to easily compress pdf files w/ Ghostscript
### MAINTAINED BY:
### hkdb <[email protected]>
### Disclaimer:
### This application is maintained by volunteers and in no way
### do the maintainers make any guarantees. Use at your own risk.
### ##############################################################
import sys
import threading
import subprocess
import traceback
import queue
import os
import re
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Gdk', '4.0')
from gi.repository import Gtk, Gdk, Gio, GLib, GObject
import pathlib
# Check GTK version for FileDialog support (GTK 4.10+)
GTK_VERSION = (Gtk.get_major_version(), Gtk.get_minor_version())
HAS_FILE_DIALOG = GTK_VERSION >= (4, 10)
class MyWindow(Gtk.ApplicationWindow):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Detect Path that the script is running from:
# For PyInstaller/AppImage, use _MEIPASS for bundled resources
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
run_path = pathlib.Path(sys._MEIPASS)
else:
run_path = pathlib.Path(__file__).parent.absolute()
header = str(run_path) + "/header.png"
# Detect Screen Resolution using GDK (Wayland compatible)
display = Gdk.Display.get_default()
monitors = display.get_monitors()
if monitors.get_n_items() > 0:
monitor = monitors.get_item(0)
geometry = monitor.get_geometry()
height = geometry.height
else:
height = 800 # Default fallback
if height < 800:
window_height = 300
else:
window_height = 450
# Set Window Specification
self.set_title("Densify - PDF Compression")
self.set_default_size(window_height, 300)
self.set_resizable(True)
self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
self.box.set_margin_top(20)
self.box.set_margin_bottom(20)
self.box.set_margin_start(20)
self.box.set_margin_end(20)
self.set_child(self.box)
# Store compression types for DropDown
self.compression_types = ["ebook", "screen", "printer", "prepress", "default"]
# Initialize selected file path
self.selected_file = None
# App Logo
if height > 799:
# Use Gtk.Picture for better image display in GTK4
self.image = Gtk.Picture()
self.image.set_filename(header)
# Explicitly set size to ensure it displays at correct dimensions
self.image.set_size_request(256, 256)
self.image.set_can_shrink(False) # Don't shrink below natural size
self.image.set_halign(Gtk.Align.CENTER)
self.box.append(self.image)
# App About
aLabel = Gtk.Label(label="An Open Source Initiative Sponsored by 3DF")
aLabel.set_markup("<small>An <a href=\"https://osi.3df.io\"" "title=\"OSI @ 3DF\">OSI</a> application sponsored by <a href=\"https://3df.io\"" "title=\"3DF Ltd.\">3DF</a></small>")
aLabel.set_use_markup(True)
self.box.append(aLabel)
# App Version
vLabel = Gtk.Label(label="v0.4.2")
vLabel.set_justify(Gtk.Justification.CENTER)
self.box.append(vLabel)
# Separator
bar = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
self.box.append(bar)
# Specify Input File
iLabel = Gtk.Label(label="PDF:")
iLabel.set_halign(Gtk.Align.START)
self.box.append(iLabel)
# FileChooserButton is removed in GTK4 - use Button with FileDialog
# Create a box to hold label and folder icon
file_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
self.file_label = Gtk.Label(label="Select PDF File...")
self.file_label.set_hexpand(True)
self.file_label.set_halign(Gtk.Align.START)
file_icon = Gtk.Image.new_from_icon_name("folder-open-symbolic")
file_box.append(self.file_label)
file_box.append(file_icon)
self.file_button = Gtk.Button()
self.file_button.set_child(file_box)
self.file_button.connect("clicked", self.on_file_button_clicked)
# Add drag and drop support
drop_target = Gtk.DropTarget.new(Gio.File, Gdk.DragAction.COPY)
drop_target.connect("drop", self.on_file_drop)
self.file_button.add_controller(drop_target)
self.box.append(self.file_button)
# Separator
bar1 = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
self.box.append(bar1)
# Specify Compression Type
tLabel = Gtk.Label(label="Type:")
tLabel.set_halign(Gtk.Align.START)
self.box.append(tLabel)
# Use ComboBoxText for classic dropdown appearance with arrow
self.cType = Gtk.ComboBoxText()
for item in self.compression_types:
self.cType.append_text(item)
self.cType.set_active(0)
self.box.append(self.cType)
# Help Button - Compression Types
self.help = Gtk.Button(label="?")
self.help.connect("clicked", self.on_help_clicked)
self.box.append(self.help)
# Separator
bar2 = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
self.box.append(bar2)
# Specify Output File
oLabel = Gtk.Label(label="Output:")
oLabel.set_halign(Gtk.Align.START)
self.box.append(oLabel)
self.oFile = Gtk.Entry()
self.oFile.set_placeholder_text("compressed.pdf")
self.box.append(self.oFile)
# Help Button - Output File
self.oHelp = Gtk.Button(label="?")
self.oHelp.connect("clicked", self.on_oHelp_clicked)
self.box.append(self.oHelp)
# Separator
bar3 = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
self.box.append(bar3)
# Progress Bar
pLabel = Gtk.Label(label="Status:")
pLabel.set_halign(Gtk.Align.START)
self.box.append(pLabel)
self.progressbar = Gtk.ProgressBar()
self.box.append(self.progressbar)
show_text = True
text = "Ready"
self.progressbar.set_text(text)
self.progressbar.set_show_text(show_text)
self.timeout_id = GLib.timeout_add(50, self.on_timeout, None)
self.activity_mode = False
# Separator
bar4 = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
self.box.append(bar4)
# Toggle Compress
self.button = Gtk.Button(label="Compress Now!")
self.button.set_sensitive(True)
self.button.connect("clicked", self.on_button_clicked)
self.box.append(self.button)
# File Button Handler - Opens FileDialog (GTK 4.10+) or FileChooserNative (older)
def on_file_button_clicked(self, button):
# Create filter for PDF files
filter_pdf = Gtk.FileFilter()
filter_pdf.set_name("PDF Files")
filter_pdf.add_mime_type("application/pdf")
filter_pdf.add_pattern("*.pdf")
if HAS_FILE_DIALOG:
# GTK 4.10+ - Use new FileDialog API
dialog = Gtk.FileDialog()
dialog.set_title("Select PDF File")
filters = Gio.ListStore.new(Gtk.FileFilter)
filters.append(filter_pdf)
dialog.set_filters(filters)
dialog.set_default_filter(filter_pdf)
dialog.open(self, None, self.on_file_dialog_response)
else:
# GTK < 4.10 - Use FileChooserDialog (deprecated but works without portals)
dialog = Gtk.FileChooserDialog(
title="Select PDF File",
action=Gtk.FileChooserAction.OPEN,
)
dialog.set_transient_for(self)
dialog.set_modal(True)
dialog.add_button("_Cancel", Gtk.ResponseType.CANCEL)
dialog.add_button("_Open", Gtk.ResponseType.ACCEPT)
dialog.add_filter(filter_pdf)
dialog.set_filter(filter_pdf)
dialog.connect("response", self.on_file_chooser_response)
dialog.present()
def on_file_dialog_response(self, dialog, result):
"""Handler for GTK 4.10+ FileDialog"""
try:
file = dialog.open_finish(result)
if file:
self.selected_file = file.get_path()
# Update label to show selected file
filename = os.path.basename(self.selected_file)
self.file_label.set_label(filename)
except GLib.Error as e:
# User cancelled or error
pass
def on_file_chooser_response(self, dialog, response):
"""Handler for GTK < 4.10 FileChooserNative"""
if response == Gtk.ResponseType.ACCEPT:
file = dialog.get_file()
if file:
self.selected_file = file.get_path()
# Update label to show selected file
filename = os.path.basename(self.selected_file)
self.file_label.set_label(filename)
dialog.destroy()
def on_file_drop(self, drop_target, value, x, y):
"""Handle file drag and drop"""
if isinstance(value, Gio.File):
file_path = value.get_path()
if file_path:
self.selected_file = file_path
filename = os.path.basename(file_path)
self.file_label.set_label(filename)
return True
return False
# Help Button Handler
def on_help_clicked(self, widget):
# Show Compression Type Descriptions Help Dialog with Pango markup for bold types
verbiage = (
"\n\n<b>screen:</b>\n"
"Selects low-resolution output similar to the Acrobat Distiller \"Screen Optimized\" setting.\n\n"
"<b>ebook:</b>\n"
"Selects medium-resolution output similar to the Acrobat Distiller \"eBook\" setting.\n\n"
"<b>printer:</b>\n"
"Selects output similar to the Acrobat Distiller \"Print Optimized\" setting.\n\n"
"<b>prepress:</b>\n"
"Selects output similar to Acrobat Distiller \"Prepress Optimized\" setting.\n\n"
"<b>default:</b>\n"
"Selects output intended to be useful across a wide variety of uses, possibly at the expense of a larger output file.\n\n"
)
self.info_markup("Types of Compression", verbiage)
# oHelp Button Handler
def on_oHelp_clicked(self, widget):
# Show Output File Help Dialog
verbiage = "The output filename must not be the same as the input file name. The compressed PDF file will be placed in the same folder as your input file folder."
self.info("Output File Name", verbiage)
# Compression Button Handler - Where all the magic happens
def on_button_clicked(self, widget):
# Disable Compress Button
self.button.set_sensitive(False)
# Set Progress Bar Text to "Compressing..." and Progress Bar to Pulse
self.progress()
# Set Command Compression Type Variable
iFile = self.selected_file
slash = "/"
oName = self.oFile.get_text()
# If Output file name was not specified, use "compressed.pdf"
if oName == None or oName == "":
oName = "compressed.pdf"
# If Input file is not specified, show an error dialog box
if iFile == None:
# Show Error Dialog
verbiage = "The input file field is empty. Please specify an input file to compress..."
self.warning("ERROR!", verbiage)
# Set Progress Bar Text to "Ready"
self.ready()
# Enable Compress Button
self.button.set_sensitive(True)
return
# If Input file does not end with .pdf, show an error dialog box
if not iFile.endswith(".pdf"):
# Show Error Dialog
verbiage = "Only PDF files can be compressed with this application. Please specify a pdf file"
self.warning("ERROR!", verbiage)
# Set Progress Bar Text to "Ready"
self.ready()
# Enable Compress Button
self.button.set_sensitive(True)
return
# Prep Type of Compression - Must happen before comparing iFile and oFile
iPath = os.path.dirname(iFile)
oFile = iPath + slash + oName
# If the Input File and Output File are the same, show an error dialog box
if iFile == oFile:
# Show Error Dialog
verbiage = "The output file name cannot be the same as the input file name."
self.warning("ERROR!", verbiage)
# Set Progress Bar Text to "Ready"
self.ready()
# Enable Compress Button
self.button.set_sensitive(True)
return
# Turn iFile to String to Prepare for Next Condition
iName = str(os.path.basename(iFile))
# If Specified Input File Name Contains Unsupported Characters, Show Dialog Error Dialog Box and Return to Main Window
# Security Precaution
if re.search('[\\\\|/:;`><{}#*\'"]', iName):
verbiage = "The input file name contains unsupported characters. Please ensure your input file name does not contain special characters / \\ : ; ` > < } { # * ' \""
self.warning("Unsupported File Name Convention!", verbiage)
self.ready()
self.button.set_sensitive(True)
return
# If Specified Output File Name Contains Unsupported Characters, Show Dialog Error Dialog Box and Return to Main Window
# Security Precaution
if re.search('[\\\\|/:;`><{}#*\'"]', oName):
verbiage = "The output file name contains unsupported characters. Please ensure your output file name does not contain special characters / \\ : ; ` > < } { # * ' \""
self.warning("Unsupported File Name Convention!", verbiage)
self.ready()
self.button.set_sensitive(True)
return
# Store context for async callbacks
context = {'iFile': iFile, 'oFile': oFile}
# Check if output file doesn't end with .pdf - if so, verify with user
if not oFile.endswith(".pdf"):
verbiage = "The output file name you specified does not end with \".pdf\". Are you sure that's what you want?"
self.verify("Output file name does not end with \".pdf\"!", verbiage,
self._continue_after_pdf_check, context)
return
# Continue with file existence check
self._continue_after_pdf_check(context)
def _continue_after_pdf_check(self, context):
"""Continue compression flow after PDF extension check"""
iFile = context['iFile']
oFile = context['oFile']
# If Specified Output File Name Matches a File in the Output Directory
if os.path.isfile(oFile):
# Show Verify Dialog
verbiage = "There's a file with the same name, \"" + oFile + "\" already in the directory. Are you sure you want to overwrite?"
self.verify("WARNING!", verbiage, self._do_compression, context)
return
# No existing file, proceed directly to compression
self._do_compression(context)
def _do_compression(self, context):
"""Perform the actual compression"""
iFile = context['iFile']
oFile = context['oFile']
# Set Compression Type
cType = self.cType.get_active_text()
# Build gs Command as list (safer - no shell injection possible)
self.cmmd = [
'gs',
'-sDEVICE=pdfwrite',
'-dCompatibilityLevel=1.6',
f'-dPDFSETTINGS=/{cType}',
'-dNOPAUSE',
'-dQUIET',
'-dBATCH',
f'-sOutputFile={oFile}',
iFile
]
# Start Compressing
q = queue.Queue()
cnow = threading.Thread(target=self.compress, args=[q])
cnow.start()
# Keep Progress Bar Active (GTK4 compatible)
while cnow.is_alive():
main_context = GLib.MainContext.default()
main_context.iteration(False)
# Don't continue until thread is finished
cnow.join()
# Setup Queue to get try catch results
success = q.get()
# If try succeeds, tell user it succeeded, else, show an error dialog
if success == True:
# Notify User
self.send_notification("PDF Compressed!", "Your PDF has been successfully compressed.")
# Get File Size
iFileSizeRaw = os.path.getsize(iFile)
oFileSizeRaw = os.path.getsize(oFile)
# Determine to Display File Size in MB or KB +- 10MB
if iFileSizeRaw < 10000000:
iFileSize = iFileSizeRaw >> 10
iUnit = "KB"
else:
iFileSize = iFileSizeRaw >> 20
iUnit = "MB"
if oFileSizeRaw < 10000000:
oFileSize = oFileSizeRaw >> 10
oUnit = "KB"
else:
oFileSize = oFileSizeRaw >> 20
oUnit = "MB"
# Set Progress Bar to Completed and Stop Pulsing
self.completed()
# Show Completion Dialog - Try Completed
verbiage = "Your PDF File has been successfully compressed from " + str(iFileSize) + iUnit + " to " + str(oFileSize) + oUnit + "! Enjoy!"
self.completion_dialog("PDF Compressed!", verbiage, oFile)
else:
# Notify User
self.send_notification("ERROR!", "Something went wrong during compression.")
# Show Error Dialog - Exception
verbiage = "Something went wrong! Maybe your PDF file is corrupted?"
self.info("ERROR!", verbiage)
# Set Progress Bar to Ready and Stop Pulsing
self.ready()
# Informational Dialog Message (GTK4 AlertDialog or MessageDialog fallback)
def info(self, title, verbiage):
if HAS_FILE_DIALOG:
# GTK 4.10+ - Use AlertDialog
dialog = Gtk.AlertDialog()
dialog.set_message(title)
dialog.set_detail(verbiage)
dialog.set_buttons(["OK"])
dialog.set_default_button(0)
dialog.set_cancel_button(0)
dialog.show(self)
else:
# GTK < 4.10 - Use MessageDialog
dialog = Gtk.MessageDialog(
transient_for=self,
modal=True,
message_type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.OK,
text=title,
secondary_text=verbiage
)
dialog.connect("response", lambda d, r: d.destroy())
dialog.present()
# Informational Dialog with Pango Markup support
def info_markup(self, title, markup_text):
# Create a custom dialog window for markup support
dialog = Gtk.Window(title=title)
dialog.set_transient_for(self)
dialog.set_modal(True)
dialog.set_resizable(False)
# Main container
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
box.set_margin_top(20)
box.set_margin_bottom(20)
box.set_margin_start(20)
box.set_margin_end(20)
dialog.set_child(box)
# Title label
title_label = Gtk.Label()
title_label.set_markup(f"<b>{title}</b>")
box.append(title_label)
# Content label with markup - auto-sizes to content
content_label = Gtk.Label()
content_label.set_markup(markup_text)
content_label.set_halign(Gtk.Align.START)
content_label.set_valign(Gtk.Align.START)
box.append(content_label)
# OK button
ok_button = Gtk.Button(label="OK")
ok_button.connect("clicked", lambda btn: dialog.close())
ok_button.set_halign(Gtk.Align.END)
box.append(ok_button)
dialog.present()
# Completion dialog with Open Folder option
def completion_dialog(self, title, verbiage, output_file):
"""Shows completion dialog with OK and Open Folder buttons"""
dialog = Gtk.Window(title=title)
dialog.set_transient_for(self)
dialog.set_modal(True)
dialog.set_resizable(False)
# Main container
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
box.set_margin_top(20)
box.set_margin_bottom(20)
box.set_margin_start(20)
box.set_margin_end(20)
dialog.set_child(box)
# Title label
title_label = Gtk.Label()
title_label.set_markup(f"<b>{title}</b>")
box.append(title_label)
# Content label
content_label = Gtk.Label(label=verbiage)
content_label.set_wrap(True)
content_label.set_max_width_chars(50)
box.append(content_label)
# Button box
button_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
button_box.set_halign(Gtk.Align.END)
button_box.set_margin_top(8)
# Open Folder button
open_folder_btn = Gtk.Button(label="Open Folder")
open_folder_btn.connect("clicked", lambda btn: self._show_in_file_manager(output_file, dialog))
button_box.append(open_folder_btn)
# OK button
ok_button = Gtk.Button(label="OK")
ok_button.connect("clicked", lambda btn: dialog.close())
button_box.append(ok_button)
box.append(button_box)
dialog.present()
def send_notification(self, title, body):
"""Send desktop notification using notify-send with clean environment"""
try:
# Clear LD_LIBRARY_PATH so notify-send uses system libraries (fixes AppImage conflicts)
env = os.environ.copy()
env.pop('LD_LIBRARY_PATH', None)
env.pop('LD_PRELOAD', None)
subprocess.run(["notify-send", title, body], env=env)
except Exception as e:
# Fallback: just print to console if notifications fail
print(f"Notification: {title} - {body}")
def _show_in_file_manager(self, file_path, dialog=None):
"""Opens file manager with file highlighted using DBus or fallback"""
if dialog:
dialog.close()
file_uri = 'file://' + file_path
try:
# Try DBus FileManager1 interface (highlights the file in most file managers)
proxy = Gio.DBusProxy.new_for_bus_sync(
Gio.BusType.SESSION,
Gio.DBusProxyFlags.NONE,
None,
'org.freedesktop.FileManager1',
'/org/freedesktop/FileManager1',
'org.freedesktop.FileManager1',
None
)
proxy.call_sync(
'ShowItems',
GLib.Variant('(ass)', ([file_uri], '')),
Gio.DBusCallFlags.NONE,
-1,
None
)
except Exception:
# Fallback: open the containing folder with xdg-open
try:
folder_path = os.path.dirname(file_path)
subprocess.Popen(['xdg-open', folder_path])
except Exception as e:
print(f"Could not open file manager: {e}")
# Warning Dialog Message (GTK4 AlertDialog or MessageDialog fallback)
def warning(self, title, verbiage):
# Pause Compression Progress Bar
self.pause()
if HAS_FILE_DIALOG:
# GTK 4.10+ - Use AlertDialog
dialog = Gtk.AlertDialog()
dialog.set_message(title)
dialog.set_detail(verbiage)
dialog.set_buttons(["OK"])
dialog.set_default_button(0)
dialog.set_cancel_button(0)
dialog.show(self)
else:
# GTK < 4.10 - Use MessageDialog
dialog = Gtk.MessageDialog(
transient_for=self,
modal=True,
message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK,
text=title,
secondary_text=verbiage
)
dialog.connect("response", lambda d, r: d.destroy())
dialog.present()
# Verify What to Do Dialog Message (GTK4 AlertDialog or MessageDialog fallback)
def verify(self, title, verbiage, on_confirm_callback, context=None):
"""
Shows a confirmation dialog. Calls on_confirm_callback(context) if user confirms.
"""
# Pause Compression Progress Bar
self.pause()
if HAS_FILE_DIALOG:
# GTK 4.10+ - Use AlertDialog
dialog = Gtk.AlertDialog()
dialog.set_message(title)
dialog.set_detail(verbiage)
dialog.set_buttons(["Cancel", "OK"])
dialog.set_default_button(1) # OK
dialog.set_cancel_button(0) # Cancel
def on_response(dialog, result):
try:
response = dialog.choose_finish(result)
# Resume Progress Bar
self.resume()
# response is button index: 0=Cancel, 1=OK
if response == 1 and on_confirm_callback:
on_confirm_callback(context)
else:
# User cancelled - reset state
self.ready()
self.button.set_sensitive(True)
except GLib.Error:
# Dialog was dismissed
self.ready()
self.button.set_sensitive(True)
dialog.choose(self, None, on_response)
else:
# GTK < 4.10 - Use MessageDialog
dialog = Gtk.MessageDialog(
transient_for=self,
modal=True,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.OK_CANCEL,
text=title,
secondary_text=verbiage
)
def on_response(dialog, response):
dialog.destroy()
# Resume Progress Bar
self.resume()
if response == Gtk.ResponseType.OK and on_confirm_callback:
on_confirm_callback(context)
else:
# User cancelled - reset state
self.ready()
self.button.set_sensitive(True)
dialog.connect("response", on_response)
dialog.present()
# Set Progress Bar Text to "Compressing..." and Progress Bar to Pulse
def progress(self):
show_text = True
text = "Compressing..."
self.progressbar.set_text(text)
self.progressbar.set_show_text(show_text)
self.activity_mode = True
self.progressbar.pulse()
# Set Progress Bar Text to "Ready" and Progress Bar to Stop
def ready(self):
show_text = True
text = "Ready"
self.progressbar.set_text(text)
self.progressbar.set_show_text(show_text)
self.activity_mode = False
self.progressbar.set_fraction(0.0)
# Enable Compress Button
self.button.set_sensitive(True)
# Set Progress Bar Text to "Puased" and Progress Bar to Stop
def pause(self):
show_text = True
text = "Paused"
self.progressbar.set_text(text)
self.progressbar.set_show_text(show_text)
self.activity_mode = False
self.progressbar.set_fraction(0.0)
# Set Progress Bar Text to "Compressing..." and Progress Bar to Resume
def resume(self):
show_text = True
text = "Compressing..."
self.progressbar.set_text(text)
self.progressbar.set_show_text(show_text)
self.activity_mode = True
self.progressbar.pulse()
# Set Progress Bar Text to "Completed" and Progress Bar to Stop
def completed(self):
show_text = True
text = "Completed"
self.progressbar.set_text(text)
self.progressbar.set_show_text(show_text)
self.activity_mode = False
self.progressbar.set_fraction(0.0)
# Enable Compress Button
self.button.set_sensitive(True)
# Compression Function to execute gs as SubProcess to be Called on a Separate Thread
def compress(self, out_queue):
try:
# Clear LD_LIBRARY_PATH so GhostScript uses system libraries (fixes AppImage conflicts)
env = os.environ.copy()
env.pop('LD_LIBRARY_PATH', None)
env.pop('LD_PRELOAD', None)
# Using list args without shell=True prevents command injection
process = subprocess.Popen(self.cmmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
out, err = process.communicate()
# Check return code to determine success
if process.returncode == 0:
out_queue.put(True)
else:
if err:
print(f"GhostScript error: {err.decode()}")
out_queue.put(False)
except Exception as e:
print(f"Compression error: {e}")
out_queue.put(False)
# Progress Bar Status Handler
def on_timeout(self, user_data):
# Update value on the progress bar
if self.activity_mode:
self.progressbar.pulse()
else:
new_value = self.progressbar.get_fraction()
if new_value > 1:
new_value = 0
self.progressbar.set_fraction(new_value)
# As this is a timeout function, return True so that it
# continues to get called
return True
class DensifyApplication(Gtk.Application):
"""GTK4 Application class for Densify"""
def __init__(self):
super().__init__(
application_id="io._3df.osi.densify",
flags=Gio.ApplicationFlags.FLAGS_NONE
)
def do_activate(self):
win = MyWindow(application=self)
win.present()
def main():
app = DensifyApplication()
return app.run(None)
if __name__ == "__main__":
main()