Exemple #1
0
    def create_button(self, widget_key):
        """create_button does not call .set_widget, as the widget contains no relevant data"""
        leftcol_suffix = self.leftcol_default_suffix

        first_col_text = self.button_firstcol_text(widget_key)
        button_text = self.button_secondcol_text(widget_key)

        if not first_col_text:
            # Don't show a suffix on an empty left column...
            leftcol_suffix = ""

            # Button text MUST be set. If not, use the description on the button instead
        if first_col_text == None:
            first_col_text = ""
        if button_text == None:
            button_text = ""
        list_columns_item, button_widget = self.urwid_twocol_button(
            first_col_text,
            button_text,
            equal_space=True,
            width_first_col=self.descr_colwidth,
            leftcol_suffix=leftcol_suffix,
        )
        self.set_widget_result(widget_key, False)
        urwid.connect_signal(button_widget, "click", self.manual_button_click, widget_key)
        return list_columns_item
Exemple #2
0
 def restoreChange(self):
     dialog = mywid.TextEditDialog(u'Restore Change', u'Restore message:',
                                   u'Restore Change', u'')
     urwid.connect_signal(dialog, 'cancel', self.app.backScreen)
     urwid.connect_signal(dialog, 'save', lambda button:
                          self.doAbandonRestoreChange(dialog, 'NEW'))
     self.app.popup(dialog)
Exemple #3
0
def item_chosen(button, choice):
	""" performs action on a selected line """
	response = urwid.Text([u'You chose ', choice, u'\n'])
	done = urwid.Button(u'Ok')
	urwid.connect_signal(done, 'click', exit_on_q)
	main.original_widget = urwid.Filler(urwid.Pile([response,
		urwid.AttrMap(done, None, focus_map='reversed')]))
Exemple #4
0
    def __init__(self, revert_order, remove_bash_prefix, remove_zsh_prefix, regexp, case_sensitive,
                 remove_duplicates, show_hits, infile):

        self.show_hits = show_hits
        self.regexp_modifier = regexp
        self.case_modifier = case_sensitive
        self.remove_bash_prefix = remove_bash_prefix

        self.list_items = []

        if revert_order:
            lines = reversed(infile.readlines())
        else:
            lines = infile

        for line in lines:
            if remove_bash_prefix:
                line = line.split(None, 1)[1].strip()

            if remove_zsh_prefix:
                line = re.split('\s+', line, maxsplit=4)[-1]

            if 'selecta <(history)' not in line:
                if not remove_duplicates or line not in self.list_items:
                    self.list_items.append(line)

        self.list_item_widgets = []

        self.line_count_display = LineCountWidget('')
        self.search_edit = SearchEdit(edit_text='')

        self.modifier_display = urwid.Text('')

        urwid.connect_signal(self.search_edit, 'done', self.edit_done)
        urwid.connect_signal(self.search_edit, 'toggle_case_modifier', self.toggle_case_modifier)
        urwid.connect_signal(self.search_edit, 'toggle_regexp_modifier', self.toggle_regexp_modifier)
        urwid.connect_signal(self.search_edit, 'change', self.edit_change)

        header = urwid.AttrMap(urwid.Columns([
            urwid.AttrMap(self.search_edit, 'input', 'input'),
            self.modifier_display,
            ('pack', self.line_count_display),
        ], dividechars=1, focus_column=0), 'head', 'head')

        self.item_list = urwid.SimpleListWalker(self.list_item_widgets)
        self.listbox = ResultList(self.item_list)

        urwid.connect_signal(self.listbox, 'resize', self.list_resize)

        self.view = urwid.Frame(body=self.listbox, header=header)

        self.loop = urwid.MainLoop(self.view, palette, unhandled_input=self.on_unhandled_input)
        self.loop.screen.set_terminal_properties(colors=256)

        self.line_count_display.update(self.listbox.last_size, len(self.item_list))

        # TODO workaround, when update_list is called directly, the linecount widget gets not updated
        self.loop.set_alarm_in(0.01, lambda *loop: self.update_list(''))

        self.loop.run()
Exemple #5
0
 def editTopic(self):
     dialog = view_change.EditTopicDialog(self.app, '')
     urwid.connect_signal(dialog, 'save',
         lambda button: self.closeEditTopic(dialog, True))
     urwid.connect_signal(dialog, 'cancel',
         lambda button: self.closeEditTopic(dialog, False))
     self.app.popup(dialog)
Exemple #6
0
 def welcome(self):
     text = WELCOME_TEXT
     dialog = mywid.MessageDialog('Welcome', text)
     lines = text.split('\n')
     urwid.connect_signal(dialog, 'close',
         lambda button: self.backScreen())
     self.popup(dialog, min_width=76, min_height=len(lines)+4)
Exemple #7
0
 def searchDialog(self, default):
     dialog = SearchDialog(self, default)
     urwid.connect_signal(dialog, 'cancel',
         lambda button: self.backScreen())
     urwid.connect_signal(dialog, 'search',
         lambda button: self._searchDialog(dialog))
     self.popup(dialog, min_width=76, min_height=8)
Exemple #8
0
def setup(mw):
	""" called by main, mw is the main_window """
	global main_window
	main_window = mw

	urwid.connect_signal(connection.sushi, "connected", maki_connected)
	urwid.connect_signal(connection.sushi, "disconnected", maki_disconnected)
Exemple #9
0
    def quit(self):
        dialog = mywid.YesNoDialog(u'Quit',
                                   u'Are you sure you want to quit?')
        urwid.connect_signal(dialog, 'no', self.backScreen)
        urwid.connect_signal(dialog, 'yes', self._quit)

        self.popup(dialog)
Exemple #10
0
    def __init__(self,
                 prompt,
                 content,
                 done_signal_handler,
                 cursor_position=None):
        """
        Initializes editor, connects 'done' signal.

        When pressing 'enter' twice the `submit` method is called, which by
        default calls `emit_done_signal` with the text that has been
        introduced.

        When pressing 'esc' the `cancel` method is called, which by default
        calls `emit_done_signal` with no arguments.

        The subclasses must call the `_wrap` method with the editor widgets
        and `BaseEditor` will wrap it in a `urwid.Colums` widget, calling to
        `urwid.WidgetWrap.__init__` with the wrapped widget.
        """
        caption = _(u'{0} (Enter key twice to validate, '
                    u'Esc or Ctrl-C to cancel) \n>> ').format(prompt)
        if content:
            content += ' '
        self.content = content
        self.editor = Edit(caption=caption,
                           edit_text=content,
                           edit_pos=cursor_position)
        self.last_key = None

        connect_signal(self, 'done', done_signal_handler)
    def _build_table(self, ui_table):
        children = []

        for key, label in ui_table.items:
            c = self._build_tableitem(ui_table, key, label)
            children.append(c)
        widget = uw.TableWidget(ui_table.label(), ui_table.header,
                                children, ui_table.multi,
                                ui_table.height, ui_table.enabled())

        for c in children:
            c._table = widget

        if ui_table.multi:
            widget.selection(ui_table.selection())
        else:
            widget.focus(ui_table.selection())

        def on_change_cb(w, d=None):
            if ui_table.multi:
                ui_table.selection(widget.selection())
            else:
                ui_table.selection(w._key)

            ui_table.on_change({ui_table.path: w._key})

        urwid.connect_signal(widget, "changed", on_change_cb)

        def on_item_value_change_cb(p, v):
            # Update the selection in the ui.Element
            widget.selection(v)

        ui_table.on_value_change.connect(on_item_value_change_cb)

        return widget
Exemple #12
0
def menu(title, choices):
  body = [urwid.Text(title), urwid.Divider()]
  for c in choices:
    button = urwid.Button(c)
    urwid.connect_signal(button, 'click', item_chosen, c)
    body.append(urwid.AttrMap(button, None, focus_map='reversed'))
  return VimListBox(urwid.SimpleFocusListWalker(body))
Exemple #13
0
 def __init__(
         self, title, login,
         command_caption='Command: (Tab to switch focus to upper '
         'frame, where you can scroll text)\nType exit or quit '
         'to close', max_size=1000):
     self.header = urwid.Text(title)
     self.model = urwid.SimpleListWalker([])
     self.body = ListView(
         self.model, lambda: self._update_focus(False), max_size=max_size)
     self.input = Input(lambda: self._update_focus(True))
     foot = urwid.Pile([
         urwid.AttrMap(
             urwid.Text(command_caption),
             'reversed'),
         urwid.AttrMap(self.input, 'normal')])
     urwid.Frame.__init__(self,
                          urwid.AttrWrap(self.body, 'normal'),
                          urwid.AttrWrap(self.header, 'reversed'),
                          foot)
     self.set_focus_path(['footer', 1])
     self._focus = True
     urwid.connect_signal(self.input,
                          'line_entered',
                          self.on_line_entered)
     self._output_styles = [s[0] for s in self.PALLETE]
     self.eloop = None
     self.login = login
Exemple #14
0
	def generate_widget(self, key, field):
		global WIDMAP

		if field.get("type", "bool") == "bool":
			wid = CheckBoxWidget(field["name"], field["value"])
			urwid.connect_signal(wid, "change", widget_changed_callback)
			wid._datakey = key
			wid._datafield = field
			f = urwid.AttrWrap(wid, 'opt','optsel')
			if field.has_key('ischild') and field['ischild']:
				f = urwid.Padding(f, width=77, left=3)
			f._widget = wid
			WIDMAP[key] = f
			self.list_content.append(f)

		elif field["type"] == "text":
			wid = EditWidget("%s: "%field["name"], str(field["value"]))
			urwid.connect_signal(wid, "change", widget_changed_callback)
			wid._datakey = key
			wid._datafield = field
			f = urwid.AttrWrap(wid, 'opt', 'optsel')
			if field.has_key('ischild') and field['ischild']:
				f = urwid.Padding(f, width=77, left=3)
			f._widget = wid
			WIDMAP[key] = f
			self.list_content.append(f)

		elif field["type"] == "info":
			wid = urwid.Text(field["name"])
			wid._datakey = key
			wid._datafield = field
			f = urwid.AttrWrap(wid, 'info', 'info')
			f._widget = wid
			WIDMAP[key] = f
			self.list_content.append(f)
Exemple #15
0
    def __init__(self, notes_dir, editor, extension):

        self.editor = editor
        self.notebook = notebook.PlainTextNoteBook(notes_dir, extension)

        # Don't filter the note list when the text in the search box changes.
        self.suppress_filter = False

        # Don't change the focused note when normally it would change
        # (e.g. when the text in the search box changes)
        self.suppress_focus = False

        self._selected_note = None

        self.search_box = AutocompleteWidget(wrap="clip")
        self.list_box = NoteFilterListBox(on_changed=self.on_list_box_changed)

        urwid.connect_signal(self.search_box, "change",
                self.on_search_box_changed)

        super(MainFrame, self).__init__(
                header=urwid.LineBox(self.search_box),
                body=None,
                focus_part="body")

        # Add all the notes to the listbox.
        self.filter(self.search_box.edit_text)
Exemple #16
0
 def item_chosen(button, server):
     global choice
     choice = server
     response = Text([u'Connecting to: ', server.connection_string(), u'\n'])
     done = Button(u'Ok')
     urwid.connect_signal(done, 'click', exit_program)
     main.original_widget = Filler(Pile([response, AttrMap(done, None, focus_map='reversed')]))
Exemple #17
0
    def __init__(self, caption=u'',
                 width_cap=conf.sizes['wgtFieldBoxDb1'][0], bindf=None, enterIsTab=False,readonly=False,cor=None):

        self._lastvalue = ''
        self._value = ''
        self.dirty = False
        self.caption = caption
        self._enterIsTab = enterIsTab
        self.capField = cap = urwid.Text(nisk.util.asUnicode((u'', caption)))
        # self.capField = urwid.Text([('key', caption[:1]), caption[1:]])
        self.textField = urwid.Edit('')
        self.textField.multiline = not enterIsTab
        urwid.connect_signal(self.textField, 'change', self.edit_changed)

        if not cor:
            cor = ('field', 'field_of')
        if len(cor) == 3:
            cap = urwid.AttrWrap(cap,cor[2])
        if len(cor) == 4:
            cap = urwid.AttrWrap(cap,cor[2],cor[3])
        
        self.readonly = readonly
        self.readonlyField = Text('')
        if readonly:
            field = urwid.AttrWrap(self.readonlyField,cor[0],cor[1])
        else:
            field = urwid.AttrWrap(self.textField,cor[0],cor[1])

        x = urwid.Columns([('fixed',  2, urwid.Text('* ')),('fixed',  width_cap,cap),
            field]
            , dividechars=0, focus_column=2)

        self.__super.__init__(x,cor[0])
Exemple #18
0
    def category_chosen(self, button, category):

        self.cat_list_overlay.original_widget.original_widget = \
                urwid.Overlay(urwid.ListBox(urwid.SimpleFocusListWalker([urwid.Button("ssdf")])),
                self.cat_list_overlay.original_widget,
                align = 'center', width = ('relative', 80),
                valign = 'middle', height = ('relative', 80),
                min_width = 24, min_height = 8,
                left = 3,
                right = 30,
                top = 2,
                bottom = 20
                )

        #刷新界面
        self.loop.draw_screen()

        #pos = self.cat_list_listBox.focus_position
        #self.cat_list_listBox.body.insert(pos + 1, urwid.Text(' nimei'))
        return
        response = urwid.Text(['You are chose', category , '\n'])
        click = urwid.Button('ok')
        urwid.connect_signal(click, 'click', self.exit_program)
        #self.base.original_widget = urwid.Filler(urwid.Pile([response, urwid.AttrMap(click, None, focus_map='reserved')]))
        self.loop.widget = urwid.Filler(urwid.Pile([response, urwid.AttrMap(click, None, focus_map='reserved')]))
Exemple #19
0
    def __init__(self, label, mask=None, align_vertical=False):
        with_linebox = False
        self._align_vertical = align_vertical

        if with_linebox:
            label = "\n" + label

        self._label = urwid.Text(label)
        self._label_attrmap = urwid.AttrMap(self._label,
                                            "plugin.widget.entry.label")
        self._edit = EditWithChars(mask=mask)
        self._edit_attrmap = urwid.AttrMap(self._edit, "plugin.widget.entry")
        self._linebox = urwid.LineBox(self._edit_attrmap)
        self._linebox_attrmap = urwid.AttrMap(self._linebox,
                                              "plugin.widget.entry.frame")

        input_widget = self._edit_attrmap
        if with_linebox:
            input_widget = self._linebox_attrmap

        alignment_widget = urwid.Columns
        if self._align_vertical:
            alignment_widget = urwid.Pile
        self._columns = alignment_widget([self._label_attrmap,
                                          input_widget])

        self._pile = urwid.Pile([self._columns])

        def on_widget_change_cb(widget, new_value):
            urwid.emit_signal(self, 'change', self, new_value)
        urwid.connect_signal(self._edit, 'change', on_widget_change_cb)

        super(Entry, self).__init__(self._pile)
 def __init__(self, title, opts, cb):
     self.title = title
     self.radio_items = OrderedDict()
     for item, desc in opts:
         self.add_radio(item, desc)
     connect_signal(self, 'done', cb)
     super().__init__(self._build_widget())
Exemple #21
0
    def create_library_buffer(self, loop, active=False):
        buf = LibraryBuffer(self.conf, loop)
        buf.active = active
        urwid.connect_signal(buf, signals.SET_FOCUS, self.update_focus)
        urwid.connect_signal(buf, signals.SET_FOOTER, self.update_footer)

        return buf
Exemple #22
0
 def query_anime(self):
     self.foot = QueryWidget('anime title: ')
     self.view.set_footer(self.foot)
     self.view.set_focus('footer')
     urwid.connect_signal(
         self.foot, 'anime_entered', self.anime_entered)
     urwid.connect_signal(self.foot, 'query_escaped', self.query_escaped)
Exemple #23
0
def main():
    term = urwid.Terminal(None)

    mainframe = urwid.LineBox(
        urwid.Pile([
            ('weight', 70, term),
            ('fixed', 1, urwid.Filler(urwid.Edit('focus test edit: '))),
        ]),
    )

    def set_title(widget, title):
        mainframe.set_title(title)

    def quit(*args, **kwargs):
        raise urwid.ExitMainLoop()

    def handle_key(key):
        if key in ('q', 'Q'):
            quit()

    urwid.connect_signal(term, 'title', set_title)
    urwid.connect_signal(term, 'closed', quit)

    loop = urwid.MainLoop(
        mainframe,
        handle_mouse=False,
        unhandled_input=handle_key)

    term.main_loop = loop
    loop.run()
Exemple #24
0
 def login(self):
     self.foot = LoginWidget('username: '******'footer')
     urwid.connect_signal(
         self.foot, 'login_authenticate', self.login_authenticate)
     urwid.connect_signal(self.foot, 'login_escaped', self.login_escaped)
    def build_widgets(self):
        title_text = Text([("body", self.name)],
                          align="center")

        desc_text = Text(["\n", strip_solo_dots(self.description)])

        self.reset_button = PlainButton("Reset to Default", self.do_reset)
        if self.optype == OptionType.BOOLEAN:
            self.control = CheckBox(self.name, state=bool(self.current_value))

        elif self.optype == OptionType.INT:
            self.control = IntEdit(caption="{}: ".format(self.name),
                                   default=self.current_value)
        elif self.optype == OptionType.STRING:
            edit_text = self.current_value or ""
            self.control = StringEditor(
                caption="{}: ".format(self.name),
                edit_text=edit_text)
        else:
            raise Exception("Unknown option type")

        if self.optype == OptionType.STRING:
            connect_signal(self.control._edit, 'change',
                           self.handle_value_changed)
        else:
            connect_signal(self.control, 'change',
                           self.handle_value_changed)

        button_grid = GridFlow([self.reset_button],
                               36, 1, 0, 'right')

        return Pile([Divider(), title_text, desc_text, self.control,
                     button_grid])
Exemple #26
0
    def handle_trees(self):
        # Reset the focus and the last directory since we're viewing trees and not a single directory
        self.QGH.focus    = '/'
        self.QGH.last_dir = '' # Otherwise, we wouldn't be able to jump to dir view

        # Wipe all the elements and populate with trees only.
        self.QGH.elements = []
        all_trees = self.QGH.Parser.all_trees();

        # Construct an itemlist
        i = 0
        for directory in sorted(all_trees):
            element  = ItemWidget(i, directory + '/', self.QGH)
            self.QGH.elements.append(element)
            i = i+1

        # Set up the walker
        self.QGH.walker  = urwid.SimpleListWalker(self.QGH.elements)
        self.QGH.listbox = urwid.ListBox(self.QGH.walker)

        # Connect the signal so that we can update the header/footer later.
        urwid.connect_signal(self.QGH.walker, 'modified', self.QGH.update)

        # Fix the header
        self.QGH.view.set_header(urwid.AttrWrap(urwid.Columns([
            urwid.Text('/', align='left'), # fakeroot
            urwid.Text('%s item(s)' % (len(self.QGH.elements)), align='right')
        ]), 'head'))

        self.QGH.view.set_body(self.QGH.listbox)
Exemple #27
0
Fichier : main.py Projet : mion/def
def main_insta(engine):
	"""
	Instant 'as-you-type' search.
	"""
	palette = [('I say', 'default,bold', 'default', 'bold'),]
	ask = urwid.Edit(('I say', u"Search: "))
	reply = urwid.Text(u"")
	button = urwid.Button(u'Exit')
	div = urwid.Divider()
	pile = urwid.Pile([ask, div, reply, div, button])
	top = urwid.Filler(pile, valign='top')

	def on_ask_change(edit, new_edit_text):
	    if len(new_edit_text) == 0:
	    	reply.set_text(('I say', 'Hey! Just start typing to get some answers.'))
	    	return

	    reply.set_text(('I say', u"Searching...\n")) 
	    results = engine.search(new_edit_text)
	    if len(results) > 0:
	    	reply.set_text(('I say', format_results(results)))
	    else:
	    	reply.set_text(('I say', u'No results for "{}"'.format(new_edit_text)))


	def on_exit_clicked(button):
	    raise urwid.ExitMainLoop()

	urwid.connect_signal(ask, 'change', on_ask_change)
	urwid.connect_signal(button, 'click', on_exit_clicked)

	urwid.MainLoop(top, palette).run()
Exemple #28
0
 def help(self):
     if not hasattr(self.loop.widget, 'help'):
         return
     global_help = [(self.config.keymap.formatKeys(k), t)
                    for (k, t) in mywid.GLOBAL_HELP]
     for d in self.config.dashboards.values():
         global_help.append((keymap.formatKey(d['key']), d['name']))
     parts = [('Global Keys', global_help),
              ('This Screen', self.loop.widget.help())]
     keylen = 0
     for title, items in parts:
         for keys, text in items:
             keylen = max(len(keys), keylen)
     text = ''
     for title, items in parts:
         if text:
             text += '\n'
         text += title+'\n'
         text += '%s\n' % ('='*len(title),)
         for keys, cmdtext in items:
             text += '{keys:{width}} {text}\n'.format(
                 keys=keys, width=keylen, text=cmdtext)
     dialog = mywid.MessageDialog('Help for %s' % version(), text)
     lines = text.split('\n')
     urwid.connect_signal(dialog, 'close',
         lambda button: self.backScreen())
     self.popup(dialog, min_width=76, min_height=len(lines)+4)
Exemple #29
0
def item_chosen(button, choice):
    response = urwid.Text([u'You chose ', choice, u'\n'])
    done = urwid.Button(u'Ok')
    urwid.connect_signal(done, 'click', exit_program)
    main.original_widget = urwid.Filler(
        urwid.Pile([response, urwid.AttrMap(done, None, focus_map='reversed')])
    )
Exemple #30
0
 def query_username(self):
     self.foot = QueryWidget('username: '******'footer')
     urwid.connect_signal(
         self.foot, 'username_entered', self.username_entered)
     urwid.connect_signal(self.foot, 'query_escaped', self.query_escaped)
Exemple #31
0
 def __init__(self, caption, callback):
     super(MenuButton, self).__init__("")
     urwid.connect_signal(self, 'click', callback)
     self._w = urwid.AttrMap(
         urwid.SelectableIcon([u'  \N{BULLET} ', caption], 2), None,
         'selected')
Exemple #32
0
def show_table_edit(frame, body, main_body, user_info, tablename):
    blank = urwid.Divider()

    edit_info = EditTableInfo()

    def rename_btn_press(button):
        #make sure new name has been entered in
        if edit_info.rename_name == "":
            #show error for blank entry
            text_error.original_widget = urwid.AttrWrap(
                urwid.Text(u"Enter in a table name."), 'error')
        else:
            #sql function to rename table
            status = user_info.db_obj.rename_table(user_info.db_conn,
                                                   tablename,
                                                   edit_info.rename_name)

            if status == 1:
                #show success message in frame footer
                frame.footer = urwid.AttrWrap(
                    urwid.Text([
                        u" Table ", tablename, " renamed to ",
                        edit_info.rename_name
                    ]), 'header')

                #redirect to main view to reload new table name
                mainview.show_main_view(frame, body, user_info)
            else:
                #show error message
                text_error.original_widget = urwid.AttrWrap(
                    urwid.Text(status), 'error')

    #signal handler for rename table input field
    def edit_change_event(self, text):
        edit_info.rename_name = text

    text_1 = urwid.Text([u"Rename table: ", tablename])
    text_error = urwid.AttrWrap(urwid.Text(u""), 'body')

    #rename edit input field
    table_rename_edit = urwid.Edit(u"New name: ", "")
    urwid.connect_signal(table_rename_edit, 'change', edit_change_event)
    table_rename_edit = urwid.AttrWrap(table_rename_edit, 'main_sel',
                                       'main_self')

    #rename button
    table_rename_btn = urwid.AttrWrap(
        urwid.Button(u"Rename", rename_btn_press), 'btnf', 'btn')

    #---------------------------------------------------------------------------------
    #setting up the add a row view
    col_names = user_info.db_obj.getcolnames(user_info.db_conn, tablename)
    col_length = len(col_names)

    #clear out and start creating query string
    edit_info.add_query_string = ""
    edit_info.add_query_string += 'INSERT INTO ' + tablename + ' VALUES ('

    add_error = urwid.AttrWrap(urwid.Text(u""), 'main_sel')
    add_text_1 = urwid.Text(
        u"Use the below form to add a row of data to the table.\nIf you leave the entry blank, it will default to NULL.\nIf you have a table with an auto-incrementing column, you can type 'DEFAULT' and it will resort to the default value.\nNote that default will also work for other columns with default values set up."
    )

    field_text = urwid.Text([
        "Now adding data for field: ",
        str(edit_info.add_current + 1), " / ",
        str(col_length)
    ])

    def edit_change_event(self, text):
        edit_info.add_field = text

    def try_again(button):
        main_body.original_widget = show_table_edit(frame, body, main_body,
                                                    user_info, tablename)

    def next_field(button):
        frame.footer = urwid.AttrWrap(urwid.Text(""), 'body')

        field_copy = edit_info.add_field.upper()

        if edit_info.add_field == "":
            edit_info.add_query_string += "NULL"
        elif edit_info.add_field.isdigit() or field_copy == "DEFAULT":
            edit_info.add_query_string += edit_info.add_field
        else:
            edit_info.add_query_string += "'" + edit_info.add_field + "'"

        edit_info.add_current += 1

        if edit_info.add_current < col_length:
            #not done, need to load another form
            next_form()
        else:
            #input is done, can run query
            add_row()

    field_input_text = urwid.Edit(
        ["Field->", col_names[edit_info.add_current], ": "])
    urwid.connect_signal(field_input_text, 'change', edit_change_event)
    field_input = urwid.AttrWrap(field_input_text, 'main_sel', 'main_self')

    #check to see if table only has one field, then next button becomes add button
    if edit_info.add_current < col_length:
        #next button
        next_field_btn = urwid.AttrWrap(urwid.Button(u"Next", next_field),
                                        'btnf', 'btn')
    else:
        #next button
        next_field_btn = urwid.AttrWrap(urwid.Button(u"Add", next_field),
                                        'btnf', 'btn')

    next_field_btn = urwid.WidgetPlaceholder(next_field_btn)

    def add_row():
        edit_info.add_query_string += ');'

        #run insert query
        query_status = user_info.db_obj.runquery(user_info.db_conn,
                                                 edit_info.add_query_string,
                                                 False)

        if query_status['success']:
            #query was successful, show success message and change view
            frame.footer = urwid.AttrWrap(
                urwid.Text(u" Row added successfully"), 'header')

            #redirect to show this page again
            main_body.original_widget = show_table_edit(
                frame, body, main_body, user_info, tablename)
        else:
            #query failed, show error message
            add_error.original_widget = urwid.AttrWrap(
                urwid.Text([
                    "Query Failed.\nQUERY: ", edit_info.add_query_string,
                    "\n\n", query_status['data']
                ]), 'error')

            #show try again button
            next_field_btn.original_widget = urwid.AttrWrap(
                urwid.Button("Try Again", try_again), 'btnf', 'btn')

    def next_form():
        #clear form
        field_input_text.set_edit_text(u"")

        #show current number to edit
        field_text.set_text([
            "Now adding data for field: ",
            str(edit_info.add_current + 1), " / ",
            str(col_length)
        ])

        #show current field name
        field_input_text.set_caption(
            ["Field->", col_names[edit_info.add_current], ": "])

        #keep processing data
        edit_info.add_query_string += ', '

        if edit_info.add_current == col_length - 1:
            #this is the last attribute to add, replace next button with add button
            next_field_btn.original_widget = urwid.AttrWrap(
                urwid.Button("Add", next_field), 'btnf', 'btn')

    #----------------------------------------------------------------------------

    add_box = urwid.Pile([
        add_error, blank, field_text, blank,
        urwid.Padding(field_input, right=5), blank,
        urwid.Padding(next_field_btn, left=5, width=13)
    ])

    edit_body = urwid.WidgetPlaceholder(
        urwid.Padding(urwid.Pile([
            blank, text_error, text_1, table_rename_edit, blank,
            urwid.Padding(table_rename_btn, left=5, width=10), blank, blank,
            add_text_1, blank,
            urwid.LineBox(add_box)
        ]),
                      left=5,
                      right=5))

    return edit_body
Exemple #33
0
 def active(self, val):
     self._active = val
     self.button = urwid.Button(self._decorate(self._active))
     urwid.PopUpLauncher.__init__(self, self.button)
     urwid.connect_signal(self.button, 'click',
                          lambda button: self.open_pop_up())
Exemple #34
0
 def create_pop_up(self):
     pop_up = ChoiceList(self, callback=self._callback)
     urwid.connect_signal(
         pop_up, 'close', lambda button: self.close_pop_up(),
     )
     return pop_up
Exemple #35
0
 def replace(self, app, data):
     link = mywid.Link(self.text.format(**data), 'link', 'focused-link')
     urwid.connect_signal(
         link, 'selected',
         lambda link: app.doSearch(self.query.format(**data)))
     return link
Exemple #36
0
 def replace(self, app, data):
     link = mywid.Link(self.text.format(**data), 'link', 'focused-link')
     urwid.connect_signal(
         link, 'selected',
         lambda link: self.activate(app, self.url.format(**data)))
     return link
Exemple #37
0
 def do_delete_ask(self):
     self.adding = True
     ask = QuestionAsker("Do you want to delete this account? [y/n] ")
     self.frame.footer = ask
     self.frame.set_focus('footer')
     urwid.connect_signal(ask, 'done', self.do_delete)
Exemple #38
0
    def _generate_options_body(self):
        """Generates the list of widgets for the options area.

        Raises:
            RuntimeError: if it is a selectable option list passed as part of a tuple and the tuple has a length greater than 4
            RuntimeError: if it is an editable value option passed as part of a tuple and the tuple has a length greater than 6
            RuntimeError: if the value for the option name key is not a str, int, float, list or tuple
        """

        self._options_body = [
            urwid.Text('OPTIONS', align='center'),
            urwid.Divider()
        ]
        self._option_widgets = []

        for group_key in self._options:
            # Get data from group key
            if type(self._options[group_key]) == dict:
                group_options_data = self._options[group_key]
                show_title = True
                divider_on = True
            elif type(self._options[group_key]) == tuple:
                # First element in tuple will be a dictionary containing the option names dictionary
                group_options_data = self._options[group_key][0]
                if len(self._options[group_key]) == 2:
                    # Assume second element is show title
                    show_title = self._options[group_key][1]
                elif len(self._options[group_key]) == 3:
                    # Assume second element is show title and divider on is third element
                    show_title = self._options[group_key][1]
                    divider_on = self._options[group_key][2]

            # Add urwid.Text() widget to _options_body to be used as a title if required
            if show_title:
                self._options_body.append(urwid.Text(group_key,
                                                     align='center'))

            # Add buttons to _options_body
            for option_name in group_options_data:

                # Create defaults for optional components
                caption = ""
                increment = None
                limits = [None, None]
                enter_fires_change_event = True
                enabled = True

                # Create a UserOption widget
                option_data = group_options_data[option_name]

                # Determine if option_data is a list, a single value or a tuple containing optional UserOption parameters
                if type(option_data) == tuple:
                    # Option data contains optional UserOption parameters

                    # Get value component from option_data tuple
                    value = option_data[0]

                    # Value component will determine if is a list of selectable values or an editable value
                    if type(value) == list:
                        # list of selectable values
                        if len(option_data) == 2:
                            caption = option_data[1]
                        elif len(option_data) == 3:
                            caption = option_data[1]
                            enter_fires_change_event = option_data[2]
                        elif len(option_data) == 4:
                            caption = option_data[1]
                            enter_fires_change_event = option_data[2]
                            enabled = option_data[3]
                        else:
                            raise RuntimeError(
                                'The tuple containing the option data when the option is a list of selectable values must have a length less of 4 or less.'
                            )
                    elif type(value) == int or type(value) == float or type(
                            value) == str:
                        # editable value
                        if len(option_data) == 2:
                            caption = option_data[1]
                        elif len(option_data) == 3:
                            caption = option_data[1]
                            increment = option_data[2]
                        elif len(option_data) == 4:
                            caption = option_data[1]
                            increment = option_data[2]
                            limits = option_data[3]
                        elif len(option_data) == 5:
                            caption = option_data[1]
                            increment = option_data[2]
                            limits = option_data[3]
                            enter_fires_change_event = option_data[4]
                        elif len(option_data) == 6:
                            caption = option_data[1]
                            increment = option_data[2]
                            limits = option_data[3]
                            enter_fires_change_event = option_data[4]
                            enabled = option_data[5]
                        else:
                            raise RuntimeError(
                                'The tuple containing the option data when the option is an editable value must have a length less of 6 or less.'
                            )

                elif type(option_data) == list:
                    # option_data is a list of selectable values
                    value = option_data

                elif type(option_data) == int or type(
                        option_data) == float or type(option_data) == str:
                    # option_data is an editable value
                    value = option_data

                else:
                    raise RuntimeError(
                        'The option data must be a list, int, float or str, or a tuple where the first element is a list, int, float or str'
                    )

                # print(option_name, value, caption, increment, limits, enter_fires_change_event, enabled)

                # Create the actual widget, connect the change signal, append user_option to body and option_widgets list
                user_option = UserOption(option_name, value, caption,
                                         increment, limits,
                                         enter_fires_change_event, enabled)
                urwid.connect_signal(user_option, 'value_change',
                                     self._option_item_selected)
                self._options_body.append(user_option)
                self._option_widgets.append(
                    user_option)  # used to find user_options

            # Add urwid.Divider() widget to _options_body if required
            if divider_on:
                self._options_body.append(urwid.Divider())
Exemple #39
0
 def question(self, msg, callback, data=u''):
     self.asker = QuestionAsker(msg, str(data))
     self.view.set_footer(urwid.AttrMap(self.asker, 'status'))
     self.view.set_focus('footer')
     urwid.connect_signal(self.asker, 'done', callback)
Exemple #40
0
            downThirdloop = 1
        downurl = urllib.unquote(str(choice.url))
        raise urwid.ExitMainLoop()

    ############################# print basic video info######################## 1st Loop info #################333#####can be done in a function too
    palette = [
        ('banner', 'black', 'light gray'),
    ]
    txt = urwid.Text(
        ('banner', u"Hello !!! \nRequested Video Information....\n "))
    p_title = urwid.Text(("Title :-  %s" % title))
    p_author = urwid.Text(("Channel :-  %s" % author))
    p_len = urwid.Text(
        ("Length :-  " + "%d" % (vid_len / 60) + ":" + "%d" % (vid_len % 60)))
    button_cont = urwid.Button(u' Continue')  #continue button
    urwid.connect_signal(button_cont, 'click', on_clicked_cont)
    button_exit = urwid.Button(u'Exit')  #exit button
    urwid.connect_signal(button_exit, 'click', exit_program)
    div = urwid.Divider(top=0)
    pile = urwid.Pile([
        txt, p_title, p_author, p_len, div,
        urwid.AttrMap(button_cont, None, focus_map='reversed'),
        urwid.AttrMap(button_exit, None, focus_map='reversed')
    ])
    main2 = urwid.Filler(pile)

    ####### starting first loop #########
    loop = urwid.MainLoop(main2, palette=[('reversed', 'standout', '')])
    loop.run()
    ####### First loop ending , Clear Screen for next screen
Exemple #41
0
 def create_edit(self, label, text, fn):
     w = urwid.Edit(label, text)
     urwid.connect_signal(w, 'change', fn)
     fn(w, text)
     w = urwid.AttrWrap(w, 'edit')
     return w
Exemple #42
0
 def create_pop_up(self):
     pop_up = PopUpDialog()
     urwid.connect_signal(pop_up, 'close',
                          lambda button: self.close_pop_up())
     return pop_up
Exemple #43
0
    def __init__(self, parent, disk, partition=None):
        self.disk = disk
        self.partition = partition
        self.model = parent.model
        self.controller = parent.controller
        self.parent = parent
        max_size = disk.free_for_partitions

        initial = {}
        label = _("Create")
        if isinstance(disk, LVM_VolGroup):
            lvm_names = {p.name for p in disk.partitions()}
        else:
            lvm_names = None
        if self.partition:
            if self.partition.flag in ["bios_grub", "prep"]:
                label = None
                initial['mount'] = None
            else:
                label = _("Save")
            initial['size'] = humanize_size(self.partition.size)
            max_size += self.partition.size

            if partition.flag != "boot":
                initial.update(initial_data_for_fs(self.partition.fs()))
            else:
                if partition.fs() and partition.fs().mount():
                    initial['mount'] = '/boot/efi'
                else:
                    initial['mount'] = None
            if isinstance(disk, LVM_VolGroup):
                initial['name'] = partition.name
                lvm_names.remove(partition.name)
        else:
            initial['fstype'] = 'ext4'
            if isinstance(disk, LVM_VolGroup):
                x = 0
                while True:
                    name = 'lv-{}'.format(x)
                    if name not in lvm_names:
                        break
                    x += 1
                initial['name'] = name

        self.form = PartitionForm(self.model, max_size, initial, lvm_names,
                                  partition)

        if not isinstance(disk, LVM_VolGroup):
            self.form.remove_field('name')

        if label is not None:
            self.form.buttons.base_widget[0].set_label(label)
        else:
            del self.form.buttons.base_widget.contents[0]
            self.form.buttons.base_widget[0].set_label(_("OK"))

        if partition is not None:
            if partition.flag == "boot":
                if partition.original_fs():
                    opts = [
                        Option(
                            (_("Use existing fat32 filesystem"), True, None)),
                        Option(("---", False)),
                        Option((_("Reformat as fresh fat32 filesystem"), True,
                                "fat32")),
                    ]
                    self.form.fstype.widget.options = opts
                    if partition.fs().preserve:
                        self.form.fstype.widget.index = 0
                    else:
                        self.form.fstype.widget.index = 2
                    self.form.mount.enabled = False
                else:
                    opts = [Option(("fat32", True))]
                    self.form.fstype.widget.options = opts
                    self.form.fstype.widget.index = 0
                    self.form.mount.enabled = False
                    self.form.fstype.enabled = False
            elif partition.flag in ["bios_grub", "prep"]:
                self.form.mount.enabled = False
                self.form.fstype.enabled = False
                self.form.size.enabled = False
            if partition.preserve:
                self.form.name.enabled = False
                self.form.size.enabled = False

        connect_signal(self.form, 'submit', self.done)
        connect_signal(self.form, 'cancel', self.cancel)

        rows = []
        focus_index = 0
        if partition is not None:
            if self.partition.flag == "boot":
                desc = boot_partition_description
                if self.partition.preserve:
                    desc += boot_partition_description_reformat
                else:
                    desc += boot_partition_description_size
                rows.extend([
                    Text(_(desc)),
                    Text(""),
                ])
            elif self.partition.flag == "bios_grub":
                rows.extend([
                    Text(_(bios_grub_partition_description)),
                    Text(""),
                ])
                focus_index = 2
            elif self.partition.flag == "prep":
                rows.extend([
                    Text(_(prep_partition_description)),
                    Text(""),
                ])
                focus_index = 2
        rows.extend(self.form.as_rows())
        self.form.form_pile = Pile(rows)
        widgets = [
            self.form.form_pile,
            Text(""),
            self.form.buttons,
        ]

        if partition is None:
            if isinstance(disk, LVM_VolGroup):
                add_name = _("logical volume")
            else:
                add_name = _("partition")
            title = _("Adding {} to {}").format(add_name, disk.label)
        else:
            if isinstance(disk, LVM_VolGroup):
                desc = _("logical volume {}").format(partition.name)
            else:
                desc = partition.short_label
            title = _("Editing {} of {}").format(desc, disk.label)

        super().__init__(title, widgets, 0, focus_index)
Exemple #44
0
W_Tail = urwid.Columns([urwid.Text(Online_inf)])


# 弹幕
def on_ask_change(edit, new_edit_text):
    Result = new_edit_text


def on_Send(new_edit_text):
    Result = str(edit)[30:-30]
    CMD = "Python-Send_blive.py " + Result
    os.system(CMD)


edit = urwid.Edit(u"发送弹幕\n")
button = urwid.Button(u'发送')
urwid.connect_signal(edit, 'change', on_ask_change)
urwid.connect_signal(button, 'click', on_Send)
# 整合
fill = urwid.ListBox(
    urwid.SimpleListWalker([Head, Vedio_inf, W_Tail, edit, button]))

view = fill

loop = urwid.MainLoop(view,
                      palette=[('body', 'dark cyan', '')],
                      unhandled_input=keypress)
loop.set_alarm_in(1, refresh)
#loop.set_alarm_in(2, refresh2)
loop.run()
Exemple #45
0
 def __init__(self, text, on_activate=None, user_data=None):
     w = AM(urwid.Text(text), 'body', 'focus')
     self.__super.__init__(w)
     if on_activate is not None:
         urwid.connect_signal(self, "activate", on_activate, user_data)
Exemple #46
0
 def edit_status(self, action, content='', prompt=''):
     self.foot = TweetEditor(content, prompt)
     self.main_frame.set_footer(self.foot)
     self.main_frame.set_focus('footer')
     if action == 'tweet':
         urwid.connect_signal(self.foot, 'done', self.api.tweet_done)
     elif action == 'reply':
         urwid.connect_signal(self.foot, 'done', self.api.reply_done)
     elif action == 'follow':
         urwid.connect_signal(self.foot, 'done', self.api.follow_done)
     elif action == 'unfollow':
         urwid.connect_signal(self.foot, 'done', self.api.unfollow_done)
     elif action == 'search':
         urwid.connect_signal(self.foot, 'done', self.api.search_done)
     elif action == 'public':
         urwid.connect_signal(self.foot, 'done', self.api.public_done)
     elif action == 'list':
         urwid.connect_signal(self.foot, 'done', self.api.list_done)
Exemple #47
0
 def __init__(self):
     self.__super.__init__(urwid.Button("click-me"))
     urwid.connect_signal(self.original_widget, 'click',
                          lambda button: self.open_pop_up())
Exemple #48
0
    def _add_column(self, p_view, p_pos=None):
        """
        Given an UIView, adds a new column widget with the todos in that view.

        When no position is given, it is added to the end, otherwise inserted
        before that position.
        """
        def execute_silent(p_cmd, p_todo_id=None):
            self._execute_handler(p_cmd, p_todo_id, lambda _: None)

        todolist = TodoListWidget(p_view, p_view.data['title'], self.keymap)
        urwid.connect_signal(todolist, 'execute_command_silent',
                             execute_silent)
        urwid.connect_signal(todolist, 'execute_command',
                             self._execute_handler)
        urwid.connect_signal(todolist, 'repeat_cmd', self._repeat_last_cmd)
        urwid.connect_signal(todolist, 'refresh', self.mainloop.screen.clear)
        urwid.connect_signal(todolist, 'add_pending_action', self._set_alarm)
        urwid.connect_signal(todolist, 'remove_pending_action',
                             self._remove_alarm)
        urwid.connect_signal(todolist, 'column_action',
                             self._column_action_handler)
        urwid.connect_signal(todolist, 'show_keystate', self._print_keystate)
        urwid.connect_signal(todolist, 'toggle_mark',
                             self._process_mark_toggle)

        options = self.columns.options(width_type='given',
                                       width_amount=config().column_width(),
                                       box_widget=True)

        item = (todolist, options)

        if p_pos == None:
            p_pos = len(self.columns.contents)

        self.columns.contents.insert(p_pos, item)

        self.columns.focus_position = p_pos
        self._blur_commandline()
Exemple #49
0
    def __init__(self, parent):

        self.parent = parent

        def format_provider(n, p):
            return p.NAME if p.config_is_valid else f"* {p.NAME}"

        def providers_sort_key(p):
            k, v = p
            if v.config_is_valid:
                return (0, str(v.NAME))
            else:
                return (1, str(v.NAME))

        self.provider_dropdown = ToolbarDropdown(
            AttrDict([(format_provider(n, p), n)
                      for n, p in sorted(providers.PROVIDERS.items(),
                                         key=providers_sort_key)]),
            label="Provider",
            default=self.parent.provider.IDENTIFIER,
            margin=1)

        urwid.connect_signal(self.provider_dropdown, "change",
                             lambda w, b, v: self._emit("provider_change", v))

        self.preview_dropdown_placeholder = urwid.WidgetPlaceholder(
            urwid.Text(""))

        self.view_dropdown_placeholder = urwid.WidgetPlaceholder(
            urwid.Text(""))

        self.auto_preview_check_box = urwid.CheckBox("Auto Preview")
        urwid.connect_signal(self.auto_preview_check_box, "change",
                             self.on_auto_preview_change)

        self.max_concurrent_tasks_widget = providers.filters.IntegerTextFilterWidget(
            text_attr="header_bright",
            focused_attr="header_focused",
            default=config.settings.tasks.max,
            minimum=1)

        def set_max_concurrent_tasks(v):
            if v:
                config.settings.tasks.max = int(v)

        self.max_concurrent_tasks_widget.connect("changed",
                                                 set_max_concurrent_tasks)

        self.profile_dropdown = ToolbarDropdown(
            AttrDict([(k, k) for k in config.settings.profiles.keys()]),
            label="Profile",
            default=config.settings.profile_name,
            margin=1)

        urwid.connect_signal(self.profile_dropdown, "change",
                             lambda w, b, v: self._emit("profile_change", v))

        self.columns = urwid.Columns(
            [
                (self.provider_dropdown.width, self.provider_dropdown),
                ("weight", 1, urwid.Padding(urwid.Text(""))),
                (20, self.view_dropdown_placeholder),
                ("weight", 1, urwid.Padding(urwid.Text(""))),
                (12, self.auto_preview_check_box),
                # (20, self.preview_dropdown_placeholder),
                # (1, urwid.Divider(u"\N{BOX DRAWINGS LIGHT VERTICAL}")),
                ("pack", urwid.Text(("Downloads"))),
                (5, self.max_concurrent_tasks_widget),
                ("weight", 1, urwid.Padding(urwid.Text(""))),
                (self.profile_dropdown.width, self.profile_dropdown),
            ],
            dividechars=3)
        # self.filler = urwid.Filler(self.columns)
        super(ProviderToolbar, self).__init__(
            urwid.Filler(urwid.AttrMap(self.columns, {None: "header"})))
Exemple #50
0
        params = command[1].split('|')
        currentNode = _list.findByName(params[0])
        if currentNode != 'not found':
            currentNode.set(params[1], params[2])
        else:
            statusLine.set_text(command[1] + ' does not exist.')
    elif command[0].startswith('d'):
        _file.write(_list, command[1])
    elif command[0].startswith('l'):
        newNodes = _file.read(command[1], statusLine)
        statusLine.set_text(str(len(newNodes)))
        for n in newNodes:
            statusLine.set_text(str(n))
            _list.add(n)
    elif command[0].startswith('q'):
        statusLine.set_text(str(len(_list.getlist())))
        for n in _list.getlist():
            bg.open_box(urwid.SolidFill(u'#'), n.name)
    elif command[0].startswith('!'):
        result = ''
        try:
            result = eval(command[1])
        except:
            result = 'an error occurred'
        statusLine.set_text(str(result))


urwid.connect_signal(textEntry, 'done', on_input)

loop.run()
Exemple #51
0
def display(node_id):
    if node_id == state.node_id_unreads:
        return

    config_adapter = ConfigAdapter()
    db = DatabaseAdapter()

    node = next(db.get_node_subscriptions(node_id))
    config_node = config_adapter.get_source(node_id)
    mark_as_read = False if config_node['mark_as_read'] == 'false' else True

    name_txt = urwid.Text(u'Name', align='right')
    name_edit = urwid.Edit(u'', edit_text=node['title'], wrap='clip')
    name_column = urwid.Columns([(18, name_txt), (2, urwid.Divider()), name_edit])

    url_txt = urwid.Text(u'URL', align='right')
    url_edit = urwid.Edit(u'', edit_text=node['source'], wrap='clip')
    url_column = urwid.Columns([(18, url_txt), (2, urwid.Divider()), url_edit])

    update_interval_txt = urwid.Text(u'Update interval', align='right')
    update_interval_edit = urwid.Edit(u'', edit_text=str(node['update_interval']))
    update_interval_column = urwid.Columns([(18, update_interval_txt), (2, urwid.Divider()), update_interval_edit])

    mark_as_read_txt = urwid.Text(u'Mark as read', align='right')
    mark_as_read_checkbox = urwid.CheckBox(u'', mark_as_read)
    mark_as_read_column = urwid.Columns([(18, mark_as_read_txt), (2, urwid.Divider()), mark_as_read_checkbox])

    body_pile = urwid.Pile([
        urwid.Divider(),
        name_column,
        url_column,
        update_interval_column,
        mark_as_read_column,
        urwid.Divider()
    ])

    # body
    body_filler = urwid.Filler(body_pile, valign='top')
    body_padding = urwid.Padding(
        body_filler,
        left=1,
        right=1
    )
    state.body = urwid.LineBox(body_padding)

    # footer
    submit_button = urwid.Button('Submit')
    urwid.connect_signal(submit_button, 'click', save, user_args=[node_id, name_edit, url_edit, update_interval_edit, mark_as_read_checkbox])
    cancel_button = urwid.Button('Cancel')
    urwid.connect_signal(cancel_button, 'click', close)
    footer = urwid.GridFlow([submit_button, cancel_button], 10, 1, 1, 'center')

    # layout
    layout = urwid.Frame(
        state.body,
        footer=footer,
        focus_part='footer'
    )

    state.body = state.loop.widget
    pile = urwid.Pile([layout])
    over = urwid.Overlay(
        pile,
        state.body,
        align='center',
        valign='middle',
        width=60,
        height=12
    )

    state.loop.widget = over

    db.close_connection()
Exemple #52
0
 def __init__(self, button):
     super(MenuBar.MenuPopup, self).__init__(button)
     self.items = button.user_data
     urwid.connect_signal(button, 'click', lambda sender: self.open_pop_up())
Exemple #53
0
    def __init__(self):
        super().__init__()

        args = self._process_flags()

        try:
            opts, args = getopt.getopt(args[1:], 'l:')
        except getopt.GetoptError as e:
            error(str(e))
            sys.exit(1)

        self.alt_layout_path = None

        for opt, value in opts:
            if opt == "-l":
                self.alt_layout_path = value

        def callback():
            self.todolist.erase()
            self.todolist.add_list(self.todofile.read())
            self._update_all_columns()
            self._redraw()

        self.column_width = config().column_width()
        self.todofile = TodoFileWatched(config().todotxt(), callback)
        self.todolist = TodoList.TodoList(self.todofile.read())

        self.marked_todos = set()

        self.columns = urwid.Columns([],
                                     dividechars=0,
                                     min_width=config().column_width())
        completer = ColumnCompleter(self.todolist)
        self.commandline = CommandLineWidget(completer, 'topydo> ')
        self.keystate_widget = KeystateWidget()
        self.status_line = urwid.Columns([
            ('weight', 1, urwid.Filler(self.commandline)),
        ])
        self.cli_wrapper = CliWrapper([(1, self.status_line)])

        self.keymap = config().column_keymap()
        self._alarm = None

        self._last_cmd = None

        # console widget
        self.console = ConsoleWidget()
        get_terminal_size(self._console_width)

        urwid.connect_signal(self.commandline, 'blur', self._blur_commandline)
        urwid.connect_signal(self.commandline, 'execute_command',
                             self._execute_handler)
        urwid.connect_signal(self.commandline, 'show_completions',
                             self._show_completion_box)
        urwid.connect_signal(self.commandline, 'hide_completions',
                             self._hide_completion_box)

        def hide_console(p_focus_commandline=False):
            if p_focus_commandline:
                self._focus_commandline()
            else:
                self._console_visible = False

        urwid.connect_signal(self.console, 'close', hide_console)

        # view widget
        self.viewwidget = ViewWidget(self.todolist)

        urwid.connect_signal(self.viewwidget, 'save',
                             lambda: self._update_view(self.viewwidget.data))

        def hide_viewwidget():
            # prevent the view widget to be hidden when the last column was
            # deleted
            if self.columns.contents:
                self._viewwidget_visible = False
                self._blur_commandline()

        urwid.connect_signal(self.viewwidget, 'close', hide_viewwidget)

        self.mainwindow = MainPile([
            ('weight', 1, self.columns),
            ('pack', self.cli_wrapper),
        ])

        urwid.connect_signal(self.mainwindow, 'blur_console', hide_console)

        # the columns should have keyboard focus
        self._blur_commandline()

        self._screen = urwid.raw_display.Screen()

        def create_color_palette():
            project_color = to_urwid_color(config().project_color())
            context_color = to_urwid_color(config().context_color())
            metadata_color = to_urwid_color(config().metadata_color())
            link_color = to_urwid_color(config().link_color())
            focus_background_color = to_urwid_color(
                config().focus_background_color())
            marked_background_color = to_urwid_color(
                config().marked_background_color())

            palette = [
                (PaletteItem.PROJECT, '', '', '', project_color, ''),
                (PaletteItem.PROJECT_FOCUS, '', 'light gray', '',
                 project_color, focus_background_color),
                (PaletteItem.CONTEXT, '', '', '', context_color, ''),
                (PaletteItem.CONTEXT_FOCUS, '', 'light gray', '',
                 context_color, focus_background_color),
                (PaletteItem.METADATA, '', '', '', metadata_color, ''),
                (PaletteItem.METADATA_FOCUS, '', 'light gray', '',
                 metadata_color, focus_background_color),
                (PaletteItem.LINK, '', '', '', link_color, ''),
                (PaletteItem.LINK_FOCUS, '', 'light gray', '', link_color,
                 focus_background_color),
                (PaletteItem.DEFAULT_FOCUS, '', 'light gray', '', '',
                 focus_background_color),
                (PaletteItem.MARKED, '', 'light blue', '', '',
                 marked_background_color),
            ]

            for C in ascii_uppercase:
                pri_color_cfg = config().priority_color(C)

                pri_color = to_urwid_color(pri_color_cfg)
                pri_color_focus = pri_color if not pri_color_cfg.is_neutral(
                ) else 'black'

                palette.append(('pri_' + C, '', '', '', pri_color, ''))
                palette.append(('pri_' + C + '_focus', '', 'light gray', '',
                                pri_color_focus, focus_background_color))

            return palette

        def create_mono_palette():
            palette = [
                (PaletteItem.DEFAULT_FOCUS, 'black', 'light gray'),
                (PaletteItem.PROJECT_FOCUS, PaletteItem.DEFAULT_FOCUS),
                (PaletteItem.CONTEXT_FOCUS, PaletteItem.DEFAULT_FOCUS),
                (PaletteItem.METADATA_FOCUS, PaletteItem.DEFAULT_FOCUS),
                (PaletteItem.LINK_FOCUS, PaletteItem.DEFAULT_FOCUS),
                (PaletteItem.MARKED, 'default,underline,bold', 'default'),
            ]

            for C in ascii_uppercase:
                palette.append(
                    ('pri_' + C + '_focus', PaletteItem.DEFAULT_FOCUS))

            return palette

        if config().colors():
            self._screen.register_palette(create_color_palette())
        else:
            self._screen.register_palette(create_mono_palette())

        self._screen.set_terminal_properties(256)

        self.mainloop = urwid.MainLoop(self.mainwindow,
                                       screen=self._screen,
                                       unhandled_input=self._handle_input,
                                       pop_ups=True)

        self.column_mode = _APPEND_COLUMN
        self._set_alarm_for_next_midnight_update()

choices = [
    "KANYE WEST", "KANYE WEST 2", "KANYE WEST 3", "KANYE WEST", "KANYE WEST 2",
    "KANYE WEST 3", "KANYE WEST", "KANYE WEST 2", "KANYE WEST 3", "KANYE WEST",
    "KANYE WEST 2", "KANYE WEST 3", "KANYE WEST", "KANYE WEST 2",
    "KANYE WEST 3", "KANYE WEST", "KANYE WEST 2", "KANYE WEST 3", "KANYE WEST",
    "KANYE WEST 2", "KANYE WEST 3", "KANYE WEST", "KANYE WEST 2",
    "KANYE WEST 3", "KANYE WEST", "KANYE WEST 2", "KANYE WEST 3", "KANYE WEST",
    "KANYE WEST 2", "KANYE WEST 3"
]
artist_body = [urwid.Divider()]
for c in choices:
    button = urwid.Button(c)
    artist_body.append(urwid.AttrMap(button, None, focus_map='reversed'))
    urwid.connect_signal(button, 'click', change_albums)
Artist_Box = urwid.ListBox(urwid.SimpleFocusListWalker(artist_body))

# albums = ["MBDTF", "YANDHI", "YEEZUS"]
# albums_body = [urwid.Divider()]
# for a in albums:
#     button = urwid.Button(a)
#     albums_body.append(urwid.AttrMap(button, None, focus_map='reversed'))
# Albums_Box = urwid.ListBox(urwid.SimpleFocusListWalker(albums_body))

music_player_columns = urwid.Columns([Artist_Box, Albums_Box], dividechars=5)

music_player = urwid.Padding(music_player_columns)

currently_playing = urwid.Text("Currently playing:")
volume = urwid.Text("Volume: 69%", align='right')
Exemple #55
0
 def create_pop_up(self):
     menu = PopupMenu(self.items)
     urwid.connect_signal(menu, 'close', self.close_pop_up)
     return urwid.AttrMap(menu, menu_palette_map)
Exemple #56
0
 def connect(self, widget, name, fn, context=None):
     import urwid as u
     self.connections.append((widget, name, fn, context))
     u.connect_signal(widget, name, fn, context)
     return widget
Exemple #57
0
        has_upper_letters,
        has_lower_letters,
        has_symbols,
        has_not_only_symbols,
        is_very_long,
    ]
    return sum(2 if feature(password) else 0 for feature in features)


def on_ask_change(edit, new_edit_text):
    score = get_score(new_edit_text)
    reply.set_text(f"Passwords strength is {score} out of 14")


def on_exit_clicked(button):
    raise urwid.ExitMainLoop()


if __name__ == "__main__":
    ask = urwid.Edit("Enter your password: "******"*")
    reply = urwid.Text("")
    button = urwid.Button("Exit")
    div = urwid.Divider()
    pile = urwid.Pile([ask, div, reply, div, button])
    top = urwid.Filler(pile, valign="top")

    urwid.connect_signal(ask, "change", on_ask_change)
    urwid.connect_signal(button, "click", on_exit_clicked)

    urwid.MainLoop(top).run()
Exemple #58
0
 def __init__(self, caption, callback, arg=None):
     super(NewButton, self).__init__("")
     urwid.connect_signal(self, 'click', callback, arg)
     self._w = urwid.AttrMap(urwid.SelectableIcon(caption, 1),
                             None,
                             focus_map='status_bar')
Exemple #59
0
 def header(self, header):
     urwid.disconnect_signal(self.body, 'set_date', self._header.on_set_date)
     self._header = header
     urwid.connect_signal(self.body, 'set_date', self._header.on_set_date)
     self.set_header(self._header)