#!/usr/bin/python # Created by Matteo Rattotti on 13/03/06. # Copyright (c) 2006 - 2007 Shiny Frog. All rights reserved. # Contact matteo.rattotti@shinyfrog.net for any problem # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder from Carbon.AppleEvents import kAEISGetURL, kAEInternetSuite import struct import deliLoader import menuBuilder import deliExport def fourCharToInt(code): return struct.unpack('l', code)[0] class DelibarAppDelegate(NibClassBuilder.AutoBaseClass): def applicationWillFinishLaunching_(self, notification): self.app = NSApplication.sharedApplication() # Setting up the status item statusbar = NSStatusBar.systemStatusBar() self.statusbarIcon = statusbar.statusItemWithLength_(25.0) # init some image self.imageIcon = NSImage.alloc().initByReferencingFile_("deliMenuIcon.png") self.busyImageIcon = NSImage.alloc().initByReferencingFile_("deliLoad.png") self.actionIcon = NSImage.alloc().initByReferencingFile_("deliAction.png") # Building basic menu self.statusbarIcon.setImage_(self.imageIcon) self.statusbarIcon.setMenu_(self.deliMenu) self.statusbarIcon.setHighlightMode_(1) # Adding some eye-candy actMenu = self.deliMenu.itemWithTitle_("Actions") actMenu.setImage_(self.actionIcon) # not silent by def self.silent = 0 # Setting the timer self.reloadTimer = None self.setTimerReload_(self) #init the whole things self.initDelibar() #print self.preferences.sortValue() self.deliLock = NSLock.alloc().init() def initDelibar(self): loader = deliLoader.deliLoader() try: store = loader.getLocal() mb = menuBuilder.menuBuilder.alloc().initWithMenuStorePrefs_(self.deliMenu, store, self.preferences) mb.createMenu() except IOError: # First time activation, so showing pref panel if not self.preferences.username() and not self.preferences.password(): self.app.activateIgnoringOtherApps_(1) self.prefWindow.makeKeyAndOrderFront_(self) # User and pass are in, but maybe the user don't have the connection else: self.errorMsg("No Data found...", "No bookmarks stored on this computer, try get online and reload!") return def reloadBookmarks_(self,sender): auto = NSAutoreleasePool.alloc().init() if self.deliLock.tryLock(): # Block other prefs control self.preferences.enablePrefs(0) loader = deliLoader.deliLoader() if self.preferences.proxy() == "": proxy = None else: proxy = self.preferences.proxy() try: store = loader.getNet(self.preferences.username(), self.preferences.password(), proxy) # locking delibar menu (Notify user that the menu is reloading) self.toggleLock(1) mb = menuBuilder.menuBuilder.alloc().initWithMenuStorePrefs_(self.deliMenu, store, self.preferences) mb.createMenu() # unlock the delibar menu self.toggleLock(0) NSLog("Reload Done") except Exception, e: if self.silent == 0: if hasattr(e, 'code'): if e.code == 401: self.errorMsg("Invalid login", "Wrong user/password, check your account information") elif e.code == 500: self.errorMsg("Del.icio.us server error", "Delicious server error, retry within few minute") elif e.code == 503: self.errorMsg("Del.icio.us service temporarily unavailable", "Delicious server error, retry within few minute") else: print Exception, e self.errorMsg("Error", "Check user/password, or your internet connection") else: NSLog("Reload failed because:") print Exception, e # unblock other prefs control self.preferences.enablePrefs(1) self.deliLock.unlock() else: self.errorMsg("May the patience be with you!", "Delibar is already trying to load your bookmarks, just wait.") # Releasing poool auto.release() def reloadAction_(self, sender): if sender.isMemberOfClass_(NSCFTimer): self.silent = 1 else: self.silent = 0 # Using a thread so the user can ejnoy using delibar without pause NSThread.detachNewThreadSelector_toTarget_withObject_('reloadBookmarks:', self, None) def rebuiltMenu_(self, sender): auto = NSAutoreleasePool.alloc().init() if self.deliLock.tryLock(): # Block other prefs control self.preferences.enablePrefs(0) loader = deliLoader.deliLoader() try: store = loader.getLocal() except IOError: self.errorMsg("No Data found...", "No bookmarks stored on this computer, try get online and reload!") auto.release() return # locking delibar menu (Notify user that the menu is reloading) self.toggleLock(1) mb = menuBuilder.menuBuilder.alloc().initWithMenuStorePrefs_(self.deliMenu, store, self.preferences) mb.createMenu() # unlock the delibar menu self.toggleLock(0) # unblock other prefs control self.preferences.enablePrefs(1) self.deliLock.unlock() else: self.errorMsg("May the patience be with you!", "Delibar is already trying to rebuild your menu, just wait.") auto.release() def rebuildAction_(self, sender): NSThread.detachNewThreadSelector_toTarget_withObject_('rebuiltMenu:', self, None) def awakeFromNib(self): # Apply logo in pref panel self.logoImg = NSImage.alloc().initByReferencingFile_("delibar.png") self.deliImg.setImage_(self.logoImg) # Install the manager for catching event (delibar:) manager = NSAppleEventManager.sharedAppleEventManager() # Add a handler for the event GURL/GURL. manager.setEventHandler_andSelector_forEventClass_andEventID_( self, 'handleEvent:withReplyEvent:', fourCharToInt('GURL'), fourCharToInt('GURL')) def setProxy_(self, sender): import getProxy proxyString = getProxy.getProxy() if proxyString != "" and proxyString != None: self.preferences.setProxy(proxyString) else: self.errorMsg("No proxy found in network preferences", "Check if you have proxy enabled, (proxy is not necessary if you don't have one)") def setOnStartup_(self, sender): import setOnStartup if sender.state() == 0: setOnStartup.setAppOnStartup("Delibar", 0) else: setOnStartup.setAppOnStartup("Delibar", 1) def setTimerReload_(self, sender): minute = self.preferences.timerValue() if minute == 0: self.timeString.setStringValue_("Disabled") else: self.timeString.setStringValue_("Minutes") NSLog("Setting timer of %s minute" %(minute * 10)) self.preferences.setTimerField(minute * 10) if minute > 0: minute = minute * 600 if self.reloadTimer is not None: self.reloadTimer.invalidate() self.reloadTimer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(minute, self, self.reloadAction_, None, 1) else: if self.reloadTimer is not None: self.reloadTimer.invalidate() def setSorting_(self, sender): # Set tag list sorting order pass def toggleLock(self, state): # Toggle between active and not active menu if state == 1: self.statusbarIcon.setImage_(self.busyImageIcon) self.statusbarIcon.setEnabled_(0) else: self.statusbarIcon.setImage_(self.imageIcon) self.statusbarIcon.setEnabled_(1) def openUrl(self, sender): # Open Url =) NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(sender.toolTip())) def hotKeyRespond_(self): if self.deliLock.tryLock(): # Responder to the globar delibar hotkey self.statusbarIcon.popUpStatusItemMenu_(self.deliMenu) self.deliLock.unlock() else: pass def handleEvent_withReplyEvent_(self, event, replyEvent): # Function for catching the delibar: url theURL = event.descriptorForKeyword_(fourCharToInt('----')).stringValue() print theURL def errorMsg(self, title, msg): # Function for standard error msg self.app.activateIgnoringOtherApps_(1) alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(title, None, None, None, msg) alert.runModal() def openPrefPanel_(self, sender): # Activate app and show prefs self.app.activateIgnoringOtherApps_(1) self.prefWindow.makeKeyAndOrderFront_(self) def htmlExp_(self): try: l = deliLoader.deliLoader() store = l.getLocal() except Exception, e: print Exception, type(e) self.errorMsg("Data not found", "You must gater some valid data first") self.app.activateIgnoringOtherApps_(1) panel = NSSavePanel.savePanel() panel.setCanCreateDirectories_(1) panel.setMessage_("Select file:") res = panel.runModalForDirectory_file_("~/", "DeliciousLink.html") if res == 1: exportPath = panel.filename() try: deliExport.exporter(store, exportPath) except Exception, e: print Exception, type(e) self.errorMsg("Error", "Invalid directory")