diff options
Diffstat (limited to 'chirpui')
| -rw-r--r-- | chirpui/bandplans.py | 107 | ||||
| -rw-r--r-- | chirpui/bankedit.py | 229 | ||||
| -rw-r--r-- | chirpui/clone.py | 2 | ||||
| -rw-r--r-- | chirpui/common.py | 43 | ||||
| -rw-r--r-- | chirpui/config.py | 9 | ||||
| -rw-r--r-- | chirpui/dstaredit.py | 3 | ||||
| -rw-r--r-- | chirpui/editorset.py | 216 | ||||
| -rw-r--r-- | chirpui/mainapp.py | 316 | ||||
| -rw-r--r-- | chirpui/memdetail.py | 60 | ||||
| -rw-r--r-- | chirpui/memedit.py | 212 | ||||
| -rw-r--r-- | chirpui/radiobrowser.py | 320 | ||||
| -rw-r--r-- | chirpui/settingsedit.py | 43 | ||||
| -rw-r--r-- | chirpui/shiftdialog.py | 24 |
13 files changed, 1227 insertions, 357 deletions
diff --git a/chirpui/bandplans.py b/chirpui/bandplans.py new file mode 100644 index 0000000..9d34cd1 --- /dev/null +++ b/chirpui/bandplans.py @@ -0,0 +1,107 @@ +# Copyright 2013 Sean Burford <sburford@google.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import gtk +from chirp import bandplan, bandplan_na, bandplan_au +from chirp import bandplan_iaru_r1, bandplan_iaru_r2, bandplan_iaru_r3 +from chirpui import inputdialog + + +class BandPlans(object): + def __init__(self, config): + self._config = config + self.plans = {} + + # Migrate old "automatic repeater offset" setting to + # "North American Amateur Band Plan" + ro = self._config.get("autorpt", "memedit") + if ro is not None: + self._config.set_bool("north_america", ro, "bandplan") + self._config.remove_option("autorpt", "memedit") + # And default new users to North America. + if not self._config.is_defined("north_america", "bandplan"): + self._config.set_bool("north_america", True, "bandplan") + + for plan in (bandplan_na, bandplan_au, bandplan_iaru_r1, + bandplan_iaru_r2, bandplan_iaru_r3): + name = plan.DESC.get("name", plan.SHORTNAME) + self.plans[plan.SHORTNAME] = (name, plan) + + rpt_inputs = [] + for band in plan.BANDS: + # Check for duplicates. + duplicates = [x for x in plan.BANDS if x == band] + if len(duplicates) > 1: + print "Bandplan %s has duplicates %s" % (name, duplicates) + # Add repeater inputs. + rpt_input = band.inverse() + if rpt_input not in plan.BANDS: + rpt_inputs.append(band.inverse()) + plan.bands = list(plan.BANDS) + plan.bands.extend(rpt_inputs) + + def get_defaults_for_frequency(self, freq): + freq = int(freq) + result = bandplan.Band((freq, freq), repr(freq)) + + for shortname, details in self.plans.items(): + if self._config.get_bool(shortname, "bandplan"): + matches = [x for x in details[1].bands if x.contains(result)] + # Add matches to defaults, favoring more specific matches. + matches = sorted(matches, key=lambda x: x.width(), + reverse=True) + for match in matches: + result.mode = match.mode or result.mode + result.step_khz = match.step_khz or result.step_khz + result.offset = match.offset or result.offset + result.duplex = match.duplex or result.duplex + result.tones = match.tones or result.tones + if match.name: + result.name = '/'.join((result.name or '', match.name)) + # Limit ourselves to one band plan match for simplicity. + # Note that if the user selects multiple band plans by editing + # the config file it will work as expected (except where plans + # conflict). + if matches: + break + + return result + + def select_bandplan(self, parent_window): + plans = ["None"] + for shortname, details in self.plans.iteritems(): + if self._config.get_bool(shortname, "bandplan"): + plans.insert(0, details[0]) + else: + plans.append(details[0]) + + d = inputdialog.ChoiceDialog(plans, parent=parent_window, + title="Choose Defaults") + d.label.set_text(_("Band plans define default channel settings for " + "frequencies in a region. Choose a band plan " + "or None for completely manual channel " + "settings.")) + d.label.set_line_wrap(True) + r = d.run() + + if r == gtk.RESPONSE_OK: + selection = d.choice.get_active_text() + for shortname, details in self.plans.iteritems(): + self._config.set_bool(shortname, selection == details[0], + "bandplan") + if selection == details[0]: + print "Selected band plan %s: %s" % (shortname, selection) + + d.destroy() diff --git a/chirpui/bankedit.py b/chirpui/bankedit.py index 23c05da..a6cb71e 100644 --- a/chirpui/bankedit.py +++ b/chirpui/bankedit.py @@ -22,69 +22,69 @@ from gobject import TYPE_INT, TYPE_STRING, TYPE_BOOLEAN from chirp import chirp_common from chirpui import common, miscwidgets -class BankNamesJob(common.RadioJob): - def __init__(self, bm, editor, cb): +class MappingNamesJob(common.RadioJob): + def __init__(self, model, editor, cb): common.RadioJob.__init__(self, cb, None) - self.__bm = bm + self.__model = model self.__editor = editor def execute(self, radio): - self.__editor.banks = [] + self.__editor.mappings = [] - banks = self.__bm.get_banks() - for bank in banks: - self.__editor.banks.append((bank, bank.get_name())) + mappings = self.__model.get_mappings() + for mapping in mappings: + self.__editor.mappings.append((mapping, mapping.get_name())) gobject.idle_add(self.cb, *self.cb_args) -class BankNameEditor(common.Editor): +class MappingNameEditor(common.Editor): def refresh(self): - def got_banks(): + def got_mappings(): self._keys = [] - for bank, name in self.banks: - self._keys.append(bank.get_index()) - self.listw.set_item(bank.get_index(), - bank.get_index(), + for mapping, name in self.mappings: + self._keys.append(mapping.get_index()) + self.listw.set_item(mapping.get_index(), + mapping.get_index(), name) - self.listw.connect("item-set", self.bank_changed) + self.listw.connect("item-set", self.mapping_changed) - job = BankNamesJob(self._bm, self, got_banks) - job.set_desc(_("Retrieving bank information")) + job = MappingNamesJob(self._model, self, got_mappings) + job.set_desc(_("Retrieving %s information") % self._type) self.rthread.submit(job) - def get_bank_list(self): - banks = [] + def get_mapping_list(self): + mappings = [] keys = self.listw.get_keys() for key in keys: - banks.append(self.listw.get_item(key)[2]) + mappings.append(self.listw.get_item(key)[2]) - return banks - - def bank_changed(self, listw, key): + return mappings + + def mapping_changed(self, listw, key): def cb(*args): self.emit("changed") name = self.listw.get_item(key)[2] - bank, oldname = self.banks[self._keys.index(key)] + mapping, oldname = self.mappings[self._keys.index(key)] def trigger_changed(*args): self.emit("changed") job = common.RadioJob(trigger_changed, "set_name", name) - job.set_target(bank) - job.set_desc(_("Setting name on bank")) + job.set_target(mapping) + job.set_desc(_("Setting name on %s") % self._type.lower()) self.rthread.submit(job) return True - def __init__(self, rthread): - common.Editor.__init__(self) - self.rthread = rthread - self._bm = rthread.radio.get_bank_model() + def __init__(self, rthread, model): + super(MappingNameEditor, self).__init__(rthread) + self._model = model + self._type = common.unpluralize(model.get_name()) types = [(gobject.TYPE_STRING, "key"), - (gobject.TYPE_STRING, _("Bank")), + (gobject.TYPE_STRING, self._type), (gobject.TYPE_STRING, _("Name"))] self.listw = miscwidgets.KeyedListWidget(types) @@ -93,7 +93,7 @@ class BankNameEditor(common.Editor): self.listw.set_sort_column(1, -1) self.listw.show() - self.banks = [] + self.mappings = [] sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) @@ -109,51 +109,60 @@ class BankNameEditor(common.Editor): self.refresh() self._loaded = True -class MemoryBanksJob(common.RadioJob): - def __init__(self, bm, cb, number): + def other_editor_changed(self, target_editor): + self._loaded = False + if self.is_focused(): + self.refresh_all_memories() + + def mappings_changed(self): + pass + +class MemoryMappingsJob(common.RadioJob): + def __init__(self, model, cb, number): common.RadioJob.__init__(self, cb, None) - self.__bm = bm + self.__model = model self.__number = number def execute(self, radio): mem = radio.get_memory(self.__number) if mem.empty: - banks = [] + mappings = [] indexes = [] else: - banks = self.__bm.get_memory_banks(mem) + mappings = self.__model.get_memory_mappings(mem) indexes = [] - if isinstance(self.__bm, chirp_common.BankIndexInterface): - for bank in banks: - indexes.append(self.__bm.get_memory_index(mem, bank)) - self.cb(mem, banks, indexes, *self.cb_args) - -class BankMembershipEditor(common.Editor): + if isinstance(self.__model, + chirp_common.MappingModelIndexInterface): + for mapping in mappings: + indexes.append(self.__model.get_memory_index(mem, mapping)) + self.cb(mem, mappings, indexes, *self.cb_args) + +class MappingMembershipEditor(common.Editor): def _number_to_path(self, number): return (number - self._rf.memory_bounds[0],) - def _get_next_bank_index(self, bank): - # NB: Only works for one-to-one bank models right now! + def _get_next_mapping_index(self, mapping): + # NB: Only works for one-to-one models right now! iter = self._store.get_iter_first() indexes = [] - ncols = len(self._cols) + len(self.banks) + ncols = len(self._cols) + len(self.mappings) while iter: vals = self._store.get(iter, *tuple([n for n in range(0, ncols)])) loc = vals[self.C_LOC] index = vals[self.C_INDEX] - banks = vals[self.C_BANKS:] - if True in banks and banks.index(True) == bank: + mappings = vals[self.C_MAPPINGS:] + if True in mappings and mappings.index(True) == mapping: indexes.append(index) iter = self._store.iter_next(iter) - index_bounds = self._bm.get_index_bounds() + index_bounds = self._model.get_index_bounds() num_indexes = index_bounds[1] - index_bounds[0] indexes.sort() for i in range(0, num_indexes): if i not in indexes: return i + index_bounds[0] # In case not zero-origin index - return 0 # If the bank is full, just wrap around! + return 0 # If the mapping is full, just wrap around! def _toggled_cb(self, rend, path, colnum): try: @@ -165,56 +174,60 @@ class BankMembershipEditor(common.Editor): if not self._store.get(iter, self.C_FILLED)[0]: return - # The bank index is the column number, minus the 3 label columns - bank, name = self.banks[colnum - len(self._cols)] + # The mapping index is the column number, minus the 3 label columns + mapping, name = self.mappings[colnum - len(self._cols)] loc, = self._store.get(self._store.get_iter(path), self.C_LOC) + is_indexed = isinstance(self._model, + chirp_common.MappingModelIndexInterface) + if rend.get_active(): # Changing from True to False - fn = "remove_memory_from_bank" + fn = "remove_memory_from_mapping" index = None else: # Changing from False to True - fn = "add_memory_to_bank" - if self._rf.has_bank_index: - index = self._get_next_bank_index(colnum - len(self._cols)) + fn = "add_memory_to_mapping" + if is_indexed: + index = self._get_next_mapping_index(colnum - len(self._cols)) else: index = None def do_refresh_memory(*args): - # Step 2: Update our notion of the memory's bank information + # Step 2: Update our notion of the memory's mapping information self.refresh_memory(loc) - def do_bank_index(result, memory): + def do_mapping_index(result, memory): if isinstance(result, Exception): - common.show_error("Failed to add {mem} to bank: {err}" + common.show_error("Failed to add {mem} to mapping: {err}" .format(mem=memory.number, err=str(result)), parent=self.editorset.parent_window) return self.emit("changed") - # Step 3: Set the memory's bank index (maybe) - if not self._rf.has_bank_index or index is None: + # Step 3: Set the memory's mapping index (maybe) + if not is_indexed or index is None: return do_refresh_memory() job = common.RadioJob(do_refresh_memory, - "set_memory_index", memory, bank, index) - job.set_target(self._bm) - job.set_desc(_("Updating bank index " - "for memory {num}").format(num=memory.number)) + "set_memory_index", memory, mapping, index) + job.set_target(self._model) + job.set_desc(_("Updating {type} index " + "for memory {num}").format(type=self._type, + num=memory.number)) self.rthread.submit(job) - def do_bank_adjustment(memory): - # Step 1: Do the bank add/remove - job = common.RadioJob(do_bank_index, fn, memory, bank) - job.set_target(self._bm) + def do_mapping_adjustment(memory): + # Step 1: Do the mapping add/remove + job = common.RadioJob(do_mapping_index, fn, memory, mapping) + job.set_target(self._model) job.set_cb_args(memory) - job.set_desc(_("Updating bank information " + job.set_desc(_("Updating mapping information " "for memory {num}").format(num=memory.number)) self.rthread.submit(job) # Step 0: Fetch the memory - job = common.RadioJob(do_bank_adjustment, "get_memory", loc) + job = common.RadioJob(do_mapping_adjustment, "get_memory", loc) job.set_desc(_("Getting memory {num}").format(num=loc)) self.rthread.submit(job) @@ -224,36 +237,38 @@ class BankMembershipEditor(common.Editor): def refresh_memory(*args): self.refresh_memory(loc) - def set_index(banks, memory): + def set_index(mappings, memory): self.emit("changed") # Step 2: Set the index job = common.RadioJob(refresh_memory, "set_memory_index", - memory, banks[0], int(new)) - job.set_target(self._bm) + memory, mappings[0], int(new)) + job.set_target(self._model) job.set_desc(_("Setting index " "for memory {num}").format(num=memory.number)) self.rthread.submit(job) - def get_bank(memory): - # Step 1: Get the first/only bank - job = common.RadioJob(set_index, "get_memory_banks", memory) + def get_mapping(memory): + # Step 1: Get the first/only mapping + job = common.RadioJob(set_index, "get_memory_mappings", memory) job.set_cb_args(memory) - job.set_target(self._bm) - job.set_desc(_("Getting bank for " - "memory {num}").format(num=memory.number)) + job.set_target(self._model) + job.set_desc(_("Getting {type} for " + "memory {num}").format(type=self._type, + num=memory.number)) self.rthread.submit(job) # Step 0: Get the memory - job = common.RadioJob(get_bank, "get_memory", loc) + job = common.RadioJob(get_mapping, "get_memory", loc) job.set_desc(_("Getting memory {num}").format(num=loc)) self.rthread.submit(job) - def __init__(self, rthread, editorset): - common.Editor.__init__(self) - self.rthread = rthread + def __init__(self, rthread, editorset, model): + super(MappingMembershipEditor, self).__init__(rthread) + self.editorset = editorset self._rf = rthread.radio.get_features() - self._bm = rthread.radio.get_bank_model() + self._model = model + self._type = common.unpluralize(model.get_name()) self._view_cols = [ (_("Loc"), TYPE_INT, gtk.CellRendererText, ), @@ -271,19 +286,22 @@ class BankMembershipEditor(common.Editor): self.C_FREQ = 2 self.C_NAME = 3 self.C_INDEX = 4 - self.C_BANKS = 5 # and beyond + self.C_MAPPINGS = 5 # and beyond cols = list(self._cols) self._index_cache = [] - for i in range(0, self._bm.get_num_banks()): - label = "Bank %i" % (i+1) + for i in range(0, self._model.get_num_mappings()): + label = "%s %i" % (self._type, (i+1)) cols.append((label, TYPE_BOOLEAN, gtk.CellRendererToggle)) self._store = gtk.ListStore(*tuple([y for x,y,z in cols])) self._view = gtk.TreeView(self._store) + is_indexed = isinstance(self._model, + chirp_common.MappingModelIndexInterface) + colnum = 0 for label, dtype, rtype in cols: if not rtype: @@ -306,7 +324,7 @@ class BankMembershipEditor(common.Editor): elif colnum == self.C_INDEX: rend.set_property("editable", True) rend.connect("edited", self._index_edited_cb) - col.set_visible(self._rf.has_bank_index) + col.set_visible(is_indexed) colnum += 1 # A non-rendered column to absorb extra space in the row @@ -330,7 +348,7 @@ class BankMembershipEditor(common.Editor): self._loaded = False def refresh_memory(self, number): - def got_mem(memory, banks, indexes): + def got_mem(memory, mappings, indexes): iter = self._store.get_iter(self._number_to_path(memory.number)) row = [self.C_FILLED, not memory.empty, self.C_LOC, memory.number, @@ -339,29 +357,30 @@ class BankMembershipEditor(common.Editor): # Hack for only one index right now self.C_INDEX, indexes and indexes[0] or 0, ] - for i in range(0, len(self.banks)): + for i in range(0, len(self.mappings)): row.append(i + len(self._cols)) - row.append(self.banks[i][0] in banks) + row.append(self.mappings[i][0] in mappings) self._store.set(iter, *tuple(row)) if memory.number == self._rf.memory_bounds[1] - 1: - print "Got all bank info in %s" % (time.time() - self._start) + print "Got all %s info in %s" % (self._type, + (time.time() - self._start)) - job = MemoryBanksJob(self._bm, got_mem, number) - job.set_desc(_("Getting bank information " - "for memory {num}").format(num=number)) + job = MemoryMappingsJob(self._model, got_mem, number) + job.set_desc(_("Getting {type} information " + "for memory {num}").format(type=self._type, num=number)) self.rthread.submit(job) def refresh_all_memories(self): for i in range(*self._rf.memory_bounds): self.refresh_memory(i) - def refresh_banks(self, and_memories=False): - def got_banks(): + def refresh_mappings(self, and_memories=False): + def got_mappings(): for i in range(len(self._cols) - len(self._view_cols) - 1, - len(self.banks)): + len(self.mappings)): col = self._view.get_column(i + len(self._view_cols)) - bank, name = self.banks[i] + mapping, name = self.mappings[i] if name: col.set_title(name) else: @@ -369,8 +388,8 @@ class BankMembershipEditor(common.Editor): if and_memories: self.refresh_all_memories() - job = BankNamesJob(self._bm, self, got_banks) - job.set_desc(_("Getting bank information")) + job = MappingNamesJob(self._model, self, got_mappings) + job.set_desc(_("Getting %s information") % self._type) self.rthread.submit(job) def focus(self): @@ -379,14 +398,14 @@ class BankMembershipEditor(common.Editor): return self._start = time.time() - self.refresh_banks(True) + self.refresh_mappings(True) self._loaded = True - def memories_changed(self): + def other_editor_changed(self, target_editor): self._loaded = False if self.is_focused(): self.refresh_all_memories() - def banks_changed(self): - self.refresh_banks() + def mappings_changed(self): + self.refresh_mappings() diff --git a/chirpui/clone.py b/chirpui/clone.py index 0786e1e..7210d4a 100644 --- a/chirpui/clone.py +++ b/chirpui/clone.py @@ -56,6 +56,8 @@ class CloneSettingsDialog(gtk.Dialog): port = conf.get("last_port") elif ports: port = ports[0] + else: + port = "" if not port in ports: ports.insert(0, port) diff --git a/chirpui/common.py b/chirpui/common.py index adacaec..8511b8b 100644 --- a/chirpui/common.py +++ b/chirpui/common.py @@ -34,9 +34,11 @@ class Editor(gobject.GObject): root = None - def __init__(self): + def __init__(self, rthread): gobject.GObject.__init__(self) + self.read_only = False self._focused = False + self.rthread = rthread def is_focused(self): return self._focused @@ -56,6 +58,18 @@ class Editor(gobject.GObject): def hotkey(self, action): pass + def set_read_only(self, read_only): + self.read_only = read_only + + def get_read_only(self): + return self.read_only + + def prepare_close(self): + pass + + def other_editor_changed(self, editor): + pass + gobject.type_register(Editor) def DBG(*args): @@ -128,16 +142,26 @@ class RadioThread(threading.Thread, gobject.GObject): (gobject.TYPE_STRING,)), } - def __init__(self, radio): + def __init__(self, radio, parent=None): threading.Thread.__init__(self) gobject.GObject.__init__(self) self.__queue = {} + if parent: + self.__runlock = parent._get_run_lock() + self.status = lambda msg: parent.status(msg) + else: + self.__runlock = threading.Lock() + self.status = self._status + self.__counter = threading.Semaphore(0) - self.__enabled = True self.__lock = threading.Lock() - self.__runlock = threading.Lock() + + self.__enabled = True self.radio = radio + def _get_run_lock(self): + return self.__runlock + def _qlock(self): self.__lock.acquire() @@ -196,7 +220,7 @@ class RadioThread(threading.Thread, gobject.GObject): self.__counter.release() self.__enabled = False - def status(self, msg): + def _status(self, msg): jobs = 0 for i in dict(self.__queue): jobs += len(self.__queue[i]) @@ -224,14 +248,14 @@ class RadioThread(threading.Thread, gobject.GObject): DBG("Running job at priority %i" % i) break self._qunlock() - + if job: self.lock() self.status(job.desc) job.execute(self.radio) last_job_desc = job.desc self.unlock() - + print "RadioThread exiting" def log_exception(): @@ -389,3 +413,8 @@ def show_diff_blob(title, result): d.run() d.destroy() +def unpluralize(string): + if string.endswith("s"): + return string[:-1] + else: + return string diff --git a/chirpui/config.py b/chirpui/config.py index d82a1db..c5b55c1 100644 --- a/chirpui/config.py +++ b/chirpui/config.py @@ -54,6 +54,12 @@ class ChirpConfig: def is_defined(self, key, section): return self.__config.has_option(section, key) + def remove_option(self, section, key): + self.__config.remove_option(section, key) + + if not self.__config.items(section): + self.__config.remove_section(section) + class ChirpConfigProxy: def __init__(self, config, section="global"): self._config = config @@ -98,6 +104,9 @@ class ChirpConfigProxy: def is_defined(self, key, section=None): return self._config.is_defined(key, section or self._section) + def remove_option(self, key, section): + self._config.remove_option(section, key) + _CONFIG = None def get(section="global"): global _CONFIG diff --git a/chirpui/dstaredit.py b/chirpui/dstaredit.py index 942c6c5..df0baa8 100644 --- a/chirpui/dstaredit.py +++ b/chirpui/dstaredit.py @@ -179,8 +179,7 @@ class DStarEditor(common.Editor): self.rthread.submit(job) def __init__(self, rthread): - common.Editor.__init__(self) - self.rthread = rthread + super(DStarEditor, self).__init__(rthread) self.loaded = False diff --git a/chirpui/editorset.py b/chirpui/editorset.py index 1f578a0..c38b7d8 100644 --- a/chirpui/editorset.py +++ b/chirpui/editorset.py @@ -19,7 +19,7 @@ import gobject from chirp import chirp_common, directory, generic_csv, generic_xml from chirpui import memedit, dstaredit, bankedit, common, importdialog -from chirpui import inputdialog, reporting, settingsedit +from chirpui import inputdialog, reporting, settingsedit, radiobrowser, config class EditorSet(gtk.VBox): __gsignals__ = { @@ -35,6 +35,68 @@ class EditorSet(gtk.VBox): (gobject.TYPE_STRING,)), } + def _make_device_mapping_editors(self, device, devrthread, index): + sub_index = 0 + memory_editor = self.editors["memedit%i" % index] + mappings = device.get_mapping_models() + for mapping_model in mappings: + members = bankedit.MappingMembershipEditor(devrthread, self, + mapping_model) + label = mapping_model.get_name() + if self.rf.has_sub_devices: + label += "(%s)" % device.VARIANT + lab = gtk.Label(label) + self.tabs.append_page(members.root, lab) + self.editors["mapping_members%i%i" % (index, sub_index)] = members + + basename = common.unpluralize(mapping_model.get_name()) + names = bankedit.MappingNameEditor(devrthread, mapping_model) + label = "%s Names" % basename + if self.rf.has_sub_devices: + label += " (%s)" % device.VARIANT + lab = gtk.Label(label) + self.tabs.append_page(names.root, lab) + self.editors["mapping_names%i%i" % (index, sub_index)] = names + + members.root.show() + members.connect("changed", self.editor_changed) + if hasattr(mapping_model.get_mappings()[0], "set_name"): + names.root.show() + members.connect("changed", lambda x: names.mappings_changed()) + names.connect("changed", lambda x: members.mappings_changed()) + names.connect("changed", self.editor_changed) + + def _make_device_editors(self, device, devrthread, index): + if isinstance(device, chirp_common.IcomDstarSupport): + memories = memedit.DstarMemoryEditor(devrthread) + else: + memories = memedit.MemoryEditor(devrthread) + + memories.connect("usermsg", lambda e, m: self.emit("usermsg", m)) + memories.connect("changed", self.editor_changed) + + if self.rf.has_sub_devices: + label = (_("Memories (%(variant)s)") % + dict(variant=device.VARIANT)) + rf = device.get_features() + else: + label = _("Memories") + rf = self.rf + lab = gtk.Label(label) + self.tabs.append_page(memories.root, lab) + memories.root.show() + self.editors["memedit%i" % index] = memories + + self._make_device_mapping_editors(device, devrthread, index) + + if isinstance(device, chirp_common.IcomDstarSupport): + editor = dstaredit.DStarEditor(devrthread) + self.tabs.append_page(editor.root, gtk.Label(_("D-STAR"))) + editor.root.show() + editor.connect("changed", self.dstar_changed, memories) + editor.connect("changed", self.editor_changed) + self.editors["dstar"] = editor + def __init__(self, source, parent_window=None, filename=None, tempname=None): gtk.VBox.__init__(self, True, 0) @@ -49,78 +111,51 @@ class EditorSet(gtk.VBox): else: raise Exception("Unknown source type") - self.rthread = common.RadioThread(self.radio) - self.rthread.setDaemon(True) - self.rthread.start() + rthread = common.RadioThread(self.radio) + rthread.setDaemon(True) + rthread.start() - self.rthread.connect("status", lambda e, m: self.emit("status", m)) + rthread.connect("status", lambda e, m: self.emit("status", m)) self.tabs = gtk.Notebook() self.tabs.connect("switch-page", self.tab_selected) self.tabs.set_tab_pos(gtk.POS_LEFT) - self.editors = { - "memedit" : None, - "dstar" : None, - "bank_names" : None, - "bank_members" : None, - "settings" : None, - } - - if isinstance(self.radio, chirp_common.IcomDstarSupport): - self.editors["memedit"] = memedit.DstarMemoryEditor(self.rthread) - self.editors["dstar"] = dstaredit.DStarEditor(self.rthread) - else: - self.editors["memedit"] = memedit.MemoryEditor(self.rthread) - - self.editors["memedit"].connect("usermsg", - lambda e, m: self.emit("usermsg", m)) - - rf = self.radio.get_features() + self.editors = {} - if rf.has_bank: - self.editors["bank_members"] = \ - bankedit.BankMembershipEditor(self.rthread, self) - - if rf.has_bank_names: - self.editors["bank_names"] = bankedit.BankNameEditor(self.rthread) - - if rf.has_settings: - self.editors["settings"] = settingsedit.SettingsEditor(self.rthread) - - lab = gtk.Label(_("Memories")) - self.tabs.append_page(self.editors["memedit"].root, lab) - self.editors["memedit"].root.show() - - if self.editors["dstar"]: - lab = gtk.Label(_("D-STAR")) - self.tabs.append_page(self.editors["dstar"].root, lab) - self.editors["dstar"].root.show() - self.editors["dstar"].connect("changed", self.dstar_changed) - - if self.editors["bank_names"]: - lab = gtk.Label(_("Bank Names")) - self.tabs.append_page(self.editors["bank_names"].root, lab) - self.editors["bank_names"].root.show() - self.editors["bank_names"].connect("changed", self.banks_changed) - - if self.editors["bank_members"]: - lab = gtk.Label(_("Banks")) - self.tabs.append_page(self.editors["bank_members"].root, lab) - self.editors["bank_members"].root.show() - self.editors["bank_members"].connect("changed", self.banks_changed) - - if self.editors["settings"]: - lab = gtk.Label(_("Settings")) - self.tabs.append_page(self.editors["settings"].root, lab) - self.editors["settings"].root.show() + self.rf = self.radio.get_features() + if self.rf.has_sub_devices: + devices = self.radio.get_sub_devices() + else: + devices = [self.radio] + + index = 0 + for device in devices: + devrthread = common.RadioThread(device, rthread) + devrthread.setDaemon(True) + devrthread.start() + self._make_device_editors(device, devrthread, index) + index += 1 + + if self.rf.has_settings: + editor = settingsedit.SettingsEditor(rthread) + self.tabs.append_page(editor.root, gtk.Label(_("Settings"))) + editor.root.show() + editor.connect("changed", self.editor_changed) + self.editors["settings"] = editor + + conf = config.get() + if (hasattr(self.rthread.radio, '_memobj') and + conf.get_bool("developer", "state")): + editor = radiobrowser.RadioBrowser(self.rthread) + lab = gtk.Label(_("Browser")) + self.tabs.append_page(editor.root, lab) + editor.connect("changed", self.editor_changed) + self.editors["browser"] = editor self.pack_start(self.tabs) self.tabs.show() - # pylint: disable-msg=E1101 - self.editors["memedit"].connect("changed", self.editor_changed) - self.label = self.text_label = None self.make_label() self.modified = (tempname is not None) @@ -171,31 +206,19 @@ class EditorSet(gtk.VBox): self.modified = False self.update_tab() - def dstar_changed(self, *args): - print "D-STAR editor changed" - memedit = self.editors["memedit"] - dstared = self.editors["dstar"] + def dstar_changed(self, dstared, memedit): memedit.set_urcall_list(dstared.editor_ucall.get_callsigns()) memedit.set_repeater_list(dstared.editor_rcall.get_callsigns()) memedit.prefill() - if not isinstance(self.radio, chirp_common.LiveRadio): - self.modified = True - self.update_tab() - - def banks_changed(self, *args): - print "Banks changed" - if self.editors["bank_members"]: - self.editors["bank_members"].banks_changed() - if not isinstance(self.radio, chirp_common.LiveRadio): - self.modified = True - self.update_tab() - def editor_changed(self, *args): + def editor_changed(self, target_editor=None): + print "%s changed" % target_editor if not isinstance(self.radio, chirp_common.LiveRadio): self.modified = True self.update_tab() - if self.editors["bank_members"]: - self.editors["bank_members"].memories_changed() + for editor in self.editors.values(): + if editor != target_editor: + editor.other_editor_changed(target_editor) def get_tab_label(self): return self.label @@ -226,7 +249,8 @@ class EditorSet(gtk.VBox): if count > 0: self.editor_changed() - gobject.idle_add(self.editors["memedit"].prefill) + current_editor = self.get_current_editor() + gobject.idle_add(current_editor.prefill) return count @@ -251,6 +275,13 @@ class EditorSet(gtk.VBox): raise Exception(_("Internal Error")) def do_import(self, filen): + current_editor = self.get_current_editor() + if not isinstance(current_editor, memedit.MemoryEditor): + # FIXME: We need a nice message to let the user know that they + # need to select the appropriate memory editor tab before doing + # and import so that we know which thread and editor to import + # into and refresh. This will do for the moment. + common.show_error("Memory editor must be selected before import") try: src_radio = directory.get_radio_by_image(filen) except Exception, e: @@ -338,11 +369,13 @@ class EditorSet(gtk.VBox): self) def prime(self): + # NOTE: this is only called to prime new CSV files, so assume + # only one memory editor for now mem = chirp_common.Memory() mem.freq = 146010000 def cb(*args): - gobject.idle_add(self.editors["memedit"].prefill) + gobject.idle_add(self.editors["memedit0"].prefill) job = common.RadioJob(cb, "set_memory", mem) job.set_desc(_("Priming memory")) @@ -358,16 +391,25 @@ class EditorSet(gtk.VBox): v.unfocus() def set_read_only(self, read_only=True): - self.editors["memedit"].set_read_only(read_only) - + for editor in self.editors.values(): + editor and editor.set_read_only(read_only) + def get_read_only(self): - return self.editors["memedit"].get_read_only() + return self.editors["memedit0"].get_read_only() def prepare_close(self): - self.editors["memedit"].prepare_close() + for editor in self.editors.values(): + editor and editor.prepare_close() def get_current_editor(self): - for e in self.editors.values(): + for lab, e in self.editors.items(): if e and self.tabs.page_num(e.root) == self.tabs.get_current_page(): return e raise Exception("No editor selected?") + + @property + def rthread(self): + """Magic rthread property to return the rthread of the currently- + selected editor""" + e = self.get_current_editor() + return e.rthread diff --git a/chirpui/mainapp.py b/chirpui/mainapp.py index e3b2eb1..719d096 100644 --- a/chirpui/mainapp.py +++ b/chirpui/mainapp.py @@ -40,6 +40,7 @@ from chirp import ic9x, kenwood_live, idrp, vx7, vx5, vx6 from chirp import CHIRP_VERSION, chirp_common, detect, errors from chirp import icf, ic9x_icf from chirpui import editorset, clone, miscwidgets, config, reporting, fips +from chirpui import bandplans CONF = config.get() @@ -129,7 +130,7 @@ class ChirpMain(gtk.Window): for _editortype, actions in mappings.items(): for _action in actions: action = self.menu_ag.get_action(_action) - action.set_sensitive(_editortype == editortype) + action.set_sensitive(editortype.startswith(_editortype)) def _connect_editorset(self, eset): eset.connect("want-close", self.do_close) @@ -300,8 +301,6 @@ If you think that it is valid, you can select a radio model below to force an op # We have to actually instantiate the IC9xICFRadio to get its # sub-devices radio = ic9x_icf.IC9xICFRadio(fname) - devices = radio.get_sub_devices() - del radio else: try: radio = directory.get_radio_by_image(fname) @@ -315,39 +314,30 @@ If you think that it is valid, you can select a radio model below to force an op common.show_error(os.path.basename(fname) + ": " + str(e)) return - if radio.get_features().has_sub_devices: - devices = radio.get_sub_devices() - else: - devices = [radio] - - prio = len(devices) first_tab = False - for device in devices: - try: - eset = editorset.EditorSet(device, self, - filename=fname, - tempname=tempname) - except Exception, e: - common.log_exception() - common.show_error( - _("There was an error opening {fname}: {error}").format( - fname=fname, - error=error)) - return - - eset.set_read_only(read_only) - self._connect_editorset(eset) - eset.show() - tab = self.tabs.append_page(eset, eset.get_tab_label()) - if first_tab: - self.tabs.set_current_page(tab) - first_tab = False - - if hasattr(eset.rthread.radio, "errors") and \ - eset.rthread.radio.errors: - msg = _("{num} errors during open:").format(num=len(eset.rthread.radio.errors)) - common.show_error_text(msg, - "\r\n".join(eset.rthread.radio.errors)) + try: + eset = editorset.EditorSet(radio, self, + filename=fname, + tempname=tempname) + except Exception, e: + common.log_exception() + common.show_error( + _("There was an error opening {fname}: {error}").format( + fname=fname, + error=e)) + return + + eset.set_read_only(read_only) + self._connect_editorset(eset) + eset.show() + self.tabs.append_page(eset, eset.get_tab_label()) + + if hasattr(eset.rthread.radio, "errors") and \ + eset.rthread.radio.errors: + msg = _("{num} errors during open:").format( + num=len(eset.rthread.radio.errors)) + common.show_error_text(msg, + "\r\n".join(eset.rthread.radio.errors)) def do_live_warning(self, radio): d = gtk.MessageDialog(parent=self, buttons=gtk.BUTTONS_OK) @@ -369,23 +359,12 @@ If you think that it is valid, you can select a radio model below to force an op d.destroy() def do_open_live(self, radio, tempname=None, read_only=False): - if radio.get_features().has_sub_devices: - devices = radio.get_sub_devices() - else: - devices = [radio] - - first_tab = True - for device in devices: - eset = editorset.EditorSet(device, self, tempname=tempname) - eset.connect("want-close", self.do_close) - eset.connect("status", self.ev_status) - eset.set_read_only(read_only) - eset.show() - - tab = self.tabs.append_page(eset, eset.get_tab_label()) - if first_tab: - self.tabs.set_current_page(tab) - first_tab = False + eset = editorset.EditorSet(radio, self, tempname=tempname) + eset.connect("want-close", self.do_close) + eset.connect("status", self.ev_status) + eset.set_read_only(read_only) + eset.show() + self.tabs.append_page(eset, eset.get_tab_label()) if isinstance(radio, chirp_common.LiveRadio): reporting.report_model_usage(radio, "live", True) @@ -585,7 +564,7 @@ If you think that it is valid, you can select a radio model below to force an op return True title = _("Proceed with experimental driver?") - text = rclass.get_experimental_warning() + text = rclass.get_prompts().experimental msg = _("This radio's driver is experimental. " "Do you want to proceed?") resp, squelch = common.show_warning(msg, text, @@ -596,6 +575,34 @@ If you think that it is valid, you can select a radio model below to force an op CONF.set_bool(sql_key, not squelch, "state") return resp == gtk.RESPONSE_YES + def _show_instructions(self, radio, message): + if message is None: + return + + if CONF.get_bool("clone_instructions", "noconfirm"): + return + + d = gtk.MessageDialog(parent=self, buttons=gtk.BUTTONS_OK) + d.set_markup("<big><b>" + _("{name} Instructions").format( + name=radio.get_name()) + "</b></big>") + msg = _("{instructions}").format(instructions=message) + d.format_secondary_markup(msg) + + again = gtk.CheckButton(_("Don't show instructions for any radio again")) + again.show() + d.vbox.pack_start(again, 0, 0, 0) + h_button_box = d.vbox.get_children()[2] + try: + ok_button = h_button_box.get_children()[0] + ok_button.grab_default() + ok_button.grab_focus() + except AttributeError: + # don't grab focus on GTK+ 2.0 + pass + d.run() + d.destroy() + CONF.set_bool("clone_instructions", again.get_active(), "noconfirm") + def do_download(self, port=None, rtype=None): d = clone.CloneSettingsDialog(parent=self) settings = d.run() @@ -609,6 +616,8 @@ If you think that it is valid, you can select a radio model below to force an op # User does not want to proceed with experimental driver return + self._show_instructions(rclass, rclass.get_prompts().pre_download) + print "User selected %s %s on port %s" % (rclass.VENDOR, rclass.MODEL, settings.port) @@ -646,6 +655,11 @@ If you think that it is valid, you can select a radio model below to force an op d.destroy() if not settings: return + prompts = radio.get_prompts() + + if prompts.display_pre_upload_prompt_before_opening_port == True: + print "Opening port after pre_upload prompt." + self._show_instructions(radio, prompts.pre_upload) if isinstance(radio, chirp_common.ExperimentalRadio) and \ not self._confirm_experimental(radio.__class__): @@ -664,6 +678,10 @@ If you think that it is valid, you can select a radio model below to force an op d.destroy() return + if prompts.display_pre_upload_prompt_before_opening_port == False: + print "Opening port before pre_upload prompt." + self._show_instructions(radio, prompts.pre_upload) + radio.set_pipe(ser) ct = clone.CloneThread(radio, "out", cb=self.cb_cloneout, parent=self) @@ -718,6 +736,7 @@ If you think that it is valid, you can select a radio model below to force an op (_("EVE Files (VX5)") + " (*.eve)", "*.eve"), (_("ICF Files") + " (*.icf)", "*.icf"), (_("Kenwood HMK Files") + " (*.hmk)", "*.hmk"), + (_("Kenwood ITM Files") + " (*.itm)", "*.itm"), (_("Travel Plus Files") + " (*.tpe)", "*.tpe"), (_("VX5 Commander Files") + " (*.vx5)", "*.vx5"), (_("VX6 Commander Files") + " (*.vx6)", "*.vx6"), @@ -783,7 +802,7 @@ If you think that it is valid, you can select a radio model below to force an op county.set_active(0) state.connect("changed", _changed, county) - d = inputdialog.FieldDialog(title="RepeaterBook Query", parent=self) + d = inputdialog.FieldDialog(title=_("RepeaterBook Query"), parent=self) d.add_field("State", state) d.add_field("County", county) d.add_field("Band", band) @@ -842,7 +861,7 @@ If you think that it is valid, you can select a radio model below to force an op if not os.path.exists(filename): print "Failed, headers were:" print str(headers) - common.show_error("RepeaterBook query failed") + common.show_error(_("RepeaterBook query failed")) self.window.set_cursor(None) return @@ -875,6 +894,87 @@ If you think that it is valid, you can select a radio model below to force an op else: self.do_open_live(radio, read_only=True) + def do_przemienniki_prompt(self): + d = inputdialog.FieldDialog(title='przemienniki.net query', + parent=self) + fields = { + "Country": + (miscwidgets.make_choice(['by', 'cz', 'de', 'lt', 'pl', + 'sk', 'uk'], False), + lambda x: str(x.get_active_text())), + "Band": + (miscwidgets.make_choice(['10m', '4m', '6m', '2m', '70cm', + '23cm', '13cm', '3cm'], False, '2m'), + lambda x: str(x.get_active_text())), + "Mode": + (miscwidgets.make_choice(['fm', 'dv'], False), + lambda x: str(x.get_active_text())), + "Only Working": + (miscwidgets.make_choice(['', 'yes'], False), + lambda x: str(x.get_active_text())), + "Latitude": (gtk.Entry(), lambda x: float(x.get_text())), + "Longitude": (gtk.Entry(), lambda x: float(x.get_text())), + "Range": (gtk.Entry(), lambda x: int(x.get_text())), + } + for name in sorted(fields.keys()): + value, fn = fields[name] + d.add_field(name, value) + while d.run() == gtk.RESPONSE_OK: + query = "http://przemienniki.net/export/chirp.csv?" + args = [] + for name, (value, fn) in fields.items(): + if isinstance(value, gtk.Entry): + contents = value.get_text() + else: + contents = value.get_active_text() + if contents: + try: + _value = fn(value) + except ValueError: + common.show_error(_("Invalid value for %s") % name) + query = None + continue + + args.append("=".join((name.replace(" ", "").lower(), + contents))) + query += "&".join(args) + print query + d.destroy() + return query + + d.destroy() + return query + + def do_przemienniki(self, do_import): + url = self.do_przemienniki_prompt() + if not url: + return + + fn = tempfile.mktemp(".csv") + filename, headers = urllib.urlretrieve(url, fn) + if not os.path.exists(filename): + print "Failed, headers were:" + print str(headers) + common.show_error(_("Query failed")) + return + + class PRRadio(generic_csv.CSVRadio, + chirp_common.NetworkSourceRadio): + VENDOR = "przemienniki.net" + MODEL = "" + + try: + radio = PRRadio(filename) + except Exception, e: + common.show_error(str(e)) + return + + if do_import: + eset = self.get_current_editorset() + count = eset.do_import(filename) + else: + self.do_open_live(radio, read_only=True) + def do_rfinder_prompt(self): fields = {"1Email" : (gtk.Entry(), lambda x: "@" in x), @@ -952,7 +1052,8 @@ If you think that it is valid, you can select a radio model below to force an op "3Zipcode" : (gtk.Entry(), lambda x: x), } - d = inputdialog.FieldDialog(title="RadioReference.com Query", parent=self) + d = inputdialog.FieldDialog(title=_("RadioReference.com Query"), + parent=self) for k in sorted(fields.keys()): d.add_field(k[1:], fields[k][0]) fields[k][0].set_text(CONF.get(k[1:], "radioreference") or "") @@ -1051,14 +1152,13 @@ If you think that it is valid, you can select a radio model below to force an op d.set_name("CHIRP") d.set_version(CHIRP_VERSION) - d.set_copyright("Copyright 2012 Dan Smith (KK7DS)") + d.set_copyright("Copyright 2013 Dan Smith (KK7DS)") d.set_website("http://chirp.danplanet.com") - d.set_authors(("Dan Smith <dsmith@danplanet.com>", - _("With significant contributions by:"), - "Marco IZ3GME", - "Rick WZ3RO", + d.set_authors(("Dan Smith KK7DS <dsmith@danplanet.com>", + _("With significant contributions from:"), "Tom KD7LXL", - "Vernon N7OH" + "Marco IZ3GME", + "Jim KC9HI" )) d.set_translator_credits("Polish: Grzegorz SQ2RBY" + os.linesep + @@ -1066,12 +1166,33 @@ If you think that it is valid, you can select a radio model below to force an op os.linesep + "Dutch: Michael PD4MT" + os.linesep + - "German: Benjamin HB9EUK") + "German: Benjamin HB9EUK" + + os.linesep + + "Hungarian: Attila HA7JA" + + os.linesep + + "Russian: Dmitry Slukin" + + os.linesep + + "Portuguese (BR): Crezivando PP7CJ") d.set_comments(verinfo) d.run() d.destroy() + def do_documentation(self): + d = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, parent=self, + type=gtk.MESSAGE_INFO) + + d.set_markup("<b><big>" + _("CHIRP Documentation") + "</big></b>\r\n") + msg = _("Documentation for CHIRP, including FAQs, and help for common " + "problems is available on the CHIRP web site, please go to\n\n" + "<a href=\"http://chirp.danplanet.com/projects/chirp/wiki/" + "Documentation\">" + "http://chirp.danplanet.com/projects/chirp/wiki/" + "Documentation</a>\n") + d.format_secondary_markup(msg.replace("\n","\r\n")) + d.run() + d.destroy() + def do_columns(self): eset = self.get_current_editorset() driver = directory.get_driver(eset.rthread.radio.__class__) @@ -1098,7 +1219,7 @@ If you think that it is valid, you can select a radio model below to force an op vbox.pack_start(label) fields = [] - memedit = eset.editors["memedit"] + memedit = eset.get_current_editor() #.editors["memedit"] unsupported = memedit.get_unsupported_columns() for colspec in memedit.cols: if colspec[0].startswith("_"): @@ -1132,7 +1253,9 @@ If you think that it is valid, you can select a radio model below to force an op conf = config.get("memedit") conf.set_bool("hide_unused", action.get_active()) else: - eset.editors["memedit"].set_hide_unused(action.get_active()) + for editortype, editor in eset.editors.iteritems(): + if "memedit" in editortype: + editor.set_hide_unused(action.get_active()) def do_clearq(self): eset = self.get_current_editorset() @@ -1173,8 +1296,8 @@ If you think that it is valid, you can select a radio model below to force an op conf = config.get() conf.set_bool("no_report", not action.get_active()) - def do_toggle_autorpt(self, action): - CONF.set_bool("autorpt", action.get_active(), "memedit") + def do_toggle_no_smart_tmode(self, action): + CONF.set_bool("no_smart_tmode", not action.get_active(), "memedit") def do_toggle_developer(self, action): conf = config.get() @@ -1186,7 +1309,7 @@ If you think that it is valid, you can select a radio model below to force an op def do_change_language(self): langs = ["Auto", "English", "Polish", "Italian", "Dutch", "German", - "Hungarian"] + "Hungarian", "Russian", "Portuguese (BR)"] d = inputdialog.ChoiceDialog(langs, parent=self, title="Choose Language") d.label.set_text(_("Choose a language or Auto to use the " @@ -1253,8 +1376,12 @@ If you think that it is valid, you can select a radio model below to force an op self.do_export() elif action in ["qrbook", "irbook"]: self.do_repeaterbook(action[0] == "i") + elif action in ["qpr", "ipr"]: + self.do_przemienniki(action[0] == "i") elif action == "about": self.do_about() + elif action == "documentation": + self.do_documentation() elif action == "columns": self.do_columns() elif action == "hide_unused": @@ -1263,8 +1390,12 @@ If you think that it is valid, you can select a radio model below to force an op self.do_clearq() elif action == "report": self.do_toggle_report(_action) - elif action == "autorpt": - self.do_toggle_autorpt(_action) + elif action == "channel_defaults": + # The memedit thread also has an instance of bandplans. + bp = bandplans.BandPlans(CONF) + bp.select_bandplan(self) + elif action == "no_smart_tmode": + self.do_toggle_no_smart_tmode(_action) elif action == "developer": self.do_toggle_developer(_action) elif action in ["cut", "copy", "paste", "delete", @@ -1314,6 +1445,7 @@ If you think that it is valid, you can select a radio model below to force an op <menu action="view"> <menuitem action="columns"/> <menuitem action="hide_unused"/> + <menuitem action="no_smart_tmode"/> <menu action="viewdeveloper"> <menuitem action="devshowraw"/> <menuitem action="devdiffraw"/> @@ -1327,21 +1459,24 @@ If you think that it is valid, you can select a radio model below to force an op <menu action="importsrc" name="importsrc"> <menuitem action="iradioreference"/> <menuitem action="irbook"/> + <menuitem action="ipr"/> <menuitem action="irfinder"/> </menu> <menu action="querysrc" name="querysrc"> <menuitem action="qradioreference"/> <menuitem action="qrbook"/> + <menuitem action="qpr"/> <menuitem action="qrfinder"/> </menu> <menu action="stock" name="stock"/> <separator/> - <menuitem action="autorpt"/> + <menuitem action="channel_defaults"/> <separator/> <menuitem action="cancelq"/> </menu> <menu action="help"> <menuitem action="about"/> + <menuitem action="documentation"/> <menuitem action="report"/> <menuitem action="developer"/> </menu> @@ -1383,28 +1518,32 @@ If you think that it is valid, you can select a radio model below to force an op ('iradioreference', None, _("RadioReference.com"), None, None, self.mh), ('irfinder', None, _("RFinder"), None, None, self.mh), ('irbook', None, _("RepeaterBook"), None, None, self.mh), + ('ipr', None, _("przemienniki.net"), None, None, self.mh), ('querysrc', None, _("Query data source"), None, None, self.mh), ('qradioreference', None, _("RadioReference.com"), None, None, self.mh), ('qrfinder', None, _("RFinder"), None, None, self.mh), + ('qpr', None, _("przemienniki.net"), None, None, self.mh), ('qrbook', None, _("RepeaterBook"), None, None, self.mh), ('export_chirp', None, _("CHIRP Native File"), None, None, self.mh), ('export_csv', None, _("CSV File"), None, None, self.mh), ('stock', None, _("Import from stock config"), None, None, self.mh), + ('channel_defaults', None, _("Channel defaults"), None, None, self.mh), ('cancelq', gtk.STOCK_STOP, None, "Escape", None, self.mh), ('help', None, _('Help'), None, None, self.mh), ('about', gtk.STOCK_ABOUT, None, None, None, self.mh), + ('documentation', None, _("Documentation"), None, None, self.mh), ] conf = config.get() re = not conf.get_bool("no_report"); hu = conf.get_bool("hide_unused", "memedit") - ro = conf.get_bool("autorpt", "memedit") dv = conf.get_bool("developer", "state") + st = not conf.get_bool("no_smart_tmode", "memedit") toggles = [\ ('report', None, _("Report statistics"), None, None, self.mh, re), ('hide_unused', None, _("Hide Unused Fields"), None, None, self.mh, hu), - ('autorpt', None, _("Automatic Repeater Offset"), None, None, self.mh, ro), + ('no_smart_tmode', None, _("Smart Tone Modes"), None, None, self.mh, st), ('developer', None, _("Enable Developer Functions"), None, None, self.mh, dv), ] @@ -1539,6 +1678,9 @@ If you think that it is valid, you can select a radio model below to force an op aboutitem = self.menu_uim.get_widget("/MenuBar/help/about") macapp.insert_app_menu_item(aboutitem, 0) + documentationitem = self.menu_uim.get_widget("/MenuBar/help/documentation") + macapp.insert_app_menu_item(documentationitem, 0) + macapp.set_use_quartz_accelerators(False) macapp.ready() @@ -1547,6 +1689,19 @@ If you think that it is valid, you can select a radio model below to force an op def __init__(self, *args, **kwargs): gtk.Window.__init__(self, *args, **kwargs) + def expose(window, event): + allocation = window.get_allocation() + CONF.set_int("window_w", allocation.width, "state") + CONF.set_int("window_h", allocation.height, "state") + self.connect("expose_event", expose) + + def state_change(window, event): + CONF.set_bool( + "window_maximized", + event.new_window_state == gtk.gdk.WINDOW_STATE_MAXIMIZED, + "state") + self.connect("window-state-event", state_change) + d = CONF.get("last_dir", "state") if d and os.path.isdir(d): platform.get_platform().set_last_dir(d) @@ -1579,7 +1734,16 @@ If you think that it is valid, you can select a radio model below to force an op self.add(vbox) - self.set_default_size(800, 600) + try: + width = CONF.get_int("window_w", "state") + height = CONF.get_int("window_h", "state") + except Exception: + width = 800 + height = 600 + + self.set_default_size(width, height) + if CONF.get_bool("window_maximized", "state"): + self.maximize() self.set_title("CHIRP") self.connect("delete_event", self.ev_delete) @@ -1598,10 +1762,6 @@ If you think that it is valid, you can select a radio model below to force an op d.destroy() CONF.set_bool("warned_about_reporting", True) - if not CONF.is_defined("autorpt", "memedit"): - print "autorpt not set et" - CONF.set_bool("autorpt", True, "memedit") - self.update_recent_files() self.update_stock_configs() self.setup_extra_hotkeys() diff --git a/chirpui/memdetail.py b/chirpui/memdetail.py index cc605fc..d202964 100644 --- a/chirpui/memdetail.py +++ b/chirpui/memdetail.py @@ -34,6 +34,9 @@ class ValueEditor: def _init(self, data): """Type-specific initialization""" + def set_sensitive(self, sensitive): + self._widget.set_sensitive(sensitive) + def get_widget(self): """Returns the widget associated with this editor""" return self._widget @@ -157,21 +160,24 @@ class OffsetEditor(FreqEditor): class MemoryDetailEditor(gtk.Dialog): """Detail editor for a memory""" - def _add(self, tab, row, name, editor, labeltxt): + def _add(self, tab, row, name, editor, labeltxt, colindex=0): label = gtk.Label(labeltxt) img = gtk.Image() label.show() - tab.attach(label, 0, 1, row, row+1) + tab.attach(label, colindex, colindex + 1, row, row + 1) + colindex += 1 editor.get_widget().show() - tab.attach(editor.get_widget(), 1, 2, row, row+1) + tab.attach(editor.get_widget(), colindex, colindex + 1, row, row + 1) + colindex += 1 img.set_size_request(15, -1) img.show() - tab.attach(img, 2, 3, row, row+1) + tab.attach(img, colindex, colindex + 1, row, row + 1) self._editors[name] = label, editor, img + return label, editor, img def _set_doc(self, name, doc): label, editor, _img = self._editors[name] @@ -179,8 +185,12 @@ class MemoryDetailEditor(gtk.Dialog): self._tips.set_tip(editor.get_widget(), doc) def _make_ui(self): + sw = gtk.ScrolledWindow() + sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) + sw.show() tab = gtk.Table(len(self._order), 3, False) - self.vbox.pack_start(tab, 1, 1, 1) + sw.add_with_viewport(tab) + self.vbox.pack_start(sw, 1, 1, 1) tab.show() row = 0 @@ -225,18 +235,21 @@ class MemoryDetailEditor(gtk.Dialog): row += 1 self._order.append(name) + def _title(self): + return _("Edit Memory #{num}").format(num=self._memory.number) + def __init__(self, features, memory, parent=None): + self._memory = memory gtk.Dialog.__init__(self, - title=_("Edit Memory" - "#{num}").format(num=memory.number), + title=self._title(), flags=gtk.DIALOG_MODAL, parent=parent, buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) + self.set_size_request(-1, 500) self._tips = gtk.Tooltips() self._features = features - self._memory = memory self._editors = {} self._elements = { @@ -322,3 +335,34 @@ class MemoryDetailEditor(gtk.Dialog): def get_memory(self): self._memory.empty = False return self._memory + +class MultiMemoryDetailEditor(MemoryDetailEditor): + def _title(self): + return _("Edit Multiple Memories") + + def __init__(self, features, memory, parent=None): + self._selections = dict() + super(MultiMemoryDetailEditor, self).__init__(features, memory, parent) + + def _toggle_selector(self, selector, *widgets): + for widget in widgets: + widget.set_sensitive(selector.get_active()) + + def _add(self, tab, row, name, editor, labeltxt): + label, editor, img = super(MultiMemoryDetailEditor, self)._add( + tab, row, name, editor, labeltxt, 1) + + selector = gtk.CheckButton() + tab.attach(selector, 0, 1, row, row + 1) + selector.show() + self._toggle_selector(selector, label, editor, img) + selector.connect("toggled", self._toggle_selector, label, editor, img) + self._selections[name] = selector + self._tips.set_tip( + selector, + _("Check this to change the {name} value").format( + name=labeltxt)) + + + def get_fields(self): + return [k for k, v in self._selections.items() if v.get_active()] diff --git a/chirpui/memedit.py b/chirpui/memedit.py index 5764ee0..b0c3ab9 100644 --- a/chirpui/memedit.py +++ b/chirpui/memedit.py @@ -33,6 +33,7 @@ import pickle import os from chirpui import common, shiftdialog, miscwidgets, config, memdetail +from chirpui import bandplans from chirp import chirp_common, errors, directory, import_logic def handle_toggle(_, path, store, col): @@ -104,10 +105,8 @@ class MemoryEditor(common.Editor): choices = { _("Tone") : chirp_common.TONES, _("ToneSql") : chirp_common.TONES, - _("DTCS Code") : sorted(chirp_common.DTCS_CODES + - chirp_common.DTCS_EXTRA_CODES), - _("DTCS Rx Code") : sorted(chirp_common.DTCS_CODES + - chirp_common.DTCS_EXTRA_CODES), + _("DTCS Code") : chirp_common.ALL_DTCS_CODES, + _("DTCS Rx Code") : chirp_common.ALL_DTCS_CODES, _("DTCS Pol") : ["NN", "NR", "RN", "RR"], _("Mode") : chirp_common.MODES, _("Power") : [], @@ -121,13 +120,14 @@ class MemoryEditor(common.Editor): return self.rthread.radio.filter_name(new) def ed_offset(self, _, path, new, __): - return chirp_common.parse_freq(new) + new = chirp_common.parse_freq(new) + return abs(new) def ed_freq(self, _foo, path, new, colnum): iter = self.store.get_iter(path) - prev, = self.store.get(iter, colnum) + was_filled, prev = self.store.get(iter, self.col("_filled"), colnum) - def set_offset(path, offset): + def set_offset(offset): if offset > 0: dup = "+" elif offset == 0: @@ -136,17 +136,37 @@ class MemoryEditor(common.Editor): dup = "-" offset *= -1 + if not dup in self.choices[_("Duplex")]: + print "Duplex %s not supported by this radio" % dup + return + if offset: self.store.set(iter, self.col(_("Offset")), offset) self.store.set(iter, self.col(_("Duplex")), dup) def set_ts(ts): - self.store.set(iter, self.col(_("Tune Step")), ts) + if ts in self.choices[_("Tune Step")]: + self.store.set(iter, self.col(_("Tune Step")), ts) + else: + print "Tune step %s not supported by this radio" % ts def get_ts(path): return self.store.get(iter, self.col(_("Tune Step")))[0] + def set_mode(mode): + if mode in self.choices[_("Mode")]: + self.store.set(iter, self.col(_("Mode")), mode) + else: + print "Mode %s not supported by this radio (%s)" % ( + mode, self.choices[_("Mode")]) + + def set_tone(tone): + if tone in self.choices[_("Tone")]: + self.store.set(iter, self.col(_("Tone")), tone) + else: + print "Tone %s not supported by this radio" % tone + try: new = chirp_common.parse_freq(new) except ValueError, e: @@ -156,16 +176,16 @@ class MemoryEditor(common.Editor): if not self._features.has_nostep_tuning: set_ts(chirp_common.required_step(new)) - if new and self._config.get_bool("autorpt") and new != prev: - try: - band = chirp_common.freq_to_band(new) - set_offset(path, 0) - for lo, hi, offset in chirp_common.STD_OFFSETS[band]: - if new > lo and new < hi: - set_offset(path, offset) - break - except Exception, e: - pass + is_changed = new != prev if was_filled else True + if new is not None and is_changed: + defaults = self.bandplans.get_defaults_for_frequency(new) + set_offset(defaults.offset or 0) + if defaults.step_khz: + set_ts(defaults.step_khz) + if defaults.mode: + set_mode(defaults.mode) + if defaults.tones: + set_tone(defaults.tones[0]) return new @@ -192,15 +212,58 @@ class MemoryEditor(common.Editor): # RX frequency as the default TX frequency self.store.set(iter, self.col("Offset"), freq) else: - band = int(freq / 100000000) - if chirp_common.STD_OFFSETS.has_key(band): - offset = chirp_common.STD_OFFSETS[band][0][2] - else: - offset = 0 + defaults = self.bandplans.get_defaults_for_frequency(freq) + offset = defaults.offset or 0 self.store.set(iter, self.col(_("Offset")), abs(offset)) return new + def ed_tone_field(self, _foo, path, new, col): + if self._config.get_bool("no_smart_tmode"): + return new + + iter = self.store.get_iter(path) + + # Python scoping hurts us here, so store this as a list + # that we can modify, instead of helpful variables :( + modes = list(self.store.get(iter, + self.col(_("Tone Mode")), + self.col(_("Cross Mode")))) + + def _tm(*tmodes): + if modes[0] not in tmodes: + modes[0] = tmodes[0] + self.store.set(iter, self.col(_("Tone Mode")), modes[0]) + def _cm(*cmodes): + if modes[0] == "Cross" and modes[1] not in cmodes: + modes[1] = cmodes[0] + self.store.set(iter, self.col(_("Cross Mode")), modes[1]) + + if col == self.col(_("DTCS Code")): + _tm("DTCS", "Cross") + _cm(*tuple([x for x in chirp_common.CROSS_MODES + if x.startswith("DTCS->")])) + elif col == self.col(_("DTCS Rx Code")): + _tm("Cross") + _cm(*tuple([x for x in chirp_common.CROSS_MODES + if x.endswith("->DTCS")])) + elif col == self.col(_("DTCS Pol")): + _tm("DTCS", "Cross") + _cm(*tuple([x for x in chirp_common.CROSS_MODES + if "DTCS" in x])) + elif col == self.col(_("Tone")): + _tm("Tone", "Cross") + _cm(*tuple([x for x in chirp_common.CROSS_MODES + if x.startswith("Tone->")])) + elif col == self.col(_("ToneSql")): + _tm("TSQL", "Cross") + _cm(*tuple([x for x in chirp_common.CROSS_MODES + if x.endswith("->Tone")])) + elif col == self.col(_("Cross Mode")): + _tm("Cross") + + return new + def _get_cols_to_hide(self, iter): tmode, duplex, cmode = self.store.get(iter, self.col(_("Tone Mode")), @@ -248,7 +311,7 @@ class MemoryEditor(common.Editor): if "DTCS" not in cmode: hide += [self.col(_("DTCS Pol"))] - if duplex == "" or duplex == "(None)": + if duplex == "" or duplex == "(None)" or duplex == "off": hide += [self.col(_("Offset"))] @@ -276,6 +339,12 @@ class MemoryEditor(common.Editor): _("Frequency") : self.ed_freq, _("Duplex") : self.ed_duplex, _("Offset") : self.ed_offset, + _("Tone") : self.ed_tone_field, + _("ToneSql"): self.ed_tone_field, + _("DTCS Code"): self.ed_tone_field, + _("DTCS Rx Code"): self.ed_tone_field, + _("DTCS Pol"): self.ed_tone_field, + _("Cross Mode"): self.ed_tone_field, } if funcs.has_key(cap): @@ -306,7 +375,7 @@ class MemoryEditor(common.Editor): msgs = self.rthread.radio.validate_memory(mem) if msgs: - common.show_error(_("Error setting memory") + \ + common.show_error(_("Error setting memory") + ": " + \ "\r\n\r\n".join(msgs)) self.prefill() return @@ -397,7 +466,7 @@ class MemoryEditor(common.Editor): else: iter = store.iter_next(_iter) - pos, = store.get(iter, self.col("Loc")) + pos, = store.get(iter, self.col(_("Loc"))) sd = shiftdialog.ShiftDialog(self.rthread) @@ -455,12 +524,12 @@ class MemoryEditor(common.Editor): return True # We changed memories - def _delete_rows_and_shift(self, paths): + def _delete_rows_and_shift(self, paths, all=False): iter = self.store.get_iter(paths[0]) starting_loc, = self.store.get(iter, self.col(_("Loc"))) for i in range(0, len(paths)): sd = shiftdialog.ShiftDialog(self.rthread) - sd.delete(starting_loc, quiet=True) + sd.delete(starting_loc, quiet=True, all=all) sd.destroy() self.prefill() @@ -640,23 +709,57 @@ class MemoryEditor(common.Editor): job.set_desc(_("Getting raw memory {number}").format(number=loc_b)) self.rthread.submit(job) - def edit_memory(self, memory): - dlg = memdetail.MemoryDetailEditor(self._features, memory) + def _copy_field(self, src_memory, dst_memory, field): + if field.startswith("extra_"): + field = field.split("_", 1)[1] + value = src_memory.extra[field].value.get_value() + dst_memory.extra[field].value = value + else: + setattr(dst_memory, field, getattr(src_memory, field)) + + def _apply_multiple(self, src_memory, fields, locations): + for location in locations: + def apply_and_set(memory): + for field in fields: + self._copy_field(src_memory, memory, field) + cb = (memory.number == locations[-1] + and self._set_memory_cb or None) + job = common.RadioJob(cb, "set_memory", memory) + job.set_desc(_("Writing memory {number}").format( + number=memory.number)) + self.rthread.submit(job) + job = common.RadioJob(apply_and_set, "get_memory", location) + job.set_desc(_("Getting original memory {number}").format( + number=location)) + self.rthread.submit(job) + + def edit_memory(self, memory, locations): + if len(locations) > 1: + dlg = memdetail.MultiMemoryDetailEditor(self._features, memory) + else: + dlg = memdetail.MemoryDetailEditor(self._features, memory) r = dlg.run() if r == gtk.RESPONSE_OK: self.need_refresh = True mem = dlg.get_memory() - mem.name = self.rthread.radio.filter_name(mem.name) - job = common.RadioJob(self._set_memory_cb, "set_memory", mem) - job.set_desc(_("Writing memory {number}").format(number=mem.number)) - self.rthread.submit(job) - self.emit("changed") + if len(locations) > 1: + self._apply_multiple(memory, dlg.get_fields(), locations) + else: + mem.name = self.rthread.radio.filter_name(mem.name) + job = common.RadioJob(self._set_memory_cb, "set_memory", mem) + job.set_desc(_("Writing memory {number}").format( + number=mem.number)) + self.rthread.submit(job) dlg.destroy() def mh(self, _action, store, paths): action = _action.get_name() - iter = store.get_iter(paths[0]) - cur_pos, = store.get(iter, self.col(_("Loc"))) + selected = [] + for path in paths: + iter = store.get_iter(path) + loc, = store.get(iter, self.col(_("Loc"))) + selected.append(loc) + cur_pos = selected[0] require_contiguous = ["delete_s", "move_up", "move_dn"] if action in require_contiguous: @@ -677,6 +780,8 @@ class MemoryEditor(common.Editor): changed = self._delete_rows(paths) elif action == "delete_s": changed = self._delete_rows_and_shift(paths) + elif action == "delete_sall": + changed = self._delete_rows_and_shift(paths, all=True) elif action in ["move_up", "move_dn"]: changed = self._move_up_down(paths, action) elif action == "exchange": @@ -691,6 +796,7 @@ class MemoryEditor(common.Editor): self._diff_raw(paths) elif action == "edit": job = common.RadioJob(self.edit_memory, "get_memory", cur_pos) + job.set_cb_args(selected) self.rthread.submit(job) if changed: @@ -724,8 +830,11 @@ class MemoryEditor(common.Editor): <menuitem action="edit"/> <menuitem action="insert_prev"/> <menuitem action="insert_next"/> - <menuitem action="delete"/> - <menuitem action="delete_s"/> + <menu action="deletes"> + <menuitem action="delete"/> + <menuitem action="delete_s"/> + <menuitem action="delete_sall"/> + </menu> <menuitem action="move_up"/> <menuitem action="move_dn"/> <menuitem action="exchange"/> @@ -747,8 +856,10 @@ class MemoryEditor(common.Editor): ("edit", _("Edit")), ("insert_prev", _("Insert row above")), ("insert_next", _("Insert row below")), - ("delete", issingle and _("Delete") or _("Delete all")), - ("delete_s", _("Delete (and shift up)")), + ("deletes", _("Delete")), + ("delete", issingle and _("this memory") or _("these memories")), + ("delete_s", _("...and shift block up")), + ("delete_sall", _("...and shift all memories up")), ("move_up", _("Move up")), ("move_dn", _("Move down")), ("exchange", _("Exchange memories")), @@ -1022,7 +1133,7 @@ class MemoryEditor(common.Editor): def _limit_key(self, which): if which not in ["lo", "hi"]: - raise Exception(_("Internal Error: Invalid limit {number").format(number=which)) + raise Exception(_("Internal Error: Invalid limit {number}").format(number=which)) return "%s_%s" % (directory.radio_class_id(self.rthread.radio.__class__), which) @@ -1110,12 +1221,6 @@ class MemoryEditor(common.Editor): self.prefill() self._config.set_bool("hide_empty", not show) - def set_read_only(self, read_only): - self.read_only = read_only - - def get_read_only(self): - return self.read_only - def set_hide_unused(self, hide_unused): self.hide_unused = hide_unused self.prefill() @@ -1175,13 +1280,14 @@ class MemoryEditor(common.Editor): return user_visible def __init__(self, rthread): - common.Editor.__init__(self) - self.rthread = rthread + super(MemoryEditor, self).__init__(rthread) self.defaults = dict(self.defaults) self._config = config.get("memedit") + self.bandplans = bandplans.BandPlans(config.get()) + self.allowed_bands = [144, 440] self.count = 100 self.show_special = self._config.get_bool("show_special") @@ -1208,6 +1314,8 @@ class MemoryEditor(common.Editor): self.choices[_("Power")] = [str(x) for x in self._features["valid_power_levels"]] self.choices[_("DTCS Pol")] = self._features["valid_dtcs_pols"] + self.choices[_("DTCS Code")] = self._features["valid_dtcs_codes"] + self.choices[_("DTCS Rx Code")] = self._features["valid_dtcs_codes"] if self._features["valid_power_levels"]: self.defaults[_("Power")] = self._features["valid_power_levels"][0] @@ -1371,7 +1479,9 @@ class MemoryEditor(common.Editor): cols = self.view.get_columns() self._config.set("column_order_%s" % self.__class__.__name__, ",".join([x.get_title() for x in cols])) - + + def other_editor_changed(self, target_editor): + self.need_refresh = True class DstarMemoryEditor(MemoryEditor): def _get_cols_to_hide(self, iter): diff --git a/chirpui/radiobrowser.py b/chirpui/radiobrowser.py new file mode 100644 index 0000000..db96b04 --- /dev/null +++ b/chirpui/radiobrowser.py @@ -0,0 +1,320 @@ +import gtk +import gobject +import pango +import re +import os + +from chirp import bitwise +from chirpui import common + +def do_insert_line_with_tags(b, line): + def i(text, *tags): + b.insert_with_tags_by_name(b.get_end_iter(), text, *tags) + + def ident(name): + if "unknown" in name: + i(name, 'grey', 'bold') + else: + i(name, 'bold') + + def nonzero(value): + i(value, 'red', 'bold') + + def foo(value): + i(value, 'blue', 'bold') + + m = re.match("^( *)([A-z0-9_]+: )(0x[A-F0-9]+) \((.*)\)$", line) + if m: + i(m.group(1)) + ident(m.group(2)) + if m.group(3) == '0x00': + i(m.group(3)) + else: + nonzero(m.group(3)) + i(' (') + for char in m.group(4): + if char == '1': + nonzero(char) + else: + i(char) + i(')') + return + + m = re.match("^( *)([A-z0-9_]+: )(.*)$", line) + if m: + i(m.group(1)) + ident(m.group(2)) + i(m.group(3)) + return + + m = re.match("^(.*} )([A-z0-9_]+)( \()([0-9]+)( bytes at )(0x[A-F0-9]+)", + line) + if m: + i(m.group(1)) + ident(m.group(2)) + i(m.group(3)) + foo(m.group(4)) + i(m.group(5)) + foo(m.group(6)) + i(")") + return + + i(line) + +def do_insert_with_tags(buf, text): + buf.set_text('') + lines = text.split(os.linesep) + for line in lines: + do_insert_line_with_tags(buf, line) + buf.insert_with_tags_by_name(buf.get_end_iter(), os.linesep) + +def classname(obj): + return str(obj.__class__).split('.')[-1] + +def bitwise_type(classname): + return classname.split("DataElement")[0] + +class FixedEntry(gtk.Entry): + def __init__(self, *args, **kwargs): + super(FixedEntry, self).__init__(*args, **kwargs) + fontdesc = pango.FontDescription("Courier bold 10") + self.modify_font(fontdesc) + +class IntegerEntry(FixedEntry): + def _colorize(self, _self): + value = self.get_text() + if value.startswith("0x"): + value = value[2:] + value = value.replace("0", "") + if not value: + self.modify_text(gtk.STATE_NORMAL, None) + else: + self.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('red')) + + def __init__(self, *args, **kwargs): + super(IntegerEntry, self).__init__(*args, **kwargs) + self.connect("changed", self._colorize) + +class BitwiseEditor(gtk.HBox): + def __init__(self, element): + super(BitwiseEditor, self).__init__(False, 3) + self._element = element + self._build_ui() + +class IntegerEditor(BitwiseEditor): + def _changed(self, entry, base): + if not self._update: + return + value = entry.get_text() + if value.startswith("0x"): + value = value[2:] + self._element.set_value(int(value, base)) + self._update_entries(skip=entry) + + def _update_entries(self, skip=None): + self._update = False + for ent, format_spec in self._entries: + if ent != skip: + ent.set_text(format_spec.format(int(self._element))) + self._update = True + + def _build_ui(self): + self._entries = [] + self._update = True + + hexdigits = ((self._element.size() / 4) + + (self._element.size() % 4 and 1 or 0)) + formats = [('Hex', 16, '0x{:0%iX}' % hexdigits), + ('Dec', 10, '{:d}'), + ('Bin', 2, '{:0%ib}' % self._element.size())] + for name, base, format_spec in formats: + lab = gtk.Label(name) + self.pack_start(lab, 0, 0, 0) + lab.show() + int(self._element) + ent = IntegerEntry() + self._entries.append((ent, format_spec)) + ent.connect('changed', self._changed, base) + self.pack_start(ent, 0, 0, 0) + ent.show() + self._update_entries() + +class BCDArrayEditor(BitwiseEditor): + def _changed(self, entry, hexent): + self._element.set_value(int(entry.get_text())) + self._format_hexent(hexent) + + def _format_hexent(self, hexent): + value = "" + for i in self._element: + a, b = i.get_value() + value += "%i%i" % (a, b) + hexent.set_text(value) + + def _build_ui(self): + lab = gtk.Label("Dec") + lab.show() + self.pack_start(lab, 0, 0, 0) + ent = FixedEntry() + ent.set_text(str(int(self._element))) + ent.show() + self.pack_start(ent, 1, 1, 1) + + lab = gtk.Label("Hex") + lab.show() + self.pack_start(lab, 0, 0, 0) + + hexent = FixedEntry() + hexent.show() + self.pack_start(hexent, 1, 1, 1) + hexent.set_editable(False) + + ent.connect('changed', self._changed, hexent) + self._format_hexent(hexent) + +class CharArrayEditor(BitwiseEditor): + def _changed(self, entry): + self._element.set_value(entry.get_text().ljust(len(self._element))) + + def _build_ui(self): + ent = FixedEntry(len(self._element)) + ent.set_text(str(self._element)) + ent.connect('changed', self._changed) + ent.show() + self.pack_start(ent, 1, 1, 1) + +class OtherEditor(BitwiseEditor): + def _build_ui(self): + name = classname(self._element) + name = bitwise_type(name) + if isinstance(self._element, bitwise.arrayDataElement): + name += " %s[%i]" % ( + bitwise_type(classname(self._element[0])), + len(self._element)) + + l = gtk.Label(name) + l.show() + self.pack_start(l, 1, 1, 1) + +class RadioBrowser(common.Editor): + def _build_ui(self): + self._display = gtk.Table(20, 2) + + self._store = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_PYOBJECT) + self._tree = gtk.TreeView(self._store) + + rend = gtk.CellRendererText() + tvc = gtk.TreeViewColumn('Element', rend, text=0) + self._tree.append_column(tvc) + self._tree.connect('button_press_event', self._tree_click) + self._tree.set_size_request(200, -1) + + self.root = gtk.HBox(False, 3) + sw = gtk.ScrolledWindow() + sw.add(self._tree) + sw.show() + self.root.pack_start(sw, 0, 0, 0) + sw = gtk.ScrolledWindow() + sw.add_with_viewport(self._display) + sw.show() + self.root.pack_start(sw, 1, 1, 1) + self._tree.show() + self._display.show() + self.root.show() + + def _fill(self, name, obj, parent=None): + iter = self._store.append(parent, (name, obj)) + + if isinstance(obj, bitwise.structDataElement): + for name, item in obj.items(): + if isinstance(item, bitwise.structDataElement): + self._fill(name, item, iter) + elif isinstance(item, bitwise.arrayDataElement): + self._fill("%s[%i]" % (name, len(item)), item, iter) + elif isinstance(obj, bitwise.arrayDataElement): + i = 0 + for item in obj: + if isinstance(obj[0], bitwise.structDataElement): + self._fill("%s[%i]" % (name, i), item, iter) + i += 1 + + def _tree_click(self, view, event): + if event.button != 1: + return + + index = [0] + + def pack(widget, pos): + self._display.attach(widget, pos, pos + 1, index[0], index[0] + 1, + xoptions=gtk.FILL, yoptions=0) + + def next_row(): + index[0] += 1 + + def abandon(child): + self._display.remove(child) + + pathinfo = view.get_path_at_pos(int(event.x), int(event.y)) + path = pathinfo[0] + iter = self._store.get_iter(path) + name, obj = self._store.get(iter, 0, 1) + + self._display.foreach(abandon) + + for name, item in obj.items(): + if item.size() % 8 == 0: + name = '<b>%s</b> <small>(%s %i bytes)</small>' % ( + name, bitwise_type(classname(item)), item.size() / 8) + else: + name = '<b>%s</b> <small>(%s %i bits)</small>' % ( + name, bitwise_type(classname(item)), item.size()) + l = gtk.Label(name + " ") + l.set_use_markup(True) + l.show() + pack(l, 0) + + if (isinstance(item, bitwise.intDataElement) or + isinstance(item, bitwise.bcdDataElement)): + e = IntegerEditor(item) + elif (isinstance(item, bitwise.arrayDataElement) and + isinstance(item[0], bitwise.bcdDataElement)): + e = BCDArrayEditor(item) + elif (isinstance(item, bitwise.arrayDataElement) and + isinstance(item[0], bitwise.charDataElement)): + e = CharArrayEditor(item) + else: + e = OtherEditor(item) + e.show() + pack(e, 1) + next_row() + + + def __init__(self, rthread): + super(RadioBrowser, self).__init__(rthread) + self._radio = rthread.radio + self._focused = False + self._build_ui() + self._fill('root', self._radio._memobj) + + def focus(self): + self._focused = True + + def unfocus(self): + if self._focused: + self.emit("changed") + self._focused = False + +if __name__ == "__main__": + from chirp import * + from chirp import directory + import sys + + r = directory.get_radio_by_image(sys.argv[1]) + class Foo: + radio = r + w = gtk.Window() + b = RadioBrowser(Foo) + w.set_default_size(1024, 768) + w.add(b.root) + w.show() + gtk.main() diff --git a/chirpui/settingsedit.py b/chirpui/settingsedit.py index b67982f..535296b 100644 --- a/chirpui/settingsedit.py +++ b/chirpui/settingsedit.py @@ -26,9 +26,8 @@ class RadioSettingProxy(settings.RadioSetting): class SettingsEditor(common.Editor): def __init__(self, rthread): - common.Editor.__init__(self) - self._rthread = rthread - + super(SettingsEditor, self).__init__(rthread) + self._changed = False self.root = gtk.HBox(False, 10) self._store = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_PYOBJECT) @@ -57,15 +56,23 @@ class SettingsEditor(common.Editor): job = common.RadioJob(self._build_ui, "get_settings") job.set_desc("Getting radio settings") - self._rthread.submit(job) + self.rthread.submit(job) def _save_settings(self): if self._top_setting_group is None: return - job = common.RadioJob(None, "set_settings", self._top_setting_group) + def setting_cb(result): + if isinstance(result, Exception): + common.show_error(_("Error in setting value: %s") % result) + elif self._changed: + self.emit("changed") + self._changed = False + + job = common.RadioJob(setting_cb, "set_settings", + self._top_setting_group) job.set_desc("Setting radio settings") - self._rthread.submit(job) + self.rthread.submit(job) def _load_setting(self, value, widget): if isinstance(value, settings.RadioSettingValueInteger): @@ -73,6 +80,8 @@ class SettingsEditor(common.Editor): adj.configure(value.get_value(), value.get_min(), value.get_max(), value.get_step(), 1, 0) + elif isinstance(value, settings.RadioSettingValueFloat): + widget.set_text(value.format()) elif isinstance(value, settings.RadioSettingValueBoolean): widget.set_active(value.get_value()) elif isinstance(value, settings.RadioSettingValueList): @@ -89,9 +98,11 @@ class SettingsEditor(common.Editor): print "Unsupported widget type %s for %s" % (value.__class__, element.get_name()) - def _save_setting(self, widget, value): + def _do_save_setting(self, widget, value): if isinstance(value, settings.RadioSettingValueInteger): value.set_value(widget.get_adjustment().get_value()) + elif isinstance(value, settings.RadioSettingValueFloat): + value.set_value(widget.get_text()) elif isinstance(value, settings.RadioSettingValueBoolean): value.set_value(widget.get_active()) elif isinstance(value, settings.RadioSettingValueList): @@ -103,8 +114,15 @@ class SettingsEditor(common.Editor): element.value.__class__, element.get_name()) + self._changed = True self._save_settings() + def _save_setting(self, widget, value): + try: + self._do_save_setting(widget, value) + except settings.InvalidValueError, e: + common.show_error(_("Invalid setting value: %s") % e) + def _build_ui_group(self, group): def pack(widget, pos): self._table.attach(widget, pos, pos+1, self._index, self._index+1, @@ -139,6 +157,9 @@ class SettingsEditor(common.Editor): widget = gtk.SpinButton() print "Digits: %i" % widget.get_digits() signal = "value-changed" + elif isinstance(value, settings.RadioSettingValueFloat): + widget = gtk.Entry() + signal = "focus-out-event" elif isinstance(value, settings.RadioSettingValueBoolean): widget = gtk.CheckButton(_("Enabled")) signal = "toggled" @@ -157,10 +178,16 @@ class SettingsEditor(common.Editor): lalign.add(widget) lalign.show() + widget.set_sensitive(value.get_mutable()) + arraybox.pack_start(lalign, 1, 1, 1) widget.show() self._load_setting(value, widget) - widget.connect(signal, self._save_setting, value) + if signal == "focus-out-event": + widget.connect(signal, lambda w, e, v: + self._save_setting(w, v), value) + else: + widget.connect(signal, self._save_setting, value) self._index += 1 diff --git a/chirpui/shiftdialog.py b/chirpui/shiftdialog.py index f35802e..0ca50a4 100644 --- a/chirpui/shiftdialog.py +++ b/chirpui/shiftdialog.py @@ -65,12 +65,15 @@ class ShiftDialog(gtk.Dialog): count / len(memories)) i.number = dst - self.rthread.radio.set_memory(i) + if i.empty: + self.rthread.radio.erase_memory(i.number) + else: + self.rthread.radio.set_memory(i) count += 1.0 return int(count) - def _get_mems_until_hole(self, start, endokay=False): + def _get_mems_until_hole(self, start, endokay=False, all=False): mems = [] llimit, ulimit = self.rthread.radio.get_features().memory_bounds @@ -81,7 +84,7 @@ class ShiftDialog(gtk.Dialog): number=pos), 0) try: mem = self.rthread.radio.get_memory(pos) - if mem.empty: + if mem.empty and not all: break except errors.InvalidMemoryLocation: break @@ -109,9 +112,8 @@ class ShiftDialog(gtk.Dialog): print "No memory list?" return 0 - def _delete_hole(self, start): - mems = self._get_mems_until_hole(start+1, endokay=True) - + def _delete_hole(self, start, all=False): + mems = self._get_mems_until_hole(start+1, endokay=True, all=all) if mems: count = self._shift_memories(-1, mems) self.rthread.radio.erase_memory(count+start) @@ -126,12 +128,12 @@ class ShiftDialog(gtk.Dialog): else: gobject.idle_add(self.set_response_sensitive, gtk.RESPONSE_OK, True) - def threadfn(self, newhole, func): + def threadfn(self, newhole, func, *args): self.status("Waiting for radio to become available", 0) self.rthread.lock() try: - count = func(newhole) + count = func(newhole, *args) except errors.InvalidMemoryLocation, e: self.status(str(e), 0) self.finished() @@ -145,13 +147,13 @@ class ShiftDialog(gtk.Dialog): def insert(self, newhole, quiet=False): self.quiet = quiet self.thread = threading.Thread(target=self.threadfn, - args=(newhole,self._insert_hole)) + args=(newhole, self._insert_hole)) self.thread.start() gtk.Dialog.run(self) - def delete(self, newhole, quiet=False): + def delete(self, newhole, quiet=False, all=False): self.quiet = quiet self.thread = threading.Thread(target=self.threadfn, - args=(newhole,self._delete_hole)) + args=(newhole, self._delete_hole, all)) self.thread.start() gtk.Dialog.run(self) |
