-
Notifications
You must be signed in to change notification settings - Fork 1
/
screengrab.py
225 lines (175 loc) · 6.03 KB
/
screengrab.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
import os
import sys
import datetime
import Image
import ImageGrab
import win32gui
import win32clipboard
import win32ui
import win32con
import settings
import urllib2
# Dropbox database files (0.7 uses dropbox.db and 0.8 uses config.db)
DROPBOX_DATABASE_FILES = ('dropbox.db', 'config.db')
# Public URL
DROPBOX_PUBLIC_URL = 'http://dl.dropbox.com'
# is.gd API URL
IS_GD_API_URL = 'http://is.gd/api.php?longurl='
# Quality options for JPEG images
JPEG_QUALITY_CHOICES = (
(30, 'Very Low'),
(40, 'Low'),
(50, 'Medium-Low'),
(60, 'Medium'),
(70, 'Medium-High'),
(80, 'High'),
(90, 'Very High'),
(100, 'Maximum')
)
def get_dropbox_path():
"""
Retrieve the Dropbox path.
Keyword arguments:
none
Returns: string
"""
import ctypes, base64, pickle, sqlite3
is_windows = True
try:
# try to get Windows path first
SHGetFolderPath = ctypes.windll.shell32.SHGetFolderPathW
except AttributeError:
is_windows = False
if is_windows:
from ctypes.wintypes import HWND, HANDLE, DWORD, LPCWSTR, MAX_PATH
SHGetFolderPath.argtypes = [HWND, ctypes.c_int, HANDLE, DWORD, LPCWSTR]
path_buffer = ctypes.wintypes.create_unicode_buffer(MAX_PATH)
# 26 is CSIDL_APPDATA, the code for retrieving the user's Application Data folder
SHGetFolderPath(0, 26, 0, 0, path_buffer)
dropbox_db_path = None
for file in DROPBOX_DATABASE_FILES:
path = os.path.join(path_buffer.value, 'Dropbox', file)
if os.path.exists(path):
dropbox_db_path = path
break
else:
dropbox_db_path = os.path.expanduser('~/.dropbox/dropbox.db')
if not dropbox_db_path:
raise IOError('Dropbox database file not found')
try:
db = sqlite3.connect(dropbox_db_path)
cur = db.cursor()
cur.execute("select key, value from config where key = 'dropbox_path'")
row = cur.fetchone()
if row:
try:
return pickle.loads(base64.b64decode(row[1]))
except Exception, e:
# Most likely a 0.8 branch where values are not base64 encoded and pickled
return row[1]
# No dropbox_path key found, assume that the folder is located in the default location
dropbox_path = os.path.join(os.path.expanduser('~'), 'My Documents', 'My Dropbox')
if not os.path.exists(dropbox_path):
raise IOError('Could not find Dropbox folder')
return dropbox_path
except Exception, e:
raise IOError('Problems reading the Dropbox database')
def get_public_folder_path():
try:
dropbox_path = get_dropbox_path()
except IOError:
# No Dropbox installation detected, check if user has manually specified location of
# the Dropbox directory
try:
settings.loadSettings()
dropbox_path = settings.settings['dropbox_directory']
except KeyError:
dropbox_path = None
if not dropbox_path:
raise IOError('Could not find Dropbox folder')
public_folder_path = os.path.join(dropbox_path, 'Public')
return public_folder_path
def get_current_active_window_placement():
"""
Return coordinates of the currently active window.
Keyword arguments:
none
Returns: tuple with 4 coordinates (left, upper, right, lower)
"""
flags, showcmd, (xy, yx), (minposX, minposY), (maxposX, maxposY, normalposX, normalposY) = win32gui.GetWindowPlacement(win32gui.GetForegroundWindow())
return (maxposX, maxposY, normalposX, normalposY)
def grab_screenshot(fullScreen = True, copyUrlIntoClipboard = False, userId = ''):
"""
Grab a screenshot.
Keyword arguments:
string fullScreen -- true to capture the full screen, false to capture only the currently active window
string copyUrlToClipboard -- true to copy the public URL to the clipboard
Returns: none
"""
if fullScreen:
image = ImageGrab.grab()
else:
image = ImageGrab.grab(get_current_active_window_placement())
time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
fileName = '%s_%s.%s' % (settings.settings['filename_prefix'], time,
('png' if settings.settings['image_format'] == 'PNG' else 'jpg'))
settings.loadSettings()
saveFolderPath = os.path.join(get_public_folder_path(), settings.settings['screenshot_save_directory'])
saveLocation = os.path.join(saveFolderPath, fileName)
# Resize the image
if settings.settings['resize_image'] == '1':
resizeValue = (float(settings.settings['resize_value'][:-1]) / 100)
image = image.resize([int(size * resizeValue) for size in image.size], Image.ANTIALIAS)
# Save it
if settings.settings['image_format'] == 'JPEG':
try:
quality = [value[0] for value in JPEG_QUALITY_CHOICES \
if value[1] == settings.settings['image_quality']][0]
quality = int(quality)
except IndexError:
quality = 100
image.save(saveLocation, settings.settings['image_format'], quality = quality)
else:
image.save(saveLocation, settings.settings['image_format'], optimize = True)
# Copy file URL to the clipboard
if copyUrlIntoClipboard and userId != '':
copy_url_to_clipboard(userId, fileName)
return fileName
def copy_url_to_clipboard(userId, fileName):
"""
Copy a public link of the saved screenshot to the clipboard.
Keyword arguments:
fileName -- Screnshot filename
Returns: none
"""
if settings.settings['screenshot_save_directory'] != '':
saveDirectory = settings.settings['screenshot_save_directory'].replace('\\', '/')
saveDirectory = saveDirectory.replace(' ', '%20')
publicURL = '%s/u/%s/%s/%s' % (DROPBOX_PUBLIC_URL, userId, saveDirectory, fileName)
else:
publicURL = '%s/u/%s/%s' % (DROPBOX_PUBLIC_URL, userId, fileName)
# If URL shortening is enabled, shorten the URL
if settings.settings['shorten_urls'] == '1':
short_url = shorten_url(publicURL)
if short_url:
publicURL = short_url
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(publicURL)
win32clipboard.CloseClipboard()
def shorten_url(long_url):
"""
Shortens a URL using is.gd service.
If URL is successfully shortened, short URL is returned,
None otherwise.
"""
try:
request = urllib2.Request(url = '%s%s' % (IS_GD_API_URL, long_url))
response = urllib2.urlopen(request, timeout = 5)
except IOError:
return None
url = response.read()
if url.find('http://is.gd') == -1:
return None
url = url.strip()
return url