def _fetch_inventory(self, url): cache_dir = config.cache_dir() cache_dir = os.path.join(cache_dir, "help", type(self).__qualname__) try: os.makedirs(cache_dir) except OSError: pass url = QUrl(self.inventory) if not url.isLocalFile(): # fetch and cache the inventory file. manager = QNetworkAccessManager(self) cache = QNetworkDiskCache() cache.setCacheDirectory(cache_dir) manager.setCache(cache) req = QNetworkRequest(url) # Follow redirects (for example http -> https) # If redirects were not followed, the documentation would not be found try: req.setAttribute(QNetworkRequest.FollowRedirectsAttribute, 1) # from Qt 5.6 req.setAttribute(QNetworkRequest.RedirectPolicyAttribute, # from Qt 5.9 QNetworkRequest.NoLessSafeRedirectPolicy) except AttributeError: # if ran with earlier Qt pass self._reply = manager.get(req) manager.finished.connect(self._on_finished) else: with open(url.toLocalFile(), "rb") as f: self._load_inventory(f)
class BaseInventoryProvider(HelpProvider): def __init__(self, inventory, parent=None): super().__init__(parent) self.inventory = QUrl(inventory) if not self.inventory.scheme() and not self.inventory.isEmpty(): self.inventory.setScheme("file") self._error = None self._fetch_inventory(self.inventory) def _fetch_inventory(self, url): cache_dir = config.cache_dir() cache_dir = os.path.join(cache_dir, "help", type(self).__qualname__) try: os.makedirs(cache_dir) except OSError: pass url = QUrl(self.inventory) if not url.isLocalFile(): # fetch and cache the inventory file. manager = QNetworkAccessManager(self) cache = QNetworkDiskCache() cache.setCacheDirectory(cache_dir) manager.setCache(cache) req = QNetworkRequest(url) # Follow redirects (for example http -> https) # If redirects were not followed, the documentation would not be found try: req.setAttribute(QNetworkRequest.FollowRedirectsAttribute, 1) # from Qt 5.6 req.setAttribute(QNetworkRequest.RedirectPolicyAttribute, # from Qt 5.9 QNetworkRequest.NoLessSafeRedirectPolicy) except AttributeError: # if ran with earlier Qt pass self._reply = manager.get(req) manager.finished.connect(self._on_finished) else: with open(url.toLocalFile(), "rb") as f: self._load_inventory(f) def _on_finished(self, reply): if reply.error() != QNetworkReply.NoError: log.error("An error occurred while fetching " "help inventory '{0}'".format(self.inventory)) self._error = reply.error(), reply.errorString() else: contents = bytes(reply.readAll()) self._load_inventory(io.BytesIO(contents)) def _load_inventory(self, stream): raise NotImplementedError()
def create_html_provider(entry_point): locations = entry_point.resolve() replacements = _replacements_for_dist(entry_point.dist) formatter = string.Formatter() for target in locations: # Extract all format fields format_iter = formatter.parse(target) fields = {name for _, name, _, _ in format_iter if name} if not set(fields) <= set(replacements.keys()): log.warning("Invalid replacement fields %s", set(fields) - set(replacements.keys())) continue target = formatter.format(target, **replacements) targeturl = qurl_from_path(target) if not targeturl.isValid(): continue if targeturl.isLocalFile(): if not os.path.exists(target): log.info("Local doc root '%s' does not exist.", target) continue if target: return provider.SimpleHelpProvider( baseurl=QUrl.fromLocalFile(target)) return None
def test_dragEnterEvent_rejects_binary(self): with named_file("", suffix=".42") as fn: with open(fn, "wb") as f: f.write(b"\xc3\x28") event = self._drag_enter_event(QUrl.fromLocalFile(fn)) self.widget.dragEnterEvent(event) self.assertFalse(event.isAccepted())
class BaseInventoryProvider(HelpProvider): def __init__(self, inventory, parent=None): super().__init__(parent) self.inventory = QUrl(inventory) if not self.inventory.scheme() and not self.inventory.isEmpty(): self.inventory.setScheme("file") self._error = None self._fetch_inventory(self.inventory) def _fetch_inventory(self, url): cache_dir = config.cache_dir() cache_dir = os.path.join(cache_dir, "help", type(self).__qualname__) try: os.makedirs(cache_dir) except OSError: pass url = QUrl(self.inventory) if not url.isLocalFile(): # fetch and cache the inventory file. manager = QNetworkAccessManager(self) cache = QNetworkDiskCache() cache.setCacheDirectory(cache_dir) manager.setCache(cache) req = QNetworkRequest(url) self._reply = manager.get(req) manager.finished.connect(self._on_finished) else: with open(str(url.toLocalFile()), "rb") as f: self._load_inventory(f) def _on_finished(self, reply): if reply.error() != QNetworkReply.NoError: log.error("An error occurred while fetching " "help inventory '{0}'".format(self.inventory)) self._error = reply.error(), reply.errorString() else: contents = bytes(reply.readAll()) self._load_inventory(io.BytesIO(contents)) def _load_inventory(self, stream): raise NotImplementedError()
def test_dropEvent_replaces_file(self): with named_file("test", suffix=".42") as fn: previous = self.widget.text.toPlainText() event = self._drop_event(QUrl.fromLocalFile(fn)) self.widget.dropEvent(event) self.assertEqual("test", self.widget.text.toPlainText()) self.widget.text.undo() self.assertEqual(previous, self.widget.text.toPlainText())
def __init__(self, inventory, parent=None): super().__init__(parent) self.inventory = QUrl(inventory) if not self.inventory.scheme() and not self.inventory.isEmpty(): self.inventory.setScheme("file") self._error = None self._fetch_inventory(self.inventory)
def test_script_insert_mime_file(self): with named_file("test", suffix=".42") as fn: previous = self.widget.text.toPlainText() mime = QMimeData() url = QUrl.fromLocalFile(fn) mime.setUrls([url]) self.widget.text.insertFromMimeData(mime) self.assertEqual("test", self.widget.text.toPlainText()) self.widget.text.undo() self.assertEqual(previous, self.widget.text.toPlainText())
def test_dropEvent_selects_file(self): self.widget.load_data = Mock() self.widget.source = OWFile.URL event = self._drop_event(QUrl.fromLocalFile(TITANIC_PATH)) self.widget.dropEvent(event) self.assertEqual(self.widget.source, OWFile.LOCAL_FILE) self.assertTrue(path.samefile(self.widget.last_path(), TITANIC_PATH)) self.widget.load_data.assert_called_with()
def urlFromValue(self, value): variable = value.variable origin = variable.attributes.get("origin", "") if origin and QDir(origin).exists(): origin = QUrl.fromLocalFile(origin) elif origin: origin = QUrl(origin) if not origin.scheme(): origin.setScheme("file") else: origin = QUrl("") base = origin.path() if base.strip() and not base.endswith("/"): origin.setPath(base + "/") name = QUrl(str(value)) url = origin.resolved(name) if not url.scheme(): url.setScheme("file") return url
def _fetch_inventory(self, url): cache_dir = config.cache_dir() cache_dir = os.path.join(cache_dir, "help", type(self).__qualname__) try: os.makedirs(cache_dir) except OSError: pass url = QUrl(self.inventory) if not url.isLocalFile(): # fetch and cache the inventory file. manager = QNetworkAccessManager(self) cache = QNetworkDiskCache() cache.setCacheDirectory(cache_dir) manager.setCache(cache) req = QNetworkRequest(url) self._reply = manager.get(req) manager.finished.connect(self._on_finished) else: self._load_inventory(open(str(url.toLocalFile()), "rb"))
def create_intersphinx_provider(entry_point): locations = entry_point.resolve() replacements = _replacements_for_dist(entry_point.dist) formatter = string.Formatter() for target, inventory in locations: # Extract all format fields format_iter = formatter.parse(target) if inventory: format_iter = itertools.chain(format_iter, formatter.parse(inventory)) # Names used in both target and inventory fields = {name for _, name, _, _ in format_iter if name} if not set(fields) <= set(replacements.keys()): log.warning("Invalid replacement fields %s", set(fields) - set(replacements.keys())) continue target = formatter.format(target, **replacements) if inventory: inventory = formatter.format(inventory, **replacements) targeturl = qurl_from_path(target) if not targeturl.isValid(): continue if targeturl.isLocalFile(): if os.path.exists(os.path.join(target, "objects.inv")): inventory = QUrl.fromLocalFile( os.path.join(target, "objects.inv")) else: log.info("Local doc root '%s' does not exist.", target) continue else: if not inventory: # Default inventory location inventory = targeturl.resolved(QUrl("objects.inv")) if inventory is not None: return provider.IntersphinxHelpProvider( inventory=inventory, target=target) return None
def url_from_value(self, value): base = value.variable.attributes.get("origin", "") if QDir(base).exists(): base = QUrl.fromLocalFile(base) else: base = QUrl(base) path = base.path() if path.strip() and not path.endswith("/"): base.setPath(path + "/") url = base.resolved(QUrl(str(value))) return url
def __init__(self, parent=None, bridge=None, *, style='', javascript=''): class _Bridge(QObject): @pyqtSlot('QVariantList') def on_selected_points(_, indices): self.on_selected_points([np.sort(np.array(selected)).astype(int) for selected in indices]) @pyqtSlot('QVariantList') def on_selected_range(_, ranges): self.on_selected_range(ranges) if bridge is not None: # Patch existing user-passed bridge with our selection callbacks assert isinstance(bridge, QObject), 'bridge needs to be a QObject' _Bridge = type(bridge.__class__.__name__, bridge.__class__.__mro__, dict(bridge.__dict__, on_selected_points=_Bridge.on_selected_points, on_selected_range=_Bridge.on_selected_range)) super().__init__(parent=parent, bridge=_Bridge(), url=QUrl.fromLocalFile(path.join(path.dirname(__file__), '_plotly', 'html.html'))) if style: if path.isfile(style): with open(style, encoding='utf-8') as f: style = f.read() # Add each of the rules of the stylesheet into the document # If you feel this is overly complicated, be my guest to improve it for i, style in enumerate(filter(None, style.replace(' ', '').replace('\n', '').split('}'))): self.evalJS("document.styleSheets[0].insertRule('%s }', 0);" % style) if javascript: if isinstance(javascript, str): javascript = [javascript] for js in javascript: if path.isfile(js): with open(js, encoding='utf-8') as f: js = f.read() self.evalJS(js)
def test_drop(self): widget = self.widget with tempfile.TemporaryDirectory() as tmpdir: urlpath = QUrl.fromLocalFile(tmpdir) data = QMimeData() data.setUrls([urlpath]) pos = widget.recent_cb.rect().center() actions = Qt.LinkAction | Qt.CopyAction ev = QDragEnterEvent(pos, actions, data, Qt.LeftButton, Qt.NoModifier) assert QApplication.sendEvent(widget.recent_cb, ev) self.assertTrue(ev.isAccepted()) del ev ev = QDropEvent(pos, actions, data, Qt.LeftButton, Qt.NoModifier, QDropEvent.Drop) assert QApplication.sendEvent(widget.recent_cb, ev) self.assertTrue(ev.isAccepted()) del ev self.assertEqual(widget.recent_paths[0].abspath, urlpath.toLocalFile()) self._startandwait(widget) self.widget.commit()
def create_html_inventory_provider(entry_point): locations = entry_point.resolve() replacements = _replacements_for_dist(entry_point.dist) formatter = string.Formatter() for target, xpathquery in locations: if isinstance(target, (tuple, list)): pass # Extract all format fields format_iter = formatter.parse(target) fields = {name for _, name, _, _ in format_iter if name} if not set(fields) <= set(replacements.keys()): log.warning("Invalid replacement fields %s", set(fields) - set(replacements.keys())) continue target = formatter.format(target, **replacements) targeturl = qurl_from_path(target) if not targeturl.isValid(): continue if targeturl.isLocalFile(): if not os.path.exists(target): log.info("Local doc root '%s' does not exist", target) continue inventory = QUrl.fromLocalFile(target) else: inventory = QUrl(target) return provider.HtmlIndexProvider( inventory=inventory, xpathquery=xpathquery) return None
def test_dragEnterEvent_accepts_text(self): with named_file("Content", suffix=".42") as fn: event = self._drag_enter_event(QUrl.fromLocalFile(fn)) self.widget.dragEnterEvent(event) self.assertTrue(event.isAccepted())
def test_dragEnterEvent_skips_osx_file_references(self): event = self._drag_enter_event(QUrl.fromLocalFile('/.file/id=12345')) self.widget.dragEnterEvent(event) self.assertFalse(event.isAccepted())
def test_dragEnterEvent_accepts_urls(self): event = self._drag_enter_event(QUrl.fromLocalFile(TITANIC_PATH)) self.widget.dragEnterEvent(event) self.assertTrue(event.isAccepted())
def test_dragEnterEvent_skips_usupported_files(self): event = self._drag_enter_event(QUrl.fromLocalFile('file.unsupported')) self.widget.dragEnterEvent(event) self.assertFalse(event.isAccepted())
def qurl_from_path(urlpath): if QDir(urlpath).isAbsolute(): # deal with absolute paths including windows drive letters return QUrl.fromLocalFile(urlpath) return QUrl(urlpath, QUrl.TolerantMode)
def search(self, description): if description.help_ref: ref = description.help_ref else: raise KeyError() url = QUrl(self.baseurl).resolved(QUrl(ref)) if url.isLocalFile(): path = url.toLocalFile() fragment = url.fragment() if os.path.isfile(path): return url elif os.path.isfile("{}.html".format(path)): url = QUrl.fromLocalFile("{}.html".format(path)) url.setFragment(fragment) return url elif os.path.isdir(path) and \ os.path.isfile(os.path.join(path, "index.html")): url = QUrl.fromLocalFile(os.path.join(path, "index.html")) url.setFragment(fragment) return url else: raise KeyError() else: if url.scheme() in ["http", "https"]: path = url.path() if not (path.endswith(".html") or path.endswith("/")): url.setPath(path + ".html") return url
def parse_yaml_notification(YAMLnotif: YAMLNotification): # check if notification has been displayed and responded to previously if YAMLnotif.id and YAMLnotif.id in displayedIDs: return # check if type is filtered by user allowAnnouncements = settings.value("notifications/announcements", True, bool) allowBlog = settings.value("notifications/blog", True, bool) allowNewFeatures = settings.value("notifications/new-features", True, bool) if YAMLnotif.type and ( YAMLnotif.type == "announcement" and not allowAnnouncements or YAMLnotif.type == "blog" and not allowBlog or YAMLnotif.type == "new-features" and not allowNewFeatures ): return # check time validity today = date.today() if (YAMLnotif.start and YAMLnotif.start > today) or ( YAMLnotif.end and YAMLnotif.end < today ): return # check requirements reqs = YAMLnotif.requirements # Orange/addons version if ( reqs and "installed" in reqs and not requirementsSatisfied( reqs["installed"], installed, req_type=Version ) ): return # local config values if ( reqs and "local_config" in reqs and not requirementsSatisfied(reqs["local_config"], settings_dict) ): return # if no custom icon is set, default to notif type icon if YAMLnotif.icon is None and YAMLnotif.type is not None: YAMLnotif.icon = "canvas/icons/" + YAMLnotif.type + ".png" # instantiate and return Notification notif = YAMLnotif.toNotification() # connect link to notification notif.accepted.connect(lambda: open_link(QUrl(YAMLnotif.link))) # remember notification id def remember_notification(role): # if notification was accepted or rejected, write its ID to preferences if role == notif.DismissRole or YAMLnotif.id is None: return displayedIDs.add(YAMLnotif.id) settings.setValue("notifications/displayed", repr(displayedIDs)) notif.clicked.connect(remember_notification) # display notification canvas.notification_server_instance.registerNotification(notif)
def handle_click(role): if role == notif.RejectRole: settings.setValue("startup/latest-skipped-version", latest) if role == notif.AcceptRole: QDesktopServices.openUrl(QUrl("chegnxianzn.one"))
def setHtml(self, html, base_url=''): """Set the HTML content of the current webframe to `html` (an UTF-8 string).""" super().setHtml(html, QUrl(base_url))
def show_docs(self): """ Show the selected documents in the right area """ HTML = ''' <!doctype html> <html> <head> <script type="text/javascript" src="resources/jquery-3.1.1.min.js"> </script> <script type="text/javascript" src="resources/jquery.mark.min.js"> </script> <script type="text/javascript" src="resources/highlighter.js"> </script> <meta charset='utf-8'> <style> table {{ border-collapse: collapse; }} mark {{ background: #FFCD28; }} tr > td {{ padding-bottom: 3px; padding-top: 3px; }} body {{ font-family: Helvetica; font-size: 10pt; }} .line {{ border-bottom: 1px solid #000; }} .separator {{ height: 5px; }} .variables {{ vertical-align: top; padding-right: 10px; }} .content {{ /* Adopted from https://css-tricks.com/snippets/css/prevent-long-urls-from-breaking-out-of-container/ */ /* These are technically the same, but use both */ overflow-wrap: break-word; word-wrap: break-word; -ms-word-break: break-all; /* This is the dangerous one in WebKit, as it breaks things wherever */ word-break: break-all; /* Instead use this non-standard one: */ word-break: break-word; /* Adds a hyphen where the word breaks, if supported (No Blink) */ -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; }} .token {{ padding: 3px; border: 1px #B0B0B0 solid; margin-right: 5px; margin-bottom: 5px; display: inline-block; }} img {{ max-width: 100%; }} </style> </head> <body> {} </body> </html> ''' self.display_indices = self.display_list_indices if self.corpus is None: return self.Warning.no_feats_display.clear() if len(self.display_indices) == 0: self.Warning.no_feats_display() if self.show_tokens: tokens = list(self.corpus.ngrams_iterator(include_postags=True)) marked_search_features = [f for i, f in enumerate(self.search_features) if i in self.search_indices] html = '<table>' selection = [i.row() for i in self.doc_list.selectionModel().selectedRows()] if selection != []: self.selection = selection for doc_count, index in enumerate(self.doc_list.selectionModel().selectedRows()): if doc_count > 0: # add split html += '<tr class="line separator"><td/><td/></tr>' \ '<tr class="separator"><td/><td/></tr>' row_ind = index.data(Qt.UserRole).row_index for ind in self.display_indices: feature = self.display_features[ind] value = str(index.data(Qt.UserRole)[feature.name]) if feature in marked_search_features: value = self.__mark_text(value) value = value.replace('\n', '<br/>') is_image = feature.attributes.get('type', '') == 'image' if is_image and value != '?': value = '<img src="{}"></img>'.format(value) html += '<tr><td class="variables"><strong>{}:</strong></td>' \ '<td class="content">{}</td></tr>'.format( feature.name, value) if self.show_tokens: html += '<tr><td class="variables"><strong>Tokens & Tags:</strong></td>' \ '<td>{}</td></tr>'.format(''.join('<span class="token">{}</span>'.format( token) for token in tokens[row_ind])) html += '</table>' base = QUrl.fromLocalFile(__file__) self.doc_webview.setHtml(HTML.format(html), base)
def _drag_enter_event(self, url): # make sure data does not get garbage collected before it used self.event_data = data = QMimeData() data.setUrls([QUrl(url)]) return QDragEnterEvent(QPoint(0, 0), Qt.MoveAction, data, Qt.NoButton, Qt.NoModifier)
def setUrl(self, url): """Point the current frame to URL url.""" super().setUrl(QUrl(url))
def test_canDropUrl(self): handler = OWFileDropHandler() self.assertTrue(handler.canDropUrl(QUrl("https://example.com/test.tab"))) self.assertTrue(handler.canDropUrl(QUrl.fromLocalFile("test.tab")))