def loadPage(self, val): logging.debug(f'val {val}') self.ui.strategyBrowse.load(QUrl(val))
def _onRequestFinished(self, reply): if reply.error() == QNetworkReply.TimeoutError: Logger.log("w", "Received a timeout on a request to the instance") self._connection_state_before_timeout = self._connection_state self.setConnectionState(ConnectionState.error) return if self._connection_state_before_timeout and reply.error( ) == QNetworkReply.NoError: # There was a timeout, but we got a correct answer again. if self._last_response_time: Logger.log( "d", "We got a response from the instance after %s of silence", time() - self._last_response_time) self.setConnectionState(self._connection_state_before_timeout) self._connection_state_before_timeout = None if reply.error() == QNetworkReply.NoError: self._last_response_time = time() http_status_code = reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) if not http_status_code: # Received no or empty reply return if reply.operation() == QNetworkAccessManager.GetOperation: if self._api_prefix + "printer" in reply.url().toString( ): # Status update from /printer. if http_status_code == 200: if not self.acceptsCommands: self.setAcceptsCommands(True) self.setConnectionText( i18n_catalog.i18nc( "@info:status", "Connected to OctoPrint on {0}").format( self._key)) if self._connection_state == ConnectionState.connecting: self.setConnectionState(ConnectionState.connected) try: json_data = json.loads( bytes(reply.readAll()).decode("utf-8")) except json.decoder.JSONDecodeError: Logger.log( "w", "Received invalid JSON from octoprint instance.") json_data = {} if "temperature" in json_data: if not self._num_extruders_set: self._num_extruders = 0 while "tool%d" % self._num_extruders in json_data[ "temperature"]: self._num_extruders = self._num_extruders + 1 # Reinitialise from PrinterOutputDevice to match the new _num_extruders self._hotend_temperatures = [ 0 ] * self._num_extruders self._target_hotend_temperatures = [ 0 ] * self._num_extruders self._num_extruders_set = True # Check for hotend temperatures for index in range(0, self._num_extruders): if ("tool%d" % index) in json_data["temperature"]: hotend_temperatures = json_data["temperature"][ "tool%d" % index] self._setHotendTemperature( index, hotend_temperatures["actual"]) self._updateTargetHotendTemperature( index, hotend_temperatures["target"]) else: self._setHotendTemperature(index, 0) self._updateTargetHotendTemperature(index, 0) if "bed" in json_data["temperature"]: bed_temperatures = json_data["temperature"]["bed"] self._setBedTemperature(bed_temperatures["actual"]) self._updateTargetBedTemperature( bed_temperatures["target"]) else: self._setBedTemperature(0) self._updateTargetBedTemperature(0) job_state = "offline" if "state" in json_data: if json_data["state"]["flags"]["error"]: job_state = "error" elif json_data["state"]["flags"]["paused"]: job_state = "paused" elif json_data["state"]["flags"]["printing"]: job_state = "printing" elif json_data["state"]["flags"]["ready"]: job_state = "ready" self._updateJobState(job_state) elif http_status_code == 401: self._updateJobState("offline") self.setConnectionText( i18n_catalog.i18nc( "@info:status", "OctoPrint on {0} does not allow access to print"). format(self._key)) elif http_status_code == 409: if self._connection_state == ConnectionState.connecting: self.setConnectionState(ConnectionState.connected) self._updateJobState("offline") self.setConnectionText( i18n_catalog.i18nc( "@info:status", "The printer connected to OctoPrint on {0} is not operational" ).format(self._key)) else: self._updateJobState("offline") Logger.log("w", "Received an unexpected returncode: %d", http_status_code) elif self._api_prefix + "job" in reply.url().toString( ): # Status update from /job: if http_status_code == 200: try: json_data = json.loads( bytes(reply.readAll()).decode("utf-8")) except json.decoder.JSONDecodeError: Logger.log( "w", "Received invalid JSON from octoprint instance.") json_data = {} progress = json_data["progress"]["completion"] if progress: self.setProgress(progress) if json_data["progress"]["printTime"]: self.setTimeElapsed(json_data["progress"]["printTime"]) if json_data["progress"]["printTimeLeft"]: self.setTimeTotal( json_data["progress"]["printTime"] + json_data["progress"]["printTimeLeft"]) elif json_data["job"]["estimatedPrintTime"]: self.setTimeTotal( max(json_data["job"]["estimatedPrintTime"], json_data["progress"]["printTime"])) elif progress > 0: self.setTimeTotal( json_data["progress"]["printTime"] / (progress / 100)) else: self.setTimeTotal(0) else: self.setTimeElapsed(0) self.setTimeTotal(0) self.setJobName(json_data["job"]["file"]["name"]) else: pass # TODO: Handle errors elif self._api_prefix + "settings" in reply.url().toString( ): # OctoPrint settings dump from /settings: if http_status_code == 200: try: json_data = json.loads( bytes(reply.readAll()).decode("utf-8")) except json.decoder.JSONDecodeError: Logger.log( "w", "Received invalid JSON from octoprint instance.") json_data = {} if "feature" in json_data and "sdSupport" in json_data[ "feature"]: self._sd_supported = json_data["feature"]["sdSupport"] if "webcam" in json_data and "streamUrl" in json_data[ "webcam"]: self._camera_shares_proxy = False stream_url = json_data["webcam"]["streamUrl"] if not stream_url: #empty string or None self._camera_url = "" elif stream_url[:4].lower() == "http": # absolute uri self._camera_url = stream_url elif stream_url[:2] == "//": # protocol-relative self._camera_url = "%s:%s" % (self._protocol, stream_url) elif stream_url[: 1] == ":": # domain-relative (on another port) self._camera_url = "%s://%s%s" % ( self._protocol, self._address, stream_url) elif stream_url[: 1] == "/": # domain-relative (on same port) self._camera_url = "%s://%s:%d%s" % ( self._protocol, self._address, self._port, stream_url) self._camera_shares_proxy = True else: Logger.log("w", "Unusable stream url received: %s", stream_url) self._camera_url = "" Logger.log("d", "Set OctoPrint camera url to %s", self._camera_url) self._camera_rotation = -90 if json_data["webcam"][ "rotate90"] else 0 if json_data["webcam"]["flipH"] and json_data[ "webcam"]["flipV"]: self._camera_mirror = False self._camera_rotation += 180 elif json_data["webcam"]["flipH"]: self._camera_mirror = True elif json_data["webcam"]["flipV"]: self._camera_mirror = True self._camera_rotation += 180 else: self._camera_mirror = False self.cameraOrientationChanged.emit() elif reply.operation() == QNetworkAccessManager.PostOperation: if self._api_prefix + "files" in reply.url().toString( ): # Result from /files command: if http_status_code == 201: Logger.log( "d", "Resource created on OctoPrint instance: %s", reply.header( QNetworkRequest.LocationHeader).toString()) else: pass # TODO: Handle errors reply.uploadProgress.disconnect(self._onUploadProgress) self._progress_message.hide() global_container_stack = Application.getInstance( ).getGlobalContainerStack() if not self._auto_print: location = reply.header(QNetworkRequest.LocationHeader) if location: file_name = QUrl( reply.header(QNetworkRequest.LocationHeader). toString()).fileName() message = Message( i18n_catalog.i18nc( "@info:status", "Saved to OctoPrint as {0}").format(file_name)) else: message = Message( i18n_catalog.i18nc("@info:status", "Saved to OctoPrint")) message.addAction( "open_browser", i18n_catalog.i18nc("@action:button", "Open OctoPrint..."), "globe", i18n_catalog.i18nc("@info:tooltip", "Open the OctoPrint web interface")) message.actionTriggered.connect( self._onMessageActionTriggered) message.show() elif self._api_prefix + "job" in reply.url().toString( ): # Result from /job command: if http_status_code == 204: Logger.log("d", "Octoprint command accepted") else: pass # TODO: Handle errors else: Logger.log("d", "OctoPrintOutputDevice got an unhandled operation %s", reply.operation())
(QColor('red'), 'rgba(255, 0, 0, 255)'), (QColor('blue'), 'rgba(0, 0, 255, 255)'), (QColor(1, 3, 5, 7), 'rgba(1, 3, 5, 7)'), ]) def test_qcolor_to_qsscolor(color, expected): assert qtutils.qcolor_to_qsscolor(color) == expected def test_qcolor_to_qsscolor_invalid(): with pytest.raises(qtutils.QtValueError): qtutils.qcolor_to_qsscolor(QColor()) @pytest.mark.parametrize('obj', [ QPoint(23, 42), QUrl('http://www.qutebrowser.org/'), ]) def test_serialize(obj): """Test a serialize/deserialize round trip. Args: obj: The object to test with. """ new_obj = type(obj)() qtutils.deserialize(qtutils.serialize(obj), new_obj) assert new_obj == obj class TestSerializeStream: """Tests for serialize_stream and deserialize_stream.""" def _set_status(self, stream, status):
def __init__(self, url): QWebPage.__init__(self) self.loadFinished.connect.(self._loadFinished) self.mainFrame().load(QUrl(url)) self.app.exec_()
def openBugReportPage(self) -> None: event = CallFunctionEvent(self._openUrl, [QUrl("http://github.com/Ultimaker/Cura/issues")], {}) cura.CuraApplication.CuraApplication.getInstance().functionEvent(event)
def file_url_name(self, file_url): return QUrl(file_url).fileName()
def _onNetworkRequestFinished(self, reply): reply_url = reply.url().toString() if "system" in reply_url: if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200: # Something went wrong with checking the firmware version! return try: system_info = json.loads( bytes(reply.readAll()).decode("utf-8")) except: Logger.log("e", "Something went wrong converting the JSON.") return address = reply.url().host() has_cluster_capable_firmware = Version( system_info["firmware"]) > self._min_cluster_version instance_name = "manual:%s" % address properties = { b"name": (system_info["name"] + " (manual)").encode("utf-8"), b"address": address.encode("utf-8"), b"firmware_version": system_info["firmware"].encode("utf-8"), b"manual": b"true", b"machine": str(system_info['hardware']["typeid"]).encode("utf-8") } if has_cluster_capable_firmware: # Cluster needs an additional request, before it's completed. properties[b"incomplete"] = b"true" # Check if the device is still in the list & re-add it with the updated # information. if instance_name in self._discovered_devices: self._onRemoveDevice(instance_name) self._onAddDevice(instance_name, address, properties) if has_cluster_capable_firmware: # We need to request more info in order to figure out the size of the cluster. cluster_url = QUrl("http://" + address + self._cluster_api_prefix + "printers/") cluster_request = QNetworkRequest(cluster_url) self._network_manager.get(cluster_request) elif "printers" in reply_url: if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200: # Something went wrong with checking the amount of printers the cluster has! return # So we confirmed that the device is in fact a cluster printer, and we should now know how big it is. try: cluster_printers_list = json.loads( bytes(reply.readAll()).decode("utf-8")) except: Logger.log("e", "Something went wrong converting the JSON.") return address = reply.url().host() instance_name = "manual:%s" % address if instance_name in self._discovered_devices: device = self._discovered_devices[instance_name] properties = device.getProperties().copy() if b"incomplete" in properties: del properties[b"incomplete"] properties[b"cluster_size"] = len(cluster_printers_list) self._onRemoveDevice(instance_name) self._onAddDevice(instance_name, address, properties)
(usertypes.LoadStatus.success_https, url.UrlType.success_https), (usertypes.LoadStatus.error, url.UrlType.error), (usertypes.LoadStatus.warn, url.UrlType.warn), (usertypes.LoadStatus.loading, url.UrlType.normal), (usertypes.LoadStatus.none, url.UrlType.normal) ]) def test_on_load_status_changed(url_widget, status, expected): """Test text when status is changed.""" url_widget.set_url(QUrl('www.example.com')) url_widget.on_load_status_changed(status) assert url_widget._urltype == expected @pytest.mark.parametrize('load_status, qurl', [ (usertypes.LoadStatus.success, QUrl('http://abc123.com/this/awesome/url.html')), (usertypes.LoadStatus.success, QUrl('http://reddit.com/r/linux')), (usertypes.LoadStatus.success, QUrl('http://ä.com/')), (usertypes.LoadStatus.success_https, QUrl('www.google.com')), (usertypes.LoadStatus.success_https, QUrl('https://supersecret.gov/nsa/files.txt')), (usertypes.LoadStatus.warn, QUrl('www.shadysite.org/some/file/with/issues.htm')), (usertypes.LoadStatus.error, QUrl('invalid::/url')), (usertypes.LoadStatus.error, QUrl()), ])
def test_on_load_status_changed(url_widget, status, expected): """Test text when status is changed.""" url_widget.set_url(QUrl('www.example.com')) url_widget.on_load_status_changed(status) assert url_widget._urltype == expected
def test_resolve_url_relative_base(): elem = get_webelem(attributes={'href': 'foo'}) with pytest.raises(ValueError): elem.resolve_url(QUrl('base'))
def openUrl(self): url = QUrl("https://github.com/kmnsys/slider-puzzle") if not QDesktopServices.openUrl(url): QMessageBox.warning(self, 'Open Url', 'Could not Open Url')
def test_resolve_url(attributes, expected): elem = get_webelem(attributes=attributes) baseurl = QUrl('http://www.example.com/') assert elem.resolve_url(baseurl) == expected
]) def test_is_editable_plugin(self, stubbed_config, setting, tagname, attributes, editable): stubbed_config.data['input']['insert-mode-on-plugins'] = setting elem = get_webelem(tagname=tagname, attributes=attributes) assert elem.is_editable() == editable @pytest.mark.parametrize( 'attributes, expected', [ # No attributes ({}, None), ({ 'href': 'foo' }, QUrl('http://www.example.com/foo')), ({ 'src': 'foo' }, QUrl('http://www.example.com/foo')), ({ 'href': 'foo', 'src': 'bar' }, QUrl('http://www.example.com/foo')), ({ 'href': '::garbage::' }, None), ({ 'href': 'http://www.example.org/' }, QUrl('http://www.example.org/')), ({ 'href': ' foo '
def createRequest(self, op, req, outgoing_data): """Return a new QNetworkReply object. Args: op: Operation op req: const QNetworkRequest & req outgoing_data: QIODevice * outgoingData Return: A QNetworkReply. """ proxy_factory = objreg.get('proxy-factory', None) if proxy_factory is not None: proxy_error = proxy_factory.get_error() if proxy_error is not None: return networkreply.ErrorNetworkReply( req, proxy_error, QNetworkReply.UnknownProxyError, self) for header, value in shared.custom_headers(url=req.url()): req.setRawHeader(header, value) # There are some scenarios where we can't figure out current_url: # - There's a generic NetworkManager, e.g. for downloads # - The download was in a tab which is now closed. current_url = QUrl() if self._tab_id is not None: assert self._win_id is not None try: tab = objreg.get('tab', scope='tab', window=self._win_id, tab=self._tab_id) current_url = tab.url() except (KeyError, RuntimeError): # https://github.com/qutebrowser/qutebrowser/issues/889 # Catching RuntimeError because we could be in the middle of # the webpage shutdown here. current_url = QUrl() request = interceptors.Request(first_party_url=current_url, request_url=req.url()) interceptors.run(request) if request.is_blocked: return networkreply.ErrorNetworkReply( req, HOSTBLOCK_ERROR_STRING, QNetworkReply.ContentAccessDenied, self) if 'log-requests' in objects.debug_flags: operation = debug.qenum_key(QNetworkAccessManager, op) operation = operation.replace('Operation', '').upper() log.webview.debug("{} {}, first-party {}".format( operation, req.url().toDisplayString(), current_url.toDisplayString())) scheme = req.url().scheme() if scheme in self._scheme_handlers: result = self._scheme_handlers[scheme](req, op, current_url) if result is not None: result.setParent(self) return result self.set_referer(req, current_url) return super().createRequest(op, req, outgoing_data)
def homePage(self): move_url = QUrl('https://twitter.com/home') self.browser.load(move_url) self.updateUrl
def __init__(self, node, iface_name): # Parent super(MainWindow, self).__init__() self.setWindowTitle('UAVCAN GUI Tool') self.setWindowIcon(get_app_icon()) self._node = node self._successive_node_errors = 0 self._iface_name = iface_name self._active_data_type_detector = ActiveDataTypeDetector(self._node) self._node_spin_timer = QTimer(self) self._node_spin_timer.timeout.connect(self._spin_node) self._node_spin_timer.setSingleShot(False) self._node_spin_timer.start(10) self._node_windows = {} # node ID : window object self._node_monitor_widget = NodeMonitorWidget(self, node) self._node_monitor_widget.on_info_window_requested = self._show_node_window self._local_node_widget = LocalNodeWidget(self, node) self._log_message_widget = LogMessageDisplayWidget(self, node) self._dynamic_node_id_allocation_widget = DynamicNodeIDAllocatorWidget( self, node, self._node_monitor_widget.monitor) self._file_server_widget = FileServerWidget(self, node) self._plotter_manager = PlotterManager(self._node) self._bus_monitor_manager = BusMonitorManager(self._node, iface_name) # Console manager depends on other stuff via context, initialize it last self._console_manager = ConsoleManager(self._make_console_context) # # File menu # quit_action = QAction(get_icon('sign-out'), '&Quit', self) quit_action.setShortcut(QKeySequence('Ctrl+Shift+Q')) quit_action.triggered.connect(self.close) file_menu = self.menuBar().addMenu('&File') file_menu.addAction(quit_action) # # Tools menu # show_bus_monitor_action = QAction(get_icon('bus'), '&Bus Monitor', self) show_bus_monitor_action.setShortcut(QKeySequence('Ctrl+Shift+B')) show_bus_monitor_action.setStatusTip('Open bus monitor window') show_bus_monitor_action.triggered.connect( self._bus_monitor_manager.spawn_monitor) show_console_action = QAction(get_icon('terminal'), 'Interactive &Console', self) show_console_action.setShortcut(QKeySequence('Ctrl+Shift+T')) show_console_action.setStatusTip('Open interactive console window') show_console_action.triggered.connect(self._show_console_window) new_subscriber_action = QAction(get_icon('newspaper-o'), '&Subscriber', self) new_subscriber_action.setShortcut(QKeySequence('Ctrl+Shift+S')) new_subscriber_action.setStatusTip('Open subscription tool') new_subscriber_action.triggered.connect(lambda: SubscriberWindow.spawn( self, self._node, self._active_data_type_detector)) new_plotter_action = QAction(get_icon('area-chart'), '&Plotter', self) new_plotter_action.setShortcut(QKeySequence('Ctrl+Shift+P')) new_plotter_action.setStatusTip('Open new graph plotter window') new_plotter_action.triggered.connect( self._plotter_manager.spawn_plotter) show_can_adapter_controls_action = QAction( get_icon('plug'), 'CAN &Adapter Control Panel', self) show_can_adapter_controls_action.setShortcut( QKeySequence('Ctrl+Shift+A')) show_can_adapter_controls_action.setStatusTip( 'Open CAN adapter control panel (if supported by the adapter)') show_can_adapter_controls_action.triggered.connect( self._try_spawn_can_adapter_control_panel) tools_menu = self.menuBar().addMenu('&Tools') tools_menu.addAction(show_bus_monitor_action) tools_menu.addAction(show_console_action) tools_menu.addAction(new_subscriber_action) tools_menu.addAction(new_plotter_action) tools_menu.addAction(show_can_adapter_controls_action) # # Help menu # uavcan_website_action = QAction(get_icon('globe'), 'Open UAVCAN &Website', self) uavcan_website_action.triggered.connect( lambda: QDesktopServices.openUrl(QUrl('http://uavcan.org'))) show_log_directory_action = QAction(get_icon('pencil-square-o'), 'Open &Log Directory', self) show_log_directory_action.triggered.connect( lambda: QDesktopServices.openUrl( QUrl.fromLocalFile(os.path.dirname(log_file.name)))) about_action = QAction(get_icon('info'), '&About', self) about_action.triggered.connect(lambda: AboutWindow(self).show()) help_menu = self.menuBar().addMenu('&Help') help_menu.addAction(uavcan_website_action) help_menu.addAction(show_log_directory_action) help_menu.addAction(about_action) # # Window layout # self.statusBar().show() def make_vbox(*widgets, stretch_index=None): box = QVBoxLayout(self) for idx, w in enumerate(widgets): box.addWidget(w, 1 if idx == stretch_index else 0) container = QWidget(self) container.setLayout(box) container.setContentsMargins(0, 0, 0, 0) return container def make_splitter(orientation, *widgets): spl = QSplitter(orientation, self) for w in widgets: spl.addWidget(w) return spl self.setCentralWidget( make_splitter( Qt.Horizontal, make_vbox(self._local_node_widget, self._node_monitor_widget, self._file_server_widget), make_splitter( Qt.Vertical, make_vbox(self._log_message_widget), make_vbox(self._dynamic_node_id_allocation_widget, stretch_index=1))))
def set_html(self, html: str, base_url: QUrl = QUrl()) -> None: raise NotImplementedError
def openUrl(self): QDesktopServices.openUrl( QUrl("https://github.com/mthnzbk/domestic/issues"))
def send(self, wormhole_code, config_file_url): config_path = QUrl(config_file_url).toLocalFile() with open(config_path, 'rb') as f: yield hpos_seed.send(wormhole_code, f.read(), self.reactor) self.success.emit()
def navigate_home(self): self.browser.setUrl(QUrl("https://www.google.com"))
def _onReviewCloudConnection(self, messageId: str, actionId: str) -> None: address = self._application.getMachineManager( ).activeMachineAddress # type: str if address: QDesktopServices.openUrl(QUrl("http://" + address + "/settings")) return
def navigate_to_url(self): q = QUrl(self.urlbar.text()) if q.scheme() == "": q.setScheme("http") self.browser.setUrl(q)
def openDocumentation(self) -> None: # Starting a web browser from a signal handler connected to a menu will crash on windows. # So instead, defer the call to the next run of the event loop, since that does work. # Note that weirdly enough, only signal handlers that open a web browser fail like that. event = CallFunctionEvent(self._openUrl, [QUrl("http://ultimaker.com/en/support/software")], {}) cura.CuraApplication.CuraApplication.getInstance().functionEvent(event)
def navigate_page(self): self.browser.setUrl(QUrl("hipycas.github.io/PyBrowse"))
def test_long_output(self, fake_windows, tmpdir, sess_man): session_path = tmpdir / 'foo.yml' items1 = [ Item(QUrl('http://www.qutebrowser.org/'), 'test title 1'), Item(QUrl('http://www.example.org/'), 'test title 2', original_url=QUrl('http://www.example.com/'), active=True), ] items2 = [ Item(QUrl('http://www.example.com/?q=foo+bar'), 'test title 3'), Item(QUrl('http://www.example.com/?q=test%20foo'), 'test title 4', active=True), ] items3 = [] items4 = [ Item(QUrl('http://www.github.com/The-Compiler/qutebrowser'), 'test title 5', active=True), ] self._set_data(fake_windows[0], 0, items1) self._set_data(fake_windows[0], 1, items2) self._set_data(fake_windows[1], 0, items3) self._set_data(fake_windows[1], 1, items4) expected = """ windows: - active: true geometry: !!binary | ZmFrZS1nZW9tZXRyeS0w tabs: - history: - title: test title 1 url: http://www.qutebrowser.org/ - active: true original-url: http://www.example.com/ scroll-pos: x: 0 y: 0 title: test title 2 url: http://www.example.org/ zoom: 1.0 - active: true history: - title: test title 3 url: http://www.example.com/?q=foo+bar - active: true scroll-pos: x: 0 y: 0 title: test title 4 url: http://www.example.com/?q=test%20foo zoom: 1.0 - geometry: !!binary | ZmFrZS1nZW9tZXRyeS0x tabs: - history: [] - active: true history: - active: true scroll-pos: x: 0 y: 0 title: test title 5 url: http://www.github.com/The-Compiler/qutebrowser zoom: 1.0 """ sess_man.save(str(session_path)) data = session_path.read_text('utf-8') assert data == textwrap.dedent(expected.strip('\n'))
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.browser = QWebEngineView() self.browser.setUrl(QUrl("https://www.google.com")) ### Navigation Toolbar navtb = QToolBar("Navigation") navtb.setIconSize(QSize(16, 16)) self.addToolBar(navtb) # Back Action back_btn = QAction(QIcon('ui/black/filled/chevron_left-48dp.svg'), "Back", self) back_btn.setStatusTip("Back to previous page") back_btn.triggered.connect(self.browser.back) navtb.addAction(back_btn) # Forward Action next_btn = QAction(QIcon('ui/black/filled/chevron_right-48dp.svg'), "Forward", self) next_btn.setStatusTip("Forward to next page") next_btn.triggered.connect(self.browser.forward) navtb.addAction(next_btn) # Reload Action reload_btn = QAction(QIcon('ui/black/filled/refresh-48dp.svg'), "Reload", self) reload_btn.setStatusTip("Reload page") reload_btn.triggered.connect(self.browser.reload) navtb.addAction(reload_btn) # Home Action home_btn = QAction(QIcon('ui/black/filled/home-18dp.svg'), "Home", self) home_btn.setStatusTip("Go home") home_btn.triggered.connect(self.navigate_home) navtb.addAction(home_btn) # HTTPS Icon self.httpsicon = QAction( QIcon('ui/black/filled/no_encryption-48dp.svg'), '', self) self.httpsicon.setStatusTip("Page is not SSL protected") self.httpsicon.setEnabled(False) #self.httpsicon.setPixmap(QPixmap('ui/black/filled/no_encryption-18dp.svg')) navtb.addAction(self.httpsicon) # URL Bar self.urlbar = QLineEdit() self.urlbar.returnPressed.connect(self.navigate_to_url) navtb.addWidget(self.urlbar) # Load stop Action stop_btn = QAction(QIcon('ui/black/filled/close-48dp.svg'), "Stop", self) stop_btn.setStatusTip("Stop loading current page") stop_btn.triggered.connect(self.browser.stop) navtb.addAction(stop_btn) # Updates self.browser.urlChanged.connect(self.update_urlbar) self.browser.loadFinished.connect(self.update_title) ### File Menu file_menu = self.menuBar().addMenu("&File") # Open Action open_file_action = QAction( QIcon('ui/black/filled/folder_open-48dp.svg'), "Open file...", self) open_file_action.setStatusTip('&Open from file') open_file_action.triggered.connect(self.open_file) file_menu.addAction(open_file_action) # Save Action save_file_action = QAction(QIcon('ui/black/filled/save-48dp.svg'), "Save file...", self) save_file_action.setText('&Save to file') save_file_action.triggered.connect(self.save_file) file_menu.addAction(save_file_action) ### Help Menu help_menu = self.menuBar().addMenu("&Help") # About dialog Action about_action = QAction(QIcon('ui/black/filled/help-48dp.svg'), "&About PyBrowse", self) about_action.setStatusTip("Find out more about PyBrowse") # Hungry! about_action.triggered.connect(self.about) help_menu.addAction(about_action) # Visit official site Action navigate_mozarella_action = QAction( QIcon('ui/black/filled/language-48dp.svg'), "PyBrowse &Homepage", self) navigate_mozarella_action.setStatusTip("Go to PyBrowse Homepage") navigate_mozarella_action.triggered.connect(self.navigate_page) help_menu.addAction(navigate_mozarella_action) self.setCentralWidget(self.browser) self.show()
def _onMessageActionTriggered(self, message, action): if action == "open_browser": QDesktopServices.openUrl(QUrl(self._base_url))
def loadPage(self): move_url = QUrl(self.url_edit.text()) self.browser.load(move_url) self.updateUrl
def test_version(tabbed_browser, qapp): utilcmds.version(win_id=0) assert tabbed_browser.loaded_url == QUrl('qute://version/')
def openURL(self, text): QDesktopServices.openUrl(QUrl(text))