-
Notifications
You must be signed in to change notification settings - Fork 24
/
densify
executable file
·467 lines (392 loc) · 17.5 KB
/
densify
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
#!/usr/bin/python3
#################################################################
### PROJECT:
### Densify
### VERSION:
### v0.3.1
### SCRIPT:
### Densify
### DESCRIPTION:
### GTK+ 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 threading
import subprocess
import traceback
import queue
import os
import re
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
from gi.overrides import GLib
import pathlib
class MyWindow(Gtk.Window, threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
# Detect Path that the script is running from:
run_path = pathlib.Path(__file__).parent.absolute()
header = str(run_path) + "/header.png"
# Detect Screen Resolution
disp = ['xrandr']
disp_results = ['grep', '*']
p = subprocess.Popen(disp, stdout=subprocess.PIPE)
p2 = subprocess.Popen(disp_results, stdin=p.stdout, stdout=subprocess.PIPE)
p.stdout.close()
resolution_string, junk = p2.communicate()
resolution = resolution_string.split()[0]
rstring = str(resolution)
rstring = rstring[1:] # Remove "b" from string
rstring = rstring[1:] # Remove "'" from beginning of string
rstring = rstring[:-1] # Remove "'" from end of string
w, h = rstring.split("x")
height = int(h)
if height < 800:
window_height = 300
else:
window_height = 450
# Set Window Specification
Gtk.Window.__init__(self, title="Densify - PDF Compression")
self.set_position(Gtk.WindowPosition.CENTER)
self.set_default_size(window_height, 300)
self.set_resizable(True)
self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8, margin=20)
self.add(self.box)
# App Logo
if height > 799:
self.image = Gtk.Image()
self.image.set_from_file(header)
self.box.pack_start(self.image, True, True, padding=1)
# 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>")
self.box.pack_start(aLabel, True, True, 0)
# App Version
vLabel = Gtk.Label(label="v0.3.2")
vLabel.set_justify(Gtk.Justification.CENTER)
self.box.pack_start(vLabel, True, True, 0)
# Separator
bar = Gtk.HSeparator()
self.box.pack_start(bar, True, True, 0)
# Specify Input File
iLabel = Gtk.Label(label="PDF:", xalign=0)
self.box.pack_start(iLabel, True, True, 0)
self.iChooser = Gtk.FileChooserButton()
self.box.pack_start(self.iChooser, True, True, 0)
# Separator
bar1 = Gtk.HSeparator()
self.box.pack_start(bar1, True, True, 0)
# Specify Compression Type
tLabel = Gtk.Label(label="Type:", xalign=0)
self.box.pack_start(tLabel, True, True, 0)
store = Gtk.ListStore(str)
for item in ["ebook", "screen", "printer", "prepress", "default"]:
store.append([item])
self.cType = Gtk.ComboBox()
self.cType.set_model(store)
self.cType.set_active(0)
self.cType.connect("changed", self.on_combobox_changed)
self.box.pack_start(self.cType, True, True, 0)
cellrenderertext = Gtk.CellRendererText()
self.cType.pack_start(cellrenderertext, True)
self.cType.add_attribute(cellrenderertext, "text", 0)
# Help Button - Compression Types
self.help = Gtk.Button(label="?")
self.help.connect("clicked", self.on_help_clicked)
self.box.pack_start(self.help, True, True, 0)
# Separator
bar2 = Gtk.HSeparator()
self.box.pack_start(bar2, True, True, 0)
# Specify Output File
oLabel = Gtk.Label(label="Output:", xalign=0)
self.box.pack_start(oLabel, True, True, 0)
self.oFile = Gtk.Entry()
self.oFile.set_placeholder_text("compressed.pdf")
self.box.pack_start(self.oFile, True, True, 0)
# Help Button - Output File
self.oHelp = Gtk.Button(label="?")
self.oHelp.connect("clicked", self.on_oHelp_clicked)
self.box.pack_start(self.oHelp, True, True, 0)
# Separator
bar3 = Gtk.HSeparator()
self.box.pack_start(bar3, True, True, 0)
# Progress Bar
pLabel = Gtk.Label(label="Status:", xalign=0)
self.box.pack_start(pLabel, True, True, 0)
self.progressbar = Gtk.ProgressBar()
self.box.pack_start(self.progressbar, True, True, 1)
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.HSeparator()
self.box.pack_start(bar4, True, True, 0)
# Toggle Compress
self.button = Gtk.Button(label="Compress Now!")
self.button.set_sensitive(True)
self.button.connect("clicked", self.on_button_clicked)
self.box.pack_start(self.button, True, True, 0)
# ComboBox Handler
def on_combobox_changed(self, combobox):
treeiter = combobox.get_active_iter()
model = combobox.get_model()
# Help Button Handler
def on_help_clicked(self, widget):
# Show Compression Type Descriptions Help Dialog
verbiage = "\n\n\nscreen:\n\nselects low-resolution output similar to the Acrobat Distiller \"Screen Optimized\" setting.\n\n\nebook:\n\nselects medium-resolution output similar to the Acrobat Distiller \"eBook\" setting.\n\n\nprinter:\n\nselects output similar to the Acrobat Distiller \"Print Optimized\" setting.\n\n\nprepress:\n\nselects output similar to Acrobat Distiller \"Prepress Optimized\" setting.\n\n\ndefault:\n\nselects output intended to be useful across a wide variety of uses, possibly at the expense of a larger output file."
self.info("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 "Completed" and Progress Bar to Pulse
self.progress()
# Set Command Compression Type Variable
iFile = self.iChooser.get_filename()
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 1
# 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 1
# Prep Type of Compression - Must happen before comparing iFile and oFile
if iFile != None:
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 1
# If Output File does not end with .pdf, verify with user that's really what they want
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?"
response = self.verify("Output file name does not end with \".pdf\"!", verbiage)
# If OK, then continue to overwrite existing file. If cancel, then stop and go back to main window
if response == Gtk.ResponseType.CANCEL:
self.ready()
# Enable Compress Button
self.button.set_sensitive(True)
return 1
# 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 Procaution
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.button.set_sensitive(True)
return 1
# If Specified Output File Name Contains Unsupported Characters, Show Dialog Error Dialog Box and Return to Main Window
# Security Procaution
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.button.set_sensitive(True)
return 1
# If Specified Output File Name Matches a File in the Output Directory
if os.path.isfile(oFile):
# Show Error Dialog
verbiage = "There's a file with the same name, \"" + oFile + "\" already in the directory. Are you sure you want to overwrite?"
response = self.verify("WARNING!", verbiage)
# If OK, then continue to overwrite existing file. If cancel, then stop and go back to main window
if response == Gtk.ResponseType.CANCEL:
self.ready()
# Enable Compress Button
self.button.set_sensitive(True)
return 1
# Set Compression Type
cTypeIter = self.cType.get_active_iter()
cTypeModel = self.cType.get_model()
cType = cTypeModel[cTypeIter][0]
# Build gs Command
self.cmmd = 'gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.6 -dPDFSETTINGS=/' + cType + ' -dNOPAUSE -dQUIET -dBATCH -sOutputFile=' + "\"" + oFile + "\"" + ' ' + "\"" +iFile + "\""
# Start Compressing
q = queue.Queue()
cnow = threading.Thread(target=self.compress, args=[q])
cnow.start()
# Keep Progress Bar Active
while cnow.is_alive():
Gtk.main_iteration_do(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
subprocess.run(["notify-send", "PDF 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.info("PDF Compressed!", verbiage)
else:
# Notify User
subprocess.run(["notify-send", "ERROR!"])
# 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
def info(self, title, verbiage):
# Show Info Dialog
dialog = Gtk.MessageDialog(parent=self, flags=0, message_type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.OK, text=title)
dialog.format_secondary_text(verbiage)
response = dialog.run()
dialog.destroy()
return response
# Warning Dialog Message
def warning(self, title, verbiage):
# Pause Compression Progress Bar
self.pause()
# Show Error Dialog
dialog = Gtk.MessageDialog(parent=self, flags=0, message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK, text=title)
dialog.format_secondary_text(verbiage)
response = dialog.run()
dialog.destroy()
return response
# Verify What to Do Dialog Message
def verify(self, title, verbiage):
# Pause Compression Progress Bar
self.pause()
# Show Error Dialog
dialog = Gtk.MessageDialog(parent=self, flags=0, message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK_CANCEL, text=title)
dialog.format_secondary_text(verbiage)
response = dialog.run()
dialog.destroy()
# Resume Compression Progress Bar & Continue
self.resume()
return response
# 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:
process = subprocess.Popen(self.cmmd, shell=True, stdout=subprocess.PIPE)
out, err = process.communicate()
out_queue.put(True)
except:
if err == None:
print("There's an error with no trace data...")
else:
print(err)
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
# Initiate Window
win = MyWindow()
win.start()
win.set_icon_from_file(str(pathlib.Path(__file__).parent.absolute()) + "/icon.png") # Set App Icon
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()