当前位置: 首页>>代码示例>>Python>>正文


Python Pile.options方法代码示例

本文整理汇总了Python中urwid.Pile.options方法的典型用法代码示例。如果您正苦于以下问题:Python Pile.options方法的具体用法?Python Pile.options怎么用?Python Pile.options使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在urwid.Pile的用法示例。


在下文中一共展示了Pile.options方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: DeployView

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class DeployView(WidgetWrap):

    def __init__(self, display_controller, placement_controller,
                 placement_view):
        self.display_controller = display_controller
        self.placement_controller = placement_controller
        self.placement_view = placement_view
        self.prev_status = None
        w = self.build_widgets()
        super().__init__(w)
        self.update()

    def selectable(self):
        return True

    def build_widgets(self):
        self.deploy_ok_msg = ("\u2713 All the required OpenStack services are "
                              "placed on a machine, and you can now deploy.")

        self.deploy_button = AttrMap(
            Button("Deploy", on_press=self.do_deploy),
            'button_primary', 'button_primary focus')
        self.deploy_grid = GridFlow([self.deploy_button], 10, 1, 0, 'center')

        self.unplaced_msg = "Some required services are still unassigned."

        self.main_pile = Pile([Divider()])
        return self.main_pile

    def update(self):
        changed = self.prev_status != self.placement_controller.can_deploy()

        if self.placement_controller.can_deploy():
            if changed:
                self.show_deploy_button()
        else:
            self.main_pile.contents[0] = (Divider(),
                                          self.main_pile.options())
            if changed:
                self.display_controller.status_error_message(self.unplaced_msg)

        self.prev_status = self.placement_controller.can_deploy()

    def show_deploy_button(self):
        self.main_pile.contents[0] = (AttrMap(self.deploy_grid,
                                              'deploy_highlight_start'),
                                      self.main_pile.options())
        self.display_controller.status_info_message(self.deploy_ok_msg)

    def do_deploy(self, sender):
        self.placement_view.do_deploy_cb()
开发者ID:mikemccracken,项目名称:bundle-placement,代码行数:53,代码来源:__init__.py

示例2: Header

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class Header(WidgetWrap):

    TITLE_TEXT = "Ubuntu OpenStack Installer - Dashboard"

    def __init__(self):
        self.text = Text(self.TITLE_TEXT)
        self.widget = Color.frame_header(self.text)
        self.pile = Pile([self.widget, Text("")])
        self.set_show_add_units_hotkey(False)
        super().__init__(self.pile)

    def set_openstack_rel(self, release):
        self.text.set_text("{} ({})".format(self.TITLE_TEXT, release))

    def set_show_add_units_hotkey(self, show):
        self.show_add_units = show
        self.update()

    def update(self):
        if self.show_add_units:
            add_unit_string = "(A)dd Services \N{BULLET}"
        else:
            add_unit_string = ""
        tw = Color.frame_subheader(
            Text(add_unit_string + " (H)elp \N{BULLET} " "(R)efresh \N{BULLET} (Q)uit", align="center")
        )
        self.pile.contents[1] = (tw, self.pile.options())
开发者ID:kavinsivak,项目名称:openstack-installer,代码行数:29,代码来源:gui.py

示例3: Header

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class Header(WidgetWrap):

    def __init__(self):
        self.title_widget = Color.frame_header(padding(Text(TITLE_TEXT)))
        self.pile = Pile([self.title_widget, Text("")])
        self.set_show_add_units_hotkey(False)
        super().__init__(self.pile)

    def set_show_add_units_hotkey(self, show):
        self.show_add_units = show
        self.update()

    def update(self):
        if self.show_add_units:
            add_unit_string = '(A)dd Services \N{BULLET}'
        else:
            add_unit_string = ''
        tw = Color.frame_subheader(Text(add_unit_string + ' (H)elp \N{BULLET} '
                                        '(R)efresh \N{BULLET} (Q)uit',
                                        align='center'))
        self.pile.contents[1] = (tw, self.pile.options())
开发者ID:laboshinl,项目名称:openstack-installer,代码行数:23,代码来源:gui.py

示例4: render_text

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
def render_text(text, K):
    # XXX: make this code lazy-reader reader-proxy aware
    txts = [make_text(t, K.width) for t in text.split('\n')]
    K.txts = txts
    piles = []
    p = Pile([])
    for t in txts[:]:
        #if 'What emerges' in t.text: pu.db
        p.contents.append((t, p.options()))
        t_size = t.rows((K.width,))
        #if piles and h(piles[-1]) > height: pu.db
        while h(p, K) > K.height:
            # Add a new pile, and send the trimmings in there
            piles.append(p)
            d = h(t, K) - (h(p, K) - K.height)
            
            #if d <= 0: pu.db
            
            # start the next column
            p_new = Pile([])
            t_extra = trim(t, d, K.width)
            # TODO: include diff status in here, and line numbers
            p_new.contents.append((t_extra, p.options()))
            p = p_new
            t = t_extra


        #if piles and h(piles[-1]) > height:
        #    # ACK!
        #    break
        if h(p, K) == K.height:
            piles.append(p)
            # start the next column
            p = Pile([])

    # all done, don't forget the last pile which we haven't added to the list yet
    piles.append(p)


    palette = [
        ('black',  'light gray', 'black'),
        ('heading', 'black', 'light gray'),
        ('important', 'black', 'light cyan'),
        ('line', 'black', 'light gray'),
        ('options', 'dark gray', 'black'),
        ('focus heading', 'white', 'dark red'),
        ('focus line', 'black', 'dark red'),
        ('diff old', 'dark red', 'black'),
        ('diff new', 'dark green', 'black'),
        ('focus options', 'black', 'light gray'),
        ('pg normal',    'white',      'black', 'standout'),
        ('pg complete',  'white',      'dark magenta'),
        ('selected', 'white', 'dark blue')]

    #piles = urwid.ListBox(urwid.SimpleFocusListWalker(piles))
    #cols = piles
    #fill = cols
    dc = int(K.max_width / K.width) # number of displayed columns
    while len(piles)  < int(dc):
        piles.append(Pile([]))
    cols = urwid.Columns(piles[:dc], dividechars=1, min_width=K.width)
    K.cols = cols
    col_widths = cols.column_widths(K.screen.get_cols_rows())
    K.displayed_columns = len( col_widths )

    def tmp_generator():
        for x in piles:
            yield urwid.Columns([x], dividechars=1, min_width=K.width)
    K.reader = LazyReader(tmp_generator())


    # XXX: I need to subclass columns, and make it so the keypress function
    # "rolls" the piles under the hood, and re-renders all the widgets.
    #
    # self.contents.append(self.contents.pop(0))
    #
    #cols.box_columns.extend(cols.widget_list)


    #grid = urwid.GridFlow(txts, cell_width=20, h_sep=4, v_sep=0, align='left')
    fill = urwid.Filler(cols, 'top', top=K.top_margin)
    K.total_cols = len(piles)

    # XXX: this is not the full story, it ignores the borders between columns
    c_columns = [sum(col_widths[:i+1]) for i in  range(K.displayed_columns)]
    border = (K.max_width - c_columns[-1]) /  K.displayed_columns
    def xpos_to_col(pos):
        for i,c in enumerate(c_columns):
            if pos < (c + i * border):
                return i

    K.xpos_to_col = xpos_to_col
    pbar = ProgressBar('pg normal', 'pg complete', K.displayed_columns, K.total_cols)
    K.pbar = pbar


    p = urwid.ListBox(urwid.SimpleListWalker([pbar]))

    all = Pile([ fill, (1, p), ])
    cmd_line_text = urwid.Edit(K.fname)
#.........这里部分代码省略.........
开发者ID:ivanov,项目名称:kanten,代码行数:103,代码来源:kanten.py

示例5: ServicesList

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class ServicesList(WidgetWrap):

    """A list of services with flexible display options.

    Note that not all combinations of display options make sense. YMMV.

    controller - a PlacementController

    display_controller - a PlacerView

    machine - a machine instance to query for constraint checking. If
    None, no constraint checking is done. If set, only services whose
    constraints are satisfied by 'machine' are shown.

    """

    def __init__(self, placement_controller, display_controller,
                 show_placements=False, title="Services"):
        self.placement_controller = placement_controller
        self.display_controller = display_controller
        self.service_widgets = []
        self.show_placements = show_placements
        self.title = title
        w = self.build_widgets()
        self.update()
        super().__init__(w)

    def selectable(self):
        # overridden to ensure that we can arrow through the buttons
        # shouldn't be necessary according to documented behavior of
        # Pile & Columns, but discovered via trial & error.
        return True

    def build_widgets(self):
        widgets = []
        if self.title:
            widgets = [Text(self.title), Divider(' ')]
        widgets += self.service_widgets
        self.service_pile = Pile(widgets)
        return self.service_pile

    def focus_top_or_next(self):
        return self._setfocus(top=False)

    def focus_top(self):
        return self._setfocus(top=True)

    def _setfocus(self, top):
        try:
            if top:
                self.service_pile.focus_position = 0
            else:
                pos = self.service_pile.focus_position
                if pos + 1 >= len(self.service_widgets):
                    return False
                self.service_pile.focus_position = pos + 1
        except IndexError:
            log.debug("caught indexerror in servicescolumn.focus_next")
            return False
        return True

    def focused_service_widget(self):
        if len(self.service_widgets) > 0:
            return self.service_pile.focus
        return None

    def find_service_widget(self, s):
        return next((sw for sw in self.service_widgets if
                     sw.service.service_name == s.service_name),
                    None)

    def update(self):
        for s in self.placement_controller.services():

            sw = self.find_service_widget(s)
            if sw is None:
                sw = self.add_service_widget(s)
            sw.update()

        allnames = [s.service_name
                    for s in self.placement_controller.services()]
        for sw in self.service_widgets:
            if sw.service.service_name not in allnames:
                self.remove_service_widget(sw.service)

        self.sort_service_widgets()

    def add_service_widget(self, service):
        sw = SimpleServiceWidget(service, self.placement_controller,
                                 self.display_controller,
                                 show_placements=self.show_placements)
        self.service_widgets.append(sw)
        options = self.service_pile.options()
        self.service_pile.contents.append((sw, options))

        # NOTE: see the + 1: indexing in remove_service_widget if you
        # re-add this divider. it should then be +2.

        # self.service_pile.contents.append((AttrMap(Padding(Divider('\u23bc'),
        #                                                    left=2, right=2),
#.........这里部分代码省略.........
开发者ID:Ubuntu-Solutions-Engineering,项目名称:bundle-placement,代码行数:103,代码来源:services_list.py

示例6: MachineWaitView

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class MachineWaitView(WidgetWrap):

    def __init__(self, display_controller, installer, config):
        self.display_controller = display_controller
        self.installer = installer
        self.config = config
        creds = self.config.getopt('maascreds')
        if os.getenv("FAKE_API_DATA"):
            self.maas_client = None
            self.maas_state = FakeMaasState()
        else:
            self.maas_client, self.maas_state = connect_to_maas(creds)
        self.spinner = Spinner(15, 4)
        w = self.build_widgets()
        super().__init__(w)
        self.update()

    def build_widgets(self):
        self.message = Text("Please review available machines in MAAS",
                            align='center')

        self.button_pile = Pile([])

        self.main_pile = Pile([self.message,
                               Divider(),
                               self.button_pile])
        return Filler(self.main_pile, valign='middle')

    def keypress(self, size, key):
        key = {'tab': 'down', 'shift tab': 'up'}.get(key, key)
        return super().keypress(size, key)

    def scroll_down(self):
        pass

    def scroll_up(self):
        pass

    def selectable(self):
        return True

    def get_status(self):
        " returns (global_ok, [ok, condition])"
        self.maas_state.invalidate_nodes_cache()
        machines = self.maas_state.machines(state=MaasMachineStatus.READY)
        powerable_machines = [m for m in machines if m.power_type is not None]
        n_powerable = len(powerable_machines)

        conditions = [(n_powerable >= 1,
                       "At least one machine enlisted with power "
                       "control (currently {})".format(n_powerable))]

        global_ok = all([ok for ok, _ in conditions])
        return global_ok, conditions

    def update(self):
        msg = ("Before continuing, ensure that at least one machine is "
               "enlisted into MAAS:")
        self.message = Text(self.spinner.next_frame() + ['\n', msg, '\n'],
                            align='center')
        contents = [(self.message,
                     self.main_pile.options())]

        global_ok, statuses = self.get_status()
        status_map = {True: ('success_icon', "\u2713 "),
                      False: ('error_icon', "<!> ")}
        contents += [(Text([status_map[status], condition],
                           align='center'),
                      self.main_pile.options())
                     for status, condition
                     in statuses]
        contents += [(Divider(), self.main_pile.options()),
                     (self.button_pile, self.main_pile.options())]
        self.main_pile.contents = contents

        if not global_ok:
            b = AttrMap(SelectableIcon(" ( Can't Continue ) "),
                        'disabled_button', 'disabled_button_focus')
        else:
            b = AttrMap(Button("Continue",
                               on_press=self.do_continue),
                        'button_primary', 'button_primary focus')

        cancel_b = AttrMap(Button("Cancel",
                                  on_press=self.do_cancel),
                           'button_secondary',
                           'button_secondary focus')
        self.button_pile.contents = [(Padding(cancel_b, width=24,
                                              align='center'),
                                      self.button_pile.options()),
                                     (Padding(b, width=24, align='center'),
                                      self.button_pile.options())]

        # ensure that the button is always focused:
        self.main_pile.focus_position = len(self.main_pile.contents) - 1

    @utils.async
    def do_continue(self, *args, **kwargs):
        self.installer.do_install()

#.........这里部分代码省略.........
开发者ID:JamesGuthrie,项目名称:openstack-installer,代码行数:103,代码来源:machinewait.py

示例7: JujuMachineWidget

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]

#.........这里部分代码省略.........
        mps = self.controller.get_all_assignments(self.juju_machine_id)
        if len(mps) > 0:
            if self.show_assignments:
                ad = defaultdict(list)
                for application, atype in mps:
                    ad[atype].append(application)
                astr = " ".join(["{}{}".format(
                    atype_to_label([atype])[0],
                    ",".join([application.service_name
                              for application in al]))
                    for atype, al in ad.items()])
                assignments.append(astr)
        else:
            if self.show_assignments:
                assignments.append("-")

        if any([application == self.application for application, _ in mps]):
            action = self.do_remove
            label = "Remove"
        else:
            action = self.do_select
            label = "Select"

        self.select_button = PlainButton(label, action)

        cols = [Text(s) for s in assignments]

        current_assignments = [a for a, _ in mps if a == self.application]
        if self.all_assigned and len(current_assignments) == 0:
            cols.append(Text(""))
        else:
            cols += [AttrMap(self.select_button, 'text',
                             'button_secondary focus')]
        opts = self.unselected_columns.options()
        self.unselected_columns.contents[4:] = [(w, opts) for w in cols]

    def update(self):
        self.update_action_buttons()

        if self.is_selected:
            self.update_selected()
        else:
            self.update_unselected()

    def update_selected(self):
        cn = self.application.service_name
        msg = Text("  Add {} to machine #{}:".format(cn,
                                                     self.juju_machine_id))
        self.pile.contents = [(msg, self.pile.options()),
                              (self.action_button_cols,
                               self.pile.options()),
                              (Divider(), self.pile.options())]

    def update_unselected(self):
        if self.show_pin:
            pinned_machine = self.controller.get_pin(self.juju_machine_id)

            if pinned_machine:
                pin_label = " {} \N{PENCIL}".format(pinned_machine.hostname)
            else:
                pin_label = " \N{PENCIL}"
            self.juju_machine_id_button.set_label('{:20s}'.format(
                self.juju_machine_id + " " + pin_label))
        else:
            self.juju_machine_id_label.set_text('{:20s}'.format(
                self.juju_machine_id))
开发者ID:conjure-up,项目名称:conjure-up,代码行数:70,代码来源:juju_machine_widget.py

示例8: DeployView

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class DeployView(WidgetWrap):

    def __init__(self, display_controller, placement_controller,
                 placement_view):
        self.display_controller = display_controller
        self.placement_controller = placement_controller
        self.placement_view = placement_view
        self.prev_status = None
        w = self.build_widgets()
        super().__init__(w)
        self.update()

    def selectable(self):
        return True

    def build_widgets(self):
        self.deploy_ok_msg = ("\u2713 All the core OpenStack services are "
                              "placed on a machine, and you can now deploy.")

        self.deploy_button = AttrMap(Button("Deploy",
                                            on_press=self.do_deploy),
                                     'button', 'button_focus')
        self.deploy_grid = GridFlow([self.deploy_button], 10, 1, 0, 'center')

        self.unplaced_msg = "Some core services are still unplaced."

        self.main_pile = Pile([Divider()])
        return self.main_pile

    def update(self):
        changed = self.prev_status != self.placement_controller.can_deploy()

        if self.placement_controller.can_deploy():
            if changed:
                self.show_deploy_button()
        else:
            self.main_pile.contents[0] = (Divider(),
                                          self.main_pile.options())
            if changed:
                self.display_controller.error_message(self.unplaced_msg)

        self.prev_status = self.placement_controller.can_deploy()

    def show_deploy_button(self):
        self.main_pile.contents[0] = (AttrMap(self.deploy_grid,
                                              'deploy_highlight_start'),
                                      self.main_pile.options())

        def fade_timeout(loop, step):
            if step == 1:
                self.display_controller.loop.set_alarm_in(5, fade_timeout, 2)
                new_attr = 'deploy_highlight_end'
            else:
                new_attr = ''
            self.main_pile.contents[0] = (AttrMap(self.deploy_grid,
                                                  new_attr),
                                          self.main_pile.options())

        self.display_controller.loop.set_alarm_in(4, fade_timeout, 1)
        self.display_controller.info_message(self.deploy_ok_msg)

    def do_deploy(self, sender):
        self.display_controller.commit_placement()
开发者ID:chrisglass,项目名称:openstack-installer,代码行数:65,代码来源:ui.py

示例9: CharmstoreColumn

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class CharmstoreColumn(WidgetWrap):

    def __init__(self, display_controller, placement_controller,
                 placement_view, metadata_controller):
        self.placement_controller = placement_controller
        self.display_controller = display_controller
        self.placement_view = placement_view
        self.metadata_controller = metadata_controller
        self.state = CharmstoreColumnUIState.RELATED
        self.prev_state = None
        self.current_search_string = ""
        w = self.build_widgets()
        super().__init__(w)
        self._related_charms = []
        self._bundle_results = []
        self._charm_results = []
        self._recommended_charms = []
        self.loading = True
        self.update()

    def build_widgets(self):
        self.title = Text('')
        self.pile = Pile([self.title])
        return self.pile

    def clear_search_results(self):
        self._bundle_results = []
        self._charm_results = []

    def handle_search_change(self, s):
        if s == "":
            self.state = CharmstoreColumnUIState.RELATED
            self.clear_search_results()
        else:
            self.state = CharmstoreColumnUIState.SEARCH_RESULTS
        self.current_search_string = s
        self.loading = True
        self.update()

    def remove_existing_charms(self, charms):
        existing_charms = [CharmStoreID(s.charm_source).as_str_without_rev()
                           for s in
                           self.placement_controller.bundle.services]
        return [c for c in charms
                if CharmStoreID(c['Id']).as_str_without_rev()
                not in existing_charms]

    def get_filtered_recommendations(self):
        opts = self.pile.options()
        if len(self._recommended_charms) == 0:
            mc = self.metadata_controller
            self._recommended_charms = mc.get_recommended_charms()
        return [(CharmWidget(d, self.do_add_charm, recommended=True), opts)
                for d in self.remove_existing_charms(self._recommended_charms)]

    def update(self):
        opts = self.pile.options()
        extra_widgets = []
        recommended_widgets = []
        if self.metadata_controller.loaded():
            recommended_widgets = self.get_filtered_recommendations()
            if len(recommended_widgets) > 0:
                top_w = recommended_widgets[0][0]
                top_w.set_header("Recommended Charms")

            self.loading = False

        series = self.placement_controller.bundle.series
        bundle_widgets = [(BundleWidget(d, self.do_add_bundle),
                           opts) for d in self._bundle_results
                          if 'bundle-metadata' in d.get('Meta', {}) and
                          'Series' in d['Meta']['bundle-metadata'] and
                          d['Meta']['bundle-metadata']['Series'] == series]

        if len(bundle_widgets) > 0:
            top_w = bundle_widgets[0][0]
            top_w.set_header("Bundles")

        filtered_charm_results = self.remove_existing_charms(
            self._charm_results)
        filtered_charm_results = filtered_charm_results[:10]

        charm_widgets = [(CharmWidget(d, self.do_add_charm),
                          opts) for d in filtered_charm_results
                         if 'charm-metadata' in d.get('Meta', {})]
        if len(charm_widgets) > 0:
            top_w = charm_widgets[0][0]
            top_w.set_header("Charms")

        if self.state == CharmstoreColumnUIState.RELATED:
            if self.loading:
                self.title.set_text("\nLoading Recommended "
                                    "and Popular Charms…")
            else:
                self.title.set_text("")
            extra_widgets = recommended_widgets
        else:
            if self.loading:
                msg = "\nSearching for '{}'…\n".format(
                    self.current_search_string)
#.........这里部分代码省略.........
开发者ID:Ubuntu-Solutions-Engineering,项目名称:bundle-placement,代码行数:103,代码来源:charmstore.py

示例10: SimpleMachineWidget

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class SimpleMachineWidget(WidgetWrap):

    """A widget displaying a machine. When selected, shows action buttons
    for placement types.

    machine - the machine to display

    controller - a PlacementController instance

    display_controller - a PlacerView instance

    show_assignments - display info about which charms are assigned
    and what assignment type (LXC, KVM, etc) they have.

    """

    def __init__(self, machine, controller,
                 display_controller, show_assignments=True):
        self.machine = machine
        self.controller = controller
        self.display_controller = display_controller
        self.show_assignments = show_assignments
        self.is_selected = False
        w = self.build_widgets()
        super().__init__(w)
        self.update()

    def selectable(self):
        return True

    def build_widgets(self):

        self.button = MenuSelectButton("I AM A MACHINE", self.do_select)
        self.action_button_cols = Columns([])
        self.action_buttons = []

        self.pile = Pile([self.button])
        return self.pile

    def update_machine(self):
        """Refresh with potentially updated machine info from controller.
        Assumes that machine exists - machines going away is handled
        in machineslist.update().
        """
        self.machine = next((m for m in self.controller.machines()
                             if m.instance_id == self.machine.instance_id),
                            None)

    def update(self):
        self.update_machine()
        self.update_action_buttons()

        if self.is_selected:
            self.update_selected()
        else:
            self.update_unselected()

    def info_markup(self):
        m = self.machine
        return [self.machine.hostname + "\n",
                'arch: {}  '.format(m.arch),
                'cores: {}  '.format(m.cpu_cores),
                'mem: {}  '.format(m.mem),
                'storage: {}'.format(m.storage)]

    def update_selected(self):
        cn = self.display_controller.selected_service.service_name
        msg = Text("  Add {} to {}:".format(cn,
                                            self.machine.hostname))
        self.pile.contents = [(msg, self.pile.options()),
                              (self.action_button_cols,
                               self.pile.options()),
                              (Divider(), self.pile.options())]

    def update_unselected(self):
        markup = self.info_markup()
        self.button.set_label(markup)
        self.pile.contents = [(AttrMap(self.button, 'text',
                                       'button_secondary focus'),
                               self.pile.options()),
                              (Divider(), self.pile.options())]

    def update_action_buttons(self):

        all_actions = [(AssignmentType.BareMetal,
                        'Add as Bare Metal',
                        self.select_baremetal),
                       (AssignmentType.LXD,
                        'Add as LXD',
                        self.select_lxd),
                       (AssignmentType.KVM,
                        'Add as KVM',
                        self.select_kvm)]

        sc = self.display_controller.selected_service
        if sc:
            allowed_set = set(sc.allowed_assignment_types)
            allowed_types = set([atype for atype, _, _ in all_actions])
            allowed_types = allowed_types.intersection(allowed_set)
        else:
#.........这里部分代码省略.........
开发者ID:benluteijn,项目名称:conjure-up,代码行数:103,代码来源:simple_machine_widget.py

示例11: ServiceWalkthroughView

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class ServiceWalkthroughView(WidgetWrap):
    def __init__(self, service, idx, n_total, metadata_controller, callback):
        self.callback = callback
        self.service = service
        self.idx = idx
        self.n_total = n_total
        self.n_remaining = n_total - idx - 1
        self.metadata_controller = metadata_controller
        self.info_handled = False
        w = self.build_widgets()
        super().__init__(w)
        self.get_async_info()
        if self.n_remaining == 0:
            self.pile.focus_position = len(self.pile.contents) - 1
        else:
            self.pile.focus_position = len(self.pile.contents) - 2

    def selectable(self):
        return True

    def build_widgets(self):
        self.description_w = Text("Description Loading…")
        self.readme_w = Text("README Loading…")
        self.scale_edit = IntegerEditor(default=self.service.num_units)
        connect_signal(self.scale_edit._edit, 'change',
                       self.handle_scale_changed)
        self.skip_rest_button = PlainButton(
            "Deploy all {} Remaining Applications with Bundle Defaults".format(
                self.n_remaining),
            self.do_skip_rest
        )
        col = Columns(
            [
                (6, Text('Units:', align='right')),
                (15,
                 Color.string_input(self.scale_edit,
                                    focus_map='string_input focus'))
            ], dividechars=1
        )

        if self.n_remaining == 0:
            buttons = [Padding.right_50(Color.button_primary(
                PlainButton("Deploy and Continue",
                            self.do_deploy),
                focus_map='button_primary focus'))]
        else:
            buttons = [
                Padding.right_50(Color.button_primary(
                    PlainButton(
                        "Deploy and Configure Next Application",
                        self.do_deploy),
                    focus_map='button_primary focus')),
                Padding.right_50(
                    Color.button_secondary(
                        self.skip_rest_button,
                        focus_map='button_secondary focus'))]

        ws = [Text("{} of {}: {}".format(self.idx+1, self.n_total,
                                         self.service.service_name.upper())),
              Padding.center(HR()),
              Padding.center(self.description_w, left=2),
              Padding.line_break(""),
              Padding.center(self.readme_w, left=2),
              Padding.center(HR())]

        if not self.service.subordinate:
            ws.append(Padding.left(col, left=1))

        ws.append(Padding.line_break(""))
        ws += buttons

        self.pile = Pile(ws)
        return Padding.center_90(Filler(self.pile, valign="top"))

    def get_async_info(self):
        info = self.metadata_controller.get_charm_info(
            self.service.csid.as_str_without_rev(),
            self.handle_info_updated)
        if info:
            self.handle_info_updated(info)

        self.metadata_controller.get_readme(
            self.service.csid.as_seriesname(),
            self.handle_readme_updated)

    def handle_info_updated(self, new_info):
        if self.info_handled:
            return
        self.info_handled = True
        EventLoop.loop.event_loop._loop.call_soon_threadsafe(
            self._update_info_on_main_thread,
            new_info)

    def _update_info_on_main_thread(self, new_info):
        self.description_w.set_text(
            new_info["Meta"]["charm-metadata"]["Summary"])
        self._invalidate()
        self.add_options()

    def add_options(self):
#.........这里部分代码省略.........
开发者ID:graywen24,项目名称:conjure-up,代码行数:103,代码来源:service_walkthrough.py

示例12: RelationsColumn

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class RelationsColumn(WidgetWrap):

    """UI to edit relations of a service
    """

    def __init__(self, display_controller, placement_controller,
                 placement_view, metadata_controller):
        self.placement_controller = placement_controller
        self.metadata_controller = metadata_controller
        self.service = None
        self.provides = set()
        self.requires = set()
        self.placement_view = placement_view
        w = self.build_widgets()
        super().__init__(w)
        self.update()

    def build_widgets(self):
        self.title = Text('')
        self.relation_widgets = []
        self.pile = Pile([Divider(), self.title] + self.relation_widgets)
        return self.pile

    def refresh(self):
        self.set_service(self.service)

    def set_service(self, service):
        self.service = service
        self.metadata_controller.add_charm(service.csid.as_str_without_rev())
        self.pile.contents = self.pile.contents[:2]
        self.provides = set()
        self.requires = set()
        self.relation_widgets = []

    def update(self):
        if self.service is None:
            return

        self.title.set_text(('body', "Edit relations for {}".format(
            self.service.service_name)))

        if len(self.relation_widgets) == 0:
            self.title.set_text(('body', "Loading Relations..."))
        else:
            self.title.set_text(('body', "Edit Relations: (Changes are "
                                 "saved immediately)"))

        p = set(self.metadata_controller.get_provides(
            self.service.csid.as_str_without_rev()))
        r = set(self.metadata_controller.get_requires(
            self.service.csid.as_str_without_rev()))
        new_provides = p - self.provides
        self.provides.update(p)
        new_requires = r - self.requires
        self.requires.update(r)

        mc = self.metadata_controller
        args = [(relname, iface, RelationType.Provides,
                 mc.get_services_for_iface(iface, RelationType.Requires))
                for relname, iface in sorted(new_provides)]

        args += [(relname, iface, RelationType.Requires,
                  mc.get_services_for_iface(iface, RelationType.Provides))
                 for relname, iface in sorted(new_requires)]

        for relname, iface, reltype, matches in args:
            if len(matches) == 0:
                rw = NoRelationWidget(relname, iface, reltype)
                self.relation_widgets.append(rw)
                self.pile.contents.append((rw,
                                           self.pile.options()))

            for tgt_relname, tgt_service in matches:
                if tgt_service.service_name == self.service.service_name:
                    continue
                rw = RelationWidget(self.service.service_name, relname,
                                    iface, reltype, tgt_service.service_name,
                                    tgt_relname,
                                    self.placement_controller,
                                    self.do_select)
                self.relation_widgets.append(rw)
                self.pile.contents.append((rw,
                                           self.pile.options()))

        for w, _ in self.pile.contents[2:]:
            w.update()
        self.sort_relation_widgets()

    def focus_prev_or_top(self):
        # ? self.pile.focus_position = len(self.pile.contents) - 1

        if len(self.pile.contents) <= 2:
            return
        pos = self.pile.focus_position
        if pos < 2:
            self.pile.focus_position = 2

    def do_select(self, source_relname, tgt_service_name,
                  tgt_relation_name):
        self.placement_controller.toggle_relation(self.service.service_name,
#.........这里部分代码省略.........
开发者ID:Ubuntu-Solutions-Engineering,项目名称:bundle-placement,代码行数:103,代码来源:relations_column.py

示例13: NewCloudView

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]
class NewCloudView(WidgetWrap):

    def __init__(self, app, cloud, schema, cb):
        self.app = app
        self.cloud = cloud
        self.input_items = schema
        self.cb = cb
        self.frame = Frame(body=self._build_widget(),
                           footer=self._build_footer())
        self.buttons_selected = False
        super().__init__(self.frame)

    def _build_widget(self):
        total_items = [Text(
            "Enter your {} credentials:".format(self.cloud.upper()))]
        total_items += [HR()]
        for k in self.input_items.keys():
            display = k
            if k.startswith('_'):
                # Don't treat 'private' keys as input
                continue
            if k.startswith('@'):
                # Strip public, not storable attribute
                display = k[1:]
            col = Columns(
                [
                    ('weight', 0.5, Text(display, align='right')),
                    Color.string_input(self.input_items[k],
                                       focus_map='string_input focus')
                ], dividechars=1
            )
            total_items.append(col)
            total_items.append(Padding.line_break(""))
        total_items.append(Text(""))
        self.pile = Pile(total_items)
        return Padding.center_60(Filler(self.pile, valign="top"))

    def _build_footer(self):
        cancel = menu_btn(on_press=self.cancel,
                          label="\n  BACK\n")
        confirm = menu_btn(on_press=self.submit,
                           label="\n ADD CREDENTIAL\n")
        self.buttons = Columns([
            ('fixed', 2, Text("")),
            ('fixed', 13, Color.menu_button(
                cancel,
                focus_map='button_primary focus')),
            Text(""),
            ('fixed', 20, Color.menu_button(
                confirm,
                focus_map='button_primary focus')),
            ('fixed', 2, Text(""))
        ])

        footer = Color.frame_footer(Pile([
            Padding.line_break(""),
            self.buttons
        ]))
        return footer

    def _swap_focus(self):
        if not self.buttons_selected:
            self.buttons_selected = True
            self.frame.focus_position = 'footer'
            self.buttons.focus_position = 3
        else:
            self.buttons_selected = False
            self.frame.focus_position = 'body'

    def keypress(self, size, key):
        if key in ['tab', 'shift tab']:
            self._swap_focus()
        rv = super().keypress(size, key)
        return rv

    def validate(self):
        """ Will provide an error text if any fields are blank
        """
        values = [i.value for i in self.input_items.values()
                  if isinstance(i, StringEditor)]

        if None in values:
            self.pile.contents[-1] = (
                Padding.center_60(
                    Color.error_major(
                        Text("Please fill all required fields."))),
                self.pile.options())
            return False
        return True

    def cancel(self, btn):
        self.cb(back=True)

    def submit(self, result):
        if self.validate():
            self.cb(self.input_items)
开发者ID:battlemidget,项目名称:conjure-up,代码行数:98,代码来源:newcloud.py

示例14: MachinesList

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]

#.........这里部分代码省略.........
            title_widgets = [Text("Machines" + cstr, align='center')]

        self.filter_edit_box = FilterBox(self.handle_filter_change)

        header_widgets = title_widgets + [Divider()]

        if self.show_filter_box:
            header_widgets += [self.filter_edit_box, Divider()]
        labels = ["FQDN", "Cores", "Memory (GiB)", "Storage (GiB)", ""]
        header_label_col = Columns([Text(m) for m in labels])
        header_widgets.append(header_label_col)
        self.header_padding = len(header_widgets)
        self.machine_pile = Pile(header_widgets + self.machine_widgets)
        return self.machine_pile

    def handle_filter_change(self, edit_button, userdata):
        self.filter_string = userdata
        self.update()

    def find_machine_widget(self, m):
        return next((mw for mw in self.machine_widgets if
                     mw.machine.instance_id == m.instance_id), None)

    def update(self):
        if app.maas.client:
            machines = app.maas.client.get_machines()
        else:
            machines = None

        if machines is None:
            if not self.loading:
                self.loading = True
                p = (Text("\n\nLoading...", align='center'),
                     self.machine_pile.options())
                self.machine_pile.contents.append(p)
            return

        if self.loading:
            self.loading = False
            self.machine_pile.contents = self.machine_pile.contents[:-1]

        if self.show_only_ready:
            machines = [m for m in machines
                        if m.status == MaasMachineStatus.READY]
        for mw in self.machine_widgets:
            machine = next((m for m in machines if
                            mw.machine.instance_id == m.instance_id), None)
            if machine is None:
                self.remove_machine(mw.machine)

        n_satisfying_machines = len(machines)

        def get_placement_filter_label(d):
            s = ""
            for atype, al in d.items():
                s += " ".join(["{} {}".format(cc.service_name,
                                              cc.display_name)
                               for cc in al])
            return s

        for m in machines:
            if not satisfies(m, self.constraints)[0]:
                self.remove_machine(m)
                n_satisfying_machines -= 1
                continue
开发者ID:conjure-up,项目名称:conjure-up,代码行数:69,代码来源:machines_list.py

示例15: MachinesList

# 需要导入模块: from urwid import Pile [as 别名]
# 或者: from urwid.Pile import options [as 别名]

#.........这里部分代码省略.........
                            mw.machine.instance_id == m.instance_id), None)
            if machine is None:
                self.remove_machine(mw.machine)

        n_satisfying_machines = len(machines)

        def get_placement_filter_label(d):
            s = ""
            for atype, al in d.items():
                s += " ".join(["{} {}".format(cc.service_name,
                                              cc.display_name)
                               for cc in al])
            return s

        for m in machines:
            if not satisfies(m, self.constraints)[0]:
                self.remove_machine(m)
                n_satisfying_machines -= 1
                continue

            assignment_names = ""
            ad = self.controller.assignments_for_machine(m)
            assignment_names = get_placement_filter_label(ad)
            filter_label = "{} {}".format(m.filter_label(),
                                          assignment_names)
            if self.filter_string != "" and \
               self.filter_string not in filter_label:
                self.remove_machine(m)
                continue

            mw = self.find_machine_widget(m)
            if mw is None:
                mw = self.add_machine_widget(m)
            mw.update()

        self.filter_edit_box.set_info(len(self.machine_widgets),
                                      n_satisfying_machines)

        self.sort_machine_widgets()

    def add_machine_widget(self, machine):
        mw = SimpleMachineWidget(machine,
                                 self.controller,
                                 self.display_controller,
                                 self.show_assignments)
        self.machine_widgets.append(mw)
        options = self.machine_pile.options()
        self.machine_pile.contents.append((mw, options))

        # NOTE: see the +1: indexing in remove_machine if you re-add
        # this divider. it should then be +2.

        # self.machine_pile.contents.append((AttrMap(Padding(Divider('\u23bc'),
        #                                                    left=2, right=2),
        #                                            'label'), options))
        return mw

    def remove_machine(self, machine):
        mw = self.find_machine_widget(machine)
        if mw is None:
            return

        self.machine_widgets.remove(mw)
        mw_idx = 0
        for w, opts in self.machine_pile.contents:
            if w == mw:
                break
            mw_idx += 1

        c = self.machine_pile.contents[:mw_idx] + \
            self.machine_pile.contents[mw_idx + 1:]
        self.machine_pile.contents = c

    def sort_machine_widgets(self):
        def keyfunc(mw):
            m = mw.machine
            hwinfo = " ".join(map(str, [m.arch, m.cpu_cores, m.mem,
                                        m.storage]))
            if str(mw.machine.status) == 'ready':
                skey = 'A'
            else:
                skey = str(mw.machine.status)
            return skey + mw.machine.hostname + hwinfo
        self.machine_widgets.sort(key=keyfunc)

        def wrappedkeyfunc(t):
            mw, options = t
            if not isinstance(mw, SimpleMachineWidget):
                return 'A'
            return keyfunc(mw)

        self.machine_pile.contents.sort(key=wrappedkeyfunc)

    def focus_prev_or_top(self):
        self.update()
        try:
            if self.machine_pile.focus_position <= self.header_padding:
                self.machine_pile.focus_position = self.header_padding
        except IndexError:
            log.debug("index error in machines_list focus_top")
开发者ID:benluteijn,项目名称:conjure-up,代码行数:104,代码来源:machines_list.py


注:本文中的urwid.Pile.options方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。