Python factory.Factory() Examples

The following are 26 code examples of factory.Factory(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module factory , or try the search function .
Example #1
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 6 votes vote down vote up
def on_key_press(self, window, event):
        """Handle a keyboard event"""
        maker = Factory()

        self.set_urgency_hint(False)

        mapping = self.terminator.keybindings.lookup(event)

        if mapping:
            dbg('Window::on_key_press: looked up %r' % mapping)
            if mapping == 'full_screen':
                self.set_fullscreen(not self.isfullscreen)
            elif mapping == 'close_window':
                if not self.on_delete_event(window,
                        gtk.gdk.Event(gtk.gdk.DELETE)):
                    self.on_destroy_event(window,
                            gtk.gdk.Event(gtk.gdk.DESTROY))
            elif mapping == 'new_tab':
                self.tab_new(self.get_focussed_terminal())
            else:
                return(False)
            return(True) 
Example #2
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 6 votes vote down vote up
def tab_new(self, widget=None, debugtab=False, _param1=None, _param2=None):
        """Make a new tab"""
        cwd = None
        profile = None

        if self.get_property('term_zoomed') == True:
            err("You can't create a tab while a terminal is maximised/zoomed")
            return

        if widget:
            cwd = widget.get_cwd()
            profile = widget.get_profile()

        maker = Factory()
        if not self.is_child_notebook():
            dbg('Making a new Notebook')
            notebook = maker.make('Notebook', window=self)
        return self.get_child().newtab(debugtab, cwd=cwd, profile=profile) 
Example #3
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 6 votes vote down vote up
def rotate(self, widget, clockwise):
        """Rotate children in this window"""
        self.set_pos_by_ratio = True
        maker = Factory()
        # collect all paned children in breadth-first order
        paned = []
        for child in self.get_children():
            if maker.isinstance(child, 'Paned'):
                paned.append(child)
        for p in paned:
            for child in p.get_children():
                if child not in paned and maker.isinstance(child, 'Paned'):
                    paned.append(child)
        # then propagate the rotation
        for p in paned:
            p.rotate(widget, clockwise)
        self.show_all()
        widget.grab_focus()
        
        while gtk.events_pending():
            gtk.main_iteration_do(False)
        self.set_pos_by_ratio = False 
Example #4
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 6 votes vote down vote up
def get_visible_terminals(self):
        """Walk down the widget tree to find all of the visible terminals.
        Mostly using Container::get_visible_terminals()"""
        terminals = {}
        if not hasattr(self, 'cached_maker'):
            self.cached_maker = Factory()
        maker = self.cached_maker
        child = self.get_child()

        if not child:
            return([])

        # If our child is a Notebook, reset to work from its visible child
        if maker.isinstance(child, 'Notebook'):
            pagenum = child.get_current_page()
            child = child.get_nth_page(pagenum)

        if maker.isinstance(child, 'Container'):
            terminals.update(child.get_visible_terminals())
        elif maker.isinstance(child, 'Terminal'):
            terminals[child] = child.get_allocation()
        else:
            err('Unknown child type %s' % type(child))

        return(terminals) 
Example #5
Source File: terminator.py    From NINJA-PingU with GNU General Public License v3.0 6 votes vote down vote up
def reconfigure(self):
        """Update configuration for the whole application"""

        if self.config['handle_size'] in xrange(0, 6):
            gtk.rc_parse_string("""
                style "terminator-paned-style" {
                    GtkPaned::handle_size = %s 
                }
                class "GtkPaned" style "terminator-paned-style" 
                """ % self.config['handle_size'])
            gtk.rc_reset_styles(gtk.settings_get_default())

        # Cause all the terminals to reconfigure
        for terminal in self.terminals:
            terminal.reconfigure()

        # Reparse our keybindings
        self.keybindings.configure(self.config['keybindings'])

        # Update tab position if appropriate
        maker = Factory()
        for window in self.windows:
            child = window.get_child()
            if maker.isinstance(child, 'Notebook'):
                child.configure() 
Example #6
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 6 votes vote down vote up
def group_tab(self, widget):
        """Group all terminals in the current tab"""
        maker = Factory()
        notebook = self.get_child()

        if not maker.isinstance(notebook, 'Notebook'):
            dbg('not in a notebook, refusing to group tab')
            return

        pagenum = notebook.get_current_page()
        while True:
            group = _('Tab %d') % pagenum
            if group not in self.terminator.groups:
                break
            pagenum += 1
        for terminal in self.get_visible_terminals():
            terminal.set_group(None, group) 
Example #7
Source File: container.py    From NINJA-PingU with GNU General Public License v3.0 6 votes vote down vote up
def get_visible_terminals(self):
        """Walk the widget tree to find all of the visible terminals. That is,
        any terminals which are not hidden in another Notebook pane"""
        if not hasattr(self, 'cached_maker'):
            self.cached_maker = Factory()
        maker = self.cached_maker
        terminals = {}

        for child in self.get_offspring():
            if not child:
                continue
            if maker.isinstance(child, 'Terminal'):
                terminals[child] = child.get_allocation()
            elif maker.isinstance(child, 'Container'):
                terminals.update(child.get_visible_terminals())
            else:
                err('Unknown child type %s' % type(child))

        return(terminals) 
Example #8
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def is_child_notebook(self):
        """Returns True if this Window's child is a Notebook"""
        maker = Factory()
        return(maker.isinstance(self.get_child(), 'Notebook')) 
Example #9
Source File: factories.py    From pysoa with Apache License 2.0 5 votes vote down vote up
def _adjust_kwargs(cls, **kwargs):  # type: (**Any) -> Dict[six.text_type, Any]
        # Factory Boy special method used to alter custom settings dictionaries.
        # Make a copy of settings and override transport to use base transport.
        kwargs['data'] = dict(
            kwargs['data'],
            transport={
                'path': 'pysoa.common.transport.local:LocalServerTransport',
            },
        )
        return kwargs 
Example #10
Source File: tweet.py    From busy-beaver with MIT License 5 votes vote down vote up
def Tweet(session):
    class _TweetFactory(factory.Factory):
        class Meta:
            model = model

        id = factory.Sequence(lambda n: n)

    return _TweetFactory 
Example #11
Source File: event_details.py    From busy-beaver with MIT License 5 votes vote down vote up
def EventDetails(session):
    class _EventDetailsFactory(factory.Factory):
        class Meta:
            model = model

        id = factory.Faker("uuid4")
        name = "ChiPy"
        url = "http://meetup.com/_ChiPy_/event/blah"
        start_epoch = int((datetime.now() + timedelta(days=1)).timestamp())
        end_epoch = start_epoch + 60 * 60 * 2
        venue = "Numerator"

    return _EventDetailsFactory 
Example #12
Source File: terminator.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def new_window(self, cwd=None):
        """Create a window with a Terminal in it"""
        maker = Factory()
        window = maker.make('Window')
        terminal = maker.make('Terminal')
        if cwd:
            terminal.set_cwd(cwd)
        window.add(terminal)
        window.show(True)
        terminal.spawn_child()

        return(window, terminal) 
Example #13
Source File: ipc.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def get_terminal_tab_title(self, uuid):
        """Return the title of a parent tab of a given terminal"""
        maker = Factory()
        terminal = self.terminator.find_terminal_by_uuid(uuid)
        window = terminal.get_toplevel()
        root_widget = window.get_children()[0]
        if maker.isinstance(root_widget, "Notebook"):
            return root_widget.get_tab_label(terminal).get_label() 
Example #14
Source File: ipc.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def get_terminal_tab(self, uuid):
        """Return the UUID of the parent tab of a given terminal"""
        maker = Factory()
        terminal = self.terminator.find_terminal_by_uuid(uuid)
        window = terminal.get_toplevel()
        root_widget = window.get_children()[0]
        if maker.isinstance(root_widget, 'Notebook'):
            return root_widget.uuid.urn 
Example #15
Source File: container.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def propagate_title_change(self, widget, title):
        """Pass a title change up the widget stack"""
        maker = Factory()
        parent = self.get_parent()
        title = widget.get_window_title()

        if maker.isinstance(self, 'Notebook'):
            self.update_tab_label_text(widget, title)
        elif maker.isinstance(self, 'Window'):
            self.title.set_title(widget, title)

        if maker.isinstance(parent, 'Container'):
            parent.propagate_title_change(widget, title) 
Example #16
Source File: paned.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        """Class initialiser"""
        self.terminator = Terminator()
        self.maker = Factory()
        Container.__init__(self)
        self.signals.append({'name': 'resize-term', 
                             'flags': gobject.SIGNAL_RUN_LAST,
                             'return_type': gobject.TYPE_NONE, 
                             'param_types': (gobject.TYPE_STRING,)})


    # pylint: disable-msg=W0613 
Example #17
Source File: util.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def enumerate_descendants(parent):
    """Walk all our children and build up a list of containers and
    terminals"""
    # FIXME: Does having to import this here mean we should move this function
    # back to Container?
    from factory import Factory

    containerstmp = []
    containers = []
    terminals = []
    maker = Factory()

    if parent is None:
        err('no parent widget specified')
        return

    for descendant in parent.get_children():
        if maker.isinstance(descendant, 'Container'):
            containerstmp.append(descendant)
        elif maker.isinstance(descendant, 'Terminal'):
            terminals.append(descendant)

        while len(containerstmp) > 0:
            child = containerstmp.pop(0)
            for descendant in child.get_children():
                if maker.isinstance(descendant, 'Container'):
                    containerstmp.append(descendant)
                elif maker.isinstance(descendant, 'Terminal'):
                    terminals.append(descendant)
            containers.append(child)

    dbg('%d containers and %d terminals fall beneath %s' % (len(containers), 
        len(terminals), parent))
    return(containers, terminals) 
Example #18
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def move_tab(self, widget, direction):
        """Handle a keyboard shortcut for moving tab positions"""
        maker = Factory()
        notebook = self.get_child()

        if not maker.isinstance(notebook, 'Notebook'):
            dbg('not in a notebook, refusing to move tab %s' % direction)
            return

        dbg('moving tab %s' % direction)
        numpages = notebook.get_n_pages()
        page = notebook.get_current_page()
        child = notebook.get_nth_page(page)

        if direction == 'left':
            if page == 0:
                page = numpages
            else:
                page = page - 1
        elif direction == 'right':
            if page == numpages - 1:
                page = 0
            else:
                page = page + 1
        else:
            err('unknown direction: %s' % direction)
            return
        
        notebook.reorder_child(child, page) 
Example #19
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def tab_change(self, widget, num=None):
        """Change to a specific tab"""
        if num is None:
            err('must specify a tab to change to')

        maker = Factory()
        child = self.get_child()

        if not maker.isinstance(child, 'Notebook'):
            dbg('child is not a notebook, nothing to change to')
            return

        if num == -1:
            # Go to the next tab
            cur = child.get_current_page()
            pages = child.get_n_pages()
            if cur == pages - 1:
                num = 0
            else:
                num = cur + 1
        elif num == -2:
            # Go to the previous tab
            cur = child.get_current_page()
            if cur > 0:
                num = cur - 1
            else:
                num = child.get_n_pages() - 1

        child.set_current_page(num)
        # Work around strange bug in gtk-2.12.11 and pygtk-2.12.1
        # Without it, the selection changes, but the displayed page doesn't
        # change
        child.set_current_page(child.get_current_page())

    # FIXME: All of these (un)group_(all|tab) methods need refactoring work 
Example #20
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def add(self, widget, metadata=None):
        """Add a widget to the window by way of gtk.Window.add()"""
        maker = Factory()
        gtk.Window.add(self, widget)
        if maker.isinstance(widget, 'Terminal'):
            signals = {'close-term': self.closeterm,
                       'title-change': self.title.set_title,
                       'split-horiz': self.split_horiz,
                       'split-vert': self.split_vert,
                       'unzoom': self.unzoom,
                       'tab-change': self.tab_change,
                       'group-all': self.group_all,
                       'ungroup-all': self.ungroup_all,
                       'group-tab': self.group_tab,
                       'ungroup-tab': self.ungroup_tab,
                       'move-tab': self.move_tab,
                       'tab-new': [self.tab_new, widget],
                       'navigate': self.navigate_terminal}

            for signal in signals:
                args = []
                handler = signals[signal]
                if isinstance(handler, list):
                    args = handler[1:]
                    handler = handler[0]
                self.connect_child(widget, signal, handler, *args)

            widget.grab_focus() 
Example #21
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def on_delete_event(self, window, event, data=None):
        """Handle a window close request"""
        maker = Factory()
        if maker.isinstance(self.get_child(), 'Terminal'):
            dbg('Window::on_delete_event: Only one child, closing is fine')
            return(False)
        elif maker.isinstance(self.get_child(), 'Container'):
            return(self.confirm_close(window, _('window')))
        else:
            dbg('unknown child: %s' % self.get_child()) 
Example #22
Source File: terminal.py    From NINJA-PingU with GNU General Public License v3.0 4 votes vote down vote up
def on_drag_data_received(self, widget, drag_context, x, y, selection_data,
            _info, _time, data):
        """Something has been dragged into the terminal. Handle it as either a
        URL or another terminal."""
        dbg('drag data received of type: %s' % selection_data.type)
        if gtk.targets_include_text(drag_context.targets) or \
           gtk.targets_include_uri(drag_context.targets):
            # copy text to destination
            txt = selection_data.data.strip(' ')
            if txt[0:7] == 'file://':
                txt = "'%s'" % urllib.unquote(txt[7:])
            else:
                txt = txt.split('\n')[0]
            for term in self.terminator.get_target_terms(self):
                term.feed(txt)
            return
        
        widgetsrc = data.terminator.terminals[int(selection_data.data)]
        srcvte = drag_context.get_source_widget()
        #check if computation requireds
        if (isinstance(srcvte, gtk.EventBox) and 
                srcvte == self.titlebar) or srcvte == widget:
            return

        srchbox = widgetsrc

        # The widget argument is actually a vte.Terminal(). Turn that into a
        # terminatorlib Terminal()
        maker = Factory()
        while True:
            widget = widget.get_parent()
            if not widget:
                # We've run out of widgets. Something is wrong.
                err('Failed to find Terminal from vte')
                return
            if maker.isinstance(widget, 'Terminal'):
                break

        dsthbox = widget

        dstpaned = dsthbox.get_parent()
        srcpaned = srchbox.get_parent()

        pos = self.get_location(widget, x, y)

        srcpaned.remove(widgetsrc)
        dstpaned.split_axis(dsthbox, pos in ['top', 'bottom'], None, widgetsrc, pos in ['bottom', 'right'])
        srcpaned.hoover()
        widgetsrc.ensure_visible_and_focussed() 
Example #23
Source File: paned.py    From NINJA-PingU with GNU General Public License v3.0 4 votes vote down vote up
def _do_redistribute(self, recurse_up=False, recurse_down=False):
        maker = Factory()
        #2 Make a list of self + all children of same type
        tree = [self, [], 0, None]
        toproc = [tree]
        number_splits = 1
        while toproc:
            curr = toproc.pop(0)
            for child in curr[0].get_children():
                if type(child) == type(curr[0]):
                    childset = [child, [], 0, curr]
                    curr[1].append(childset)
                    toproc.append(childset)
                    number_splits = number_splits+1
                else:
                    curr[1].append([None,[], 1, None])
                    p = curr
                    while p:
                        p[2] = p[2] + 1
                        p = p[3]
                    # (1c) If Shift modifier, redistribute lower sections too
                    if recurse_down and \
                      (maker.isinstance(child, 'VPaned') or \
                       maker.isinstance(child, 'HPaned')):
                        gobject.idle_add(child.do_redistribute, False, True)
                    
        #3 Get ancestor x/y => a, and handle size => hs
        avail_pixels=self.get_length()
        handle_size = self.style_get_property('handle-size')
        #4 Math! eek (a - (n * hs)) / (n + 1) = single size => s
        single_size = (avail_pixels - (number_splits * handle_size)) / (number_splits + 1)
        arr_sizes = [single_size]*(number_splits+1)
        for i in range(avail_pixels % (number_splits + 1)):
            arr_sizes[i] = arr_sizes[i] + 1
        #5 Descend down setting the handle position to s
        #  (Has to handle nesting properly)
        toproc = [tree]
        while toproc:
            curr = toproc.pop(0)
            for child in curr[1]:
                toproc.append(child)
                if curr[1].index(child) == 0:
                    curr[0].set_position((child[2]*single_size)+((child[2]-1)*handle_size))
                    gobject.idle_add(curr[0].set_position, child[2]*single_size) 
Example #24
Source File: container.py    From NINJA-PingU with GNU General Public License v3.0 4 votes vote down vote up
def describe_layout(self, count, parent, global_layout, child_order):
        """Describe our current layout"""
        layout = {}
        maker = Factory()
        mytype = maker.type(self)
        if not mytype:
            err('unable to detemine own type. %s' % self)
            return({})

        layout['type'] = mytype
        layout['parent'] = parent
        layout['order'] = child_order

        if hasattr(self, 'get_position'):
            position = self.get_position()
            if hasattr(position, '__iter__'):
                position = ':'.join([str(x) for x in position])
            layout['position'] = position

        if hasattr(self, 'get_size'):
            layout['size'] = self.get_size()

        labels = []
        if mytype == 'Notebook':
            for tabnum in xrange(0, self.get_n_pages()):
                page = self.get_nth_page(tabnum)
                label = self.get_tab_label(page)
                labels.append(label.get_custom_label())
        if len(labels) > 0:
            layout['labels'] = labels

        name = 'child%d' % count
        count = count + 1

        global_layout[name] = layout

        child_order = 0
        for child in self.get_children():
            if hasattr(child, 'describe_layout'):
                count = child.describe_layout(count, name, global_layout, child_order)
            child_order = child_order + 1

        return(count) 
Example #25
Source File: notebook.py    From NINJA-PingU with GNU General Public License v3.0 4 votes vote down vote up
def closetab(self, widget, label):
        """Close a tab"""
        tabnum = None
        try:
            nb = widget.notebook
        except AttributeError:
            err('TabLabel::closetab: called on non-Notebook: %s' % widget)
            return

        for i in xrange(0, nb.get_n_pages() + 1):
            if label == nb.get_tab_label(nb.get_nth_page(i)):
                tabnum = i
                break

        if tabnum is None:
            err('TabLabel::closetab: %s not in %s. Bailing.' % (label, nb))
            return

        maker = Factory()
        child = nb.get_nth_page(tabnum)

        if maker.isinstance(child, 'Terminal'):
            dbg('Notebook::closetab: child is a single Terminal')
            child.close()
            # FIXME: We only do this del and return here to avoid removing the
            # page below, which child.close() implicitly does
            del(label)
            return
        elif maker.isinstance(child, 'Container'):
            dbg('Notebook::closetab: child is a Container')
            dialog = self.construct_confirm_close(self.window, _('tab'))
            result = dialog.run()
            dialog.destroy()

            if result == gtk.RESPONSE_ACCEPT:
                containers = None
                objects = None
                containers, objects = enumerate_descendants(child)

                while len(objects) > 0:
                    descendant = objects.pop()
                    descendant.close()
                    while gtk.events_pending():
                        gtk.main_iteration()
                return
            else:
                dbg('Notebook::closetab: user cancelled request')
                return
        else:
            err('Notebook::closetab: child is unknown type %s' % child)
            return

        nb.remove_page(tabnum)
        del(label) 
Example #26
Source File: window.py    From NINJA-PingU with GNU General Public License v3.0 4 votes vote down vote up
def set_rough_geometry_hints(self):
        """Walk all the terminals along the top and left edges to fake up how
        many columns/rows we sort of have"""
        if not hasattr(self, 'cached_maker'):
            self.cached_maker = Factory()
        maker = self.cached_maker
        if maker.isinstance(self.get_child(), 'Notebook'):
            dbg("We don't currently support geometry hinting with tabs")
            return

        terminals = self.get_visible_terminals()
        column_sum = 0
        row_sum = 0

        for terminal in terminals:
            rect = terminal.get_allocation()
            if rect.x == 0:
                cols, rows = terminal.get_size()
                row_sum = row_sum + rows
            if rect.y == 0:
                cols, rows = terminal.get_size()
                column_sum = column_sum + cols

        if column_sum == 0 or row_sum == 0:
            dbg('column_sum=%s,row_sum=%s. No terminals found in >=1 axis' %
                (column_sum, row_sum))
            return

        # FIXME: I don't think we should just use whatever font size info is on
        # the last terminal we inspected. Looking up the default profile font
        # size and calculating its character sizes would be rather expensive
        # though.
        font_width, font_height = terminal.get_font_size()
        total_font_width = font_width * column_sum
        total_font_height = font_height * row_sum

        win_width, win_height = self.get_size()
        extra_width = win_width - total_font_width
        extra_height = win_height - total_font_height

        dbg('setting geometry hints: (ewidth:%s)(eheight:%s),\
(fwidth:%s)(fheight:%s)' % (extra_width, extra_height, 
                            font_width, font_height))
        self.set_geometry_hints(self, -1, -1, -1, -1, extra_width,
                extra_height, font_width, font_height, -1.0, -1.0)