svg_ok = True debut, fin = self.get_bounds() caracteres = self.get_slice(debut, fin, False) try: file = open(self.nomfichier, "w") file.write(caracteres) file.close() resultat = True self.set_modified(False) except IOError, (num_err, msg_err): erreur = "Erreur d'ecriture dans '%s': %s" % (self.nomfichier, msg_err) fenetre = TestTexte.pile_fenetre_active.recuperer() dialogue = gtk.MessageDialog(fenetre, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, erreur) dialogue.run() dialogue.destroy() if not resultat and svg_ok: try: os.rename(nomfichier_svg, self.nomfichier) except OSError, (num_err, msg_err): erreur = "Impossible de restaurer la copie de sauvegarde '%s' de '%s': %s\nLa copie de sauvegarde '%s' n'a pas ete modifiee." % ( nomfichier_svg, self.nomfichier, msg_err, nomfichier_svg) fenetre = TestTexte.pile_fenetre_active.recuperer() dialogue = gtk.MessageDialog(fenetre, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, erreur) dialogue.run()
def show_error(message, wnd=None): md = gtk.MessageDialog(wnd, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, message) md.run() md.destroy()
return False # uninstall the timeout # if feof(image_stream) self.pixbuf_loader = None else: # if(image_stream) ... try: self.image_stream = open(ALPHA_IMAGE, "rb") except IOError, error: error_message = "Unable to open image file 'alphatest.png' : %s" dialog = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, error_message % error) dialog.connect("response", lambda d, r: d.destroy()) dialog.show() self.load_timeout = 0 return False # uninstall the timeout if self.pixbuf_loader is not None: self.pixbuf_loader.close() self.pixbuf_loader = None self.pixbuf_loader = gtk.gdk.PixbufLoader()
def __init__(self, parent, filename, claimtable=None): logging.debug("Launching ClaimTableWizard") self.filename = filename self.parent = parent if not claimtable: self.re_import = False self.claimtable = self.parent.on_new_table(self, data=self.filename) _, fil = os.path.split(self.filename) self.claimtable.set_tab_text(fil) else: self.re_import = True self.claimtable = claimtable # Build the dialog self.dialog = gtk.Dialog(title="Import as...") self.dialog.connect("delete-event", self.on_cancel) # Open the file try: self.f = open(self.filename, "rb") except (OSError, IOError) as e: logging.error("ClaimTableWizard: unable to open csv file " + self.filename) logging.error(e) error_msg = gtk.MessageDialog(self.parent.window, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, \ "Can not open csv file") error_msg.format_secondary_text("Make sure %s is readable and try again." \ % self.filename) error_msg.run() error_msg.destroy() self.claimtable.destroy() return # Build the treeview model self.reader = csv.reader(self.f) try: self.liststore = gtk.ListStore(str, str) headers = self.reader.next() for h in headers: self.liststore.append([h, "Not imported"]) treeview = gtk.TreeView(self.liststore) treeview.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH) except StopIteration: logging.error("ClaimTableWizard: unable to parse file " + self.filename) error_msg = gtk.MessageDialog(self.parent.window, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, \ "Unable to parse file") error_msg.format_secondary_text( "Please select another file and try again.") error_msg.run() error_msg.destroy() self.claimtable.destroy() return # Open the file with the options file mapping settings if not claimtable and self.claimtable.options.items("Mapping"): self.open_w_mapping() return else: self.open_w_mapping() # Re-import the table # Build column one cell = gtk.CellRendererText() column_one = gtk.TreeViewColumn("Column", cell, text=0) treeview.append_column(column_one) # Build column two, a combo box to select the appropriate header combo = gtk.CellRendererCombo() combolist = gtk.ListStore( *[str for t in tables.table_layout["header"]]) combobox = gtk.ComboBox(combolist) combobox.append_text("Not imported") for h in tables.table_layout["header"]: combobox.append_text(h) combo.set_property("editable", True) combo.set_property("model", combolist) combo.set_property("text-column", 0) combo.set_property("has-entry", False) combo.connect("edited", self.on_combo_changed) column_two = gtk.TreeViewColumn("Import as", combo, text=1) treeview.append_column(column_two) # Build the province selector radiobuttons provinces = list(self.claimtable.claimtable.supported().keys()) def change_province(button): self.claimtable.options.set("Settings", "province", button.get_label()) province_frame = gtk.HBox() label = gtk.Label("Province/State: ") button_zero = gtk.RadioButton(label=provinces[0]) button_zero.connect("pressed", change_province) province_frame.pack_end(button_zero, False, False, 0) for p in provinces[1:]: button = gtk.RadioButton(label=p, group=button_zero) if self.claimtable.options.get("Settings", "province") == p: button.set_active(True) button.connect("pressed", change_province) province_frame.pack_end(button, False, False, 0) province_frame.pack_end(label, False, False, 0) # Build the bottom frame that holds the apply/cancel buttons and the province radiobuttons bottom_frame = gtk.HBox() cancel_button = gtk.Button(label="Cancel", stock=gtk.STOCK_CANCEL) cancel_button.connect("clicked", self.on_cancel) apply_button = gtk.Button(label="Import", stock=gtk.STOCK_APPLY) apply_button.connect("clicked", self.on_apply) bottom_frame.pack_end(apply_button, False, False, 0) bottom_frame.pack_end(cancel_button, False, False, 0) bottom_frame.pack_end(province_frame, False, False, 20) # Pack the dialog self.dialog.vbox.pack_start(treeview, True, True, 0) self.dialog.vbox.pack_end(bottom_frame, True, True, 0) self.dialog.show_all() height = treeview.get_cell_area(0, column_one).height self.dialog.resize(320, height * len(headers)) response = self.dialog.run() self.dialog.destroy() if response == gtk.RESPONSE_CANCEL: # Hit the 'Cancel' button... if not claimtable: self.claimtable.destroy()
def not_root_dialog(): errorMB = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("You are not root.")) ret = errorMB.run() errorMB.destroy() return ret
def __init__(self, partitions, diskset, intf, parent, origrequest, isNew=0): self.partitions = partitions self.diskset = diskset self.origrequest = origrequest self.isNew = isNew self.intf = intf self.parent = parent self.dialog = None # # start of editRaidRequest # availraidparts = self.partitions.getAvailRaidPartitions( origrequest, self.diskset) # if no raid partitions exist, raise an error message and return if len(availraidparts) < 2: dlg = gtk.MessageDialog( self.parent, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("At least two unused software RAID " "partitions are needed to create " "a RAID device.\n\n" "First create at least two partitions " "of type \"software RAID\", and then " "select the \"RAID\" option again.")) gui.addFrame(dlg) dlg.show_all() dlg.set_position(gtk.WIN_POS_CENTER) dlg.run() dlg.destroy() return if isNew: tstr = _("Make RAID Device") else: try: tstr = _("Edit RAID Device: /dev/md%s") % ( origrequest.raidminor, ) except: tstr = _("Edit RAID Device") dialog = gtk.Dialog(tstr, self.parent) gui.addFrame(dialog) dialog.add_button('gtk-cancel', 2) dialog.add_button('gtk-ok', 1) dialog.set_position(gtk.WIN_POS_CENTER) maintable = gtk.Table() maintable.set_row_spacings(5) maintable.set_col_spacings(5) row = 0 # Mount Point entry lbl = createAlignedLabel(_("_Mount Point:")) maintable.attach(lbl, 0, 1, row, row + 1) self.mountCombo = createMountPointCombo(origrequest) lbl.set_mnemonic_widget(self.mountCombo.entry) maintable.attach(self.mountCombo, 1, 2, row, row + 1) row = row + 1 # Filesystem Type lbl = createAlignedLabel(_("File System _Type:")) maintable.attach(lbl, 0, 1, row, row + 1) if not origrequest.getPreExisting(): (self.fstypeoption, self.fstypeoptionMenu) = createFSTypeMenu( origrequest.fstype, fstypechangeCB, self.mountCombo, ignorefs=["software RAID", "PPC PReP Boot"]) lbl.set_mnemonic_widget(self.fstypeoption) else: if origrequest.fstype.getName(): self.fstypeoption = gtk.Label(origrequest.fstype.getName()) else: self.fstypeoption = gtk.Label(_("Unknown")) maintable.attach(self.fstypeoption, 1, 2, row, row + 1) row = row + 1 # raid minors lbl = createAlignedLabel(_("RAID _Device:")) maintable.attach(lbl, 0, 1, row, row + 1) if not origrequest.getPreExisting(): availminors = self.partitions.getAvailableRaidMinors()[:16] reqminor = origrequest.raidminor if reqminor is not None: availminors.append(reqminor) availminors.sort() (self.minorOption, self.minorOptionMenu) = self.createRaidMinorMenu( availminors, reqminor) lbl.set_mnemonic_widget(self.minorOption) else: self.minorOption = gtk.Label("md%s" % (origrequest.raidminor, )) maintable.attach(self.minorOption, 1, 2, row, row + 1) row = row + 1 # raid level lbl = createAlignedLabel(_("RAID _Level:")) maintable.attach(lbl, 0, 1, row, row + 1) if not origrequest.getPreExisting(): # Create here, pack below numparts = len(availraidparts) if origrequest.raidspares: nspares = origrequest.raidspares else: nspares = 0 if origrequest.raidlevel: maxspares = raid.get_raid_max_spares(origrequest.raidlevel, numparts) else: maxspares = 0 spareAdj = gtk.Adjustment(value=nspares, lower=0, upper=maxspares, step_incr=1) self.sparesb = gtk.SpinButton(spareAdj, digits=0) self.sparesb.set_data("numparts", numparts) if maxspares > 0: self.sparesb.set_sensitive(1) else: self.sparesb.set_value(0) self.sparesb.set_sensitive(0) else: self.sparesb = gtk.Label(str(origrequest.raidspares)) if not origrequest.getPreExisting(): (self.leveloption, self.leveloptionmenu) = \ self.createRaidLevelMenu(availRaidLevels, origrequest.raidlevel) lbl.set_mnemonic_widget(self.leveloption) else: self.leveloption = gtk.Label(origrequest.raidlevel) maintable.attach(self.leveloption, 1, 2, row, row + 1) row = row + 1 # raid members lbl = createAlignedLabel(_("_RAID Members:")) maintable.attach(lbl, 0, 1, row, row + 1) # XXX need to pass in currently used partitions for this device (self.raidlist, sw) = self.createAllowedRaidPartitionsList( availraidparts, origrequest.raidmembers, origrequest.getPreExisting()) lbl.set_mnemonic_widget(self.raidlist) self.raidlist.set_size_request(275, 80) maintable.attach(sw, 1, 2, row, row + 1) row = row + 1 if origrequest.getPreExisting(): self.raidlist.set_sensitive(gtk.FALSE) # number of spares - created widget above lbl = createAlignedLabel(_("Number of _spares:")) maintable.attach(lbl, 0, 1, row, row + 1) maintable.attach(self.sparesb, 1, 2, row, row + 1) lbl.set_mnemonic_widget(self.sparesb) row = row + 1 # format or not? self.formatButton = None self.fsoptionsDict = {} if (origrequest.fstype and origrequest.fstype.isFormattable() ) and not origrequest.getPreExisting(): self.formatButton = gtk.CheckButton(_("_Format partition?")) if origrequest.format == None or origrequest.format != 0: self.formatButton.set_active(1) else: self.formatButton.set_active(0) # it only makes sense to show this for preexisting RAID if origrequest.getPreExisting(): maintable.attach(self.formatButton, 0, 2, row, row + 1) row = row + 1 else: (row, self.fsoptionsDict) = createPreExistFSOptionSection( self.origrequest, maintable, row, self.mountCombo, showbadblocks=0) # put main table into dialog dialog.vbox.pack_start(maintable) dialog.show_all() self.dialog = dialog return
def ok_button_clicked(self, button): nfiles = len(self.files) if nfiles <= 0: return False folder = self.folder_entry.get_text() picture_duration = int(self.pdur_spinner.get_text()) if self.pdur_combo.get_active_text() == "min": picture_duration = picture_duration * 60 elif self.pdur_combo.get_active_text() == "hr": picture_duration = picture_duration * 60 * 60 transition_duration = int(self.tdur_spinner.get_text()) if self.tdur_combo.get_active_text() == "min": transition_duration = transition_duration * 60 elif self.tdur_combo.get_active_text() == "hr": transition_duration = transition_duration * 60 * 60 document = """<background><starttime><year>2009</year><month>08</month><day>04</day><hour>00</hour><minute>00</minute><second>00</second></starttime></background>""" dom = xml.dom.minidom.parseString(document) for i in range(0, nfiles): static = dom.createElement("static") duration = dom.createElement("duration") duration.appendChild(dom.createTextNode(str(picture_duration))) static.appendChild(duration) file = dom.createElement("file") file.appendChild(dom.createTextNode(self.files[i])) static.appendChild(file) dom.documentElement.appendChild(static) if transition_duration <= 0: continue transition = dom.createElement("transition") duration = dom.createElement("duration") duration.appendChild(dom.createTextNode(str(transition_duration))) transition.appendChild(duration) frm = dom.createElement("from") frm.appendChild(dom.createTextNode(self.files[i])) transition.appendChild(frm) to = dom.createElement("to") if i < nfiles - 1: to.appendChild(dom.createTextNode(self.files[i + 1])) else: to.appendChild(dom.createTextNode(self.files[0])) transition.appendChild(to) dom.documentElement.appendChild(transition) try: save_filename = os.path.join(folder, "background-1.xml") f = open(save_filename, 'w') f.write(dom.toxml("utf-8")) f.close() except IOError as (errno, strerror): try: save_filename = os.path.join(os.path.expanduser("~"), ".dynamic-wallpaper.xml") f = open(save_filename, 'w') f.write(dom.toxml("utf-8")) f.close() except Error as (errno, strerror): dialog = gtk.MessageDialog( parent=None, flags=gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK, message_format=strerror) dialog.set_title('Error') dialog.connect('response', lambda dialog, response: dialog.destroy()) dialog.run() return False
def check_version_cache_for_upgrade(): ''' Prompt user to offer to upgrade if cached latest MicroDrop version is newer than currently installed version. .. versionadded:: 0.7.8 ''' # Get currently installed `microdrop` package information. # # Example `installed_info`: # # {u'base_url': None, # u'build_number': 0, # u'build_string': u'0', # u'channel': u'sci-bots', # u'dist_name': u'microdrop-2.10.2-0', # u'name': u'microdrop', # u'platform': None, # u'version': u'2.10.2', # u'with_features_depends': None} try: installed_info = ch.package_version('microdrop', verbose=False) except NameError: # Installed MicroDrop Conda package not found (perhaps this is a # development environment?) return cached_path, cached_info = load_cached_version() latest_version = cached_info.get('version') installed_version = installed_info.get('version') # If cached latest MicroDrop version is more recent than the currently # installed version, prompt user to offer to upgrade. if all([GUI_AVAILABLE, not cached_info.get('ignore'), latest_version is not None]): if (pkg_resources.parse_version(latest_version) <= pkg_resources.parse_version(installed_version)): return # Display dialog. dialog = gtk.MessageDialog(type=gtk.MESSAGE_QUESTION) dialog.set_icon_from_file(ICON_PATH) dialog.set_title('Upgrade to MicroDrop v{}'.format(latest_version)) dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, "Not now", gtk.RESPONSE_NO, "Never", gtk.RESPONSE_CANCEL) dialog.set_markup('A new version of MicroDrop is available.\n\n' 'Would you like to upgrade to MicroDrop v{} (current' ' version: v{})?'.format(latest_version, installed_version)) response = dialog.run() dialog.destroy() if response == gtk.RESPONSE_CANCEL: # Ignore this specific version from now on. try: with cached_path.open('w') as output: cached_info = {'version': latest_version, 'ignore': True} yaml.dump(cached_info, stream=output) print ('new version available: MicroDrop v{} (not installing ' 'now)'.format(latest_version)) except: logger.error('Error caching latest version.', exc_info=True) elif response == gtk.RESPONSE_YES: # User selected `Yes`, so upgrade MicroDrop, but restrict upgrade # to within the same major version. try: major_version = int(cre_version.match(installed_version) .group('major')) install_log_json = ch.conda_exec('install', '--json', 'microdrop >={}, <{}' .format(major_version, major_version + 1)) install_response = json.loads(install_log_json) unlinked, linked = ch.install_info(install_response) print ch.format_install_info(unlinked, linked) try: # Remove stale cached MicroDrop version data. cached_path.remove() except: pass except: logger.error('Error upgrading MicroDrop.', exc_info=True)
print "Error connecting to tpfand: ", ex msgdialog = gtk.MessageDialog( None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _("Unable to connect to ThinkPad Fan Control daemon (tpfand).\n\n" "Please make sure you are running this program on a supported IBM/Lenovo ThinkPad, a recent thinkpad_acpi module is loaded with fan_control=1 and tpfand has been started." )) msgdialog.set_title(_("ThinkPad Fan Control Configuration")) msgdialog.run() exit(1) # check required daemon version daemon_version = controller.get_version() if daemon_version < build.required_daemon_version: msgdialog = gtk.MessageDialog( None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _("The version of the ThinkPad Fan Control daemon (tpfand) installed on your system is too old.\n\n" "This version of tpfan-admin requires tpfand %s or later, however tpfand %s is installed on your system." ) % (build.required_daemon_version, daemon_version)) msgdialog.set_title(_("ThinkPad Fan Control Configuration")) msgdialog.run() exit(2) # Load Glade file my_xml = gtk.glade.XML(build.data_dir + 'tpfan-admin.glade') # Load icons gtk.window_set_default_icon_from_file(build.data_dir + build.icon_filename) # Init dialogs about_dialog = my_xml.get_widget('aboutDialog') temperature_dialog = temperaturedialog.TemperatureDialog()
def message(self, data=None, type=gtk.BUTTONS_OK): msg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, type, data) rval = msg.run() msg.destroy() return rval
def load_profiles_info(profiles_path): ''' Load list of profiles from file. If file does not exist or list is empty, the profile list is initialized with the default profile directory path (creating a profile at the default location, if it does not already exist). .. versionchanged:: 0.1.post61 If profile already exists in the default profile path, but the profile does not match the MicroDrop major version, a default profile path is used that is specific to MicroDrop major version of the form ``MicroDrop-v<major_version>``. Parameters ---------- profiles_path : str Path to file containing list of profiles. Returns ------- df_profiles : pandas.DataFrame Table of MicroDrop profile descriptions including the columns: - ``path`` File system path to profile directory. - ``used_timestamp`` Most recent time that profile was launched. ''' profiles_path = ph.path(profiles_path) profiles_path.parent.makedirs_p() if profiles_path.exists(): with profiles_path.open('r') as input_: profiles_str = input_.read() try: profiles = [profile_i for profile_i in yaml.load(profiles_str) if ph.path(profile_i['path']).isdir()] except: logger.error('Error reading list of profiles from `%s`.', profiles_path, exc_info=True) profiles = [] else: profiles = [] default_profile_path = mpm.bin.get_plugins_directory().parent if default_profile_path.isdir(): try: # Verify default profile directory matches major MicroDrop version. verify_or_create_profile_version(default_profile_path) except VersionError: # Default profile path already exists, but profile does not match # MicroDrop major version. # Query the currently installed version of the MicroDrop Python package. installed_version_str = (pkg_resources .get_distribution('microdrop').version) major_version = get_major_version(installed_version_str) # Use default profile path specific to MicroDrop major version. default_profile_path = (default_profile_path.parent .joinpath('MicroDrop-v{}' .format(major_version))) if not profiles and not default_profile_path.isdir(): # No existing profiles. Create default profile. print ('No existing profiles. Create default profile at {}.' .format(default_profile_path)) create_config_directory(output_dir=default_profile_path) for sub_directory_i in ('devices', 'plugins'): default_profile_path.joinpath(sub_directory_i).makedirs_p() # Create a `RELEASE-VERSION` file and populate it with the installed # MicroDrop package version. release_version_path = default_profile_path.joinpath('RELEASE-VERSION') with release_version_path.open('w') as output: output.write(pkg_resources.get_distribution('microdrop').version) if GUI_AVAILABLE: major_version = installed_major_version() dialog = gtk.MessageDialog(type=gtk.MESSAGE_INFO) dialog.set_icon_from_file(ICON_PATH) dialog.set_title('New MicroDrop {} profile created' .format(major_version)) dialog.add_buttons(gtk.STOCK_OK, gtk.RESPONSE_OK) dialog.set_markup('No existing profiles for MicroDrop {}.\n\n' 'Created default profile at {}.' .format(major_version, default_profile_path)) dialog.run() dialog.destroy() if not profiles and default_profile_path.isdir(): # No profiles list found or empty profiles list. # # Use default profile path. profiles = [{'path': str(default_profile_path), 'used_timestamp': None}] df_profiles = pd.DataFrame(None, columns=SAVED_COLUMNS) df_profiles = import_profile(df_profiles, default_profile_path, parent=None) else: df_profiles = pd.DataFrame(profiles, columns=SAVED_COLUMNS) df_profiles.loc[df_profiles.used_timestamp == 'nan', 'used_timestamp'] = '' df_profiles.sort_values('used_timestamp', ascending=False, inplace=True) df_profiles.drop_duplicates(subset=['path'], inplace=True) return df_profiles
class gPodderDevicePlaylist(BuilderWidget): finger_friendly_widgets = [ 'btnCancelPlaylist', 'btnSavePlaylist', 'treeviewPlaylist' ] def new(self): self.linebreak = '\n' if self._config.mp3_player_playlist_win_path: self.linebreak = '\r\n' self.mountpoint = util.find_mount_point(self._config.mp3_player_folder) if self.mountpoint == '/': self.mountpoint = self._config.mp3_player_folder log('Warning: MP3 player resides on / - using %s as MP3 player root', self.mountpoint, sender=self) self.playlist_file = os.path.join( self.mountpoint, self._config.mp3_player_playlist_file) icon_theme = gtk.icon_theme_get_default() try: self.icon_new = icon_theme.load_icon(gtk.STOCK_NEW, 16, 0) except Exception, e: log('Icon missing from theme: %s', gtk.STOCK_NEW, sender=self) self.icon_new = None # add column two check_cell = gtk.CellRendererToggle() check_cell.set_property('activatable', True) check_cell.connect('toggled', self.cell_toggled) check_column = gtk.TreeViewColumn(_('Use'), check_cell, active=1) self.treeviewPlaylist.append_column(check_column) # add column three column = gtk.TreeViewColumn(_('Filename')) icon_cell = gtk.CellRendererPixbuf() column.pack_start(icon_cell, False) column.add_attribute(icon_cell, 'pixbuf', 0) filename_cell = gtk.CellRendererText() column.pack_start(filename_cell, True) column.add_attribute(filename_cell, 'text', 2) column.set_resizable(True) self.treeviewPlaylist.append_column(column) # Make treeview reorderable self.treeviewPlaylist.set_reorderable(True) # init liststore self.playlist = gtk.ListStore(gtk.gdk.Pixbuf, bool, str) self.treeviewPlaylist.set_model(self.playlist) # read device and playlist and fill the TreeView title = _('Reading files from %s') % self._config.mp3_player_folder message = _( 'Please wait your media file list is being read from device.') dlg = gtk.MessageDialog(self.main_window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_NONE) dlg.set_title(title) dlg.set_markup('<span weight="bold" size="larger">%s</span>\n\n%s' % (title, message)) dlg.show_all() threading.Thread(target=self.process_device, args=[dlg]).start()
def editDevice(self, button, iter): devName = self.network_device_entry.get_text() if self.network_device_store.get_value(iter, 0) != devName: if self.doesDeviceExist(devName) is None: return self.network_device_store.set_value(iter, 0, devName) if self.network_type_option_menu.get_active() == 0: self.network_device_store.set_value(iter, 1, "DHCP") elif self.network_type_option_menu.get_active() == 2: self.network_device_store.set_value(iter, 1, "BOOTP") else: if not self.deviceIsFilledIn(): text = (_("Please fill in the network information")) dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, text) dlg.set_position(gtk.WIN_POS_CENTER_ON_PARENT) dlg.set_modal(True) rc = dlg.run() dlg.destroy() return None if self.gw_entry.get_text() != "": try: socket.inet_pton(socket.AF_INET, self.gw_entry.get_text()) except: text = (_("Please enter a valid gateway address.")) dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, text) dlg.set_position(gtk.WIN_POS_CENTER_ON_PARENT) dlg.set_modal(True) rc = dlg.run() dlg.destroy() return None if self.nameserver_entry.get_text() != "": try: socket.inet_pton(socket.AF_INET, self.nameserver_entry.get_text()) except: text = (_("Please enter a valid nameserver address.")) dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, text) dlg.set_position(gtk.WIN_POS_CENTER_ON_PARENT) dlg.set_modal(True) rc = dlg.run() dlg.destroy() return None self.network_device_store.set_value(iter, 1, _("Static IP")) self.network_device_store.set_value( iter, 2, self.ip_entry.get_text().strip()) self.network_device_store.set_value( iter, 3, self.netmask_entry.get_text().strip()) self.network_device_store.set_value( iter, 4, self.gw_entry.get_text().strip()) self.network_device_store.set_value( iter, 5, self.nameserver_entry.get_text().strip()) self.resetDialog()
def run(self, id, activity=None): #TODO Convert to use activity... logging.debug(">>") try: uri = "http://api.openstreetmap.org/api/0.6/gpx/create" #URI for uploading traces to OSM if 'username' not in self.options or self.options[ 'username'] == "" or 'password' not in self.options or self.options[ 'password'] == "": logging.error("Must have username and password configured") raise Exception("Must have username and password configured") username = self.options['username'] password = self.options['password'] gpx_file = "%s/gpx/%s.gpx" % (self.conf_dir, id) if not os.path.isfile(gpx_file): raise Exception(str(gps_file) + ' File not found') #GPX file is ok and found, so open it logging.debug("GPX file: %s found, size: %d" % (gpx_file, os.path.getsize(gpx_file))) f = open(gpx_file, 'r') file_contents = f.read() #TODO Fix to use etree functionality..... if file_contents.find( "<?xml version='1.0' encoding='ASCII'?>") != -1: logging.debug( "GPX file: %s has ASCII encoding - updating to UTF-8 for OSM support" % gpx_file) f.close() #Close readonly file f = open(gpx_file, 'w') #and open file for writing file_contents = file_contents.replace( "<?xml version='1.0' encoding='ASCII'?>", "<?xml version='1.0' encoding='UTF-8'?>", 1) f.write(file_contents) #Write new content f.close() #Close f = open(gpx_file, 'r') #Reopen in readonly mode #Get extra info from user response = self.display_options_window() if not response == gtk.RESPONSE_ACCEPT: f.close() logging.debug("User abort") return if self.makeanon: logging.debug("User requested anonymizing of GPX data") f.close() #Close standard gpxfile gpx_file = self.make_gpx_private(gpx_file) f = open(gpx_file, 'r') #Open anonymous gpxfile in readonly mode fields = (("description", self.description), ("tags", self.tags), ("visibility", self.visibility)) logging.debug("Added fields: %s" % str(fields)) #Multipart encode the request boundary, body = self.multipart_encode(fields=fields, files=(("file", f), )) content_type = 'multipart/form-data; boundary=%s' % boundary #Finished with the file so close it f.close() #Add the http headers to the request h = httplib2.Http() headers = {'Content-Type': content_type} #Add basic authentication credentials to the request h.add_credentials(username, password) #Show user something is happening msg = _( "Posting GPX trace to Openstreetmap\n\nPlease wait this could take several minutes" ) md = gtk.MessageDialog(self.pytrainer_main.windowmain.window1, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, msg) md.set_title(_("Openstreetmap Extension Processing")) md.set_modal(True) md.show() while gtk.events_pending(): # This allows the GUI to update gtk.main_iteration() # before completion of this entire action logging.debug("before request posting") #POST request to OSM res, content = h.request(uri, 'POST', body=body, headers=headers) logging.debug("after request posting") logging.debug("Got response status: %s, reason: %s, content: %s" % (res.status, res.reason, content)) if res.reason == 'OK': res_msg = "Successfully posted to OSM.\nYou should get an email with the outcome of the upload soon\n\nTrace id is %s" % content else: res_msg = "Some error occured\nGot a status %s, reason %s\nContent was: %s" % ( res.status, res.reason, content) #Close 'Please wait' dialog md.destroy() #Show the user the result md = gtk.MessageDialog(self.pytrainer_main.windowmain.window1, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, res_msg) md.set_title(_("Openstreetmap Extension Upload Complete")) md.set_modal(False) md.run() md.destroy() except Exception as e: msg = _("Error while uploading file to OSM: " + str(e)) md = gtk.MessageDialog(self.pytrainer_main.windowmain.window1, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, msg) md.set_title(_("Openstreetmap Extension Error")) md.run() md.destroy() return finally: logging.debug("<<")
def crear_dialogo(self, texto, icono): dialog = gtk.MessageDialog(self.ventana, 0, icono, gtk.BUTTONS_OK, texto) response = dialog.run() if response == gtk.RESPONSE_OK: dialog.destroy()
def __init__(self): dummy = _('Timekpr Control Panel') dummy = _('Timekpr Client') gladefile = VAR['TIMEKPRSHARED'] + '/timekpr.glade' self.wTree = gtk.glade.XML(gladefile, 'mainwindow', APP_NAME) self.get_limit_spin() self.get_from_spin() self.get_to_spin() self.get_labels() self.singleLimits = self.wTree.get_widget("singleLimits") self.singleBoundaries = self.wTree.get_widget("singleBoundaries") self.limitCheck = self.wTree.get_widget("limitCheck") self.boundariesCheck = self.wTree.get_widget("boundariesCheck") self.userSelect = self.wTree.get_widget("userSelect") self.rewardSpin = self.wTree.get_widget("rewardSpin") self.labelrewardspin = self.wTree.get_widget("labelrewardspin") self.labeluserstatus = self.wTree.get_widget("labeluserstatus") self.limiticon = self.wTree.get_widget("imagelimited1") self.boundariesicon = self.wTree.get_widget("imagelimited2") self.alldayloginicon = self.wTree.get_widget("imagealldaylogin") self.lockedicon = self.wTree.get_widget("imagelocked") self.timeleftlabel = self.wTree.get_widget("timeleftlabel") self.extendLimitsButton = self.wTree.get_widget("extendLimitsButton") self.rewardButton = self.wTree.get_widget("rewardButton") self.clearallButton = self.wTree.get_widget( "ClearAllRestrictionsButton") self.resettimeButton = self.wTree.get_widget("ResetTimeButton") self.lockLabel = self.wTree.get_widget("labelunlockbutton") self.statusbar = self.wTree.get_widget("statusbar") self.statusbarCID = self.statusbar.get_context_id("timekprstatus") self.limits = [] dic = { "on_limitCheck_toggled": self.limitCheck_toggled, "on_boundariesCheck_toggled": self.boundariesCheck_toggled, "on_rewardButton_clicked": self.rewardButton_clicked, "on_extendLimitsButton_clicked": self.extendLimitsButton_clicked, "on_ClearAllRestrictionsButton_clicked": self.clearallrestrictions, "on_ResetTimeButton_clicked": self.resettimefile, "on_UnlockButton_clicked": self.lockunlockaccount, "on_apply_clicked": self.apply_clicked, "on_singleBoundaries_toggled": self.singleBoundariesCheck_toggled, "on_singleLimits_toggled": self.singleLimitsCheck_toggled, "on_userSelect_toggled": self.read_settings, "on_refresh_clicked": self.refreshButton_clicked, "on_cancel_clicked": self.cancel_clicked, "on_aboutmenuitem_select": self.showaboutdialog, 'gtk_main_quit': gtk.main_quit } self.wTree.signal_autoconnect(dic) #Using /etc/shadow spwd module for userinfo in getpwall(): if isnormal(userinfo[0]): self.userSelect.append_text(userinfo[0]) self.userSelect.set_active(0) #Ensure we have at least one available normal user if self.userSelect.get_active_text() is None: dlg = gtk.MessageDialog( None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _("You need to have at least one normal user available to configure timekpr" )) dlg.set_default_response(gtk.RESPONSE_CLOSE) dlg.run() dlg.destroy() exit( "Error: You need to have at least one normal user available to configure timekpr" ) self.read_settings(self) return
def initialise_view(self): if len(self.shortcircuit) == 0: # Set TreeViews self.liststorefs = gtk.ListStore(str, str, str, str, str, long, gobject.TYPE_PYOBJECT) list_filter = self.liststorefs.filter_new() list_sort = gtk.TreeModelSort(list_filter) list_sort.set_sort_column_id(1, gtk.SORT_ASCENDING) self.snaptreeview = self.xml.get_widget("snaplist") self.snaptreeview.set_model(self.liststorefs) self.snaptreeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE) cell0 = gtk.CellRendererText() cell1 = gtk.CellRendererText() cell2 = gtk.CellRendererText() cell3 = gtk.CellRendererText() cell4 = gtk.CellRendererText() cell5 = gtk.CellRendererText() typecol = gtk.TreeViewColumn(_("Type"), cell0, text=0) typecol.set_sort_column_id(0) typecol.set_resizable(True) typecol.connect("clicked", self.__on_treeviewcol_clicked, 0) self.snaptreeview.append_column(typecol) mountptcol = gtk.TreeViewColumn(_("Mount Point"), cell1, text=1) mountptcol.set_sort_column_id(1) mountptcol.set_resizable(True) mountptcol.connect("clicked", self.__on_treeviewcol_clicked, 1) self.snaptreeview.append_column(mountptcol) fsnamecol = gtk.TreeViewColumn(_("File System Name"), cell2, text=2) fsnamecol.set_sort_column_id(2) fsnamecol.set_resizable(True) fsnamecol.connect("clicked", self.__on_treeviewcol_clicked, 2) self.snaptreeview.append_column(fsnamecol) snaplabelcol = gtk.TreeViewColumn(_("Snapshot Name"), cell3, text=3) snaplabelcol.set_sort_column_id(3) snaplabelcol.set_resizable(True) snaplabelcol.connect("clicked", self.__on_treeviewcol_clicked, 3) self.snaptreeview.append_column(snaplabelcol) cell4.props.xalign = 1.0 creationcol = gtk.TreeViewColumn(_("Creation Time"), cell4, text=4) creationcol.set_sort_column_id(5) creationcol.set_resizable(True) creationcol.connect("clicked", self.__on_treeviewcol_clicked, 5) self.snaptreeview.append_column(creationcol) # Note to developers. # The second element is for internal matching and should not # be i18ned under any circumstances. typestore = gtk.ListStore(str, str) typestore.append([_("All"), "All"]) typestore.append([_("Backups"), "Backup"]) typestore.append([_("Snapshots"), "Snapshot"]) self.typefiltercombo = self.xml.get_widget("typefiltercombo") self.typefiltercombo.set_model(typestore) typefiltercomboCell = gtk.CellRendererText() self.typefiltercombo.pack_start(typefiltercomboCell, True) self.typefiltercombo.add_attribute(typefiltercomboCell, 'text', 0) # Note to developers. # The second element is for internal matching and should not # be i18ned under any circumstances. fsstore = gtk.ListStore(str, str) fslist = self.datasets.list_filesystems() fsstore.append([_("All"), None]) for fsname, fsmount in fslist: fsstore.append([fsname, fsname]) self.fsfilterentry = self.xml.get_widget("fsfilterentry") self.fsfilterentry.set_model(fsstore) self.fsfilterentry.set_text_column(0) fsfilterentryCell = gtk.CellRendererText() self.fsfilterentry.pack_start(fsfilterentryCell) schedstore = gtk.ListStore(str, str) # Note to developers. # The second element is for internal matching and should not # be i18ned under any circumstances. schedstore.append([_("All"), None]) schedstore.append([_("Monthly"), "monthly"]) schedstore.append([_("Weekly"), "weekly"]) schedstore.append([_("Daily"), "daily"]) schedstore.append([_("Hourly"), "hourly"]) schedstore.append([_("1/4 Hourly"), "frequent"]) self.schedfilterentry = self.xml.get_widget("schedfilterentry") self.schedfilterentry.set_model(schedstore) self.schedfilterentry.set_text_column(0) schedentryCell = gtk.CellRendererText() self.schedfilterentry.pack_start(schedentryCell) self.schedfilterentry.set_active(0) self.fsfilterentry.set_active(0) self.typefiltercombo.set_active(0) else: cloned = self.datasets.list_cloned_snapshots() num_snap = 0 num_rsync = 0 for snapname in self.shortcircuit: # Filter out snapshots that are the root # of cloned filesystems or volumes try: cloned.index(snapname) dialog = gtk.MessageDialog( None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _("Snapshot can not be deleted")) text = _("%s has one or more dependent clones " "and will not be deleted. To delete " "this snapshot, first delete all " "datasets and snapshots cloned from " "this snapshot.") \ % snapname dialog.format_secondary_text(text) dialog.run() sys.exit(1) except ValueError: path = os.path.abspath(snapname) if not os.path.exists(path): snapshot = zfs.Snapshot(snapname) self.backuptodelete.append(snapshot) num_snap += 1 else: self.backuptodelete.append(RsyncBackup(snapname)) num_rsync += 1 confirm = self.xml.get_widget("confirmdialog") summary = self.xml.get_widget("summarylabel") total = len(self.backuptodelete) text = "" if num_rsync != 0: if num_rsync == 1: text = _("1 external backup will be deleted.") else: text = _( "%d external backups will be deleted.") % num_rsync if num_snap != 0: if len(text) != 0: text += "\n" if num_snap == 1: text += _("1 snapshot will be deleted.") else: text += _("%d snapshots will be deleted.") % num_snap summary.set_text(text) response = confirm.run() if response != 2: sys.exit(0) else: # Create the thread in an idle loop in order to # avoid deadlock inside gtk. glib.idle_add(self.__init_delete) return False
def autorun(self, *args): def getCDDev(): drives = kudzu.probe(kudzu.CLASS_CDROM, kudzu.BUS_UNSPEC, kudzu.PROBE_ALL) return map (lambda d: d.device, drives) #Create a gtkInvisible widget to block until the autorun is complete i = gtk.Invisible () i.grab_add () dev = None mounted = False while not mounted: for device in getCDDev(): if device is None: continue try: subprocess.call(["mount", "-o", "ro", "/dev/%s" % device, "/mnt"]) dev = device break except: continue if dev is None: dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_NONE, (_("A CD-ROM has not been detected. Please insert " "a CD-ROM in the drive and click \"OK\" to continue."))) dlg.set_position(gtk.WIN_POS_CENTER) dlg.set_modal(True) cancelButton = dlg.add_button('gtk-cancel', 0) okButton = dlg.add_button('gtk-ok', 1) rc = dlg.run() dlg.destroy() if rc == 0: #Be sure to remove the focus grab if we have to return here. #Otherwise, the user is stuck i.grab_remove () return else: mounted = True if os.access("/mnt/autorun", os.R_OK): #If there's an autorun file on the cd, run it pid = start_process("/mnt/autorun") flag = None while not flag: while gtk.events_pending(): gtk.main_iteration_do() child_pid, status = os.waitpid(pid, os.WNOHANG) if child_pid == pid: flag = 1 else: time.sleep(0.1) else: #There's no autorun on the disc, so complain dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_NONE, (_("The autorun program cannot be found on the CD. " "Click \"OK\" to continue."))) dlg.set_position(gtk.WIN_POS_CENTER) dlg.set_modal(True) okButton = dlg.add_button('gtk-ok', 0) rc = dlg.run() dlg.destroy() if rc == 0: #Be sure to remove the focus grab if we have to return here. #Otherwise, the user is stuck i.grab_remove () #I think system-config-packages will do a umount, but just in case it doesn't... try: subprocess.call(["umount", "/mnt"]) except: #Yep, system-config-packages has already umounted the disc, so fall through and go on pass #Remove the focus grab of the gtkInvisible widget i.grab_remove ()
except Error as (errno, strerror): dialog = gtk.MessageDialog( parent=None, flags=gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK, message_format=strerror) dialog.set_title('Error') dialog.connect('response', lambda dialog, response: dialog.destroy()) dialog.run() return False except Error as (errno, strerror): dialog = gtk.MessageDialog(parent=None, flags=gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK, message_format=strerror) dialog.set_title('Error') dialog.connect('response', lambda dialog, response: dialog.destroy()) dialog.run() return False backgrounds_file = os.path.join(os.path.expanduser("~/.gnome2/"), "backgrounds.xml") doc = xml.dom.minidom.parse(backgrounds_file) wallpaper = dom.createElement("wallpaper") wallpaper.setAttribute("deleted", "false") name = dom.createElement("name")
def helpWindow(widget): info = "File with the MSA should contain sequences of the same length, preceded by an identifier, which occurs after the \">\". In other cases the file will be regarded as inpcorrect. Repetitive sequences will be omitted.\n\nInput file: file .fasta with MSA\n\nOutput directory: directory where MSA visualization will be saved\n\nOutput filename: the name of the file where MSA visualization will be saved (default MSAvis)\n\nnumber of aas in row: number of aminoacids in one row in graph. Enter the number greater than 0 (Default 30)\n\n\nAuthors: M.Habich, M.Maksymiuk, M.Stepniewska, K.Wreczycka" help = gtk.MessageDialog(parent=None, flags=gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_NONE, message_format=info) help.show_all() help.connect("destroy", gtk.main_quit) gtk.main()
def show_message(self, text): msg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, text) msg.show_all() msg.connect("response", lambda *a: msg.destroy())
def show_login_dialog(self, title, message, username=None, password=None, username_prompt=None, register_callback=None, register_text=None): if username_prompt is None: username_prompt = _('Username') if register_text is None: register_text = _('New user') dialog = gtk.MessageDialog( self.main_window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL) dialog.add_button(_('Login'), gtk.RESPONSE_OK) dialog.set_image( gtk.image_new_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_DIALOG)) dialog.set_title(_('Authentication required')) dialog.set_markup('<span weight="bold" size="larger">' + title + '</span>') dialog.format_secondary_markup(message) dialog.set_default_response(gtk.RESPONSE_OK) if register_callback is not None: dialog.add_button(register_text, gtk.RESPONSE_HELP) username_entry = gtk.Entry() password_entry = gtk.Entry() username_entry.connect('activate', lambda w: password_entry.grab_focus()) password_entry.set_visibility(False) password_entry.set_activates_default(True) if username is not None: username_entry.set_text(username) if password is not None: password_entry.set_text(password) table = gtk.Table(2, 2) table.set_row_spacings(6) table.set_col_spacings(6) username_label = gtk.Label() username_label.set_markup('<b>' + username_prompt + ':</b>') username_label.set_alignment(0.0, 0.5) table.attach(username_label, 0, 1, 0, 1, gtk.FILL, 0) table.attach(username_entry, 1, 2, 0, 1) password_label = gtk.Label() password_label.set_markup('<b>' + _('Password') + ':</b>') password_label.set_alignment(0.0, 0.5) table.attach(password_label, 0, 1, 1, 2, gtk.FILL, 0) table.attach(password_entry, 1, 2, 1, 2) dialog.vbox.pack_end(table, True, True, 0) dialog.show_all() response = dialog.run() while response == gtk.RESPONSE_HELP: register_callback() response = dialog.run() password_entry.set_visibility(True) username = username_entry.get_text() password = password_entry.get_text() success = (response == gtk.RESPONSE_OK) dialog.destroy() return (success, (username, password))
def message_dialog(self, par, typ, msg): d = gtk.MessageDialog(par, gtk.DIALOG_MODAL, typ, gtk.BUTTONS_OK, msg) d.set_property('use-markup', True) d.run() d.destroy()
def start_client(self, computer_no, session_k, person): computer = settings.computers[computer_no] ip = computer[1] name = computer[0] session = self.sessions[session_k] end = datetime.now() + timedelta(minutes=session['duration']) def do_start(credits_left, extension=False): self.log( '{person:s} now has {credits:d} credits left today'.format( person=person, credits=credits_left)) self.kill_timeout(ip) self.start_timeout(ip, session['duration'], session['username']) if not extension: self.start_lightdm(ip, session) self.started_clients[computer_no] = { 'end': end, 'username': session['username'], } self.log( '{person:s} now has {credits:d} credits left today'.format( person=person, credits=credits_left)) if computer_no in self.started_clients: if self.started_clients[computer_no].get( 'username', None) == session['username']: if self.started_clients[computer_no].get( 'end', None) > datetime.now(): extension_lenght = int( (datetime.now() - self.started_clients[computer_no] ['end']).total_seconds() // 60) + session['duration'] self.log( "'{name:s}' already started - extending {session:s}" " duration until {end:s} for student {person:s}". format( end=str(end), name=name, session=session['name'], person=person, )) credits_left = 0 try: credits_left = settings.save_usage( person, extension_lenght) do_start(credits_left, extension=True) except settings.NoMoreCredits: dialog = gtk.MessageDialog( type=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, buttons=gtk.BUTTONS_YES_NO, message_format= "{person:s} does not have enough credits - do you want to proceed?" .format(person=person)) def on_response(dialog, response_id): if response_id == gtk.RESPONSE_YES: credits_left = settings.save_usage( person, extension_lenght, force=True) do_start(credits_left) dialog.destroy() dialog.connect("response", on_response) dialog.run() return else: self.log( "Session for {name:s} expired, spawning new".format( name=name, )) credits_left = 0 try: credits_left = settings.save_usage(person, session['credits_cost']) self.log( "Starting new session on {name:s} for person {person:s}, ends in {min:d} minutes" .format( name=name, min=session['duration'], person=person, )) do_start(credits_left) except settings.NoMoreCredits: dialog = gtk.MessageDialog( type=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, buttons=gtk.BUTTONS_YES_NO, message_format= "{person:s} does not have enough credits - do you want to proceed?" .format(person=person)) def on_response(dialog, response_id): if response_id == gtk.RESPONSE_YES: credits_left = settings.save_usage(person, session['credits_cost'], force=True) do_start(credits_left) dialog.destroy() dialog.connect("response", on_response) dialog.run()
def nothing_found_dialog(): dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, _("Package not found!")) ret = dialog.run() dialog.destroy() return ret
def convert(self, widget): md1 = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Error while removing pdfs") cmnd4 = "rm -fr tmp" flag = os.system(cmnd4) if flag != 0: md1.run() md1.destroy() return flag = 1 if not os.path.isdir("tmp"): print "creating tmp folder" os.makedirs("tmp") j = 100 for p in self.filelist: print p cmnd = "tiff2pdf -o 'tmp/" + str( j) + self.out2 + "_temp.pdf' '" + p + "'" flag = os.system(cmnd) j = j + 1 md1 = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Error while creating pdf") if flag != 0: md1.run() md1.destroy() return #Merging pdf files to a single pdf files md1 = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Error while merging pdf") cmnd2 = "pdftk tmp/*.pdf cat output 'tmp/" + self.out2 + "_file_merged.pdf'" flag = os.system(cmnd2) if flag != 0: md1.run() md1.destroy() return #Converting pdf file to djvu file md1 = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Error while creating djvu") cmnd3 = "pdf2djvu -o " + self.outputfilename + ".djvu 'tmp/" + self.out2 + "_file_merged.pdf'" flag = os.system(cmnd3) if flag != 0: md1.run() md1.destroy() return j = 100 md1 = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Error while removing pdfs") cmnd4 = "rm -fr tmp" flag = os.system(cmnd4) if flag != 0: md1.run() md1.destroy() return md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, "Successfully Converted") md.run() #Displaying successful message md.destroy()
def export_snippets(self, filename=None, show_dialogs=True): snippets = self.selected_snippets() if not snippets or len(snippets) == 0: return False usersnippets = [] systemsnippets = [] # Iterate through snippets and look for system snippets for snippet in snippets: if snippet.can_modify(): usersnippets.append(snippet) else: systemsnippets.append(snippet) export_snippets = snippets if len(systemsnippets) != 0 and show_dialogs: # Ask if system snippets should also be exported message = _('Do you want to include selected <b>system</b> snippets in your export?') mes = gtk.MessageDialog(flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format=message) mes.set_property('use-markup', True) resp = mes.run() mes.destroy() if resp == gtk.RESPONSE_NO: export_snippets = usersnippets elif resp != gtk.RESPONSE_YES: return False if len(export_snippets) == 0 and show_dialogs: message = _('There are no snippets selected to be exported') message_dialog(self.dlg, gtk.MESSAGE_INFORMATION, message) return False if not filename: dlg = gtk.FileChooserDialog(parent=self.dlg, title=_('Export snippets'), action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) dlg._export_snippets = export_snippets dlg.add_filter(self.file_filter(_('All supported archives'), ('*.gz','*.bz2','*.tar'))) dlg.add_filter(self.file_filter(_('Gzip compressed archive'), ('*.tar.gz',))) dlg.add_filter(self.file_filter(_('Bzip2 compressed archive'), ('*.tar.bz2',))) dlg.add_filter(self.file_filter(_('All files'), '*')) dlg.set_do_overwrite_confirmation(True) dlg.set_current_name(self.default_export_name) dlg.connect('response', self.on_export_response) dlg.set_local_only(True) dlg.show() return True else: return self.export_snippets_real(filename, export_snippets, show_dialogs)
def dialog_error(self, error): md = gtk.MessageDialog(self.W, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, error) md.run() md.destroy()
def progressive_timeout(self, image): # This shows off fully-paranoid error handling, so looks scary. # You could factor out the error handling code into a nice separate # function to make things nicer. if self.image_stream is not None: # file is already opened try: buf = self.image_stream.read(256) bytes_read = len(buf) except IOError, error: dialog = gtk.MessageDialog( self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Failure reading image file 'alphatest.png': %s" % error) dialog.connect("response", lambda d, r: d.destroy()) self.image_stream.close() self.image_stream = None dialog.show() self.load_timeout = 0 return False # uninstall the timeout if not self.pixbuf_loader.write(buf, bytes_read): dialog = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Failed to load image") dialog.connect("response", lambda d, r: d.destroy()) self.image_stream.close() self.image_stream = None dialog.show() self.load_timeout = 0 return False # uninstall the timeout #if(feof(image_stream)): if bytes_read == 0: self.image_stream.close() self.image_stream = None # Errors can happen on close, e.g. if the image # file was truncated we'll know on close that # it was incomplete. if not self.pixbuf_loader.close(): dialog = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Failed to load image") dialog.connect("response", lambda d, r: d.destroy()) dialog.show() self.pixbuf_loader = None self.load_timeout = 0 return False # uninstall the timeout # if feof(image_stream) self.pixbuf_loader = None
def doRefreshRepos(self, thisrepo=None, destroy=True, progress=False): pbar = PirutProgressCallback(_("Retrieving software information"), self.mainwin) if progress: pbar.show() self._busyCursor() while True: try: self.__allowRepoEdit = True self.reposSetup(pbar, thisrepo) self.__allowRepoEdit = False except yum.Errors.LockError: d = gtk.MessageDialog( self.mainwin, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_NONE, _("Another application is currently " "running which is accessing software " "information.")) b = d.add_button(_("_Quit"), 0) b.set_image( gtk.image_new_from_stock("gtk-quit", gtk.ICON_SIZE_BUTTON)) b = d.add_button(_("_Retry"), 1) b.set_image( gtk.image_new_from_stock("gtk-redo", gtk.ICON_SIZE_BUTTON)) d.set_default_response(1) d.show_all() rc = d.run() d.destroy() if rc == 1: continue else: self.quit(unlock=False) except PirutResetError: # repos have been reset... pbar.set_fraction(0.0) pbar.show() continue except PirutCancelledError, e: pbar.hide() self._normalCursor() d = PirutDetailsDialog(self.mainwin, gtk.MESSAGE_ERROR, None, _("Cancel?")) d.format_secondary_text( _("Software information is required " "to continue.")) d.add_button(_("_Exit"), gtk.RESPONSE_CANCEL, 'gtk-quit') d.add_button(_("_Continue retrieval"), gtk.RESPONSE_OK, 'gtk-redo') rc = d.run() d.destroy() if rc == gtk.RESPONSE_CANCEL: self.quit() else: pbar.set_fraction(0.0) pbar.show() continue except (IOError, PirutDownloadError, yum.Errors.RepoError), e: pbar.hide() self._normalCursor() d = PirutDetailsDialog( self.mainwin, gtk.MESSAGE_ERROR, [('gtk-quit', gtk.RESPONSE_CANCEL), (_("Repository Manager"), 5, 'gtk-edit')], _("Unable to retrieve software information")) d.format_secondary_text( _("Unable to retrieve software " "information. This could be caused by " "not having a network connection " "available.")) d.set_details("%s" % (e, )) rc = d.run() d.destroy() if rc == 5: d = PirutRepoSelector(self) rc = d.run() d.destroy() # if things have changed, then we need to redo repo setup if rc: self.reset(False, True) pbar.set_fraction(0.0) pbar.show() continue self.quit()