def __init__( self, *args, **kwargs ):
        tk.Tk.__init__( self, *args, **kwargs )
        self.protocol( "WM_DELETE_WINDOW", self.destroy )

        self.wm_title("bent file explorer")
        self.text_last_command = tk.StringVar()
        #print( self.winfo_screenwidth() )

        widget_file_explorer = Explorer( self )
        frame_bottom = tk.Frame( self )

        btn_quit = tk.Button( frame_bottom,
            text="QUIT",
            command=self.Quit )

        lbl_last_command = tk.Label( frame_bottom,
                textvariable = self.text_last_command )

        widget_file_explorer.grid( row=0, sticky='nesw' )
        #post grid row column configure - must be called after grid but should be specified by the widget itself, not here
        widget_file_explorer.pgrc_configure()
        frame_bottom.grid( row=1, sticky='nesw' )
        btn_quit.grid( column=2, sticky='e' )
        lbl_last_command.grid( column=0, sticky='w' )

        self.rowconfigure('0', weight=1)
        self.columnconfigure('all', weight=1)
        frame_bottom.columnconfigure('all', weight=1)
Example #2
0
def print_map(win_map, path, start_row, start_col):
    """
    Prints a map of paths that lead to treasure
    :param start_row: The starting row of the map
    :param start_col: The starting column of the map
    :param path: the stack of directions that have been made
    :param win_map: The map that has the winning paths on it
    :return: none
    """
    if path.size() == 0:
        return
    else:
        path = copy.deepcopy(path)
        path.items.reverse()
        winner = Explorer(start_row, start_col)
        print(
            "The following is the total paths to treasure. Underscore's denote the path to a treasure:"
        )
        for i in range(path.size() - 1):
            forward = path.pop()
            if forward == "north":
                winner.move_n()
            elif forward == "south":
                winner.move_s()
            elif forward == "east":
                winner.move_e()
            elif forward == "west":
                winner.move_w()
            win_map[winner.row][winner.col] = "_"
    for i in win_map:
        print(i)
Example #3
0
def explore(fs):
    from Explorer import Explorer

    renderer = Explorer()
    renderer.render(fs.root())

    gtk.mainloop()

    return
Example #4
0
def explore(fs):
    from Explorer import Explorer
    
    renderer = Explorer()
    renderer.render(fs.root())

    gtk.mainloop()

    return
Example #5
0
 def Run(self):
     self._universe = Universe()
     w = Explorer(self._universe, 0, self._maze._entrance, self._maze, {},
                  "")
     self._universe.AddWorldsForEvaluation([w])
     solutionWorld = self._universe.Run()
     print(f"Short path to solution is {solutionWorld._generation}.")
     return solutionWorld._generation
Example #6
0
def main():
    cave_map = parse_file("cave_2.txt")
    win_map = copy.deepcopy(cave_map)
    start_row, start_col = find_start(cave_map)
    test = Explorer(start_row, start_col)
    path = Stack()
    not_finished = True
    while not_finished:
        not_finished = advance(test, cave_map, path, win_map, start_row,
                               start_col)
    print("There was no more treasure.")
Example #7
0
class Tester:
    def __init__(self):
        self.explorer = Explorer(True)

    def test(self):
        file = open('resultsfile.txt', 'w')
        i = 0
        for file_name in os.listdir('labelme-luna16-Data/test'):
            print(file_name)
            image = cv2.imread(
                f'labelme-luna16-Data/test/{file_name}/images/img.png', 0)
            image_label = cv2.imread(
                f'labelme-luna16-Data/test/{file_name}/label_viz.png')
            label = cv2.imread(
                f'labelme-luna16-Data/test/{file_name}/masks/label.png')
            label = cv2.cvtColor(label, cv2.COLOR_BGR2GRAY)
            ret, label = cv2.threshold(label, 20, 255, cv2.THRESH_BINARY)
            boxes, mask = self.explorer.explore(image)
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
            if not boxes.size == 0:
                for box in boxes:
                    cls = str(box[0])
                    x1 = int(box[1])
                    y1 = int(box[2])
                    x2 = int(box[3])
                    y2 = int(box[4])
                    image = cv2.rectangle(image, (x1, y1), (x2, y2),
                                          (0, 0, 255), 1)
                    image = cv2.putText(image, cls[:5], (x1, y1),
                                        cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                        (0, 0, 255))
            file.write(file_name + '\n')
            file.write(str(int(boxes.size // 5)) + '\n')
            if not boxes.size == 0:
                for box in boxes:
                    cls = str(box[0])
                    x1 = int(box[1])
                    y1 = int(box[2])
                    w = int(box[3] - box[1])
                    h = int(box[4] - box[2])
                    file.write(f'{x1} {y1} {w} {h} {cls}\n')
                # image = cv2.resize(image,None,fx=2,fy=2)
            cv2.imshow('JK', image)
            cv2.imshow('mask', mask)
            cv2.imshow('labelviz', image_label)
            cv2.imwrite(f'biaozhu/{i}.png', label)
            cv2.imwrite(f'yuche/{i}.png', mask)
            i += 1
            #if cv2.waitKey(1) == ord('c'):
            #break
        file.close()
Example #8
0
    def __init__(self,
                 x_min,
                 y_min,
                 x_max,
                 y_max,
                 show_gui=False,
                 url="http://localhost:50000"):
        self.__robot = Robot(url)
        self.__robot_drive = RobotDrive(self.__robot)

        # Map grid size in meters per square (robot is 450 x 400 x 243 (LxWxH))
        MAP_GRID_SIZE = .2

        # Set coordinates and dimensions of local map area within the world coordinate system
        width_wcs = x_max - x_min
        height_wcs = y_max - y_min
        width_grid = math.ceil(width_wcs / MAP_GRID_SIZE)
        height_grid = math.ceil(height_wcs / MAP_GRID_SIZE)

        self.__local_map = OccupancyGrid(x_min, y_min, MAP_GRID_SIZE,
                                         height_grid, width_grid)
        self.__laser = LaserSensorModel(self.__robot, self.__local_map)
        self.__show_map = ShowMap(height_grid, width_grid, show_gui)
        self.__explorer = Explorer(self.__robot, self.__local_map)
        self.__path_planner = WavefrontPlanner(self.__robot, self.__local_map)
        self.__obstacle_avoider = ObstacleAvoider(self.__robot,
                                                  self.__local_map)

        # Keep track of number of steps taken in the main_loop
        self.__SCAN_FREQUENCY = 10
        self.__cycles = 0
        self.__loop_running = False
        self.__take_a_scan = False
        self.__determine_frontiers = False
        self.__in_reactive_state = False
        self.__in_warning = False
        self.__in_danger = False
        self.__in_reactive = False
Example #9
0
def main():
    parser = argparse.ArgumentParser(
        description='Creates a classification dataset from a segmentation one.'
    )
    parser.add_argument(
        'path',
        type=str,
        help='Absolute path containing the images and masks folders.')
    parser.add_argument('--patch_size',
                        type=int,
                        default=224,
                        help='Size of each patch.')
    parser.add_argument('--max_patches_per_image',
                        type=int,
                        default=100,
                        help='How many patches to extract from each image.')
    args = parser.parse_args()

    explorer = Explorer(args.path)
    converter = Converter(explorer,
                          patch_size=args.patch_size,
                          max_patches_per_image=args.max_patches_per_image)
    converter.process_images()
Example #10
0
    def sample(self, keep=None):
        """
        Sample the posterior and return the weighted average result of the
        Model.

        The more sensible result of this method is a SampleList which contains
        samples taken from the posterior distribution.

        Parameters
        ----------
        keep : None or dict of {int:float}
            Dictionary of indices (int) to be kept at a fixed value (float)
            Hyperparameters follow model parameters
            The values will override those at initialization.
            They are only used in this call of fit.

        """
        if keep is None:
            keep = self.keep
        fitlist = self.makeFitlist(keep=keep)

        self.initWalkers(fitlist=fitlist)
        for eng in self.engines:
            eng.walkers = self.walkers

        self.distribution.ncalls = 0  #  reset number of calls

        self.plotData()

        if self.verbose >= 1:
            print("Fit", ("all" if keep is None else fitlist), "parameters of")
            print(" ", self.model._toString("  "))
            print("Using a", self.distribution, "with")
            np = self.model.npchain
            for name, hyp in zip(self.distribution.PARNAMES,
                                 self.distribution.hyperpar):
                print("  %-7.7s   " % name, end="")
                if np in fitlist:
                    print("unknown")
                else:
                    print("  (fixed)  ", hyp.hypar)
#                    print( "%7.2f  (fixed)" % hyp.hypar )
                np += 1
            print("Moving the walkers with")
            for eng in self.engines:
                print(" ", eng)

        if self.verbose >= 2:
            print("Iteration   logZ        H     LowL     npar    parameters")

        explorer = Explorer(self)

        self.logZ = -sys.float_info.max
        self.info = 0

        logWidth = math.log(1.0 -
                            math.exp((-1.0 * self.discard) / self.ensemble))

        if self.optionalRestart():
            logWidth -= self.iteration * (1.0 * self.discard) / self.ensemble

        while self.iteration < self.getMaxIter():

            #  find worst walker(s) in ensemble
            worst = self.findWorst()
            worstLogW = logWidth + self.walkers[worst[-1]].logL

            # Keep posterior samples
            self.storeSamples(worst, worstLogW - math.log(self.discard))

            # Update Evidence Z and Information H
            logZnew = numpy.logaddexp(self.logZ, worstLogW)

            self.info = (math.exp(worstLogW - logZnew) * self.lowLhood +
                         math.exp(self.logZ - logZnew) *
                         (self.info + self.logZ) - logZnew)
            self.logZ = logZnew

            if self.verbose >= 3 or (self.verbose >= 2
                                     and self.iteration % 100 == 0):
                kw = worst[0]
                pl = self.walkers[kw].parlist[self.walkers[kw].fitIndex]
                np = len(pl)
                print(
                    "%8d %8.1f %8.1f %8.1f %6d " %
                    (self.iteration, self.logZ, self.info, self.lowLhood, np),
                    fmt(pl))

                self.plotResult(worst[0], self.iteration)

            self.samples.weed(self.maxsize)  # remove overflow in samplelist

            self.copyWalker(worst)

            # Explore the copied walker(s)
            explorer.explore(worst, self.lowLhood, fitlist)

            # Shrink the interval
            logWidth -= (1.0 * self.discard) / self.ensemble
            self.iteration += 1

            self.optionalSave()

        # End of Sampling
        self.addEnsembleToSamples(logWidth)

        # Calculate weighted average and stdevs for the parameters;
        self.samples.LogZ = self.logZ
        self.samples.info = self.info
        self.samples.normalize()

        # put the info into the model
        self.model.parameters = self.samples.parameters
        self.model.stdevs = self.samples.stdevs

        if self.verbose >= 1:
            self.report()

        return self.samples.average(self.xdata)
Example #11
0
class RobotController:
    def __init__(self,
                 x_min,
                 y_min,
                 x_max,
                 y_max,
                 show_gui=False,
                 url="http://localhost:50000"):
        self.__robot = Robot(url)
        self.__robot_drive = RobotDrive(self.__robot)

        # Map grid size in meters per square (robot is 450 x 400 x 243 (LxWxH))
        MAP_GRID_SIZE = .2

        # Set coordinates and dimensions of local map area within the world coordinate system
        width_wcs = x_max - x_min
        height_wcs = y_max - y_min
        width_grid = math.ceil(width_wcs / MAP_GRID_SIZE)
        height_grid = math.ceil(height_wcs / MAP_GRID_SIZE)

        self.__local_map = OccupancyGrid(x_min, y_min, MAP_GRID_SIZE,
                                         height_grid, width_grid)
        self.__laser = LaserSensorModel(self.__robot, self.__local_map)
        self.__show_map = ShowMap(height_grid, width_grid, show_gui)
        self.__explorer = Explorer(self.__robot, self.__local_map)
        self.__path_planner = WavefrontPlanner(self.__robot, self.__local_map)
        self.__obstacle_avoider = ObstacleAvoider(self.__robot,
                                                  self.__local_map)

        # Keep track of number of steps taken in the main_loop
        self.__SCAN_FREQUENCY = 10
        self.__cycles = 0
        self.__loop_running = False
        self.__take_a_scan = False
        self.__determine_frontiers = False
        self.__in_reactive_state = False
        self.__in_warning = False
        self.__in_danger = False
        self.__in_reactive = False

    def main(self):

        # Start program
        self.__loop_running = True
        self.__take_a_scan = True
        self.__determine_frontiers = True

        try:
            self.main_loop()
            self.end_program()
        except KeyboardInterrupt:
            self.__robot.setMotion(0, 0)

    def main_loop(self):
        while self.__loop_running:
            # Force take a scan
            if self.__cycles % self.__SCAN_FREQUENCY == 0:
                self.__take_a_scan = True

            # Update map if scan flag is true
            if self.__take_a_scan:
                self.__do_take_scan()

            # Update frontier nodes
            if self.__determine_frontiers:
                self.__do_determine_frontiers()

            # If robot has a point to navigate to, take next step
            if self.__robot_drive.has_navigation_point():
                self.__robot_drive.take_step()

            # If no navigation point, determine new frontier nodes
            if not self.__robot_drive.has_navigation_point():
                self.__determine_frontiers = True
                self.__robot.setMotion(0.0, 0.0)

            # Check distance to obstacle and set flags
            self.__in_danger, self.__in_warning = self.__obstacle_avoider.in_danger(
            )

            # If "too" close to obstacle, slow max speed
            self.__robot_drive.warning(self.__in_warning)

            # If in reactive mode but no longer in danger, break out of reactive mode
            if not self.__in_danger and self.__in_reactive:
                self.__in_reactive = False

            # If in danger, but not in reactive mode, start reactive mode
            if self.__in_danger and not self.__in_reactive:
                self.__in_reactive = True
                self.__determine_frontiers = True
                self.__robot.setMotion(0.0, 0.0)

            # Keep track of total cycles
            self.__cycles += 1

            # Wait before next cycle
            time.sleep(.1)

    def end_program(self):
        self.__show_map.close()
        self.__robot.setMotion(0.0, 0.0)
        print("Map has been discovered. End Mapmaker program!")

    def __do_take_scan(self):

        # Get robot position
        position_wcs = self.__robot.getPosition()
        heading = self.__robot.getHeading()
        self.__laser.update_grid(position_wcs['X'], position_wcs['Y'])

        # Calculate the robot's position on the grid.
        robot_col, robot_row = self.__local_map.wcs_to_grid(
            position_wcs['X'], position_wcs['Y'])

        # Update map with latest grid values and the robot's position
        self.__show_map.updateMap(self.__local_map.get_grid(), robot_col,
                                  robot_row, heading)

        self.__show_map.close()

        self.__take_a_scan = False

    def __do_determine_frontiers(self):
        frontiers = self.__explorer.get_frontiers()

        if len(frontiers) > 0:
            # add/update green dots on the image
            self.__show_map.set_frontiers(frontiers)

            # Get new path from the path planner
            try:
                path, frontier_x, frontier_y = self.__path_planner.get_path_to_frontier(
                    frontiers)
            except:
                self.__loop_running = False
                return

            path_grid = np.array(path)

            # Convert path (grid) to WCS
            path_x_wcs, path_y_wcs = self.__local_map.grid_to_wcs(
                path_grid[:, 0], path_grid[:, 1])
            path_wcs = np.zeros((len(path_x_wcs), 2))
            path_wcs[:, 0] = path_x_wcs
            path_wcs[:, 1] = path_y_wcs

            # Give WCS path to robot drive
            self.__robot_drive.set_WCS_path(np.array(path_wcs))

            self.__show_map.set_path(path_grid)

            # Close flag
            self.__determine_frontiers = False

        else:
            ## TODO what to do when no frontier nodes are returned
            #raise Exception("no frontier nodes found")
            self.__loop_running = False
Example #12
0
 def __init__(self):
     self.explorer = Explorer(True)
Example #13
0
class MainWindow:
    
    PYCAMIMG_FILE_EXTENSION = ".cmmg"
    PYCAMIMG_TITLE = "PyCamimg"
    
    __DEFAULT_WINDOW_WIDTH__ = 800
    __DEFAULT_WINDOW_HEIGHT__ = 600
    
    def __init__(self,
                 cores,
                 domain=None,
                 languages=None,
                 currentLang=None,
                 setLanguage=None):
        """
        @summary: Initialize PyCamimg main window.
        @param cores: List of preloaded CamCores.
        @param domain: GetText domain to use.
        @param languages: List of languages that it can use.
        @param currentLang: Current language of the list.
        @param setLanguage: Function reference to set new language.     
        """
        # Initialize current tab
        self.__lsTabs__ = []
        self.__currentTab__ = None

        # Language configuration
        self.__langs__ = languages
        self.__currLang__ = currentLang

        # Set pycamimg domain if domain is None
        if (domain == None):
            domain = pycamimg.gettextName

        # Initialize UI
        self.__initUI__(domain)
        
        # Initialize other treeviews
        self.__initTargets__(cores)

    def __initUI__(self, domain):
        """
        @summary: Initialize UI of PyCamimg.
        @param domain: GetText domain to use.
        """
        self.__menuBar__ = None
        self.__toolBar__ = None
        
        __log__.debug("Initializing UI...")        
        # Create the toplevel window
        self.__mainWindow__ = gtk.Window()
        self.__mainWindow__.connect("destroy", self.__quitEvent__)
        self.__mainWindow__.connect("delete-event", self.__queryQuitEvent__)
        self.__mainWindow__.set_size_request(self.__DEFAULT_WINDOW_WIDTH__, self.__DEFAULT_WINDOW_HEIGHT__)
        self.__mainWindow__.set_title(self.PYCAMIMG_TITLE)
        self.__mainWindow__.set_icon_from_file(os.path.join(__ICONS_FOLDER__, "pycamimg.png"))
        
        vbox = gtk.VBox()
        self.__mainWindow__.add(vbox)
        
        self.__initUIMenu__(domain)
        
        if (self.__menuBar__ != None):
            vbox.pack_start(self.__menuBar__, False)
        
        # Recovers TreeViews
        self.__eExplorer__ = Explorer(showHiddens=Configuration().getConfiguration().getboolean("NAVIGATOR", "show_hiddens"))
        __log__.debug("\tExplorer widget: %s" % self.__eExplorer__)
        
        # Enabled navigator buttons (back and forward buttons)
        self.__eExplorer__.enabledNavigationButtons()
        
        # self.__eExplorer__.goHome()
        __log__.debug("Went to home directory");
        
        self.__operations__ = RegOperations()
        __log__.debug("\tOperations widget: %s" % self.__operations__)
        
        hPaned = gtk.HPaned()
        hPaned.set_position(int(self.__DEFAULT_WINDOW_WIDTH__ * 0.85))
        hPaned.pack1(self.__eExplorer__.getControl())
        hPaned.pack2(self.__operations__.getControl(), False, True)
        
        vBoxWorkArea = gtk.VBox()
        if (self.__toolBar__ != None):
            vBoxWorkArea.pack_start(self.__toolBar__, False)
            
        self.__nbProjects__ = gtk.Notebook()
        self.__nbProjects__.set_tab_pos(gtk.POS_TOP)
        self.__nbProjects__.set_scrollable(True)
        self.__nbProjects__.set_show_border(True)
        self.__nbProjects__.connect("switch-page", self.__changeProjectEvent__)
        __log__.debug("Project Notebook: %s" % self.__nbProjects__)
        
        vBoxWorkArea.pack_start(self.__nbProjects__, True, True)
        
        vPaned = gtk.VPaned()
        vPaned.set_position(int(self.__DEFAULT_WINDOW_HEIGHT__ * 0.40))
        
        vPaned.add1(hPaned)
        vPaned.add2(vBoxWorkArea)
        
        vbox.pack_start(vPaned, True, True)
        
        
        self.__statBar__ = gtk.Statusbar()
        self.__statBar__.set_has_resize_grip(True)
        
        vbox.pack_start(self.__statBar__, False)
        
        # Search project plugins, that define the kind of project.
        self.__searchPlugins__()
        
        self.__enableOptions__(blockGtk=False)
    
    def __initUIMenu__(self, domain):
        """
        @summary: Initialize menu of window. 
        @param domain: Domain used to translation.
        """
        actionGroupMenu = gtk.ActionGroup("ActionGroupMenu")
        
        # Create actions
        actionGroupMenu.add_actions([("FileMenuAction", None, _("_File")),
                                     ("NewProjectAction", None, _("New Project")),
                                     ("OpenProjectAction", gtk.STOCK_OPEN, _("_Open"), "<Control>o", _("Open PyCamimg project"), self.__openProjectEvent__),
                                     ("SaveProjectAction", gtk.STOCK_SAVE, _("_Save"), "<Control>s", _("Save current project"), self.__saveProjectEvent__),
                                     ("SaveAsProjectAction", gtk.STOCK_SAVE_AS, _("Save _As"), None, _("Save current project"), self.__saveAsProjectEvent__),
                                     ("QuitAction", gtk.STOCK_QUIT, _("_Quit"), "<Control>q", _("Quit PyCamimg"), self.__queryQuitMenuItemEvent__),
                                     ("ToolsMenuAction", None, _("_Tools")),
                                     ("OperationsAction", None, _("Operations")),
                                     ("PreferencesAction", gtk.STOCK_PREFERENCES, _("_Preferences"), None, _("Preferences of PyCamimg"), self.__openOptionsEvent__),
                                     ("PluginsAction", gtk.STOCK_CONNECT, _("P_lugins"), None, _("Plugins of PyCamimg"), self.__openPlunginsEvent__),
                                     ("HelpMenuAction", None, _("_Help")),
                                     ("AboutAction", gtk.STOCK_ABOUT, _("_About PyCamimg"), None, _("Preferences of PyCamimg"), self.__openAboutEvent__),
                                     ("AddItemAction", gtk.STOCK_ADD, _("Add Images"), None, _("Add selected images"), self.__addImageEvent__),
                                     ("DelItemAction", gtk.STOCK_DELETE, _("Delete Images"), None, _("Delete selected images"), self.__deleteImageEvent__),
                                     ("DelOperationsAction", gtk.STOCK_CLEAR, _("Delete Operations"), None, _("Delete selected operations"), self.__deleteOperationsEvent__),
                                     ("RunAction", gtk.STOCK_EXECUTE, _("Run"), None, _("Run current project"), self.__runEvent__)])
        actionGroupMenu.add_toggle_actions([("ChangeViewAction", gtk.STOCK_CONVERT, _("Toggle view"), None, _("Toggle between differents views"), self.__changeViewProjectEvent__)])

        actionGroupMenu.set_translation_domain(domain)
        
        __log__.debug("There is a xml path. UI Menus and tools will be recovered from path %s" % __XMLUI_FOLDER__)
        print __XMLUI_FOLDER__
        self.__uiManager__ = FactoryControls.getUIManager(os.path.join(__XMLUI_FOLDER__, "MainMenu.xml"), self.__mainWindow__, actionGroupMenu)[0]
        
        self.__menuBar__ = self.__uiManager__.get_widget("/MenuPyCaming")
        self.__toolBar__ = self.__uiManager__.get_widget("/ToolsPyCamimg")
        self.__toolBar__.set_style(gtk.TOOLBAR_BOTH_HORIZ)
        self.__toolBar__.set_tooltips(True)
        

    
    def __searchPlugins__(self):
        """
        @summary: Search plugins of PyCamimg.
        """
        self.__searchProjectPlugins__()
        self.__searchOperationsPlugins__()
    
    def __searchProjectPlugins__(self):
        """
        @summary: Search new kind of projects, and create a menu item for each.
        """
        __log__.debug("Project modules are loaded")
        
        projectTypes = Loader.getPluginsType(pycamimg.core.plugins.ICamimgPlugin.PLUGIN_TYPE.PROJECT)
        actionGroupProjectPlugins = gtk.ActionGroup("ActionGroupProjectPlugins")
        self.__uiManager__.insert_action_group(actionGroupProjectPlugins, pos=-1)
        
        for project in projectTypes:
            __log__.debug("Processing plugin %s" % project[Loader.INDEX_PLUGIN].getName())    
                        
            projectInstance = project[Loader.INDEX_PLUGIN_INSTANCE]()
            __log__.debug("Creating new menu item for project type %s" % projectInstance.getTypeName())
            
            aAction = projectInstance.getGtkAction()
            if (aAction != None):
                aAction.connect("activate", self.__newProjectEvent__, project[Loader.INDEX_PLUGIN_INSTANCE])
                __log__.debug("Add activate signal to  %s" % projectInstance.getTypeName())
                actionGroupProjectPlugins.add_action(aAction)
            else:
                __log__.debug("There is not action for %s" % projectInstance.getTypeName())
                
            if (projectInstance.getXmlLocation() != ""):
                self.__uiManager__.add_ui_from_file(os.path.join(__XMLUI_FOLDER__, projectInstance.getXmlLocation()))
            
                mi = self.__uiManager__.get_widget("/MenuPyCaming/FileMenu/NewProject/NewProjectAdditions/%s" % projectInstance.getTypeName())
                if (mi != None):
                    iconPath = os.path.join(__ICONS_FOLDER__, projectInstance.getIconName())
                    __log__.debug("Get project icon from %s" % iconPath)
                    UIUtils.setImageToMenuItem(mi, iconPath, doGObject=False)
                else:
                    __log__.warning("It could not update icon of %s. Action name %s was not found." % (projectInstance.getTypeName(), projectInstance.getTypeName()))
            else:
                __log__.debug("%s is not in menu." % projectInstance.getTypeName())
                
            __log__.debug("Added new project type %s" % projectInstance.getTypeName())
            
    def __searchOperationsPlugins__(self):
        """
        @summary: Search operations, and create a menu item for each.
        """
        __log__.debug("Project modules are loaded")
        
        operationsPlugins = Loader.getPluginsType(pycamimg.core.plugins.ICamimgPlugin.PLUGIN_TYPE.OPERATION)
        actionGroupOperationPlugins = gtk.ActionGroup("ActionGroupOperationPlugins")
        self.__uiManager__.insert_action_group(actionGroupOperationPlugins, pos=-1)
        
        for operation in operationsPlugins:
            __log__.debug("Processing plugin %s" % operation[Loader.INDEX_PLUGIN])    
                        
            operationInstance = operation[Loader.INDEX_PLUGIN_INSTANCE]()
            __log__.debug("Creating operation %s" % operationInstance.getOperationName())
            
            lActions = operationInstance.getActions()
            if (lActions != None):
                for aAction in lActions:
                    aAction.connect("activate", self.__activateOperation__, operationInstance.callbackAction)
                    __log__.debug("Add activate signal to  %s" % operationInstance.getOperationName())
                    actionGroupOperationPlugins.add_action(aAction)
            else:
                __log__.debug("There is not action for %s" % operationInstance.getOperationName())
                
            if (operationInstance.getXmlLocation() != ""):
                self.__uiManager__.add_ui_from_file(os.path.join(__XMLUI_FOLDER__, operationInstance.getXmlLocation()))
                
                dIcons = operationInstance.getIconsActions()
                for actionPath, iconPath in dIcons.iteritems():
                    mi = self.__uiManager__.get_widget(actionPath)
                    if (mi != None): 
                        iconPath = os.path.join(__ICONS_FOLDER__, iconPath)            
                        __log__.debug("Get project icon from %s" % iconPath)
                        if (isinstance(mi, gtk.ImageMenuItem)):
                            UIUtils.setImageToMenuItem(mi, iconPath, doGObject=False)
                        elif (isinstance(mi, gtk.ToolButton)):
                            UIUtils.setImageToToolItem(mi, iconPath, size=self.__toolBar__.get_icon_size(), doGObject=False)
                        else:
                            __log__.warning("Unknown type control.")
                    else:
                        __log__.warning("It could not update icon of %s. Action name %s was not found." % (operationInstance.getOperationName(), actionPath))
            else:
                __log__.debug("%s is not in menu." % operationInstance.getOperationName())
                
            __log__.debug("Added new operation %s" % operationInstance.getOperationName())
    
    
### INITIALIZE TreeViews ###
    def __initTargets__(self, cores):
        """
        @summary: Initialize tabs.
        @param cores: A list of cores that are preloaded. 
        """
        for core in cores:
            self.__addNewProject__(core)
        __log__.info("Initialized target projects")
            
    def __addNewProject__(self, core=None, threadBlock=True, focused=False, projectType=None):
        """
        @summary: Add new project.
        @param core: Core that will be added. Default value is None
        @param threadBlock: True if it will be locked gtk-loop. Default True
        @param focused: True if new tab project will get the focus.
        """
        __log__.debug("Add new project: core=%s | threadBlock=%s | focused=%s | projectType=%s" % (core, threadBlock, focused, projectType))
        if (core == None):
            core = CamCore(temp=__TEMP_FOLDER__, projectType=projectType)
            __log__.debug("New core created. %s" % core)
            
        text = ""
        if (core.getName() == ""):    
            text = "%s_%d" % (_("Project"), len(self.__lsTabs__))
        else:
            text = core.getName()
        __log__.info("Project name %s" % text)
        tab = TabProject(core, name=text, iconsPath=os.path.join(__ICONS_FOLDER__),
                         iconName=core.getProjectType().getIconName())
        tab.setCloseCallback(self.__closeProject__)
        __log__.debug("Callbacks set")
        core.setName(text)
        tab.addToNotebook(self.__nbProjects__, threadBlock=threadBlock, focused=focused)
        tab.load()
        
        self.__lsTabs__.append(tab)
        
        if (self.__currentTab__ == None):
            __log__.debug("There is not current tab. It will set %s as current tab." % core.getName())
            self.__currentTab__ = tab
        
        __log__.debug("New project added to project notebook")
        
        self.__enableOptions__(blockGtk=threadBlock)
                
    def __closeProject__(self, index):
        """
        @summary: Runs when project is closed.
        @param index: Index of project that will be closed. 
        """
        __log__.debug("Close project %d" % index)
        
        tab = self.__lsTabs__[index]
        if (tab != None):
            core = tab.getCore()
            if (core != None):
                __log__.debug("%s will be deleted" % core.getName())
                del core
                core = None
            self.__lsTabs__.remove(tab)
            if (tab == self.__currentTab__):
                self.__currentTab__ = None
            tab.closeTab()            
            del tab
            __log__.debug("Tab was closed and core was deleted")
        else:
            __log__.warn("Index %d does not exist" % index)
        
        self.__enableOptions__(blockGtk=False)
    
    def __refreshProjects__(self):
        """
        @summary: Refresh all open projects.
        """
        for tbTab in self.__lsTabs__:
            if (tbTab != None):
                tbTab.load()
                __log__.debug("Core %s reloaded" % tbTab.getCore().getName())
                
    
    def __enableOptions__(self, blockGtk=True):
        """
        @summary: Enable or disable all options.
        """
        enable = (self.__currentTab__ != None)
        
        toolbar = self.__uiManager__.get_widget("/ToolsPyCamimg")
        imiSave = self.__uiManager__.get_widget("/MenuPyCaming/FileMenu/SaveProject")
        imiSaveAs = self.__uiManager__.get_widget("/MenuPyCaming/FileMenu/SaveAsProject")
        iOptions = 0
        
        mOperations = self.__uiManager__.get_widget("/MenuPyCaming/ToolsMenu/Operations")
        if (mOperations != None):
            if (mOperations.get_submenu() != None):
                __log__.debug("Enabling operations of operation menu")
                mOperations.get_submenu().foreach(lambda mi: UIUtils.enabledWidget(mi, enable, blockGtk))
            else:
                __log__.debug("Operation menu does not have menu")
                        
        if (toolbar != None):
            iOptions = toolbar.get_n_items()
            
        if (iOptions > 0):
            for i in range(0, iOptions):
                itItem = toolbar.get_nth_item(i)
                if (itItem != None):
                    if (blockGtk):
                        gtk.gdk.threads_enter()
                    try:
                        itItem.set_sensitive(enable)
                    finally:
                        if (blockGtk):
                            gtk.gdk.threads_leave()
                else:
                    __log__.warning("It could not recover item of index %d" % i)
        else:
            __log__.debug("There are not options.")
            
        if (imiSave != None):
            imiSave.set_sensitive(enable)
            
        if (imiSaveAs != None):
            imiSaveAs.set_sensitive(enable)
            
           
    def __updateTitle__(self, threadBlock=False):
        """Update title of the window"""
        title = ""
        if (self.__currentTab__ != None):
            if (self.__currentTab__.getCore().getFilename() != None):
                title = "%s - %s - %s" % (self.__currentTab__.getCore().getName(),
                                          self.__currentTab__.getCore().getFilename(),
                                          self.PYCAMIMG_TITLE)
            else:
                title = "%s - %s" % (self.__currentTab__.getCore().getName(), self.PYCAMIMG_TITLE)
        else:
            title = self.PYCAMIMG_TITLE
            
        __log__.debug("New window title %s" % title)

        UIUtils.setTitleWindow(self.__mainWindow__, title, doGObject=threadBlock)

#####PUBLIC METHODS#######
# TOOLBAR ITEMS: CLICK EVENT

    def __addImageEvent__ (self, b):
        """
        @summary: Add into target TreeView selected files from the files TreeView.
        @param b: Button that threw event. 
        """
        files = self.__eExplorer__.getSelectedFiles()
        if (self.__currentTab__ != None):
            # Send files to target TreeView
            addThread = Thread(target=self.__currentTab__.addTargetFiles, args=(files,))
            addThread.start()
            __log__.debug("Add thread started. %s" % addThread)
        else:
            __log__.debug("There is not a tab selected")

    def __deleteImageEvent__ (self, b):
        """
        @summary: Delete files from target TreeView.
        @param b: Button that threw event.
        """
        if (self.__currentTab__ != None):
            delThread = Thread(target=self.__currentTab__.deleteSelectedImages, args=())
            delThread.start()
            __log__.debug("Delete thread started. %s" % delThread)
        else:
            __log__.debug("There is not a tab selected")

    def __deleteOperationsEvent__ (self, b):
        """
        @summary: Delete operations of an item.
        @param b: Button that threw event.
        """
        if (self.__currentTab__ == None):
            __log__.debug("There is not current project")
            return
        
        paths = self.__currentTab__.getSelection()
        model = self.__currentTab__.getModel()
        if ((paths == None) or (model == None)):
            __log__.error("It can not recover tree selection. Set selection at 0.")
            iNRows = 0
        else:
            iNRows = len(paths)
        
        if iNRows > 0:
            path = paths[0]
            iter = model.get_iter(path)
            if (iter != None):
                file = model.get_value(iter, self.__currentTab__.COLUMN_SOURCE)
                item = self.__currentTab__.getCore().getItem(file)
                operationsDialog = OperationsDialog(
                                    item,
                                    iter,
                                    callback=self.__applyDeleteOperationsItemCallback__,
                                    parent=self.__mainWindow__)
        
                __log__.debug("Operations dialog created. %s" % operationsDialog)
                operationsDialog.run()
                del operationsDialog
            else:
                __log__.error("It can not recover iter from path %s. Abort open delete operations dialog." % path)
                FactoryControls.getMessage(_("It can not get item"),
                                           title=_("Delete operations"),
                                           type=gtk.MESSAGE_ERROR,
                                           parent=self.__mainWindow__)
            
        else:
            FactoryControls.getMessage(_("Select one item"),
                                       title=_("Delete operations"),
                                       parent=self.__mainWindow__)

    def __applyDeleteOperationsItemCallback__(self, item, iter):
        """
        @summary: Apply changes on item.
        @param item: Item that has changes. 
        @param iter: Iter where item is. 
        """
        if ((item != None) and (iter != None)):
            self.__currentTab__.updateItemDescription(iter, item, gtkLock=False)

    def openPreview (self, b):
        """
        @summary: Open image.
        @param b: Button that threw event. 
        """
        
        if (self.__currentTab__ == None):
            __log__.debug("There is not current project")
            return
        
        paths = self.__currentTab__.getSelection()
        model = self.__currentTab__.getModel()
        if ((paths == None) or (model == None)):
            __log__.error("It can not recover tree selection. Set selection at 0.")
            iNRows = 0
        else:
            iNRows = len(paths)
        
        if iNRows > 0:
            path = paths[0]
            iter = model.get_iter(path)
            if (iter != None):
                file = model.get_value(iter, 1)
                meta = ImgMeta(file)
                meta.show()
            else:
                __log__.error("It can not recover iter from path %s. Abort preview" % path)
                FactoryControls.getMessage(_("It can not show image"),
                                           title=_("Preview"),
                                           type=gtk.MESSAGE_ERROR,
                                           parent=self.__mainWindow__)
            
        else:
            FactoryControls.getMessage(_("Select one item"),
                                       title=_("Preview"),
                                       parent=self.__mainWindow__)

    def __openPlunginsEvent__(self, b):
        """
        @summary: Open plugins window.
        @param b: Button that threw event.
        """
        pluginsDialog = PluginsDialog(parent=self.__mainWindow__)
        __log__.debug("Plugins dialog created. %s" % pluginsDialog)
        pluginsDialog.run()
            
        del pluginsDialog
        pluginsDialog = None

    def __openOptionsEvent__ (self, b):
        """
        @summary: Open options window.
        @param b: Button that threw event.
        """
        optionsDialog = OptionsDialog(self.__langs__,
                                      self.__currLang__,
                                      callback=self.__applyConfigurationCallback__,
                                      parent=self.__mainWindow__)
        
        __log__.debug("Option dialog created. %s" % optionsDialog)
        optionsDialog.run()
        
    def __changeProjectEvent__ (self, notebook, page, pageNum):
        """
        @summary: Handle change tab signal.
        @param notebook: GtkNotebook control that threw event.
        @param page: New page.
        @param pageNum: Number of new page.  
        """
        if (self.__lsTabs__ != None):
            if (len(self.__lsTabs__) > pageNum):
                self.__currentTab__ = self.__lsTabs__[pageNum]
                self.__updateTitle__(threadBlock=False)
                self.__enableOptions__(blockGtk=False)
            else:
                __log__.warning("There is not tab at index %d" % pageNum)
        else:
            __log__.warning("There is not list of tabs.")
    

    def __runEvent__ (self, b):
        """
        @summary: Do current project.
        @param b: Button that threw event.
        """
        if (self.__currentTab__ != None):
            self.__currentTab__.setOrderToCore()
            exWindow = ExecuteWindow(self.__currentTab__.getCore(),
                                     parent=self.__mainWindow__)
            __log__.debug("Execute window created. %s" % exWindow)            
            exWindow.run()
        else:
            FactoryControls.getMessage(
                _("There isn't current project"),
                title=_("Execute"),
                parent=self.__mainWindow__)

    def __activateOperation__ (self, action, callback=None):
        """
        @summary: Handle operation action.
        @param action: Action that threw event.
        @param callback: Function reference of operation. 
        """
        if (isinstance(action, gtk.Action)):
            if (callback != None):
                callback(action, self.__currentTab__, userData=self.__mainWindow__)
                __log__.info("Action of operation %s threw." % action.get_name())
            else:
                __log__.debug("Callback of %s is None" % action.get_name())
        else:
            __log__.warning("action is not gtk.Action")

    def __openAboutEvent__ (self, b):
        """
        @summary: Handle button about.
        @param b: Button that threw event.
        """
        self.showAbout()

    def __newProjectEvent__ (self, b, projectType=None):
        """
        @summary: Handle new project action.
        @param b: Button that threw event.
        @param projectType: Class reference of project to create. 
        """
        self.__addNewProject__(threadBlock=False, projectType=projectType)
        __log__.info("New project created.")
    
    def __openProjectEvent__ (self, b):
        """
        @summary: Handle open project action.
        @param b: Button that threw event.
        """
        
        fileSel = gtk.FileChooserDialog(title=_("Open project"),
                                        parent=self.__mainWindow__,
                                        action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                                 gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
        
        fileSel.set_default_response(gtk.RESPONSE_CANCEL)
        
        filterCam = gtk.FileFilter()
        filterCam.set_name(_("PyCamimg file"))
        filterCam.add_pattern("*%s" % self.PYCAMIMG_FILE_EXTENSION)
        fileSel.add_filter(filterCam)
        
        fileSel.set_modal(True)
        fileSel.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        if (fileSel.run() == gtk.RESPONSE_ACCEPT):
            filename = fileSel.get_filename()
            __log__.debug("Open project from %s" % filename)
            if (not filename.endswith(self.PYCAMIMG_FILE_EXTENSION)):
                filename = "%s%s" % (filename, self.PYCAMIMG_FILE_EXTENSION)
            
            try:
                core = CamCore.load(filename, tempFolder=__TEMP_FOLDER__)
            except Exception, e:
                __log__.error("It could not load project from %s. %s" % (filename, e))
                FactoryControls.getMessage(_("An error was occurred when it was loading project from %s" % filename),
                                           type=gtk.MESSAGE_ERROR,
                                           title=_("Open project"),
                                           parent=self.__mainWindow__)
                return
            finally:
Example #14
0
 def __initUI__(self, domain):
     """
     @summary: Initialize UI of PyCamimg.
     @param domain: GetText domain to use.
     """
     self.__menuBar__ = None
     self.__toolBar__ = None
     
     __log__.debug("Initializing UI...")        
     # Create the toplevel window
     self.__mainWindow__ = gtk.Window()
     self.__mainWindow__.connect("destroy", self.__quitEvent__)
     self.__mainWindow__.connect("delete-event", self.__queryQuitEvent__)
     self.__mainWindow__.set_size_request(self.__DEFAULT_WINDOW_WIDTH__, self.__DEFAULT_WINDOW_HEIGHT__)
     self.__mainWindow__.set_title(self.PYCAMIMG_TITLE)
     self.__mainWindow__.set_icon_from_file(os.path.join(__ICONS_FOLDER__, "pycamimg.png"))
     
     vbox = gtk.VBox()
     self.__mainWindow__.add(vbox)
     
     self.__initUIMenu__(domain)
     
     if (self.__menuBar__ != None):
         vbox.pack_start(self.__menuBar__, False)
     
     # Recovers TreeViews
     self.__eExplorer__ = Explorer(showHiddens=Configuration().getConfiguration().getboolean("NAVIGATOR", "show_hiddens"))
     __log__.debug("\tExplorer widget: %s" % self.__eExplorer__)
     
     # Enabled navigator buttons (back and forward buttons)
     self.__eExplorer__.enabledNavigationButtons()
     
     # self.__eExplorer__.goHome()
     __log__.debug("Went to home directory");
     
     self.__operations__ = RegOperations()
     __log__.debug("\tOperations widget: %s" % self.__operations__)
     
     hPaned = gtk.HPaned()
     hPaned.set_position(int(self.__DEFAULT_WINDOW_WIDTH__ * 0.85))
     hPaned.pack1(self.__eExplorer__.getControl())
     hPaned.pack2(self.__operations__.getControl(), False, True)
     
     vBoxWorkArea = gtk.VBox()
     if (self.__toolBar__ != None):
         vBoxWorkArea.pack_start(self.__toolBar__, False)
         
     self.__nbProjects__ = gtk.Notebook()
     self.__nbProjects__.set_tab_pos(gtk.POS_TOP)
     self.__nbProjects__.set_scrollable(True)
     self.__nbProjects__.set_show_border(True)
     self.__nbProjects__.connect("switch-page", self.__changeProjectEvent__)
     __log__.debug("Project Notebook: %s" % self.__nbProjects__)
     
     vBoxWorkArea.pack_start(self.__nbProjects__, True, True)
     
     vPaned = gtk.VPaned()
     vPaned.set_position(int(self.__DEFAULT_WINDOW_HEIGHT__ * 0.40))
     
     vPaned.add1(hPaned)
     vPaned.add2(vBoxWorkArea)
     
     vbox.pack_start(vPaned, True, True)
     
     
     self.__statBar__ = gtk.Statusbar()
     self.__statBar__.set_has_resize_grip(True)
     
     vbox.pack_start(self.__statBar__, False)
     
     # Search project plugins, that define the kind of project.
     self.__searchPlugins__()
     
     self.__enableOptions__(blockGtk=False)
Example #15
0
#! /usr/bin/env python

'''
Robot side
'''

import rospy

from Drive import Drive_Keys
from Explorer import Explorer
from Runner import Runner

if __name__ == "__main__":
    rospy.init_node('drive_bot')
    explorer = Explorer()
    runner = Runner()
    drive_keys = Drive_Keys()
    rospy.spin()