-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnipper.py
405 lines (308 loc) · 16 KB
/
snipper.py
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
import os
import sys
import time
import json
import ctypes
import subprocess
from threading import Thread
import tkinter as tk
from tkinter import W, N, S, E, NW, LEFT
from tkinter import BooleanVar, messagebox, filedialog, ttk
import docx
from docx.shared import Inches
from PIL import Image, ImageGrab, ImageTk
from pynput import keyboard
from plyer import notification
class SnipperTool():
def __init__(self,
master,
title='Snipper Tool',
width=500,
height=350,
dict_image_format={'PNG':'.png', 'BMP':'.bmp', 'JPEG':'.jpeg'},
dict_image_editor_application={'MS Paint': 'mspaint'}):
self.master = master
self.title = title
self.width = width
self.height = height
self.dict_image_format = dict_image_format
self.dict_image_editor_application = dict_image_editor_application
self.control_padd = 10 # padding between widgets
self.blank_col_padd = 50 # padding blank col
self.text_box_dir_path = None
self.btn_browse = None
self.btn_start = None
self.btn_create_docx = None
self.btn_exit = None
self.chk_box_save_setings = BooleanVar()
self.logo = None
self.bg_image = None
self.path_icon = None
self.path_settings_file = None
self.cmb_box_image_ext = None
self.cmb_box_image_editor = None
self.thread_start_process = None
self.show_image_captured_notification = True # No usage at the moment
self._draw_window()
# region Drawing Window
def _draw_window(self):
self.master.title(self.title)
self._set_file_path()
self._set_window_size_and_position()
self._draw_layout()
self._draw_icon_and_logo()
self._write_header_and_instructions()
self._draw_text_box()
self._draw_buttons()
self._draw_settings()
def _set_window_size_and_position(self):
# get screen width and height
width_screen = self.master.winfo_screenwidth()
height_screen = self.master.winfo_screenheight()
# calculate position (x and y coordinates) for the Tk root window
x_window_pos = (width_screen/2) - (self.width/2)
y_window_pos = (height_screen/2) - (self.height/2)
# set the dimensions & position of window
self.master.geometry('%dx%d+%d+%d' % (self.width, self.height, x_window_pos, y_window_pos))
self.master.resizable(width=False, height=False)
def _draw_layout(self):
for i in range(1, 6):
self.master.columnconfigure(i, weight=1)
for i in range(6):
self.master.rowconfigure(i, weight=1)
# 6 is for blank label
padding_col = self.blank_col_padd - (self.control_padd/2) - 6
# Left blank column
lbl_pad = tk.Label(self.master, text="", )
lbl_pad.grid(row=0, column=0, padx=(padding_col, 0), rowspan=11, sticky=W)
# Right blank column
lbl_pad = tk.Label(self.master, text="", )
lbl_pad.grid(row=0, column=7, padx=(0, padding_col), rowspan=11, sticky=W)
def _draw_icon_and_logo(self):
if self.path_icon is not None and os.path.exists(self.path_icon):
self.master.iconbitmap(self.path_icon)
image_logo = (Image.open(self.path_icon)).resize((50, 50))
self.logo = ImageTk.PhotoImage(image_logo)
tk_label_logo = tk.Label(self.master)
tk_label_logo.image = self.logo
tk_label_logo['image'] = self.logo
tk_label_logo.grid(row=0, column=2, columnspan=1, sticky=W+E,
padx=(self.control_padd/2, 0), pady=(self.control_padd, 0))
def _write_header_and_instructions(self):
# Header
label_header = "Snipper Tool"
header = tk.Label(self.master, text=label_header, font=("Arial", 25))
header.grid(row=0, column=3, columnspan=4, sticky=W, pady=(self.control_padd, 0))
# Instructions
font_inst = ("Helvetica", 8)
label_inst = "Instructions :\n" + \
"1: Click on the ' Browse ' button to select the folder.\n" + \
"2: Click on the ' Start ' button to start the process.\n" + \
"3: Press ' PrintScreen ' key to capture the screenshot.\n" + \
"4: Press ' Insert ' key to capture a screenshot & edit.\n" + \
"5: Click on ' Build Docx ' button to create a document.\n" + \
" With images available in selected folder."
label_inst = tk.Label(self.master, text=label_inst, font=font_inst,
justify=LEFT, wraplength=400, anchor=NW)
label_inst.grid(row=5, column=1, columnspan=6, sticky=W,
padx=self.control_padd/2, pady=(0, self.control_padd/2))
def _draw_text_box(self):
self.text_box_dir_path = tk.Entry(self.master, bd=2, width=36)
self.text_box_dir_path.grid(row=1, column=1, columnspan=4, sticky=W+E,
padx=self.control_padd/2, pady=(self.control_padd/2, 0))
self.text_box_dir_path.delete(0, tk.END)
def _draw_buttons(self):
self.btn_browse = tk.Button(self.master, text="Browse", width=10, command=self._browse_dir)
self.btn_browse.grid(row=1, column=5, sticky=W+N+E+S,
padx=self.control_padd/2, pady=self.control_padd/2)
self.btn_start = tk.Button(self.master, text="Start", command=self._start_capture_process)
self.btn_start.grid(row=3, column=1, columnspan=2, sticky=W+N+E+S,
padx=self.control_padd/2, pady=self.control_padd/2)
self.btn_create_docx = tk.Button(self.master, text="Create Docx",
command=self._create_document)
self.btn_create_docx.grid(row=3, column=3, columnspan=2, sticky=W+N+E+S,
padx=self.control_padd/2, pady=self.control_padd/2)
self.btn_exit = tk.Button(self.master, text="Exit", width=10, command=self.exit)
self.btn_exit.grid(row=3, column=5, sticky=W+N+E+S,
padx=self.control_padd/2, pady=self.control_padd/2)
def _draw_settings(self):
font_text = ('Callibri', '8')
# Image extension type drop-down
label_type = tk.Label(self.master, text="Type:", anchor=W)
# "Editor:"
label_type.grid(row=2, column=1, sticky=W,
padx=(self.control_padd/2, 0), pady=self.control_padd/2)
self.cmb_box_image_ext = ttk.Combobox(self.master, width=8,
state='readonly', font=font_text,
values=list(self.dict_image_format.keys()))
self.cmb_box_image_ext.grid(row=2, column=2, sticky=W+E,
padx=(0, self.control_padd/2),
pady=self.control_padd/2)
# Image editor type drop-down
label_editor = tk.Label(self.master, text="Editor:", )
label_editor.grid(row=2, column=3, sticky=W,
padx=(self.control_padd/2, 0), pady=self.control_padd/2)
image_editors = list(self.dict_image_editor_application.keys())
self.cmb_box_image_editor = ttk.Combobox(self.master, width=7, state='readonly',
font=font_text, values=image_editors)
self.cmb_box_image_editor.grid(row=2, column=4, sticky=W+E,
padx=(0, self.control_padd/2),
pady=self.control_padd/2)
# Save config check box
chk_box_save = tk.Checkbutton(self.master, text='Save config',
variable=self.chk_box_save_setings,
onvalue=True, offvalue=False, command=self._save_setting)
chk_box_save.grid(row=2, column=5, sticky=W,
padx=self.control_padd/2, pady=self.control_padd/2)
self._set_default_settings_value()
# endregion Drawing Window
# region Settings
def _set_file_path(self):
assets_path = os.path.join(os.getcwd(), 'assets')
if not os.path.exists(assets_path):
os.mkdir(assets_path)
self.path_icon = os.path.join(assets_path, 'SnipperIcon.ico')
# For executable or installer to have write access
# Creating settings in user APPDATA folder
path_settings = os.path.join(os.getenv('APPDATA'), self.title)
if not os.path.exists(path_settings):
os.mkdir(path_settings)
self.path_settings_file = os.path.join(path_settings, 'settings.json')
def _set_default_settings_value(self):
self.cmb_box_image_ext.current(0)
self.cmb_box_image_editor.current(0)
self.chk_box_save_setings.set(False)
self._load_settings()
self.cmb_box_image_ext.bind("<<ComboboxSelected>>", self._save_setting)
self.cmb_box_image_editor.bind("<<ComboboxSelected>>", self._save_setting)
def _load_settings(self):
if os.path.exists(self.path_settings_file):
settings = None
with open(self.path_settings_file, "r") as read_file:
settings = json.load(read_file)
list_keys = list(self.dict_image_format.keys())
if 'image_type' in settings and settings['image_type'] in list_keys:
self.cmb_box_image_ext.current(list_keys.index(settings['image_type']))
list_keys = list(self.dict_image_editor_application.keys())
if 'image_editor' in settings and settings['image_editor'] in list_keys:
self.cmb_box_image_editor.current(list_keys.index(settings['image_editor']))
if 'save_config' in settings and isinstance(settings['save_config'], bool):
self.chk_box_save_setings.set(settings['save_config'])
def _save_setting(self, event=None):
try:
if self.chk_box_save_setings.get():
settings = {'image_type': self.cmb_box_image_ext.get(),
'image_editor': self.cmb_box_image_editor.get(),
'save_config': self.chk_box_save_setings.get()}
with open(self.path_settings_file, "w") as write_file:
json.dump(settings, write_file)
else:
if os.path.exists(self.path_settings_file):
os.remove(self.path_settings_file)
except Exception as error:
messagebox.showinfo(self.title, str(error))
# endregion Settings
def _browse_dir(self):
dir_path = filedialog.askdirectory()
self.text_box_dir_path.delete(0, tk.END)
self.text_box_dir_path.insert(0, dir_path)
# region Capture Process
def _start_capture_process(self):
if os.path.exists(self.text_box_dir_path.get()) and self.thread_start_process is None:
self.thread_start_process = Thread(target=self._listen_key_events, daemon=True)
self.thread_start_process.start()
messagebox.showinfo(self.title, 'Process started.')
self.master.iconify() # Minimises window tool
elif not os.path.exists(self.text_box_dir_path.get()):
messagebox.showinfo(self.title, "Please select correct path.")
elif self.thread_start_process is not None:
self._notify('Process already running.', 3, self.title, self.path_icon)
def _listen_key_events(self):
with keyboard.Listener(on_release=self._on_key_relase) as listener:
listener.join()
def _on_key_relase(self, key):
if key == keyboard.Key.print_screen:
# self._capture_screen(open_image=False)
thread = Thread(target=self._capture_screen, args=(False, ), daemon=True)
thread.start()
elif key == keyboard.Key.insert:
# self._capture_screen(open_image=True)
thread = Thread(target=self._capture_screen, args=(True, ), daemon=True)
thread.start()
def _capture_screen(self, open_image=False, prefix_name='Screen_Shot_'):
image_file_extn = self.dict_image_format[self.cmb_box_image_ext.get()]
image_file_name = prefix_name + self.time_stamp() + image_file_extn
image_file_path = os.path.join(self.text_box_dir_path.get(), image_file_name)
ImageGrab.grab().save(image_file_path)
if self.show_image_captured_notification:
message = 'Image captured ' + image_file_name
self._notify(message, 2, self.title, self.path_icon)
if open_image:
app_name = self.dict_image_editor_application[self.cmb_box_image_editor.get()]
open_image_in_editor_cmd = [app_name, os.path.abspath(image_file_path)]
subprocess.Popen(open_image_in_editor_cmd, shell=True)
# endregion Capture Process
# region Create Document
def _create_document(self):
"""Creates word document wiht images present in selected directory"""
if not os.path.exists(self.text_box_dir_path.get()):
messagebox.showinfo(self.title, 'Please select correct path.')
return
list_path_images_in_dir = self._get_list_path_images()
# If any images in selected directory
if list_path_images_in_dir:
doc = docx.Document()
# Setting page layout of 1 inch margin from all sides
for section in doc.sections:
section.top_margin, section.bottom_margin = Inches(1), Inches(1)
section.left_margin, section.right_margin = Inches(1), Inches(1)
# Adding images to word document
for index, file_path in enumerate(list_path_images_in_dir):
doc.add_heading(str(index + 1), 4).style = 'List'
doc.add_picture(file_path, width=Inches(6.5), height=Inches(3.65))
doc.add_paragraph('') # For new line
# Saving word document
doc_name = 'Document_' + self.time_stamp() + '.docx'
path_doc = os.path.abspath(os.path.join(self.text_box_dir_path.get(), doc_name))
doc.save(path_doc)
# Show messsage
count_images = str(len(list_path_images_in_dir))
msg = "Word document created with " + count_images + " images at " + path_doc + '.'
messagebox.showinfo(self.title, msg)
else:
messagebox.showinfo(self.title, "No images present in selected directory.")
def _get_list_path_images(self):
list_path_images_in_dir = []
image_extensions = tuple(list(self.dict_image_format.values()) + ['.jpg'])
# Finding all images present in selected directory
for file_name in os.listdir(self.text_box_dir_path.get()):
if file_name.lower().endswith(image_extensions):
path_image = os.path.abspath(os.path.join(self.text_box_dir_path.get(), file_name))
list_path_images_in_dir.append(path_image)
return list_path_images_in_dir
# endregion Create Document
def exit(self):
"""To close the application"""
self.master.destroy()
def time_stamp(self):
"""Returns time stamp with custom format as string"""
return str(time.strftime("%Y-%m-%d-%H-%M-%S"))
def _notify(self, message: str, timeout: int, title: str, app_icon: str) -> None:
"""
Shows notification message
Args:
message (str): the message to display
timeout (int): the time for which notification should be visible
title (str): title of notification
app_icon (str): accessible path of icon file
"""
notification.notify(title=title, message=message,
app_name=title, app_icon=app_icon,
timeout=timeout)
# DPI aware
if 'win' in sys.platform:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
if __name__ == "__main__":
MASTER = tk.Tk()
SnipperTool(MASTER)
MASTER.mainloop()