def get_special_folders(use_categories=True): # TODO: Use subclasses here (something like SpecialShortcut, or # FixedShortcut) with suppress(Exception): yield Shortcut( "desktop folder", SHORTCUT_TYPE_FOLDER, get_special_folder_path(shellcon.CSIDL_DESKTOPDIRECTORY)) with suppress(Exception): yield Shortcut("my documents folder", SHORTCUT_TYPE_FOLDER, get_special_folder_path(shellcon.CSIDL_PERSONAL)) with suppress(Exception): yield Shortcut("my pictures folder", SHORTCUT_TYPE_FOLDER, get_special_folder_path(shellcon.CSIDL_MYPICTURES)) with suppress(Exception): yield Shortcut("my videos folder", SHORTCUT_TYPE_FOLDER, get_special_folder_path(shellcon.CSIDL_MYVIDEO)) with suppress(Exception): yield Shortcut("my music folder", SHORTCUT_TYPE_FOLDER, get_special_folder_path(shellcon.CSIDL_MYMUSIC)) if not isfile(RECYCLE_BIN_LINK): recycle_shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) recycle_shortcut.SetPath("") recycle_shortcut.SetWorkingDirectory("") recycle_shortcut.SetIDList( ['\x1f\x00@\xf0_d\x81P\x1b\x10\x9f\x08\x00\xaa\x00/\x95N']) recycle_shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save( RECYCLE_BIN_LINK, 0) yield Shortcut("recycle bin", SHORTCUT_TYPE_FOLDER, RECYCLE_BIN_LINK)
def decodeSuggestions(self, data, headers=None): suggestions = [] charset = "utf-8" if headers: with suppress(Exception): content_type = headers.get("Content-Type", headers.get("content-type", "")).lower() if content_type and "charset=" in content_type: charset = content_type.split("charset=")[-1] try: decoded = data.decode(charset) except Exception as e: logging.error("%s-suggest query unicode decoding failed: %s", self.name, e) else: try: json = jsonlib.loads(decoded) except Exception as e: logging.error(u"Error parsing JSON data: %s; data: '%s'", e, decoded) else: if json: suggestions = [ strip_html_tags(i) for i in json[1] if (json and len(json) > 1 and json[1] and i.startswith("=")) ][:1] return suggestions
def decodeSuggestions(self, data, headers=None): suggestions = [] charset = "utf-8" if headers: with suppress(Exception): content_type = headers.get( "Content-Type", headers.get("content-type", "")).lower() if content_type and "charset=" in content_type: charset = content_type.split("charset=")[-1] try: decoded = data.decode(charset) except Exception as e: logging.error( "%s-suggest query unicode decoding failed: %s", self.name, e) else: try: # Optionally remove JSONP function wrapper (google searches) decoded = self.remove_google_jsonp_wrapper(decoded) json = jsonlib.loads(decoded) except Exception as e: logging.error( u"Error parsing JSON data: %s; data: '%s'", e, decoded) else: if json: suggestions = [strip_html_tags(s) for s in self.parser(json)][:10] # Limit number of suggestions return suggestions
def close_connections(self): """Close any HTTP1.1 persistent connections and invalidate connection pool""" if self._connection_pool is not None: with suppress(Exception): #print "Closing current HTTP1.1 persistent connection" self._connection_pool.close() #print "Invalidating connection pool" self._connection_pool = None
def __suggestion_thread_func(self): """Suggestions thread. This thread waits for text and if the text has changed between the calls, it calls the self.__suggest(text) function. It polls for text changes only every 100ms to avoid overloading of the webservice used for suggestions. """ last_typed_text = None text = None self.__stop_suggestion_thread = False try: while not self.__stop_suggestion_thread: # Act only on valid text. if not text: try: # Blocking wait for first update request text = self._update_queue.get(block=True) finally: self._update_queue.task_done() # text == None is issued only on thread stop request in order to wakeup the initial # blocking queue.get(). if text is None: continue if text != last_typed_text: # If text differs, get the suggestions from webservice suggestions = self.__suggest(text) last_typed_text = text if suggestions: self.__last_text_for_suggestions = text # If we got any suggestions, update the command parameter suggestions self.caller.setParameterSuggestions(suggestions) text = None # Wait for any additional requests to accumulate before updating # Loop for 100ms and collect the most recently typed text started = datetime.datetime.now() elapsed_ms = 0 while elapsed_ms < self.polling_interval: time_to_wait = self.polling_interval - elapsed_ms if time_to_wait > 0: with suppress(Empty): text = self._update_queue.get(block=True, timeout=time_to_wait / 1000) self._update_queue.task_done() tdiff = datetime.datetime.now() - started elapsed_ms = (tdiff.days * 24 * 60 * 60 + tdiff.seconds) * 1000 + tdiff.microseconds / 1000.0 else: pass finally: self.__suggestion_thread = None
def onKeyEventTabComplete(self, eventType, keyCode): oldText = self.__suggestionList.getUserText() if self.__parameterSuggestionList.isActive(): self.__parameterSuggestionList.cycleActiveSuggestion(1) suggestion = self.__parameterSuggestionList.getActiveSuggestion() # print suggestion activeCmd = self.__suggestionList.getActiveCommand() with suppress(Exception): userText = "%s%s" % ( activeCmd.PREFIX, suggestion) self.__suggestionList.setUserText(userText) # self.__parameterSuggestionList.setSuggestions([]) else: # Allow handlers to act upon Tab key even if the text # has not been modified self.__eventMgr.triggerEvent( "textModified", keyCode, oldText, oldText, quasimodeId=self.__quasimodeID) self.__suggestionList.autoType()
def _save_shortcut(self, shortcut_name, text): target = text file_type = self._get_shortcut_type(target) if file_type == shortcuts.SHORTCUT_TYPE_EXECUTABLE: shortcut_file_path = os.path.join(self._get_learn_as_dir(), shortcut_name + (".desktop")) if os.path.isfile(shortcut_file_path): raise ShortcutAlreadyExistsError() dsk = xdg.DesktopEntry.DesktopEntry(shortcut_file_path) dsk.set("Version", "1.0") dsk.set("Name", shortcut_name) dsk.set("Type", "Application") dsk.set("Icon", "application-x-executable") dsk.set("Exec", target) dsk.set("Terminal", "0") dsk.set("Path", os.path.abspath(os.path.dirname(target))) dsk.write(trusted=True) with suppress(Exception): subprocess.Popen( ["gnome-desktop-item-edit", shortcut_file_path]) elif file_type == shortcuts.SHORTCUT_TYPE_FOLDER: shortcut_file_path = os.path.join(self._get_learn_as_dir(), shortcut_name + (".desktop")) if os.path.isfile(shortcut_file_path): raise ShortcutAlreadyExistsError() dsk = xdg.DesktopEntry.DesktopEntry(shortcut_file_path) dsk.set("Version", "1.0") dsk.set("Name", shortcut_name) dsk.set("Type", "Application") dsk.set("Icon", "gtk-directory") dsk.set("Exec", "xdg-open \"%s\"" % os.path.abspath(target)) dsk.set("Terminal", "0") dsk.set("Path", os.path.abspath(target)) file_type = shortcuts.SHORTCUT_TYPE_EXECUTABLE dsk.write(trusted=True) with suppress(Exception): subprocess.Popen( ["gnome-desktop-item-edit", shortcut_file_path]) elif file_type == shortcuts.SHORTCUT_TYPE_URL: shortcut_file_path = os.path.join(self._get_learn_as_dir(), shortcut_name + (".desktop")) if os.path.isfile(shortcut_file_path): raise ShortcutAlreadyExistsError() dsk = xdg.DesktopEntry.DesktopEntry(shortcut_file_path) dsk.set("Version", "1.0") dsk.set("Name", shortcut_name) dsk.set("Icon", "applications-internet") dsk.set("URL", target) dsk.set("Type", "Link") dsk.write(trusted=True) with suppress(Exception): subprocess.Popen( ["gnome-desktop-item-edit", shortcut_file_path]) else: """ #FIXME: This is probably not a good idea to create Application type .desktop entry for a document shortcut_file_path = os.path.join( self._get_learn_as_dir(), shortcut_name + (".desktop") ) if os.path.isfile(shortcut_file_path): raise ShortcutAlreadyExistsError() dsk = xdg.DesktopEntry.DesktopEntry(shortcut_file_path) dsk.set("Version", "1.0") dsk.set("Name", shortcut_name) dsk.set("Type", "Application") dsk.set("Icon", "gtk-directory") dsk.set("Exec", "xdg-open \"%s\"" % os.path.abspath(target)) dsk.set("Terminal", "0") dsk.set("Path", os.path.abspath(target)) file_type = shortcuts.SHORTCUT_TYPE_EXECUTABLE dsk.write(trusted=True) with suppress(Exception): subprocess.Popen(["gnome-desktop-item-edit", shortcut_file_path]) """ # This would be better, but problem is that on load, it's determined ax executable instead of a document. shortcut_file_path = os.path.join(self._get_learn_as_dir(), shortcut_name) if os.path.isfile(shortcut_file_path): raise ShortcutAlreadyExistsError() os.symlink(target, shortcut_file_path) return shortcuts.Shortcut(shortcut_name, file_type, shortcut_file_path, shortcut_file_path, category=learned_shortcuts.SHORTCUT_CATEGORY) """
def get_font_detail(self, font_id): assert font_id is not None and len(font_id.strip()) > 0 # while not self.__font_detail_cache_lock(False): # logging.warn("font cache lock acquire() has been blocked" font_id = font_id.strip().lower() if font_id in self.__font_detail_cache: #logging.debug("Font cache hit for \"%s\"" % font_id) return self.__font_detail_cache[font_id] font_detail = None try: regkey = win32api.RegOpenKeyEx( # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy win32api.RegConnectRegistry( None, win32con.HKEY_LOCAL_MACHINE ), # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy FONT_LIST_REG_KEY) i = 0 try: RegEnumValue = win32api.RegEnumValue # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy # Optimization _splitext = os.path.splitext _pathjoin = os.path.join while True: font_name, font_file, _ = RegEnumValue(regkey, i) i += 1 _, ext = _splitext(font_file) if ext.lower() != ".ttf": continue font_path = _pathjoin(FONT_DIR, font_file) m = match_bare_font_name(font_name) if m: font_name = m.group(1) if simplify_font_name(font_id) == simplify_font_name(font_name).lower() or \ simplify_font_name(font_id) == simplify_font_name(_splitext(font_file)[0].lower()): font_detail = FontDetail([font_name], font_path, font_file) self.__font_detail_cache[font_id] = font_detail break except Exception as e: # Eroor 259: No more data is available, thrown by reg.EnumValue if not hasattr(e, "winerror") or e.winerror != 259: raise # Make a dent in the cache even if we did not find anything self.__font_detail_cache[font_id] = None finally: if regkey: with suppress(Exception): win32api.RegCloseKey( regkey ) # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy """ font_name2 = self._get_font_name_from_file(font_path) if font_name2 and font_name != font_name2: font_info['names'].append(font_name2) """ except Exception as e: logging.error(e) return font_detail
if dname[0] == 1 and dname[1] == 0: # This one is usually looking best font_full_name = s break # Unicode, Unicode 2.0, English elif dname[0] == 0 and dname[1] == 3: font_full_name = s break # Windows, Version 1.1 elif dname[0] == 3 and dname[1] == 1: font_full_name = unicode(s, "UTF-16BE") break except Exception, e: logging.error(e) finally: with suppress(Exception): if f: f.close() return font_full_name @synchronized() def get_font_detail(self, font_id): assert font_id is not None and len(font_id.strip()) > 0 # while not self.__font_detail_cache_lock(False): # logging.warn("font cache lock acquire() has been blocked" font_id = font_id.strip().lower() if font_id in self.__font_detail_cache:
def wrapper(*args, **kwargs): with suppress(Exception): pythoncom.CoInitialize() return fn(*args, **kwargs)
def __initialize_pythoncom(func, *args, **kwargs): """ Function decorator. Initialize Python COM interface before function call """ with suppress(Exception): pythoncom.CoInitialize() yield func(*args, **kwargs)
def stop(self): '''Stop main loop by exiting from gtk mainloop''' with suppress(Exception): self.__keyListener.unlock() gtk.main_quit()
def draw(self, document, activeIndex): """ Draws the text described by document. An updating call; at the end of this method, the displayed window should reflect the drawn content. """ def _computeWidth(doc): lines = [] for b in doc.blocks: lines.extend(b.lines) if len(lines) == 0: return 0 return max([l.xMax for l in lines]) def _computeHeight(doc): height = 0 for b in doc.blocks: height += b.height # for line in b.lines: # height += line.lineHeight return height width = _computeWidth(document) + layout.L_MARGIN + layout.R_MARGIN width = max(width, 300) height = document.height # _computeHeight(document) cr = self.__context # Clear the areas where the corners of the rounded rectangle will be. cr.save() cr.set_source_rgba(0, 0, 0, 0) cr.set_operator(cairo.OPERATOR_SOURCE) # IGNORE:E1101 @UndefinedVariable cr.rectangle(width - rounded_rect.CORNER_RADIUS, height - rounded_rect.CORNER_RADIUS, rounded_rect.CORNER_RADIUS, rounded_rect.CORNER_RADIUS) cr.rectangle(width - rounded_rect.CORNER_RADIUS, 0, rounded_rect.CORNER_RADIUS, rounded_rect.CORNER_RADIUS) cr.paint() """ # Draw the background rounded rectangle. corners = [] #corners.append( rounded_rect.UPPER_LEFT ) #if document.roundUpperRight: corners.append( rounded_rect.UPPER_RIGHT ) #if document.roundLowerRight: corners.append( rounded_rect.LOWER_RIGHT ) #if document.roundLowerLeft: corners.append( rounded_rect.LOWER_LEFT ) """ corners = { rounded_rect.UPPER_RIGHT: None, rounded_rect.LOWER_RIGHT: 14, rounded_rect.LOWER_LEFT: None } document.background = xmltextlayout.colorHashToRgba( layout.MAIN_BACKGROUND_COLOR) cr.set_source_rgba(*document.background) rounded_rect.drawRoundedRect(context=cr, rect=(0, 0, width, height), softenedCorners=corners) cr.fill_preserve() cr.set_source_rgba(*xmltextlayout.colorHashToRgba("#404040")) cr.set_line_width(1.0) if activeIndex is not None: bar_left = layout.L_MARGIN - 2 bar_width = width - bar_left - layout.L_MARGIN + 2 bar_height = document.blocks[0].height bar_top = activeIndex * bar_height + document.marginTop rounded_rect.drawRoundedRect(context=cr, rect=( bar_left, bar_top, bar_width, bar_height), softenedCorners=rounded_rect.ALL_CORNERS, radius=2) cr.fill_preserve() # cr.stroke() cr.restore() # Next, draw the text. document.draw(layout.L_MARGIN, document.shrinkOffset, self.__context) width = min(self.__window.getMaxWidth(), width) # height = document.blocks[0].height * len(document.blocks) #layout.PARAMETERSUGGESTION_SCALE[-1]*layout.HEIGHT_FACTOR #height = min( self.__window.getMaxHeight(), height ) #self.__window.setSize( width, height ) if not self.__is_visible and not self.__animatingShow: self.__animatingShow = True self.__animatingHide = False self.__is_visible = True self.__timeSinceDismissal = 0 with suppress(AssertionError): self.__evtManager.registerResponder( self.animationTick, "timer") else: # Just refreshing started = time.time() self.__window.setOpacity(MAX_OPACITY) # print time.time() - started self.__window.update()