forked from fwenzel/upshot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upshot.py
executable file
·322 lines (264 loc) · 11.2 KB
/
upshot.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
#!/usr/bin/env python
import glob
import logging
import os
import shutil
import sys
import time
import urllib
import urlparse
from AppKit import *
from PyObjCTools import AppHelper
from watchdog.events import (FileCreatedEvent, FileMovedEvent,
FileSystemEventHandler)
from watchdog.observers import Observer
import DropboxDetect
import Preferences
from lib import utils
from lib.notifications import Growler
from lib.windows import alert
SCREENSHOT_DIR = utils.get_pref(
domain='com.apple.screencapture', key='location',
default=os.path.join(os.environ['HOME'], 'Desktop'))
DROPBOX_DIR = utils.detect_dropbox_folder()
PUBLIC_DIR = os.path.join(DROPBOX_DIR or '', 'Public')
SHARE_DIR = os.path.join(PUBLIC_DIR, 'Screenshots')
HOMEPAGE_URL = 'http://upshot.it'
DROPBOX_PUBLIC_INFO = 'https://www.dropbox.com/help/16'
TIME_THRESHOLD = 15 # How many seconds after creation do we handle a file?
# Set up logging
LOG_LEVEL = logging.DEBUG
logging.basicConfig(level=LOG_LEVEL)
log = logging.getLogger('upshot')
# Local settings
try:
from settings_local import *
except ImportError:
pass
class Upshot(NSObject):
"""OS X status bar icon."""
image_paths = {
'icon16': 'icon16.png',
'icon16-off': 'icon16-off.png',
}
images = {}
statusitem = None
observer = None # Screenshot directory observer.
menuitems = {} # Shortcut to our menuitems.
def applicationDidFinishLaunching_(self, notification):
if not DROPBOX_DIR: # Oh-oh.
alert('Unable to detect Dropbox folder',
'UpShot requires Dropbox, for now. Please install it, then '
'try again.', ['OK'])
self.quit_(self)
if not os.path.exists(PUBLIC_DIR): # No public folder?
pressed = alert(
'Unable to detect Public Dropbox folder',
'UpShot requires a Dropbox Public folder. You seem to have '
'Dropbox, but no Public folder.\n\n'
'Since October 2012, Dropbox will only create a public '
'folder for you if you opt in to it.\n\n'
'Please do so before using UpShot.',
['Learn How to Create a Dropbox Public Folder',
'Quit UpShot'])
if pressed == NSAlertFirstButtonReturn:
# Open Dropboc opt-in
sw = NSWorkspace.sharedWorkspace()
sw.openURL_(NSURL.URLWithString_(DROPBOX_PUBLIC_INFO))
self.quit_(self)
self.build_menu()
# Go do something useful.
if utils.get_pref('dropboxid'):
self.startListening_()
else:
self.stopListening_()
DropboxDetect.DropboxDetectWindowController.showWindow()
def build_menu(self):
"""Build the OS X status bar menu."""
# Create the statusbar item
statusbar = NSStatusBar.systemStatusBar()
self.statusitem = statusbar.statusItemWithLength_(NSVariableStatusItemLength)
# Set statusbar icon and color/grayscale mode.
for tag, img in self.image_paths.items():
self.images[tag] = NSImage.alloc().initByReferencingFile_(img)
self.images[tag].setTemplate_(
utils.get_pref('iconset') == 'grayscale')
self.statusitem.setImage_(self.images['icon16'])
self.statusitem.setHighlightMode_(1)
self.statusitem.setToolTip_('Upshot Screenshot Sharing')
# Build menu.
self.menu = NSMenu.alloc().init()
m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Browse Screenshots', 'openShareDir:', '')
self.menu.addItem_(m)
self.menuitems['opensharedir'] = m
self.menu.addItem_(NSMenuItem.separatorItem())
m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Start Screenshot Sharing', 'startListening:', '')
m.setHidden_(True) # Sharing is on by default.
self.menu.addItem_(m)
self.menuitems['start'] = m
m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Pause Screenshot Sharing', 'stopListening:', '')
self.menu.addItem_(m)
self.menuitems['stop'] = m
m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
"Need to detect Dropbox ID. Open Preferences!", '', '')
m.setHidden_(True) # We hopefully don't need this.
self.menu.addItem_(m)
self.menuitems['needpref'] = m
m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Preferences...', 'openPreferences:', '')
self.menu.addItem_(m)
self.menuitems['preferences'] = m
self.menu.addItem_(NSMenuItem.separatorItem())
m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Open UpShot Project Website', 'website:', '')
self.menu.addItem_(m)
self.menuitems['website'] = m
m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'About UpShot', 'about:', '')
self.menu.addItem_(m)
self.menuitems['about'] = m
self.menu.addItem_(NSMenuItem.separatorItem())
m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Quit UpShot', 'quit:', '')
self.menu.addItem_(m)
self.menuitems['quit'] = m
self.statusitem.setMenu_(self.menu)
def update_menu(self):
"""Update status bar menu based on app status."""
if self.statusitem is None:
return
# Apply iconset
self.images['icon16'].setTemplate_(
utils.get_pref('iconset') == 'grayscale')
running = (self.observer is not None)
self.statusitem.setImage_(self.images['icon16' if running else
'icon16-off'])
if utils.get_pref('dropboxid'): # Runnable.
self.menuitems['stop'].setHidden_(not running)
self.menuitems['start'].setHidden_(running)
self.menuitems['needpref'].setHidden_(True)
else: # Need settings.
self.menuitems['start'].setHidden_(True)
self.menuitems['stop'].setHidden_(True)
self.menuitems['needpref'].setHidden_(False)
def openShareDir_(self, sender=None):
"""Open the share directory in Finder."""
sw = NSWorkspace.sharedWorkspace()
sw.openFile_(SHARE_DIR)
def about_(self, sender=None):
"""Open standard About dialog."""
app = NSApplication.sharedApplication()
app.activateIgnoringOtherApps_(True)
app.orderFrontStandardAboutPanel_(sender)
def website_(self, sender=None):
"""Open the UpShot homepage in a browser."""
sw = NSWorkspace.sharedWorkspace()
sw.openURL_(NSURL.URLWithString_(HOMEPAGE_URL))
def openPreferences_(self, sender=None):
Preferences.PreferencesWindowController.showWindow()
def startListening_(self, sender=None):
"""Start listening for changes to the screenshot dir."""
event_handler = ScreenshotHandler()
self.observer = Observer()
self.observer.schedule(event_handler, path=SCREENSHOT_DIR)
self.observer.start()
self.update_menu()
log.debug('Listening for screen shots to be added to: %s' % (
SCREENSHOT_DIR))
growl = Growler.alloc().init()
growl.notify('UpShot started', 'and listening for screenshots!')
def stopListening_(self, sender=None):
"""Stop listening to changes ot the screenshot dir."""
if self.observer is not None:
self.observer.stop()
self.observer.join()
self.observer = None
log.debug('Stop listening for screenshots.')
growl = Growler.alloc().init()
growl.notify('UpShot paused',
'Not listening for screenshots for now!')
self.update_menu()
def restart_(self, sender=None):
self.stopListening_()
self.startListening_()
def quit_(self, sender=None):
"""Default quit event."""
log.debug('Terminating.')
self.stopListening_()
NSApplication.sharedApplication().terminate_(sender)
class ScreenshotHandler(FileSystemEventHandler):
"""Handle file creation events in our screenshot dir."""
def on_created(self, event):
"""File creation, handles screen clips."""
f = event.src_path
if isinstance(event, FileCreatedEvent) and not (
os.path.basename(f).startswith('.')):
self.handle_screenshot_candidate(f)
def on_moved(self, event):
"""
Catch move event: For full screenshots, OS X creates a temp file,
then moves it to its final name.
"""
if not isinstance(event, FileMovedEvent):
return
self.handle_screenshot_candidate(event.dest_path)
def handle_screenshot_candidate(self, f):
"""Given a candidate file, handle it if it's a screenshot."""
# Do not act on files that are too old (so we don't swallow files
# that are not new screenshots).
if os.path.getctime(f) - time.time() > TIME_THRESHOLD:
return
# The file could be anything. Only act if it's a screenshot.
if not utils.is_screenshot(f):
return
# Create target dir if needed.
if not os.path.isdir(SHARE_DIR):
log.debug('Creating share dir %s' % SHARE_DIR)
os.makedirs(SHARE_DIR)
# Move image file to target dir.
log.debug('Moving %s to %s' % (f, SHARE_DIR))
if utils.get_pref('randomize'): # Randomize file names?
ext = os.path.splitext(f)[1]
while True:
shared_name = utils.randname() + ext
target_file = os.path.join(SHARE_DIR, shared_name)
if not os.path.exists(target_file):
log.debug('New file name is: %s' % shared_name)
if utils.get_pref('copyonly'):
shutil.copy(f, target_file)
else:
shutil.move(f, target_file)
break
else:
shared_name = os.path.basename(f)
shutil.move(f, SHARE_DIR)
target_file = os.path.join(SHARE_DIR, shared_name)
# Create shared URL
url = utils.share_url(urllib.quote(shared_name))
logging.debug('Share URL is %s' % url)
logging.debug('Copying to clipboard.')
utils.pbcopy(url)
# Notify user.
growl = Growler.alloc().init()
growl.setCallback(self.notify_callback)
growl.notify('Screenshot shared!',
'Your URL is: %s\n\n'
'Click here to view file.' % url,
context=target_file)
def notify_callback(self, filepath):
"""
When growl notification is clicked, open Finder with shared file.
"""
ws = NSWorkspace.sharedWorkspace()
ws.activateFileViewerSelectingURLs_(
NSArray.arrayWithObject_(NSURL.fileURLWithPath_(filepath)))
if __name__ == '__main__':
# Prepare preferences service.
Preferences.set_defaults()
app = NSApplication.sharedApplication()
delegate = Upshot.alloc().init()
app.setDelegate_(delegate)
AppHelper.runEventLoop()