def update(self): try: url = ("http://xoap.weather.com/weather/local/%s?cc=*&" % self.get_location_code()) params = {"unit": self.o_units.value, "dayf": 10} url = url + urlencode(params) try: f = urlopen(url) except IOError: # server or connection down self.set_image('-') tooltips.set_tip(self, 'n.a.') self.label.set_text('n.a.') return True doc = minidom.parse(f) f.close() self.weather.from_xml(doc) tooltips.set_tip(self, str(self.weather.info)) self.set_image(self.weather.info.icon) self.label.set_text("%s°%s" % (self.weather.info.temperature, self.weather.units.temperature)) if self.forecast_window: self.forecast_window.set_weather(self.weather) except: rox.report_exception() return True
def xds_load_from_stream(self, name, mimetype, stream): if name is None: raise NonLocalFile() if mimetype is None: mimetype=rox.mime.get_type(name) self.mtype.set_text(_('Type: %s') % str(mimetype)) strm, ofname=tempfile.mkstemp(suffix='.png') #strm.close() try: self.thumb.run(name, ofname, 128) except: rox.report_exception() try: self.icon.set_from_file(ofname) except: rox.report_exception() try: os.remove(ofname) except: pass self.add_button(rox.g.STOCK_OK, rox.g.RESPONSE_OK) self.mime_type=rox.mime.get_type(name)
def xds_load_from_stream(self, name, mimetype, stream): if name is None: raise NonLocalFile() if mimetype is None: mimetype = rox.mime.get_type(name) self.mtype.set_text(_('Type: %s') % str(mimetype)) strm, ofname = tempfile.mkstemp(suffix='.png') #strm.close() try: self.thumb.run(name, ofname, 128) except: rox.report_exception() try: self.icon.set_from_file(ofname) except: rox.report_exception() try: os.remove(ofname) except: pass self.add_button(rox.g.STOCK_OK, rox.g.RESPONSE_OK) self.mime_type = rox.mime.get_type(name)
def __init__(self): MemoList.__init__(self) self.visible = MemoList() path = basedir.load_first_config('rox.sourceforge.net', 'Memo', 'Entries') if path: try: from xml.dom import minidom, Node doc = minidom.parse(path) except: rox.report_exception() errors = 0 root = doc.documentElement for node in root.getElementsByTagName('memo'): try: memo = memo_from_node(node) self.add(memo, update=0) except: if not errors: rox.report_exception() errors = 1 self.update_visible() app_options.add_notify(self.update_visible)
def destroyed(widget): rox.toplevel_unref() if self.changed(): try: self.options.save() except: rox.report_exception()
def report_exception(self): """Report an exception (if debug enabled)""" if self.debug<1: return #exc=sys.exc_info()[:2] #sys.stderr.write('%s: %s %s\n' % (sys.argv[0], exc[0], exc[1])) rox.report_exception()
def xds_load_from_file(self, path): """Try to load this local file. Override this if you have a better way to load files. The default method opens the file and calls xds_load_from_stream().""" try: self.xds_load_from_stream(path, None, open(path, 'rb')) except: rox.report_exception()
def _report_save_error(): "Report a AbortSave nicely, otherwise use report_exception()" value = sys.exc_info()[1] if isinstance(value, AbortSave): value.show() else: rox.report_exception()
def _resume(self): # Remove from our blockers' queues for blocker in self._rox_blockers: blocker.remove_task(self) # Resume the task try: new_blockers = self.next() except StopIteration: # Task ended self.finished.trigger() return except Exception: # Task crashed rox.report_exception() self.finished.trigger() return if new_blockers is None: # Just give up control briefly new_blockers = (_idle_blocker, ) else: if isinstance(new_blockers, Blocker): # Wrap a single yielded blocker into a list new_blockers = (new_blockers, ) # Are we blocking on something that already happened? for blocker in new_blockers: if blocker.happened: new_blockers = (_idle_blocker, ) break # Add to new blockers' queues for blocker in new_blockers: blocker.add_task(self) self._rox_blockers = new_blockers
def infowin(pname, info=None): """Open info window for this program. info is a source of the AppInfo.xml file, if None then $APP_DIR/AppInfo.xml is loaded instead""" if info is None: info = os.path.join(rox.app_dir, "AppInfo.xml") try: app_info = AppInfo.AppInfo(info) except: rox.report_exception() return try: iw = InfoWin( pname, app_info.getAbout("Purpose")[1], app_info.getAbout("Version")[1], app_info.getAuthors(), app_info.getAbout("Homepage")[1], ) iw.show() return iw except: rox.report_exception()
def report_exception(self): """Report an exception (if debug enabled)""" if self.debug < 1: return #exc=sys.exc_info()[:2] #sys.stderr.write('%s: %s %s\n' % (sys.argv[0], exc[0], exc[1])) rox.report_exception()
def __init__(self, program, leaf): "program/leaf is a Choices pair for the saved options." self.program = program self.leaf = leaf self.pending = {} # Loaded, but not registered self.options = {} # Name -> Option self.callbacks = [] self.too_late_for_registrations = 0 path = choices.load(program, leaf) if not path: return try: doc = minidom.parse(path) root = doc.documentElement assert root.localName == 'Options' for o in root.childNodes: if o.nodeType != Node.ELEMENT_NODE: continue if o.localName != 'Option': print "Warning: Non Option element", o continue name = o.getAttribute('name') self.pending[name] = data(o) except: rox.report_exception()
def _resume(self): # Remove from our blockers' queues for blocker in self._rox_blockers: del blocker._rox_lib_tasks[self] # Resume the task try: new_blockers = self.next() except StopIteration: # Task ended return except Exception: # Task crashed rox.report_exception() return if new_blockers is None: # Just give up control briefly new_blockers = (_idle_blocker,) else: if isinstance(new_blockers, Blocker): # Wrap a single yielded blocker into a list new_blockers = (new_blockers,) # Are we blocking on something that already happened? for blocker in new_blockers: if blocker.happened: new_blockers = (_idle_blocker,) break # Add to new blockers' queues for blocker in new_blockers: blocker.add_task(self) self._rox_blockers = new_blockers
def _activate(self, action, widget): if self.caller: try: self.fns[action].activate(self.caller) except: rox.report_exception() else: raise Exception("No caller for menu!")
def run_rox_process(): global rox_pid run_rox = basedir.load_first_config(constants.site, 'ROX-Session', 'RunROX') or \ os.path.join(rox.app_dir, 'RunROX') try: rox_pid = os.spawnlp(os.P_NOWAIT, run_rox, run_rox, rox.app_dir) children.register_child(rox_pid, rox_process_died) except: rox.report_exception() rox_process_died(0)
def send_to_file(data, path): try: file = open(path, 'wb') try: file.write(data) finally: file.close() except: rox.report_exception() return 0 return 1
def __init__(self, name): self.name = name self.indexes = [] for dir in theme_dirs: theme_dir = os.path.join(dir, name) index_file = os.path.join(theme_dir, 'index.theme') if os.path.exists(os.path.join(index_file)): try: self.indexes.append(Index(theme_dir)) except: rox.report_exception()
def __init__(self, path): self.path = path if path == '-': source = sys.stdin else: try: source = file(path) self.mode = os.stat(path).st_mode except: rox.report_exception() sys.exit(1) self.path = path start = source.read(300) try: if source is sys.stdin: raise Exception("Always copy stdin!") source.seek(0) self.source = source except: # Input is not a regular, local, seekable file, so copy it # to a local temp file. import shutil tmp = Tmp() tmp.write(start) tmp.flush() shutil.copyfileobj(source, tmp) tmp.seek(0) tmp.flush() self.source = tmp self.default = self.guess_format(start) if path == '-': name = 'Data' else: name = path for ext in known_extensions: if path.endswith('.' + ext): new = path[:-len(ext)-1] if len(new) < len(name): name = new if self.default.add_extension: name += '.' + self.default.extension if name == path: # Default name is same as input. Change it somehow... if '.' in os.path.basename(name): name = name[:name.rindex('.')] else: name += '.unpacked' self.default_name = name
def save_to_file(self, path): op = self.get_selected_op() if hasattr(op, 'save_to_file'): op.save_to_file(self.data, path) else: saving.Saveable.save_to_file(self, path) #If the delete_choice is set, try to remove the file if self.delete_choice.get_active(): try: os.remove(sys.argv[1]) except: rox.report_exception()
def save(self): save_dir = basedir.save_config_path('rox.sourceforge.net', 'Memo') path = os.path.join(save_dir, 'Entries.new') if not path: sys.stderr.write("Memo: Saving disabled by CHOICESPATH\n") return try: f = os.open(path, os.O_CREAT | os.O_WRONLY, 0600) self.save_to_stream(os.fdopen(f, 'w')) real_path = os.path.join(save_dir, 'Entries') os.rename(path, real_path) except: rox.report_exception()
def got_response(widget, response): if self.save_in_progress: try: document.save_cancelled() except: rox.report_exception() return if response == int(g.RESPONSE_CANCEL): self.destroy() elif response == int(g.RESPONSE_OK): self.save_area.save_to_file_in_entry() elif response == int(g.RESPONSE_DELETE_EVENT): pass else: raise Exception('Unknown response!')
def __init__(self, name): if not name: name = 'ROX' IconTheme.__init__(self, name) self.indexes = [] for leaf in theme_dirs: theme_dir = os.path.join(leaf, name) index_file = os.path.join(theme_dir, 'index.theme') if os.path.exists(os.path.join(index_file)): try: self.indexes.append(Index(theme_dir)) except: rox.report_exception()
def __init__(self, name): if not name: name='ROX' IconTheme.__init__(self, name) self.indexes = [] for leaf in theme_dirs: theme_dir = os.path.join(leaf, name) index_file = os.path.join(theme_dir, 'index.theme') if os.path.exists(os.path.join(index_file)): try: self.indexes.append(Index(theme_dir)) except: rox.report_exception()
def __init__(self, screen): self.screen = screen self.selection_atom = g.gdk.atom_intern(_property_name(screen), False) self.xsettings_atom = g.gdk.atom_intern('_XSETTINGS_SETTINGS', False) self.manager_atom = g.gdk.atom_intern('MANAGER', False) self.serial = 0 self.window = g.Invisible() self.window.add_events(g.gdk.PROPERTY_CHANGE_MASK) self.window.connect('property-notify-event', self.property_notify) # List of commands to execute at an opportune moment self.to_run = [] if manager_check_running(0): print >> sys.stderr, _("An XSETTINGS manager is already running. " "Not taking control of XSETTINGS...") return else: g.gdk.selection_owner_set(self.window.window, self.selection_atom, self.get_server_time(), False) if _get_manager(screen) != self.window.window: info('Failed to acquire XSettings manager selection') self.terminate() return # Can't see how to do this with PyGTK. But, since nothing else is # running at this point, we're probably OK. # XSendEvent (display, RootWindow (display, screen), # False, StructureNotifyMask, (XEvent *)&xev); info('Acquired XSettings selection successfully - window %s', self.window.window) # Load settings try: path = basedir.load_first_config(constants.site, 'ROX-Session', 'Settings.xml') if path: self.load_settings(path) except: rox.report_exception() self.notify()
def install_mime_info(application, package_file = None): """Copy 'package_file' as ~/.local/share/mime/packages/<application>.xml. If package_file is None, install <app_dir>/<application>.xml. If already installed, does nothing. May overwrite an existing file with the same name (if the contents are different)""" application += '.xml' if not package_file: package_file = os.path.join(rox.app_dir, application) new_data = file(package_file).read() # See if the file is already installed package_dir = os.path.join('mime', 'packages') resource = os.path.join(package_dir, application) for x in basedir.load_data_paths(resource): try: old_data = file(x).read() except: continue if old_data == new_data: return # Already installed global _cache_uptodate _cache_uptodate = False # Not already installed; add a new copy try: # Create the directory structure... new_file = os.path.join(basedir.save_data_path(package_dir), application) # Write the file... file(new_file, 'w').write(new_data) # Update the database... if os.path.isdir('/uri/0install/zero-install.sourceforge.net'): command = '/uri/0install/zero-install.sourceforge.net/bin/update-mime-database' else: command = 'update-mime-database' if os.spawnlp(os.P_WAIT, command, command, basedir.save_data_path('mime')): os.unlink(new_file) raise Exception(_("The '%s' command returned an error code!\n" \ "Make sure you have the freedesktop.org shared MIME package:\n" \ "http://www.freedesktop.org/standards/shared-mime-info.html") % command) except: rox.report_exception()
def _ActionInvoked(nid, action): try: memo = _nid_to_memo.get(nid, None) if memo: if action == 'edit': from EditBox import EditBox EditBox(memo).show() elif action == 'delete': from main import memo_list memo_list.delete(memo) elif action == 'hide': from main import memo_list memo_list.set_hidden(memo, 1) elif action in ('ok', 'default'): pass else: raise Exception('Unknown action "%s"' % action) except Exception: rox.report_exception()
def got_log_data(src, cond): global real_stderr got = os.read(src, 1000) if not got: g.input_remove(input_tag) log.log('ROX-Session: read(stderr) failed!\n') return False try: log.log_raw(got) while got and real_stderr is not None: written = os.write(real_stderr, got) if written < 0: log.log('ROX-Session: write to stderr failed!') os.close(real_stderr) real_stderr = None break got = got[written:] except: rox.report_exception() return True
def response(self, widget, response): try: if response == DELETE: memo_list.delete(self.memo) elif response == HIDE: self.add(hide=1) elif response == int(g.RESPONSE_YES): self.add() elif response == int(g.RESPONSE_HELP): from rox import filer filer.open_dir(rox.app_dir + '/Help') return elif response == int(g.RESPONSE_CANCEL): pass elif response == int(g.RESPONSE_DELETE_EVENT): return else: raise Exception("Unknown response: %d" % response) except: rox.report_exception() self.destroy()
def __init__(self, program, leaf, site=None): """program/leaf is a Choices pair for the saved options. If site is given, the basedir module is used for saving choices (the new system). Otherwise, the deprecated choices module is used.""" self.site = site self.program = program self.leaf = leaf self.pending = {} # Loaded, but not registered self.options = {} # Name -> Option self.callbacks = [] self.too_late_for_registrations = 0 if site: path = basedir.load_first_config(site, program, leaf) else: path = choices.load(program, leaf) if not path: return try: doc = minidom.parse(path) root = doc.documentElement assert root.localName == 'Options' for o in root.childNodes: if o.nodeType != Node.ELEMENT_NODE: continue if o.localName == 'Option': name = o.getAttribute('name') self.pending[name] = data(o) elif o.localName == 'ListOption': name = o.getAttribute('name') v = [] for s in o.getElementsByTagName('Value'): v.append(data(s)) self.pending[name] = v else: print "Warning: Non Option element", o except: rox.report_exception()
def __init__(self, program, leaf, site = None): """program/leaf is a Choices pair for the saved options. If site is given, the basedir module is used for saving choices (the new system). Otherwise, the deprecated choices module is used.""" self.site = site self.program = program self.leaf = leaf self.pending = {} # Loaded, but not registered self.options = {} # Name -> Option self.callbacks = [] self.too_late_for_registrations = 0 if site: path = basedir.load_first_config(site, program, leaf) else: path = choices.load(program, leaf) if not path: return try: doc = minidom.parse(path) root = doc.documentElement assert root.localName == 'Options' for o in root.childNodes: if o.nodeType != Node.ELEMENT_NODE: continue if o.localName == 'Option': name = o.getAttribute('name') self.pending[name] = data(o) elif o.localName=='ListOption': name = o.getAttribute('name') v=[] for s in o.getElementsByTagName('Value'): v.append(data(s)) self.pending[name]=v else: print "Warning: Non Option element", o except: rox.report_exception()
def xds_data_received(self, widget, context, x, y, selection, info, time): "Called when we get some data. Internal." if selection.data is None: # Timeout? context.drop_finish(False, time) return if info == TARGET_RAW: try: self.xds_load_from_selection(selection, context.rox_leafname) except: context.drop_finish(False, time) raise context.drop_finish(True, time) return 1 if info != TARGET_URILIST: return 0 uris = extract_uris(selection.data) if not uris: alert("Nothing to load!") context.drop_finish(False, time) return 1 try: try: self.xds_load_uris(uris) except RemoteFiles: if len(uris) != 1 or not provides(context, 'application/octet-stream'): raise widget.drag_get_data(context, 'application/octet-stream', time) return 1 # Don't do drag_finish except: context.drop_finish(False, time) rox.report_exception() else: context.drop_finish(True, time) return 1
def infowin(pname, info=None): """Open info window for this program. info is a source of the AppInfo.xml file, if None then $APP_DIR/AppInfo.xml is loaded instead""" if info is None: info = os.path.join(rox.app_dir, 'AppInfo.xml') try: app_info = rox.AppInfo.AppInfo(info) except: rox.report_exception() return try: iw = InfoWin(pname, app_info.getAbout('Purpose')[1], app_info.getAbout('Version')[1], app_info.getAuthors(), app_info.getAbout('Homepage')[1]) iw.show() return iw except: rox.report_exception()
def manage_session(test_mode): log.init() if not mydbus.dbus_version_ok and not xxmlrpc.working: rox.alert(problem_msg) set_up_environment() session.init() children.init() session_dbus.init() # Start even if DBus is too old, for session bus xml_settings = settings.init() if mydbus.dbus_version_ok: service = dbus.service.BusName(constants.session_service, bus=session_dbus.get_session_bus()) SessionObject3x(service) # This is like the D-BUS service, except using XML-RPC-over-X xml_service = xxmlrpc.XXMLRPCServer(constants.session_service) xml_service.add_object('/Session', XMLSessionObject()) xml_service.add_object('/Settings', xml_settings) try: if test_mode: print "Test mode!" print "Started", os.system( "(/bin/echo hi >&2; sleep 4; date >&2)&") print "OK" else: try: wm.start() except: rox.report_exception() g.main() finally: session_dbus.destroy()
def install_button_handler(*args): try: if rox.roxlib_version>=(2, 0, 3): rox.mime_handler.install_from_appinfo(injint='http://www.kerofin.demon.co.uk/2005/interfaces/VideoThumbnail') else: try: from zeroinstall.injector import basedir have_zeroinstall=True except: have_zeroinstall=False in_zeroinstall=False if have_zeroinstall: for d in basedir.xdg_cache_dirs: if rox._roxlib_dir.find(d)==0 or __file__.find(d)==0: in_zeroinstall=True break if in_zeroinstall: app_info_path = os.path.join(rox.app_dir, 'AppInfo.xml') ainfo = rox.AppInfo.AppInfo(app_info_path) can_thumbnail = ainfo.getCanThumbnail() win=rox.mime_handler.InstallList(rox.app_dir, "thumbnail handler", 'MIME-thumb', can_thumbnail, _("""Thumbnail handlers provide support for creating thumbnail images of types of file. The filer can generate thumbnails for most types of image (JPEG, PNG, etc.) but relies on helper applications for the others.""")) if win.run()!=int(rox.g.RESPONSE_ACCEPT): win.destroy() return try: types=win.get_active() for tname in types: mime_type = rox.mime.lookup(tname) sname=rox.mime_handler.save_path('rox.sourceforge.net', 'MIME-thumb', '%s_%s' % (mime_type.media, mime_type.subtype)) tmp=sname+'.tmp%d' % os.getpid() f=file(tmp, 'w') f.write('#!/bin/sh\n\n') f.write('0launch http://www.kerofin.demon.co.uk/2005/interfaces/VideoThumbnail "$@"\n') f.close() os.chmod(tmp, 0755) # os.symlink(rox.app_dir, tmp) os.rename(tmp, sname) types=win.get_uninstall() for tname in types: mime_type = rox.mime.lookup(tname) sname=rox.mime_handler.save_path('rox.sourceforge.net', 'MIME-thumb', '%s_%s' % (mime_type.media, mime_type.subtype)) os.remove(sname) finally: win.destroy() else: rox.mime_handler.install_from_appinfo() except: rox.report_exception()
try: self.do_action(action) except InProgress: pass except Beep, b: from rox import g g.gdk.beep() self.set_status(str(b)) #(type, val, tb) = sys.exc_info() #if not val.may_record: # return 0 exit = 'fail' except Done: raise except: rox.report_exception() def add_display(self, display): "Calls move_from(old_node) when we move and update_all() on updates." self.displays.append(display) #print "Added:", self.displays def remove_display(self, display): self.displays.remove(display) #print "Removed, now:", self.displays if not self.displays: self.delete() def update_replace(self, old, new): if old == self.root: self.root = new
def report_exception(self): """Report an exception if debug enabled, otherwise ignore it""" if self.debug < 1: return rox.report_exception()
def report_exception(self): """Report an exception if debug enabled, otherwise ignore it""" if self.debug<1: return rox.report_exception()
def install_button_handler(*args): try: rox.mime_handler.install_from_appinfo(injint=manage.injector_uri) except: rox.report_exception()
def __init__(self, path, root_program = None, dome_data = None, do_load = 1): "If root_program is given, then no data is loaded (used for lock_and_copy)." self.uri = 'Prog.dome' import Namespaces self.namespaces = Namespaces.Namespaces() if dome_data: from Ft.Xml.InputSource import InputSourceFactory isrc = InputSourceFactory() dome_data = NonvalParse(isrc.fromUri(dome_data)) self.clear_undo() doc = None if path: if path != '-': self.uri = path if do_load and (path.endswith('.html') or path.endswith('.htm')): doc = self.load_html(path) if not doc and not root_program: from Ft.Xml.InputSource import InputSourceFactory isrc = InputSourceFactory() try: doc = NonvalParse(isrc.fromUri(path)) except: import rox rox.report_exception() if not doc: doc = implementation.createDocument(None, 'root', None) root = doc.documentElement self.root_program = None data_to_load = None from Program import Program, load_dome_program print root.namespaceURI, root.localName if root.namespaceURI == constants.DOME_NS and root.localName == 'dome': for x in root.childNodes: if x.namespaceURI == constants.DOME_NS: if x.localName == 'namespaces': self.load_ns(x) elif x.localName == 'dome-program': self.root_program = load_dome_program(x, self.namespaces) elif x.localName == 'dome-data': for y in x.childNodes: if y.nodeType == Node.ELEMENT_NODE: data_to_load = y if dome_data: data_to_load = dome_data.documentElement elif (root.namespaceURI == constants.XSLT_NS and root.localName in ['stylesheet', 'transform']) or \ root.hasAttributeNS(constants.XSLT_NS, 'version'): import xslt self.root_program = xslt.import_sheet(doc) self.doc = implementation.createDocument(None, 'xslt', None) data_to_load = None src = self.doc.createElementNS(None, 'Source') if dome_data: src.appendChild(self.import_with_ns(dome_data.documentElement)) self.doc.documentElement.appendChild(src) self.doc.documentElement.appendChild(self.doc.createElementNS(None, 'Result')) self.strip_space() data_to_load = None dome_data = None else: data_to_load = root if root_program: self.root_program = root_program else: if not self.root_program: self.root_program = Program('Root') if data_to_load: self.doc = implementation.createDocument(None, 'root', None) if not root_program: node = self.import_with_ns(data_to_load) self.doc.replaceChild(node, self.doc.documentElement) self.strip_space() self.views = [] # Notified when something changes self.locks = {} # Node -> number of locks self.hidden = {} # Node -> Message self.hidden_code = {} # XPath to generate Message, if any