Exemple #1
0
    def split_axis(self, widget, vertical=True, cwd=None, sibling=None, widgetfirst=True):
        """Split the window"""
        if self.get_property("term_zoomed") == True:
            err("You can't split while a terminal is maximised/zoomed")
            return

        order = None
        maker = Factory()
        self.remove(widget)

        if vertical:
            container = maker.make("VPaned")
        else:
            container = maker.make("HPaned")

        if not sibling:
            sibling = maker.make("Terminal")
            sibling.set_cwd(cwd)
            sibling.spawn_child()
        self.add(container)
        container.show_all()

        order = [widget, sibling]
        if widgetfirst is False:
            order.reverse()

        for term in order:
            container.add(term)
        container.show_all()
Exemple #2
0
 def __init__(self, first_page):
     Factory.__init__(self)
     self.first_page = first_page
     self.category = urlparse.urlsplit(first_page).path.split("/")[2]
     self.save_path = os.path.join("ccrt", self.category)
     self.filename = "subject_urls_" + self.category + ".txt"
     self.d_filename = "subject_urls_" + self.category + "_d.txt"
Exemple #3
0
def get_probe_edit_form(probe_class, resource_identifier=None):
    """get the form to edit a Probe"""

    probe_obj = Factory.create_obj(probe_class)
    if resource_identifier:
        resource = views.get_resource_by_id(resource_identifier)
        if resource:
            probe_obj.expand_params(resource)

    probe_info = probe_obj.get_plugin_vars()
    probe_vars = ProbeVars(
        None, probe_class, probe_obj.get_default_parameter_values())

    # Get only the default Checks for this Probe class
    checks_avail = probe_obj.get_checks_info_defaults()
    checks_avail = probe_obj.expand_check_vars(checks_avail)

    for check_class in checks_avail:
        check_obj = Factory.create_obj(check_class)
        check_params = check_obj.get_default_parameter_values()
        probe_check_param_defs = \
            probe_info['CHECKS_AVAIL'][check_class]['PARAM_DEFS']
        for param in probe_check_param_defs:
            if 'value' in probe_check_param_defs[param]:
                check_params[param] = probe_check_param_defs[param]['value']

        # Appends 'check_vars' to 'probe_vars' (SQLAlchemy)
        CheckVars(probe_vars, check_class, check_params)

    return render_template('includes/probe_edit_form.html',
                           lang=g.current_lang,
                           probe=probe_vars, probe_info=probe_info)
Exemple #4
0
    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,
                'group-all-toggle': self.group_all_toggle,
                'ungroup-all': self.ungroup_all,
                'group-tab': self.group_tab,
                'group-tab-toggle': self.group_tab_toggle,
                '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()
Exemple #5
0
    def rotate(self, widget, clockwise):
        """Rotate children in this window"""
        self.set_pos_by_ratio = True
        maker = Factory()
        child = self.get_child()

        # 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, 'Paned'):
            parent = child.get_parent()
            # Need to get the allocation before we remove the child,
            # otherwise _sometimes_ we get incorrect values.
            alloc = child.get_allocation()
            parent.remove(child)
            child.rotate_recursive(parent, alloc.width, alloc.height,
                                   clockwise)

            self.show_all()
            while Gtk.events_pending():
                Gtk.main_iteration_do(False)
            widget.grab_focus()

        self.set_pos_by_ratio = False
Exemple #6
0
    def layout_done(self):
        """Layout operations have finished, record that fact"""
        self.doing_layout = False
        maker = Factory()

        window_last_active_term_mapping = {}
        for window in self.windows:
            if window.is_child_notebook():
                source = window.get_toplevel().get_children()[0]
            else:
                source = window
            window_last_active_term_mapping[window] = copy.copy(
                source.last_active_term)

        for terminal in self.terminals:
            if not terminal.pid:
                terminal.spawn_child()

        for window in self.windows:
            if window.is_child_notebook():
                # For windows with a notebook
                notebook = window.get_toplevel().get_children()[0]
                # Cycle through pages by number
                for page in xrange(0, notebook.get_n_pages()):
                    # Try and get the entry in the previously saved mapping
                    mapping = window_last_active_term_mapping[window]
                    page_last_active_term = mapping.get(
                        notebook.get_nth_page(page), None)
                    if page_last_active_term is None:
                        # Couldn't find entry, so we find the first child of type Terminal
                        children = notebook.get_nth_page(page).get_children()
                        for page_last_active_term in children:
                            if maker.isinstance(page_last_active_term,
                                                'Terminal'):
                                page_last_active_term = page_last_active_term.uuid
                                break
                        else:
                            err('Should never reach here!')
                            page_last_active_term = None
                    if page_last_active_term is None:
                        # Bail on this tab as we're having no luck here, continue with the next
                        continue
                    # Set the notebook entry, then ensure Terminal is visible and focussed
                    urn = page_last_active_term.urn
                    notebook.last_active_term[notebook.get_nth_page(
                        page)] = page_last_active_term
                    if urn:
                        term = self.find_terminal_by_uuid(urn)
                        if term:
                            term.ensure_visible_and_focussed()
            else:
                # For windows without a notebook ensure Terminal is visible and focussed
                if window_last_active_term_mapping[window]:
                    term = self.find_terminal_by_uuid(
                        window_last_active_term_mapping[window].urn)
                    term.ensure_visible_and_focussed()

        for window in self.windows:
            if window.uuid == self.last_active_window:
                window.show()
Exemple #7
0
    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()
Exemple #8
0
        def new_factory_pair(neutral):
            # Generate a new factory in one hemisphere.
            dist = random.random() * self.max_dist / 2.0
            angle = random.random() * math.pi

            pos_x = math.cos(angle) * dist
            pos_y = math.sin(angle) * dist

            stock = self.random_stock(neutral=neutral)

            if neutral:
                production = self.random_production()
            else:
                production = 1

            team = 0 if neutral else 1

            start_id = len(self.factories)
            new_factory = Factory(fid=start_id,
                                  team=team,
                                  production=production,
                                  stock=stock,
                                  position=(pos_x, pos_y))
            rotated_factory = Factory(fid=start_id + 1,
                                      team=-team,
                                      production=production,
                                      stock=stock,
                                      position=(-pos_x, -pos_y))

            return [new_factory, rotated_factory]
Exemple #9
0
    def reconfigure(self):
        """Update configuration for the whole application"""

        if self.style_provider is not None:
            Gtk.StyleContext.remove_provider_for_screen(
                Gdk.Screen.get_default(),
                self.style_provider)
            self.style_provider = None
        if self.config['handle_size'] in xrange(0, 6):
            css = """
                GtkPaned {
                    -GtkPaned-handle-size: %s
                }
                """ % self.config['handle_size']
            self.style_provider = Gtk.CssProvider()
            self.style_provider.load_from_data(css)
            Gtk.StyleContext.add_provider_for_screen(
                Gdk.Screen.get_default(), 
                self.style_provider,     
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        # 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()
Exemple #10
0
 def run(self):
     modules = self._module_conf.get_modules()
     factory = Factory()
     for module in modules:
         test_base = factory.create(module)
         test_base.initialize(self._module_conf.get_config(module))
         test_base.run()
Exemple #11
0
    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)
Exemple #12
0
    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())
Exemple #13
0
    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()
Exemple #14
0
    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()
Exemple #15
0
    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 = []
        child = self.get_child()

        # 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, '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
Exemple #16
0
    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()
Exemple #17
0
    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 = []
        child = self.get_child()

        # 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, '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
Exemple #18
0
    def load_config(cls,verbose=True):
        parser = argparse.ArgumentParser()
        parser.add_argument('-c','--config')
        args = parser.parse_args()

        if not args.config:
            print('Missing -c[config file]')
            exit()

        file = args.config.replace('.py','')
        pathfile = 'configs/{}.py'.format(file)
        if not os.path.isfile(pathfile):
            exit('Config file "{}" does not exist'.format(pathfile))

        config_file = "configs.{}".format(file)

        if not config_file:
            exit('Please supply a config file. Example: python run.py my_config (without .py)\n')

        if verbose:
            print('Loading config: {}'.format(file))

        try:
            current_config = __import__(config_file,fromlist="Config")
        except ImportError:
            print('Unable to load config.')
            raise

        cls.configIntegrityCheck(current_config.Config)
        cls.configRequiredCheck(current_config.Config)

        Factory.set('Config',current_config.Config)
        if verbose:
            print('Config loaded')
Exemple #19
0
    def rotate(self, widget, clockwise):
        """Rotate children in this window"""
        self.set_pos_by_ratio = True
        maker = Factory()
        child = self.get_child()

        # 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, 'Paned'):
            parent = child.get_parent()
            # Need to get the allocation before we remove the child,
            # otherwise _sometimes_ we get incorrect values.
            alloc = child.get_allocation()
            parent.remove(child)
            child.rotate_recursive(parent, alloc.width, alloc.height, clockwise)

            self.show_all()
            while Gtk.events_pending():
                Gtk.main_iteration_do(False)
            widget.grab_focus()

        self.set_pos_by_ratio = False
Exemple #20
0
    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())
Exemple #21
0
def init():
    # Config.show_keep_alive_after_idle = 1
    Config = Factory.get('Config')
    Lang = Factory.get('Translation')
    try:
        Config.printSettings()
        Db.init()

        if not ServerControl.is_server_running():
            out(Lang.get('server_not_running'))
            ServerControl.start_server()

        custom_import(Config.events_config,'events') #Load events

        Rcon.init(Config.rcon_host, Config.rcon_port, Config.query_port, Config.rcon_password, Config.rcon_socket_timeout)

        InputHandler.init() #Activate listening for terminal input

        #custom_import(Config.events_config,'input') #Load terminal input configuration
        custom_import(Config.tasks_config,'tasks') #Load tasks

        # Prevent threads from dying due to early main completed execution.
        while True:
            if Storage.terminate_application is True:
                exit()
            time.sleep(1)  # Important part of not being a CPU hog.

    except KeyboardInterrupt:
        Storage.terminate_application = True
Exemple #22
0
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)
Exemple #23
0
    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)
Exemple #24
0
 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()
 def set_up_mocks(self):
     self.factory = Factory()
     self.mock_datetime = MagicMock()
     self.factory.register('DateTimeWrapper', self.mock_datetime)
     self.mock_fs_wrapper = MagicMock()
     self.factory.register('FsWrapper', self.mock_fs_wrapper)
     self.mock_file_20190315 = MagicMock()
     self.mock_file_20190317 = MagicMock()
Exemple #26
0
 def get_tab(self, uuid=None):
     """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
Exemple #27
0
 def get_tab_title(self, uuid=None):
     """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()
Exemple #28
0
 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
Exemple #29
0
    def split_axis(self,
                   widget,
                   vertical=True,
                   cwd=None,
                   sibling=None,
                   widgetfirst=True):
        """Split the axis of a terminal inside us"""
        dbg('called for widget: %s' % widget)
        order = None
        page_num = self.page_num(widget)
        if page_num == -1:
            err('Notebook::split_axis: %s not found in Notebook' % widget)
            return

        label = self.get_tab_label(widget)
        self.remove(widget)

        maker = Factory()
        if vertical:
            container = maker.make('vpaned')
        else:
            container = maker.make('hpaned')

        self.get_toplevel().set_pos_by_ratio = True

        if not sibling:
            sibling = maker.make('terminal')
            sibling.set_cwd(cwd)
            if self.config['always_split_with_profile']:
                sibling.force_set_profile(None, widget.get_profile())
            sibling.spawn_child()
            if widget.group and self.config['split_to_group']:
                sibling.set_group(None, widget.group)
        elif self.config['always_split_with_profile']:
            sibling.force_set_profile(None, widget.get_profile())

        self.insert_page(container, None, page_num)
        self.child_set_property(container, 'tab-expand', True)
        self.child_set_property(container, 'tab-fill', True)
        self.set_tab_reorderable(container, True)
        self.set_tab_label(container, label)
        self.show_all()

        order = [widget, sibling]
        if widgetfirst is False:
            order.reverse()

        for terminal in order:
            container.add(terminal)
        self.set_current_page(page_num)

        self.show_all()

        while Gtk.events_pending():
            Gtk.main_iteration_do(False)
        self.get_toplevel().set_pos_by_ratio = False

        GObject.idle_add(terminal.ensure_visible_and_focussed)
Exemple #30
0
    def get_version(cls):
        data = Rcon.query_server()
        if data:
            if Factory.has('GUI_CONTROL'):
                Factory.get('GUI_CONTROL').set_server_version(data['game_version'])

            out('Server is running game version: ', data['game_version'])
        else:
            out('Unable to retrieve server game version')
Exemple #31
0
 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,)})
 def set_up_mocks(self):
     self.factory = Factory()
     self.mock_url_validator = MagicMock()
     self.factory.register('UrlValidator', self.mock_url_validator)
     self.mock_pagegroup_extractor = MagicMock()
     self.factory.register('UrlPagegroupExtractor',
                           self.mock_pagegroup_extractor)
     self.mock_url_router = MagicMock()
     self.factory.register('UrlRouter', self.mock_url_router)
Exemple #33
0
 def set_label_function(self, name_label_function):
     """
     :Raises NpyTransferFunctionError:
         If name_label_function does not correspond to a label function.
     """
     try:
         Factory.check_prefix(name_label_function, Label.prefix)
         self._label_function = Factory.build_instance_by_name(name_label_function)
     except NpyTransferFunctionError, e:
         raise NpyTransferFunctionError, e.msg
Exemple #34
0
    def ungroup_tab(self, widget):
        """Ungroup all terminals in the current tab"""
        maker = Factory()
        notebook = self.get_child()

        if not maker.isinstance(notebook, 'Notebook'):
            dbg('note in a notebook, refusing to ungroup tab')
            return
        
        self.set_groups(None, self.get_visible_terminals())
Exemple #35
0
    def ungroup_tab(self, widget):
        """Ungroup all terminals in the current tab"""
        maker = Factory()
        notebook = self.get_child()

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

        self.set_groups(None, self.get_visible_terminals())
Exemple #36
0
 def set_autoresize(self, autoresize):
     """Must be called on the highest ancestor in one given orientation"""
     """TODO write some better doc :)"""
     maker = Factory()
     children = self.get_children()
     self.child_set_property(children[0], 'resize', False)
     self.child_set_property(children[1], 'resize', not autoresize)
     for child in children:
         if maker.type(child) == maker.type(self):
             child.set_autoresize(autoresize)
Exemple #37
0
 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())
Exemple #38
0
 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())
 def set_up_mocks(self):
     self.factory = Factory()
     self.mock_godaddy_task_retriever = MagicMock()
     self.factory.register('GoDaddyTaskRetriever',
                           self.mock_godaddy_task_retriever)
     self.mock_godaddy_tasks_merger = MagicMock()
     self.factory.register('GoDaddyTasksMerger',
                           self.mock_godaddy_tasks_merger)
     self.mock_logger = MagicMock()
     self.factory.register('Logger', self.mock_logger)
Exemple #40
0
 def set_autoresize(self, autoresize):
     """Must be called on the highest ancestor in one given orientation"""
     """TODO write some better doc :)"""
     maker = Factory()
     children = self.get_children()
     self.child_set_property(children[0], 'resize', False)
     self.child_set_property(children[1], 'resize', not autoresize)
     for child in children:
         if maker.type(child) == maker.type(self):
             child.set_autoresize(autoresize)
Exemple #41
0
 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())
    def test_resolve_battles(self):
        # (Factory, occupying_troops, expt_team, expt_stock)
        test_battles = [
            # Neutral factory with no troops can be taken over
            (Factory(0, 0, 0, 0, (0, 0)), {-1: 0, 1: 1}, 1, 1),
            (Factory(0, 0, 0, 0, (0, 0)), {-1: 2, 1: 1}, -1, 1),
            # Neutral factory with no troops, stalemate doesn't change team
            (Factory(0, 0, 0, 0, (0, 0)), {-1: 1, 1: 1}, 0, 0),
            # Team factory changes hands on loss
            (Factory(0, 1, 0, 10, (0, 0)), {-1: 20, 1: 5}, -1, 5),
            (Factory(0, -1, 0, 10, (0, 0)), {-1: 5, 1: 20}, 1, 5),
            # Team factory with 0 resulting troops doesnt change hands
            (Factory(0, 1, 0, 10, (0, 0)), {-1: 10, 1: 0}, 1, 0),
            (Factory(0, -1, 0, 10, (0, 0)), {-1: 0, 1: 10}, -1, 0),
            # Reinforcement
            (Factory(0, 1, 0, 5, (0, 0)), {-1: 10, 1: 20}, 1, 15),
            (Factory(0, -1, 0, 5, (0, 0)), {-1: 20, 1: 10}, -1, 15),
        ]

        for factory, occupying_troops, expt_team, expt_stock in test_battles:
            factory.occupying_troops = occupying_troops
            factory.resolve_battles()

            self.assertEqual(factory.team, expt_team)
            self.assertEqual(factory.stock, expt_stock)

            # Reset occupiers
            self.assertEqual(
                factory.occupying_troops, {-1: 0, 1: 0}
            )
Exemple #43
0
    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, 'ismaximised'):
            layout['maximised'] = self.ismaximised
        
        if hasattr(self, 'isfullscreen'):
            layout['fullscreen'] = self.isfullscreen
        if hasattr(self, 'ratio'):
            layout['ratio'] = self.ratio

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

        if hasattr(self, 'title'):
            layout['title'] = self.title.text

        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())
            layout['active_page'] = self.get_current_page()
        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)
Exemple #44
0
    def layout_done(self):
        """Layout operations have finished, record that fact"""
        self.doing_layout = False
        maker = Factory()

        window_last_active_term_mapping = {}
        for window in self.windows:
            if window.is_child_notebook():
                source = window.get_toplevel().get_children()[0]
            else:
                source = window
            window_last_active_term_mapping[window] = copy.copy(source.last_active_term)

        for terminal in self.terminals:
            if not terminal.pid:
                terminal.spawn_child()

        for window in self.windows:
            if window.is_child_notebook():
                # For windows with a notebook
                notebook = window.get_toplevel().get_children()[0]
                # Cycle through pages by number
                for page in xrange(0, notebook.get_n_pages()):
                    # Try and get the entry in the previously saved mapping
                    mapping = window_last_active_term_mapping[window]
                    page_last_active_term = mapping.get(notebook.get_nth_page(page),  None)
                    if page_last_active_term is None:
                        # Couldn't find entry, so we find the first child of type Terminal
                        children = notebook.get_nth_page(page).get_children()
                        for page_last_active_term in children:
                            if maker.isinstance(page_last_active_term, 'Terminal'):
                                page_last_active_term = page_last_active_term.uuid
                                break
                        else:
                            err('Should never reach here!')
                            page_last_active_term = None
                    if page_last_active_term is None:
                        # Bail on this tab as we're having no luck here, continue with the next
                        continue
                    # Set the notebook entry, then ensure Terminal is visible and focussed
                    urn = page_last_active_term.urn
                    notebook.last_active_term[notebook.get_nth_page(page)] = page_last_active_term
                    if urn:
                        term = self.find_terminal_by_uuid(urn)
                        if term:
                            term.ensure_visible_and_focussed()
            else:
                # For windows without a notebook ensure Terminal is visible and focussed
                if window_last_active_term_mapping[window]:
                    term = self.find_terminal_by_uuid(window_last_active_term_mapping[window].urn)
                    term.ensure_visible_and_focussed()

        for window in self.windows:
            if window.uuid == self.last_active_window:
                window.show()
Exemple #45
0
    def ungroup_tab(self, widget):
        """Ungroup all terminals in the current tab"""
        maker = Factory()
        notebook = self.get_child()

        if not maker.isinstance(notebook, "Notebook"):
            dbg("note in a notebook, refusing to ungroup tab")
            return

        for terminal in self.get_visible_terminals():
            terminal.set_group(None, None)
Exemple #46
0
def main():
    try:
        config = load_config()
        init_logger('logs/cloudsweep.log')
        logger    = logging.getLogger('clouddump')
        service   = Factory().create(
                        config['service']['driver'], config['service'])
        service.delete_old_files()
        logger.info("Program terminated successfully")
    except SystemExit:
        logger.info("Program terminated with errors")
Exemple #47
0
 def haveColoredBlocksChildren(self):
     if len(self.getchildren()) != 2:
         return False
     for child in self.getchildren():
         label = child.get(addNS('xmoto_label', 'xmoto'), '')
         parser = Factory().create('label_parser')
         label = parser.parse(label)
         if 'typeid' in label:
             # only entities have a typeid
             return False
     return True
Exemple #48
0
    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)
Exemple #49
0
    def restart(self):
        """Reset all the games variables causing a restart."""
        for _, sprite_group in self._entities.items():
            sprite_group.empty()

        self._tank = Factory.create_tank(self._entities['all'],
                                         self._entities['tanks'])
        self._shields = Factory.create_shields(self._entities['all'],
                                               self._entities['shields'])
        self._alien_horde = Factory.create_horde(self._entities['all'],
                                                 self._entities['ships'])
Exemple #50
0
    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)
 def __init__(self, master=None):
     self.controller = Controller()
     self.factory = Factory()
     self._init_constructors()
     tkinter.Frame.__init__(self, master)
     self.create_widgets()
     self.register = registrator.PluginsRegistrator()
     self.register.register_plugins()
     self._search_plugins()
     # display the menu
     root.config(menu=self.menubar)
     self.pack()
Exemple #52
0
    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)
Exemple #53
0
    def split_axis(self, widget, vertical=True, cwd=None, sibling=None, widgetfirst=True):
        """Split the axis of a terminal inside us"""
        dbg('called for widget: %s' % widget)
        order = None
        page_num = self.page_num(widget)
        if page_num == -1:
            err('Notebook::split_axis: %s not found in Notebook' % widget)
            return

        label = self.get_tab_label(widget)
        self.remove(widget)

        maker = Factory()
        if vertical:
            container = maker.make('vpaned')
        else:
            container = maker.make('hpaned')

        self.get_toplevel().set_pos_by_ratio = True

        if not sibling:
            sibling = maker.make('terminal')
            sibling.set_cwd(cwd)
            if self.config['always_split_with_profile']:
                sibling.force_set_profile(None, widget.get_profile())
            sibling.spawn_child()
            if widget.group and self.config['split_to_group']:
                sibling.set_group(None, widget.group)
        elif self.config['always_split_with_profile']:
            sibling.force_set_profile(None, widget.get_profile())

        self.insert_page(container, None, page_num)
        self.child_set_property(container, 'tab-expand', True)
        self.child_set_property(container, 'tab-fill', True)
        self.set_tab_reorderable(container, True)
        self.set_tab_label(container, label)
        self.show_all()

        order = [widget, sibling]
        if widgetfirst is False:
            order.reverse()

        for terminal in order:
            container.add(terminal)
        self.set_current_page(page_num)

        self.show_all()

        while Gtk.events_pending():
            Gtk.main_iteration_do(False)
        self.get_toplevel().set_pos_by_ratio = False

        GObject.idle_add(terminal.ensure_visible_and_focussed)
Exemple #54
0
    def __init__(self, _meotech):

        print "Engine - init >>>"

        # MeoTehc
        self.meotech = _meotech

        ### Setup Engine Holders ###

        # Create Game Object Holders
        self.GameObjects = {}
        self.GameObjects["player"] = None
        self.GameObjects["level"] = {}
        self.GameObjects["object"] = {}
        self.GameObjects["light"] = {}
        self.GameObjects["sensor"] = {}

        # Create Render Object Holders for sorting stuff in sceneG.
        # nodepaths
        self.RenderObjects = {}
        self.BulletObjects = {}

        # none visual
        self.BulletObjects["main"] = render.attachNewNode("Bullet_main")
        self.BulletObjects["player"] = self.BulletObjects[
            "main"].attachNewNode("Bullet_player")
        self.BulletObjects["level"] = self.BulletObjects["main"].attachNewNode(
            "Bullet_level")
        self.BulletObjects["object"] = self.BulletObjects[
            "main"].attachNewNode("Bullet_object")
        self.BulletObjects["sensor"] = self.BulletObjects[
            "main"].attachNewNode("Bullet_sensor")

        # Visuals
        self.RenderObjects["level"] = render.attachNewNode("Render_level")
        self.RenderObjects["object"] = render.attachNewNode("Render_object")
        self.RenderObjects["light"] = render.attachNewNode("Render_light")

        ### Engine Holders END ###

        # Setup Bullet Physics
        self.bulletWorld = BulletWorld()
        self.bulletWorld.setGravity(Vec3(GRAVITY_X, GRAVITY_Y, GRAVITY_Z))

        # Init Factory
        self.factory = Factory(self)
        self.factory.parseLevelFile("test")

        # Init Input

        # Start Engine Loop
        # Controls Physics and other engine related Things
        taskMgr.add(self.engineLoop, "Engine_Loop")
Exemple #55
0
    def ungroup_tab(self, widget):
        """Ungroup all terminals in the current tab"""
        maker = Factory()
        notebook = self.get_child()

        if not maker.isinstance(notebook, 'Notebook'):
            dbg('note in a notebook, refusing to ungroup tab')
            return
        
        for terminal in self.get_visible_terminals():
            terminal.set_group(None, None)
        self.terminator.focus_changed(self.terminator.last_focused_term)
Exemple #56
0
    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)
Exemple #57
0
    def __init__(self, www_path):
        self.factory = Factory()
        self.factory.register('DateTimeWrapper', DateTimeWrapper())
        self.factory.register('FsWrapper', FsWrapper())
        self.filepathhandler = FilePathHandler(www_path)

        daily_log_writer = DailyFileWriter(self.factory, DAILY_LOG_NAME,
                                           DAILY_LOG_EXT)
        daily_err_writer = DailyFileWriter(self.factory, DAILY_LOG_NAME,
                                           DAILY_ERR_EXT)
        daily_logger = Logger(self.factory, daily_log_writer, daily_err_writer)
        self.logger = LogChainer(daily_logger)
        self.logger.chain(ConsoleLogger(True))
Exemple #58
0
 def get_tab_title(self, uuid=None):
     """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"):
         for tab_child in root_widget.get_children():
             terms = [tab_child]
             if not maker.isinstance(terms[0], "Terminal"):
                 terms = enumerate_descendants(tab_child)[1]
             if terminal in terms:
                 return root_widget.get_tab_label(tab_child).get_label()