def pickColorAsync(self, callback, startingcolor, startingalpha, screenX=None, screenY=None): from wnd.dlgs.choosecolor import ChooseColor global colorDialog global customColors def _adjustWindow(hwnd, msg, wp, lp): #log.debug("pos = (%d, %d)", pos[0], pos[1]) colorDialog.SetWindowPos(screenX, screenY) if not callback or not hasattr(callback, "handleResult"): raise COMException( nsError.NS_ERROR_INVALID_ARG, "pickColorAsync got invalid callback %r" % (callback, )) if screenX is not None and screenY is None: raise COMException( nsError.NS_ERROR_INVALID_ARG, "pickColorAsync: can't have screenX without screenY") # parse the starting colors try: startingcolor = startingcolor.lstrip("#") colors = [ int(startingcolor[x:x + 2], 16) for x in range(0, 6, 2) ] except Exception: raise COMException( nsError.NS_ERROR_INVALID_ARG, "pickColorAsync: invalid starting color %r" % (startingcolor, )) if colorDialog is None: colorDialog = ChooseColor() bgr = colors[2] * 2**16 + colors[1] * 2**8 + colors[0] #log.debug("bgr in: %r -> %x (%r)", colors, bgr, bgr) if screenX or screenY: colorDialog.onINIT = _adjustWindow res = colorDialog.Run(None, 'fullopen', 'hook', customcolors=customColors, initcolor=bgr) if res is not None: b, g, r = [(res & (2**x - 1)) >> (x - 8) for x in range(24, 0, -8)] #log.debug("bgr out: %r -> %x (%r)", [r,g,b], res, res) for i, x in enumerate(colorDialog._dlgs_colors): customColors[i] = int(x) callback.handleResult("#%02x%02x%02x" % (r, g, b), startingalpha) else: callback.handleResult(None, startingalpha)
def pickColorAsync(self, callback, startingcolor, startingalpha, screenX=0, screenY=0): if not callback or not hasattr(callback, "handleResult"): raise COMException( nsError.NS_ERROR_INVALID_ARG, "pickColorAsync got invalid callback %r" % (callback, )) # remember the calling thread tm = components.classes["@mozilla.org/thread-manager;1"]\ .getService(components.interfaces.nsIThreadManager) originalThread = tm.currentThread import threading t = threading.Thread(name="color picker processs", target=self._mac_get_color_from_process, kwargs={ "startingcolor": startingcolor, "startingalpha": startingalpha, "callback": callback, "originalThread": originalThread }) t.setDaemon(True) t.start()
def pickColorAsync(self, callback, startingcolor, startingalpha, screenX=None, screenY=None): if not callback or not hasattr(callback, "handleResult"): raise COMException( nsError.NS_ERROR_INVALID_ARG, "pickColorAsync got invalid callback %r" % (callback, )) if screenX is not None and screenY is None: raise COMException( nsError.NS_ERROR_INVALID_ARG, "pickColorAsync: can't have screenX without screenY") # parse the starting colors try: startingcolor = startingcolor.lstrip("#") colors = [ int(startingcolor[x:x + 2], 16) for x in range(0, 6, 2) ] except Exception: raise COMException( nsError.NS_ERROR_INVALID_ARG, "pickColorAsync: invalid starting color %r" % (startingcolor, )) # The Carbon GetColor API takes RGBColors with 16-bit components where = MacOSXSystemColorPicker.Point(screenX or -1, screenY or -1) inColor = MacOSXSystemColorPicker.RGBColor( *map(lambda x: x * 256, colors)) outColor = MacOSXSystemColorPicker.RGBColor() resp = [False, outColor] def run_picker(): """ runnable used to open the color picker on a background thread """ try: success = self.GetColor(where, "Colors", ctypes.pointer(inColor), ctypes.pointer(resp[1])) if success: resp[0] = True except Exception, e: log.exception("An error occurred: %r", e) originalThread.dispatch( run_callback, components.interfaces.nsIThread.DISPATCH_NORMAL)
def update(self, notification, summary=None, details=None, progress=None, actions=None): if summary is not None: notification.summary = summary if details is not None: notification.details = details if progress is not None: if progress > notification.maxProgress: raise COMException( nsError.NS_ERROR_INVALID_ARG, "Progress %r is larger than maximum %r" % (progress, notification.maxProgress)) notification.progress = progress for action_data in actions or []: action_data = action_data.copy() # shallow copy if not "identifier" in action_data: raise COMException( nsError.NS_ERROR_INVALID_ARG, "tried to update action without identifier") if "remove" in action_data: notification.removeAction(action_data["identifier"]) continue actions = notification.getActions(action_data["identifier"]) if not actions: # new action action = self._wrap(KoNotificationAction()) action.identifier = action_data["identifier"] else: # existing action action = actions[0] del action_data["identifier"] for k, v in action_data.items(): if not hasattr(action, k): raise COMException( nsError.NS_ERROR_INVALID_ARG, "Unexpected property %r on action %s" % (k, action.identifier)) setattr(action, k, v) notification.updateAction(action) if any(x is not None for x in (summary, details, progress, actions)): self.addNotification(notification)
def setter(self, value): if setCheck is not None and not setCheck(self, value): raise COMException(nsError.NS_ERROR_ILLEGAL_VALUE) oldVal = getattr(self, name, defaultValue) setattr(self, name, value) if oldVal != value: manager = self._manager if manager: manager.addNotification(self)
def install( self ): # Result: void - None if xpcom.server.tracer is not None: raise COMException(nsError.NS_ERROR_UNEXPECTED) self.collecting = 1 self.classes = {} self.methods = {} self.all_classes = 0 xpcom.server.tracer = self._makeTracer xpcom.server.tracer_unwrap = tracer_unwrap
def checkValidVersion(self): version = self.phpInfoEx.version if not version: # Allow for None or empty string reject = True else: # last point can be something like 10-beta version = tuple([int(x) for x in re.match(r"(\d+)\.(\d+)\.(\d+)", version).groups()]) reject = (version < (4,0,5)) if reject: errmsg = "Could not find a suitable PHP interpreter for "\ "linting, need 4.0.5 or later." raise COMException(nsError.NS_ERROR_NOT_AVAILABLE, errmsg)
def _doHandleException(self, func_name, exc_info): try: # allow this exception to be caught in JavaScript from xpcom import components xs = components.classes["@mozilla.org/exceptionservice;1"].getService(components.interfaces.nsIExceptionService) xm = xs.currentExceptionManager except: xs = xm = components = None exc_val = exc_info[1] if isinstance(exc_val, (ServerException, COMException)): try: # we can only unwrap python exceptions, so ignore if we # cannot unwrap. # Update the exception information so it is accurate, just # raising Server/COMException will not have all the data exc_val = xpcom.server.UnwrapObject(exc_val) exc_val.setExcInfo(exc_info) except ValueError, e: pass if xm and exc_val.message is None: exc = xm.getCurrentException() if exc: # someone we called raised an exception, so we're the # inner exception. If we cannot modify the exception to # add ourselves as the inner, then reset the exception # to a python based class try: # we can only unwrap python exceptions, so ignore if we # cannot unwrap exc = xpcom.server.UnwrapObject(exc) exc.inner = exc_val exc_val = exc except ValueError, e: pyexec = exc_val exc_val = COMException(exc.result, exc.message) exc_val.filename = exc.filename exc_val.lineNumber = exc.lineNumber exc_val.filename = exc.filename exc_val.name = exc.name exc_val.location = exc.location exc_val.inner = pyexec
def add(self, summary, tags, identifier, context=None, **kwargs): # ko.notifications.add types = 0 if "actions" in kwargs: types |= Ci.koINotificationManager.TYPE_ACTIONABLE if "maxProgress" in kwargs: assert kwargs["maxProgress"] > 0 or \ kwargs["maxProgress"] in (Ci.koINotificationProgress.PROGRESS_INDETERMINATE, Ci.koINotificationProgress.PROGRESS_NOT_APPLICABLE), \ "adding notification with maxProgress %r not >0" % (kwargs["maxProgress"],) types |= Ci.koINotificationManager.TYPE_PROGRESS if "details" in kwargs: types |= Ci.koINotificationManager.TYPE_TEXT if any(x in kwargs for x in ("timeout", "highlight", "interactive", "log")): types |= Ci.koINotificationManager.TYPE_STATUS notification = self.createNotification(identifier, tags, context, types) notification.summary = summary kwargs = kwargs.copy() # shallow copy for prop in ("iconURL", "severity", "description", "details", "maxProgress", "progress", "timeout", "highlight", "interactive", "log"): if prop in kwargs: setattr(notification, prop, kwargs[prop]) del kwargs[prop] if "actions" in kwargs: for action_data in kwargs["actions"]: action = self._wrap(KoNotificationAction()) for k, v in action_data.items(): if not hasattr(action, k): raise COMException( nsError.NS_ERROR_INVALID_ARG, "invalid action argument %r" % (k, )) setattr(action, k, v) notification.updateAction(action) del kwargs["actions"] if kwargs.keys(): log.warning( "ko.notifications.add called with unknown arguments %r", kwargs.keys()) self.addNotification(notification) return notification
def updateAction(self, action): if not action.identifier: raise COMException(nsError.NS_ERROR_NOT_INITIALIZED, "action has no identifier") oldaction = self.getActions(action.identifier) if oldaction: self.actions[self.actions.index(oldaction[0])] = action else: self.actions.append(action) manager = self._manager if manager: try: index = manager.index(manager._wrap(self)) manager._notify(self, Ci.koINotificationListener.REASON_UPDATED, aOldIndex=index, aNewIndex=index) except ValueError: # we have a manager, but we're not in it? pass return len(oldaction) > 0
pyexec = exc_val exc_val = COMException(exc.result, exc.message) exc_val.filename = exc.filename exc_val.lineNumber = exc.lineNumber exc_val.filename = exc.filename exc_val.name = exc.name exc_val.location = exc.location exc_val.inner = pyexec else: # Unhandled exception - always print a warning. logger.error("Unhandled exception calling '%s'", func_name, exc_info=exc_info) if hasattr(exc_val, "__class__"): message = "%s: %s" % (exc_info[1].__class__.__name__, str(exc_val)) else: message = str(exc_val) exc_val = COMException(nsError.NS_ERROR_FAILURE, message) if components: exc_val.setExcInfo(exc_info) if components: xs.currentExceptionManager.setCurrentException(exc_val) return exc_val.result # Called whenever an unhandled Python exception is detected as a result # of _CallMethod_ - this exception may have been raised during the _CallMethod_ # invocation, or after its return, but when unpacking the results # eg, type errors, such as a Python integer being used as a string "out" param. def _CallMethodException_(self, com_object, index, info, params, exc_info): # Later we may want to have some smart "am I debugging" flags? # Or maybe just delegate to the actual object - it's probably got the best
def do_short(self, p1, p2): # This should cause the caller to see a "debug" NS_ERROR_FAILURE exception. raise COMException(nsError.NS_ERROR_NOT_IMPLEMENTED)
# The contents of this file are subject to the Mozilla Public License Version
def getParentIndex(self, index): if index < 0: raise COMException(nsError.NS_ERROR_INVALID_ARG, "getParentIndex with index %r < 0" % (index, )) if index >= self.rowCount: raise COMException( nsError.NS_ERROR_INVALID_ARG, "getParentIndex with index %r >= %r" % (index, self.rowCount)) original_index = index # the index we started with parent = self # the ancestor we're examining parent_index = 0 # the index of the ancestor # index is now the index relative to the parent-being-examined if self.log: path = [(index, parent.text)] try: while not index in parent._index_to_children: i = max( filter(lambda k: k < index, parent._index_to_children.keys())) # i is the offset of the next parent to use (from the current parent) parent_size = 1 if not parent.invisible else 0 # how many rows the parent itself takes parent_index = parent_index + parent_size + i parent = parent._index_to_children[i] child_size = 1 if not parent.invisible else 0 # how many rows the new parent takes index = index - i - child_size if self.log: path.append((index, parent.text)) except ValueError: # invalid, e.g. index -1 if self.log: self.log.debug( "getParentIndex: error getting %r from %r (of %r)" "; original index %r, path %r dirty %r", index, parent, parent.rowCount, original_index, path, self.invalidater.dirty) return -1 if parent == self: # the parent is the root element parent_index = -1 if self.log: self.log.debug("getParentIndex: %r -> %r=%r", original_index, index, parent_index) if parent_index == original_index: # ughh... that sounds broken! if self.log: self.log.error( "getParentIndex: parent of %r seems to be %r (%r)", original_index, parent_index, parent) raise COMException( nsError.NS_ERROR_UNEXPECTED, "getParentIndex claimed parent of %r is %r" % (original_index, parent_index)) return parent_index
def identifier(self, value): if hasattr(self, "_id"): raise COMException( nsError.NS_ERROR_ALREADY_INITIALIZED, "koNotificationAction already has id %r" % (self._id)) setattr(self, "_id", value)
def setter(self, value): if setCheck is not None and not setCheck(self, value): raise COMException(nsError.NS_ERROR_ILLEGAL_VALUE) oldVal = getattr(self, name, defaultValue) setattr(self, name, value)
def lint_with_text(self, request, text): """Lint the given PHP content. Raise an exception if there is a problem. """ cwd = request.cwd #print "----------------------------" #print "PHP Lint" #print text #print "----------------------------" php = self.phpInfoEx.getExecutableFromDocument(request.koDoc) if php is None: errmsg = "Could not find a suitable PHP interpreter for linting." raise COMException(nsError.NS_ERROR_NOT_AVAILABLE, errmsg) self.checkValidVersion() # save php buffer to a temporary file phpfilename = tempfile.mktemp() fout = open(phpfilename, 'wb') fout.write(text) fout.close() p = None try: argv = [php, '-n', '-d', 'display_errors=1', '-d', 'display_startup_errors=1', '-d', 'output_buffering=0', '-d', 'xdebug.remote_enable=off', '-d', 'error_reporting=2047', '-q', '-l', phpfilename] env = koprocessutils.getUserEnv() cwd = cwd or None p = process.ProcessOpen(argv, cwd=cwd, env=env) stdout, stderr = p.communicate() # The relevant output is contained in stdout. lines = stdout.splitlines(1) finally: os.unlink(phpfilename) results = koLintResults() if lines: datalines = re.split('\r\n|\r|\n',text) numLines = len(datalines) lines = [l for l in lines if l.find('error') != -1] for line in lines: #print line line = line.strip() # remove html from error output line = re.sub('<.*?>',"",line) lineText = line.rfind(' ') try: lineNo = int(line[lineText+1:]) except ValueError, e: continue #print "Line Number: ", lineNo result = KoLintResult() # XXX error in FILENAME at line XXX # Previous fix (change done for bug 42553 -- (change 254015) # This fix allows for either "at" or "on" between the # filename and the line # # Sample error message: # PHP Fatal error: Can't use function return value in write context in C:\home\ericp\lab\komodo\bugs\bz42553a.php on line 3 m = re.match(r'(.*?)\bin .*?(\b(?:on|at)\s+line\s+\d+)', line) if m: result.description = string.join(m.groups()) else: result.description = line result.lineStart = result.lineEnd = lineNo result.columnStart = 1 result.columnEnd = len(datalines[result.lineEnd-1]) + 1 result.severity = result.SEV_ERROR results.addResult(result)
def uninstall( self ): # Result: void - None if xpcom.server.tracer is not self._makeTracer: raise COMException(nsError.NS_ERROR_UNEXPECTED) self.collecting = 0 xpcom.server.tracer = xpcom.server.tracer_unwrap = None