def restore_directory_state(self, fname): """Restore directory expanded state""" root = osp.normpath(to_text_string(fname)) if not osp.exists(root): # Directory has been (re)moved outside Spyder return for basename in os.listdir(root): path = osp.normpath(osp.join(root, basename)) if osp.isdir(path) and path in self.__expanded_state: self.__expanded_state.pop(self.__expanded_state.index(path)) if self._to_be_loaded is None: self._to_be_loaded = [] self._to_be_loaded.append(path) self.setExpanded(self.get_index(path), True) if not self.__expanded_state and not is_pyqt46: self.fsmodel.directoryLoaded.disconnect( self.restore_directory_state)
def delete_file(self, fname, multiple, yes_to_all): """Delete file.""" # if multiple: # buttons = ( # QMessageBox.Yes | QMessageBox.YesAll | QMessageBox.No | # QMessageBox.Cancel # ) # else: # buttons = QMessageBox.Yes | QMessageBox.No msg_box = MessageBoxQuestion( title="Delete", text="Do you really want to delete " "<b>{0}</b>?".format(osp.basename(fname)), ) if msg_box.exec_(): yes_to_all = True else: return False # if answer == QMessageBox.No: # return yes_to_all # elif answer == QMessageBox.Cancel: # return False # elif answer == QMessageBox.YesAll: # yes_to_all = True try: if osp.isfile(fname): misc.remove_file(fname) self.sig_removed.emit(fname) else: self.remove_tree(fname) self.sig_removed_tree.emit(fname) return yes_to_all except EnvironmentError as error: action_str = 'delete' msg_box = MessageBoxError( text="<b>Unable to %s <i>%s</i></b>" "<br><br>Error message:<br>%s" % (action_str, fname, to_text_string(error)), title='Project Explorer', ) msg_box.exec_() return False
def local_test(): # pragma: no cover """Run local test.""" from anaconda_navigator.utils.py3compat import to_text_string from anaconda_navigator.utils.qthelpers import qapplication app = qapplication(test_time=5) widget = ListWidgetContent() widget.show() for i in range(10): item = ListItemContent(title='Title ' + str(i), description='Description', summary='Summary', tags=['social'], subtitle='subtitle', uri=to_text_string(i)) widget.addItem(item) widget.update_style_sheet() app.exec_()
def _write(self, fp): """ Private write method for Python 2 The one from configparser fails for non-ascii Windows accounts """ if self._defaults: fp.write("[%s]\n" % cp.DEFAULTSECT) for (key, value) in self._defaults.items(): fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in self._sections: fp.write("[%s]\n" % section) for (key, value) in self._sections[section].items(): if key == "__name__": continue if (value is not None) or (self._optcre == self.OPTCRE): value = to_text_string(value) key = " = ".join((key, value.replace('\n', '\n\t'))) fp.write("%s\n" % (key)) fp.write("\n")
def create_new_file(self, current_path, title, filters, create_func): """Create new file Returns True if successful""" if current_path is None: current_path = '' if osp.isfile(current_path): current_path = osp.dirname(current_path) self.parent_widget.redirect_stdio.emit(False) fname, _selfilter = getsavefilename(self, title, current_path, filters) self.parent_widget.redirect_stdio.emit(True) if fname: try: create_func(fname) return fname except EnvironmentError as error: QMessageBox.critical( self, _("New file"), _("<b>Unable to create file <i>%s</i>" "</b><br><br>Error message:<br>%s") % (fname, to_text_string(error)))
def __init__(self, title='', text='', value=None, value_type=None): """Base message box dialog.""" super(InputDialog, self).__init__() # Widgets self.label = LabelBase(text) self.text = LineEditBase() self.button_ok = ButtonPrimary('Ok') self.button_cancel = ButtonNormal('Cancel') # Widget setup self.setWindowTitle(to_text_string(title)) if value: self.text.setText(str(value)) # Layouts layout = QVBoxLayout() layout_text = QHBoxLayout() layout_text.addWidget(self.label) layout_text.addWidget(SpacerHorizontal()) layout_text.addWidget(self.text) layout_buttons = QHBoxLayout() layout_buttons.addStretch() layout_buttons.addWidget(self.button_cancel) layout_buttons.addWidget(SpacerHorizontal()) layout_buttons.addWidget(self.button_ok) layout.addLayout(layout_text) layout.addWidget(SpacerVertical()) layout.addWidget(SpacerVertical()) layout.addLayout(layout_buttons) self.setLayout(layout) # Signals self.button_ok.clicked.connect(self.accept) self.button_cancel.clicked.connect(self.reject)
def _write(self, fp): """Private write method for Python 2. The one from configparser fails for non-ascii Windows accounts. """ if self._defaults: fp.write("[{section}]\n".format(section=cp.DEFAULTSECT)) for (key, value) in self._defaults.items(): write_value = str(value).replace('\n', '\n\t') fp.write("{key} = {value}\n".format(key=key, value=write_value)) fp.write("\n") for section in self._sections: fp.write("[{section}]\n".format(section=section)) for (key, value) in self._sections[section].items(): if key == "__name__": continue if (value is not None) or (self._optcre == self.OPTCRE): value = to_text_string(value) key = " = ".join((key, value.replace('\n', '\n\t'))) fp.write("{0}\n".format(key)) fp.write("\n")
def _is_valid_api_url(self, url, verify=None): """Callback for is_valid_api_url.""" # Check response is a JSON with ok: 1 data = {} if verify is None: verify_value = self._client_api.get_ssl() else: verify_value = verify try: r = requests.get( url, proxies=self.proxy_servers, verify=verify_value, timeout=self.DEFAULT_TIMEOUT, ) content = to_text_string(r.content, encoding='utf-8') data = json.loads(content) except Exception as error: logger.error(str(error)) return data.get('ok', 0) == 1
def _get_api_info(self, url): """Callback.""" data = { "api_url": url, "api_docs_url": "https://api.anaconda.org/docs", "conda_url": "https://conda.anaconda.org/", "main_url": "https://anaconda.org/", "pypi_url": "https://pypi.anaconda.org/", "swagger_url": "https://api.anaconda.org/swagger.json", } try: r = requests.get( url, proxies=self.proxy_servers, verify=self._client_api.get_ssl(), timeout=self.DEFAULT_TIMEOUT, ) content = to_text_string(r.content, encoding='utf-8') new_data = json.loads(content) data['conda_url'] = new_data.get('conda_url', data['conda_url']) except Exception as error: logger.error(str(error)) return data
def handle_qbytearray(obj, encoding): """Qt/Python3 compatibility helper.""" if isinstance(obj, QByteArray): obj = obj.data() return to_text_string(obj, encoding=encoding)
def __init__( self, name=None, display_name=None, description=None, command=None, versions=None, image_path=None, prefix=None, needs_license=False, non_conda=False, ): """Item with custom widget for the applications list.""" super(ListItemApplication, self).__init__() self.api = AnacondaAPI() self.prefix = prefix self.name = name self.display_name = display_name if display_name else name self.url = '' self.expired = False self.needs_license = needs_license self.description = description self.command = command self.versions = versions self.image_path = image_path if image_path else ANACONDA_ICON_256_PATH self.style_sheet = None self.timeout = 2000 self.non_conda = non_conda self._vscode_version_value = None # Widgets self.button_install = ButtonApplicationInstall("Install") # or Try! self.button_launch = ButtonApplicationLaunch("Launch") self.button_options = ButtonApplicationOptions() self.label_license = LabelApplicationLicense('') self.button_license = ButtonApplicationLicense('') self.label_icon = LabelApplicationIcon() self.label_name = LabelApplicationName(self.display_name) self.label_description = LabelApplicationDescription(self.description) self.button_version = ButtonApplicationVersion( to_text_string(self.version)) self.menu_options = QMenu('Application options') self.menu_versions = QMenu('Install specific version') self.pixmap = QPixmap(self.image_path) self.timer = QTimer() self.widget = WidgetApplication() self.frame_spinner = FrameApplicationSpinner() self.spinner = NavigatorSpinner(self.widget, total_width=16) lay = QHBoxLayout() lay.addWidget(self.spinner) self.frame_spinner.setLayout(lay) # Widget setup self.button_version.setFocusPolicy(Qt.NoFocus) self.button_version.setEnabled(True) self.label_description.setAlignment(Qt.AlignCenter) self.timer.setInterval(self.timeout) self.timer.setSingleShot(True) self.label_icon.setPixmap(self.pixmap) self.label_icon.setScaledContents(True) # important on High DPI! self.label_icon.setMaximumWidth(self.ICON_SIZE) self.label_icon.setMaximumHeight(self.ICON_SIZE) self.label_icon.setAlignment(Qt.AlignCenter) self.label_name.setAlignment(Qt.AlignCenter) self.label_name.setWordWrap(True) self.label_description.setWordWrap(True) self.label_description.setAlignment(Qt.AlignTop | Qt.AlignHCenter) self.frame_spinner.setVisible(False) # Layouts layout_spinner = QHBoxLayout() layout_spinner.addWidget(self.button_version, 0, Qt.AlignCenter) layout_spinner.addWidget(self.frame_spinner, 0, Qt.AlignCenter) layout_license = QHBoxLayout() layout_license.addStretch() layout_license.addWidget(self.label_license, 0, Qt.AlignCenter) layout_license.addWidget(self.button_license, 0, Qt.AlignCenter) layout_license.addStretch() layout_main = QVBoxLayout() layout_main.addWidget(self.button_options, 0, Qt.AlignRight) layout_main.addWidget(self.label_icon, 0, Qt.AlignCenter) layout_main.addWidget(self.label_name, 0, Qt.AlignCenter) layout_main.addLayout(layout_spinner) layout_main.addLayout(layout_license) layout_main.addWidget(self.label_description, 0, Qt.AlignCenter) layout_main.addWidget(self.button_launch, 0, Qt.AlignCenter) layout_main.addWidget(self.button_install, 0, Qt.AlignCenter) self.widget.setLayout(layout_main) self.widget.setStyleSheet(load_style_sheet()) self.setSizeHint(self.widget_size()) # This might help with visual quirks on the home screen self.widget.setMinimumSize(self.widget_size()) # Signals self.button_install.clicked.connect(self.install_application) self.button_launch.clicked.connect(self.launch_application) self.button_options.clicked.connect(self.actions_menu_requested) self.button_license.clicked.connect(self.launch_url) self.timer.timeout.connect(self._application_launched) # Setup self.update_status()
def __init__(self, type_, error='', title='', text='', learn_more=None): """Base message box dialog.""" super(MessageBox, self).__init__() from anaconda_navigator.utils.analytics import GATracker self.tracker = GATracker() self.label_text = QLabel(to_text_string(text)) self.textbox_error = QTextEdit() self.button_ok = ButtonPrimary('Ok') self.button_yes = ButtonPrimary('Yes') self.button_no = ButtonNormal('No') self.button_copy = ButtonNormal('Copy text') self.button_learn = ButtonNormal('Learn more') self.button_remove = ButtonDanger('Remove') self.button_cancel = ButtonNormal('Cancel') self.button_send = ButtonNormal('Report Issue', parent=self) self.label_text.setOpenExternalLinks(False) self.label_text.setWordWrap(True) self.label_text.linkActivated.connect(self.url_clicked) self.textbox_error.setReadOnly(True) self.textbox_error.setFrameStyle(QTextEdit.Plain) self.textbox_error.setFrameShape(QTextEdit.NoFrame) self.setMinimumWidth(260) self.textbox_error.verticalScrollBar().show() self.setWindowTitle(to_text_string(title)) error = to_text_string(error).split('\n') error = '<br>'.join(error) self.textbox_error.setText(error) # Layouts layout = QVBoxLayout() layout.addWidget(self.label_text) layout.addWidget(SpacerVertical()) if error: layout.addWidget(self.textbox_error) layout.addWidget(SpacerVertical()) layout.addWidget(self.button_copy) layout.addWidget(SpacerVertical()) layout.addWidget(SpacerVertical()) layout_buttons = QHBoxLayout() layout_buttons.addStretch() layout.addLayout(layout_buttons) self.layout = layout self.setLayout(layout) # Signals self.button_copy.clicked.connect(self.copy_text) self.button_ok.clicked.connect(self.accept) self.button_yes.clicked.connect(self.accept) self.button_no.clicked.connect(self.reject) self.button_remove.clicked.connect(self.accept) self.button_cancel.clicked.connect(self.reject) self.button_send.clicked.connect(self.send) # Setup self.button_learn.setVisible(bool(learn_more)) if bool(learn_more): layout_buttons.addWidget(self.button_learn) layout_buttons.addWidget(SpacerHorizontal()) self.button_learn.clicked.connect( lambda: self.show_url(learn_more) ) if type_ == self.ERROR_BOX: layout_buttons.addWidget(self.button_send) layout_buttons.addWidget(SpacerHorizontal()) layout_buttons.addWidget(self.button_ok) self.button_yes.setVisible(False) self.button_no.setVisible(False) self.button_remove.setVisible(False) self.button_cancel.setVisible(False) elif type_ == self.INFORMATION_BOX: layout_buttons.addWidget(self.button_ok) self.button_yes.setVisible(False) self.button_no.setVisible(False) self.textbox_error.setVisible(False) self.button_copy.setVisible(False) self.button_remove.setVisible(False) self.button_cancel.setVisible(False) elif type_ == self.QUESTION_BOX: layout_buttons.addStretch() layout_buttons.addWidget(self.button_no) layout_buttons.addWidget(SpacerHorizontal()) layout_buttons.addWidget(self.button_yes) layout_buttons.addWidget(SpacerHorizontal()) self.textbox_error.setVisible(False) self.button_ok.setVisible(False) self.button_copy.setVisible(False) self.button_remove.setVisible(False) self.button_cancel.setVisible(False) elif type_ == self.REMOVE_BOX: layout_buttons.addStretch() layout_buttons.addWidget(self.button_cancel) layout_buttons.addWidget(SpacerHorizontal()) layout_buttons.addWidget(self.button_remove) layout_buttons.addWidget(SpacerHorizontal()) self.textbox_error.setVisible(False) self.button_ok.setVisible(False) self.button_copy.setVisible(False) self.button_yes.setVisible(False) self.button_no.setVisible(False) self.button_send.setVisible(False) self.layout_buttons = layout_buttons
def __init__(self, name=None, description=None, command=None, pixmap=None, version=None, versions=None, path=None, dev_tool=True, prefix=None, is_conda_app=False, packages_widget=None): super(ListItemApplication, self).__init__() self.api = AnacondaAPI() self.command = command self.dev_tool = dev_tool self.installed = False self.is_conda_app = is_conda_app self.name = name self.path = path self.pixmap = pixmap if pixmap else QPixmap(ANACONDA_ICON_64_PATH) self.prefix = prefix self.timeout = 10000 # In miliseconds self.version = version self.versions = versions self.packages_widget = packages_widget # Widgets self.button_install = ButtonApplicationInstall("Install") self.button_launch = ButtonApplicationLaunch("Launch") self.button_options = ButtonApplicationOptions() self.label_icon = LabelApplicationIcon() self.label_name = LabelApplicationName(name) self.label_description = LabelApplicationDescription(description) # self.label_update = LabelApplicationUpdate() self.button_version = ButtonApplicationVersion(to_text_string(version)) self.label_spinner = LabelApplicationSpinner() # self.label_version = LabelApplicationVersion(to_text_string(version)) self.menu_options = QMenu('Application options') self.menu_versions = QMenu('Install specific version') self.movie_spinner = QMovie(SPINNER_WHITE_16_PATH) self.timer = QTimer() self.widget = WidgetApplication() # Widget setup self.button_version.setFocusPolicy(Qt.NoFocus) self.label_name.setToolTip(description) self.label_description.setAlignment(Qt.AlignCenter) self.movie_spinner.start() self.timer.setInterval(self.timeout) self.timer.setSingleShot(True) self.label_icon.setToolTip(description) self.label_icon.setPixmap( self.pixmap.scaled(self.ICON_SIZE, self.ICON_SIZE, Qt.KeepAspectRatio, Qt.SmoothTransformation)) self.label_icon.setAlignment(Qt.AlignCenter) self.label_name.setAlignment(Qt.AlignCenter) self.label_name.setWordWrap(True) self.label_description.setWordWrap(True) self.label_description.setAlignment(Qt.AlignTop | Qt.AlignHCenter) self.label_spinner.setVisible(False) self.label_spinner.setMinimumWidth(16) self.label_spinner.setMinimumHeight(16) # Layouts layout = QVBoxLayout() layout.addWidget(self.button_options, 0, Qt.AlignRight) layout.addWidget(self.label_icon, 0, Qt.AlignCenter) layout.addWidget(self.label_name, 0, Qt.AlignCenter) layout.addWidget(self.label_description, 0, Qt.AlignCenter) # hlayout = QHBoxLayout() # hlayout.addWidget(self.label_update) # hlayout.addWidget(self.label_version) # layout.addLayout(hlayout) # layout.addWidget(self.label_version, 0, Qt.AlignCenter) layout.addWidget(self.button_version, 0, Qt.AlignCenter) layout.addWidget(self.label_spinner, 0, Qt.AlignCenter) layout.addWidget(self.button_launch, 0, Qt.AlignCenter) layout.addWidget(self.button_install, 0, Qt.AlignCenter) self.widget.setLayout(layout) self.widget.setStyleSheet(load_style_sheet()) self.setSizeHint(self.widget.sizeHint()) # Signals self.button_install.clicked.connect(self.install_application) self.button_launch.clicked.connect(self.launch_application) self.button_options.clicked.connect(self.actions_menu_requested) self.timer.timeout.connect(self._application_launched) # Setup self.update_status()
def filter_changed(self): """Trigger the filter.""" group = self._filterbox text = self._searchbox if group in [C.ALL]: group = '-'.join([ to_text_string(C.INSTALLED), to_text_string(C.UPGRADABLE), to_text_string(C.NOT_INSTALLED), to_text_string(C.DOWNGRADABLE), to_text_string(C.MIXGRADABLE) ]) elif group in [C.INSTALLED]: group = '-'.join([ to_text_string(C.INSTALLED), to_text_string(C.UPGRADABLE), to_text_string(C.DOWNGRADABLE), to_text_string(C.MIXGRADABLE) ]) elif group in [C.UPGRADABLE]: group = '-'.join( [to_text_string(C.UPGRADABLE), to_text_string(C.MIXGRADABLE)]) elif group in [C.DOWNGRADABLE]: group = '-'.join([ to_text_string(C.DOWNGRADABLE), to_text_string(C.MIXGRADABLE) ]) elif group in [C.SELECTED]: group = '-'.join([ to_text_string(C.ACTION_INSTALL), to_text_string(C.ACTION_REMOVE), to_text_string(C.ACTION_UPGRADE), to_text_string(C.ACTION_DOWNGRADE), ]) else: group = to_text_string(group) if self.proxy_model is not None: self.proxy_model.set_filter(text, group) self.resize_rows() # Update label count count = self.verticalHeader().count() if count == 0: count_text = _("0 packages available ") elif count == 1: count_text = _("1 package available ") elif count > 1: count_text = to_text_string(count) + _(" packages available ") if text != '': count_text = count_text + _('matching "{0}"').format(text) # Give information on selected packages selected_text = '' if self.source_model: action_count = self.source_model.get_action_count() if action_count: plural = 's' if action_count != 1 else '' selected_text = '{0} package{1} selected'.format( action_count, plural) self.sig_status_updated.emit(count_text, selected_text, None, None)
def create_script(fname): """Create a new Python script""" text = os.linesep.join(["# -*- coding: utf-8 -*-", "", ""]) encoding.write(to_text_string(text), fname, 'utf-8')
def get_filename(self, index): """Return filename associated with *index*""" if index: return osp.normpath(to_text_string(self.fsmodel.filePath(index)))
def update_history(self, directory): """Update browse history""" directory = osp.abspath(to_text_string(directory)) if directory in self.history: self.histindex = self.history.index(directory)
def filter_status(row, text, status): """Filter status helper function.""" test1 = to_text_string(row[C.COL_STATUS]) in to_text_string(status) test2 = to_text_string(row[C.COL_ACTION]) in to_text_string(status) return test1 or test2
def setup_filter(self, root_path, path_list): """Setup proxy model filter parameters""" self.root_path = osp.normpath(to_text_string(root_path)) self.path_list = [osp.normpath(to_text_string(p)) for p in path_list] self.invalidateFilter()
def search_string_changed(self, text): """Update the search string text.""" text = to_text_string(text) self._searchbox = text self.filter_changed()
def get_filename(self, index): """Return filename from index""" if index: path = self.fsmodel.filePath(self.proxymodel.mapToSource(index)) return osp.normpath(to_text_string(path))