예제 #1
0
    def setUp(self):
        p = Project(name='Test Project')
        self.task = Task(p)
        p.append_task(self.task)

        props = getProperties(self.task)
        self.props = [
            'project_name' , 'id'         , 'name'
            'description' , 'path'       , 'taskobject_name' , 
            'taskobject_help', 
            'command_name' , 'setting'    , 'config'          , 
            'config_view'  , 'state_name' , 
            'inputs'       , 'outputs'    , 
        ]

        self.methods = [
            'save' , 'load' , 'copy' , 'delete' , 'tail' ,
        ]

        self.requests = [
            'defineTaskObject' , 'invokeConvert' , 'invokeSend'  , 
            'invokeSubmit'     , 'invokeStop'    , 'invokeAbort' , 
            'invokeReceive'    , 
        ]
        self.event = self.task.getEvent('none_object')
        self.event = self.task.getEvent('init')
	def testEqual(self):
		testProjectA = Project(title="TestProjectA", fixedData="FixedTest",
			movingData="MovingTest", isReference=True)
		testProjectB = Project(title="TestProjectB", fixedData="FixedTest",
			movingData="MovingTest", isReference=True)
		self.assertEqual(testProjectA, testProjectA)
		self.assertNotEqual(testProjectA, testProjectB)
		testProjectB.title = "TestProjectA"
		self.assertEqual(testProjectA, testProjectB)
예제 #3
0
 def read(self,file,owner):
     _, tail = os.path.split(file)
     p = Project(None)
     tree = etree.parse(file)
     root = tree.getroot() #tj.root
     for child in root: #tj.project
         p_att = child.attrib
         #p.file = file
         p.name = tail
         p.owner = owner #p_att["owner"]
         p.dtFrom = datetime.strptime(p_att["dt_from"], "%d.%m.%Y")
         p.dtTo = datetime.strptime(p_att["dt_to"], "%d.%m.%Y")
         p.folderId = None            
         for subChild in child: #tj.engine
             e = Engine(None)
             e_att = subChild.attrib
             e.name = e_att["name"]
             for subSubChild in subChild: #tj.job
                 j = Job(None)
                 j_att = subSubChild.attrib
                 j.name = j_att["name"]
                 j.days = int(j_att["days"])
                 j.duration = int(j_att["duration"])
                 j.start = datetime.strptime(j_att["start"], "%d.%m.%Y")
                 j.color = j_att["color"]
                 #j.engine = e.name
                 e.addJob(j)
             p.addEngine(e)
     return p
예제 #4
0
    def load_project(self, json_file):
        qDebug("load project "+json_file)
        if not os.path.exists(json_file):
            raise Exception("project.dice not found in "+str(json_file))

        project = Project(self)
        project.path = os.path.abspath(os.path.dirname(json_file))
        project.project_config = JsonOrderedDict(json_file)

        if "projectName" in project.project_config:
            project.name = project.project_config["projectName"]

        self.project = project  # set project before using self.desk, so it can access the project
        self.desk.load_desk(project.project_config)
        project.loaded = True
        self.home.add_recent_project(project.name, json_file)
예제 #5
0
    def __init__(self, app):
        """
        Initialization of the Main window. This is directly called after the
        Logger has been initialized. The Function loads the GUI, creates the
        used Classes and connects the actions to the GUI.
        """
        QMainWindow.__init__(self)

        self.app = app

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        self.canvas = self.ui.canvas
        if g.config.mode3d:
            self.canvas_scene = self.canvas
        else:
            self.canvas_scene = None

        self.TreeHandler = TreeHandler(self.ui)

        self.MyPostProcessor = MyPostProcessor()
        self.d2g = Project(self)

        self.createActions()
        self.connectToolbarToConfig()

        self.filename = ""

        self.valuesDXF = None
        self.shapes = Shapes([])
        self.entityRoot = None
        self.layerContents = Layers([])
        self.newNumber = 1

        self.cont_dx = 0.0
        self.cont_dy = 0.0
        self.cont_rotate = 0.0
        self.cont_scale = 1.0
예제 #6
0
def project_main(options, args):
    p = Project(options.projectName, allow_create=options.projectCreate)

    if options.deleteGroup:
        p.group_delete(options.deleteGroup)

    if options.loadELF:
        p.load_elf(options.loadELF,
                   load_segments=options.loadSegments,
                   load_symbols=options.loadSymbols)

    if options.symbolize:
        for addr in args[1:]:
            addr = int(addr, 0)
            name = p.symbolize(addr)
            print("0x%x = %s" % (addr, name))

    if options.show:
        p.show()
예제 #7
0
def inspect_host(spec):
    toolchain = Toolchain(spec=spec)
    print('Host Environment:')
    print('  Host: {} {}'.format(spec.host, spec.arch))
    print('  Target: {} {}'.format(spec.target, spec.arch))
    compiler_path = toolchain.compiler_path()
    if not compiler_path:
        compiler_path = '(Will Install)'
    print('  Compiler: {} (version: {}) {}'.format(spec.compiler,
                                                   toolchain.compiler_version,
                                                   compiler_path))
    compilers = ['{} {}'.format(c[0], c[1]) for c in Toolchain.all_compilers()]
    print('  Available Compilers: {}'.format(', '.join(compilers)))
    print('  Available Projects: {}'.format(', '.join(Project.projects())))
예제 #8
0
    def __init__(self, app):
        """
        Initialization of the Main window. This is directly called after the
        Logger has been initialized. The Function loads the GUI, creates the
        used Classes and connects the actions to the GUI.
        """
        QMainWindow.__init__(self)

        #Build the configuration window
        self.config_window = ConfigWindow(g.config.makeConfigWindgets(), g.config.var_dict, g.config.var_dict.configspec, self)
        self.config_window.finished.connect(self.updateConfiguration)

        self.app = app

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        self.canvas = self.ui.canvas
        if g.config.mode3d:
            self.canvas_scene = self.canvas
        else:
            self.canvas_scene = None

        self.TreeHandler = TreeHandler(self.ui)
        self.configuration_changed.connect(self.TreeHandler.updateConfiguration)

        self.MyPostProcessor = MyPostProcessor()
        self.d2g = Project(self)

        self.createActions()
        self.connectToolbarToConfig()

        self.filename = ""

        self.valuesDXF = None
        self.shapes = Shapes([])
        self.entityRoot = None
        self.layerContents = Layers([])
        self.newNumber = 1

        self.cont_dx = 0.0
        self.cont_dy = 0.0
        self.cont_rotate = 0.0
        self.cont_scale = 1.0
예제 #9
0
def test_project_basic(project_name):
    print("Loading project %s" % project_name)
    p = Project("projects/%s" % project_name)

    print("Set default group active")
    assert p.deactivate_all_groups()
    assert p.set_active_group("default")

    print("Save")
    assert p.save()

    print("Generating build scripts")
    assert p.create_build_scripts()

    run("make -C projects/%s" % project_name)
예제 #10
0
    def load_project(self, json_file):
        qDebug("load project " + json_file)
        if not os.path.exists(json_file):
            raise Exception("project.dice not found in " + str(json_file))

        project = Project(self)
        project.path = os.path.abspath(os.path.dirname(json_file))
        project.project_config = JsonOrderedDict(json_file)

        if "projectName" in project.project_config:
            project.name = project.project_config["projectName"]

        self.project = project  # set project before using self.desk, so it can access the project
        self.desk.load_desk(project.project_config)
        project.loaded = True
        self.home.add_recent_project(project.name, json_file)
예제 #11
0
    def __init__(self, parent=None):
        super(Dice, self).__init__(parent)

        self.application_dir = QCoreApplication.applicationDirPath()

        self.__project = Project(self)  # used as an empty default project, replaced by load_project()
        self.__desk = None
        self.__settings = None
        self.__home = None
        qmlRegisterType(Project, "DICE", 1, 0, "Project")

        self.__theme = Theme(self)
        self.__memory = MemoryInfo(self)
        self.__error = ErrorHandler(self)
        qmlRegisterType(MemoryInfo, "DICE", 1, 0, "MemoryInfo")
        qmlRegisterType(ErrorHandler, "DICE", 1, 0, "ErrorHandler")
        qmlRegisterType(BasicWrapper, "DICE", 1, 0, "BasicWrapper")
        qmlRegisterType(Camera, "DICE", 1, 0, "Camera")

        self.__app_log_buffer = {}
        self.__app_log_write_interval = 500
        self.__app_log_writer = self.__init_log_writer()

        self.__qml_engine = None
        self.__qml_context = None
        self.__app_window = None
        self.__main_window = None

        self.__core_apps = CoreAppListModel(self)

        qmlRegisterType(CoreApp, "DICE", 1, 0, "CoreApp")
        qmlRegisterType(BasicApp, "DICE", 1, 0, "BasicApp")

        self.executor = ThreadPoolExecutor(max_workers=2)  # TODO: set the max_workers from a configuration

        self.core_app_loaded.connect(self.__insert_core_app, Qt.QueuedConnection)
        self.__app_candidates = None
        self.__current_loading_core_app_index = 0
        self.__load_next_core_app()  # load the first core app in this thread, but the other in the executor
예제 #12
0
from multiprocessing import freeze_support

from core.project import Project

if __name__ == '__main__':
    freeze_support()
    test_proj = Project()
    test_proj.init(config_path='test_conf.ini')
    test_proj.set_log_path('logs.log')

    # test_proj.prepare_sonic_data()
    # test_proj.prepare_ammonia_data()
    test_proj.generate_turb_stats()
    # test_proj.generate_fp_grds()
    # test_proj.plot()
예제 #13
0
class frankensteinCLI(internalblue.cli.InternalBlueCLI):
    def __init__(self, main_args):
        super().__init__(main_args)

        if self.internalblue.fw.FW_NAME == "CYW20735B1":
            self.internalblue.patchRom(0x3d32e, b"\x70\x47\x70\x47")
        elif self.internalblue.fw.FW_NAME == "CYW20819A1":
            self.internalblue.patchRom(0x2330e, b"\x70\x47\x70\x47")
        self.internalblue.registerHciCallback(self.debug_hci_callback)
        self.internalblue.registerHciCallback(self.map_memory_hci_callback)
        self.internalblue.registerHciCallback(self.xmit_state_hci_callback)

    """
        Print info messages emitted from the firmware
    """

    def debug_hci_callback(self, record):
        hcipkt = record[0]
        if not issubclass(hcipkt.__class__, hci.HCI_Event):
            return

        #We use event code 0xfe for info text messages
        #Buffer messages until a newline is found
        if hcipkt.event_code == 0xfe:
            self.msg += hcipkt.data.decode("utf-8")
            while "\n" in self.msg:
                msg_split = self.msg.split("\n")
                self.logger.info("Firmware says: %s" % msg_split[0])
                self.msg = "\n".join(msg_split[1:])

        #We use event code 0xfd for data
        if hcipkt.event_code == 0xfd:
            self.logger.info("Firmware says: %s" % hexlify(hcipkt.data))

        return

    msg = ""
    """
        Loads Sections from ELF file to firmware
        Loads symbols into global dict
        Executes entry point of ELF on behalf
    """

    def load_ELF(self, fname):
        "Loads an ELF file to device and executes entry point"

        try:
            fd = open(fname, "rb")
            self.elf = elffile.ELFFile(fd)
        except:
            traceback.print_exc()
            self.logger.warn("Could not parse ELF file...")
            return False

        if "_fini" in symbols:
            fini = symbols["_fini"]
            if yesno("Found _fini of already installed patch at 0x%x. Execute?"
                     % fini):
                self.launchRam(fini - 1)

        #load sections
        for i in range(self.elf.num_sections()):
            section = self.elf.get_section(i)
            if section.header["sh_flags"] & SH_FLAGS.SHF_ALLOC != 0:
                addr = section.header["sh_addr"]
                name = section.name

                #NOBITS sections contains no data in file
                #Will be initialized with zero
                if section.header["sh_type"] == "SHT_NOBITS":
                    data = b"\x00" * section.header["sh_size"]
                else:
                    data = section.data()

                self.logger.info("Loading %s @ 0x%x - 0x%x (%d bytes)" %
                                 (name, addr, addr + len(data), len(data)))
                #write section data to device
                self.writeMem(addr, data)

        #load symbols
        n = 0
        for i in range(self.elf.num_sections()):
            section = self.elf.get_section(i)
            if section.header.sh_type == 'SHT_SYMTAB':
                for symbol in section.iter_symbols():
                    if symbol.name != "" and "$" not in symbol.name:
                        symbols[symbol.name] = symbol.entry["st_value"]
                        n += 1
        self.logger.info("Loaded %d symbols" % n)

        return self.elf.header.e_entry

    """
    Command implementation
    """
    description = "Loads an ELF file to device and executes entry point"
    loadelf_parser = argparse.ArgumentParser(description=description)
    loadelf_parser.add_argument("fname", help="ELF file to load")

    @cmd2.with_argparser(loadelf_parser)
    def do_loadelf(self, args):
        if args == None:
            return False

        if not os.path.exists(args.fname):
            self.logger.warn("Could not find file %s" % args.fname)
            return False

        entry = self.load_ELF(args.fname)

        #execute entrypoint
        if entry and entry != 0:
            if yesno("Found nonzero entry point 0x%x. Execute?" % entry):
                self.launchRam(entry - 1)

        return False

    """
    Map memory events
    """

    def map_memory_hci_callback(self, record):
        hcipkt = record[0]
        if not issubclass(hcipkt.__class__, hci.HCI_Event):
            return

        #State report
        if hcipkt.event_code == 0xfa:
            addr = struct.unpack("I", hcipkt.data[:4])[0]
            if addr == 0xffffffff:
                self.expected_addr = -1
                self.segment_start = -1

            #addr is mapped
            elif addr & 1 == 0:
                if self.expected_addr != addr:
                    if self.expected_addr != -1:
                        print("Found Map 0x%x - 0x%x" %
                              (self.segment_start, self.expected_addr))

                    self.segment_start = addr
                self.expected_addr = addr + 256
                self.last_addr = addr

            #Not mapped
            else:
                self.last_addr = addr

            if self.watchdog:
                self.watchdog.cancel()
            self.watchdog = Timer(1, self.watchdog_handle)
            self.watchdog.start()

    def watchdog_handle(self):
        self.logger.warn("Firmware died at address 0x%x while mapping memory" %
                         (self.last_addr & 0xfffffffe))

    """
    Command implementation
    """
    description = "Loads an ELF file to device and executes entry point"
    mapmemory_parser = argparse.ArgumentParser(description=description)
    mapmemory_parser.add_argument("start",
                                  help="Start address for mapping",
                                  type=internalblue.cli.auto_int)
    watchdog = None

    @cmd2.with_argparser(mapmemory_parser)
    def do_mapmemory(self, args):
        if args == None:
            return False

        patch = "projects/%s/gen/map_memory.patch" % self.internalblue.fw.FW_NAME
        if not os.path.exists(patch):
            self.logger.warn("Could not find file %s" % patch)
            return False

        entry = self.load_ELF(patch)

        start = struct.pack("I", args.start)
        self.last_addr = args.start
        self.writeMem(symbols["map_memory_start"], start)

        self.launchRam(entry - 1)

        return False

    """
    Receive state dump
    """

    def xmit_state_hci_callback(self, record):
        hcipkt = record[0]
        if not issubclass(hcipkt.__class__, hci.HCI_Event):
            return

        #State report
        if hcipkt.event_code == 0xfc:
            saved_regs, cont = struct.unpack("II", hcipkt.data[:8])
            if cont != 0:
                self.logger.info(
                    "Receiving firmware state: regs@0x%x cont@0x%x" %
                    (saved_regs, cont))
                self.segment_data = []
                self.segments = {}
                self.succsess = True
                self.saved_regs = saved_regs
                self.cont = cont

            else:
                if not self.succsess:
                    return
                self.logger.info("Received fuill firmware state")

                groupName = datetime.now().strftime(
                    "internalBlue_%m.%d.%Y_%H.%M.%S")
                self.project = Project("projects/" +
                                       self.internalblue.fw.FW_NAME)
                self.project.group_add(groupName)
                self.project.group_deactivate_all()
                self.project.group_set_active(groupName, True)
                self.project.save()
                self.project.add_symbol(groupName, "cont", self.cont | 1)
                self.project.add_symbol(groupName, "get_int",
                                        symbols["get_int"])
                self.project.add_symbol(groupName, "set_int",
                                        symbols["set_int"])
                self.project.add_symbol(groupName, "saved_regs",
                                        self.saved_regs)
                for segment_addr in self.segments:
                    self.project.add_segment(
                        groupName, "", segment_addr,
                        b"".join(self.segments[segment_addr]))

                self.project.save()

        if hcipkt.event_code == 0xfb:
            segment_addr, size, current = struct.unpack(
                "III", hcipkt.data[:12])
            self.segment_data += [hcipkt.data[12:]]

            #Check if we have missed an HCI event
            if segment_addr + len(self.segment_data) * 128 != current + 128:
                if self.succsess:
                    print(hex(segment_addr), hex(len(self.segment_data) * 128),
                          hex(current + 128))
                    self.logger.info("Failed to receive state")
                self.succsess = False

            #Fully received memory dumo
            if len(self.segment_data) * 128 == size:
                self.logger.info("Received segment 0x%x - 0x%x" %
                                 (segment_addr, segment_addr + size))
                self.segments[segment_addr] = self.segment_data
                self.segment_data = []

    """
    Command implementation
    """
    description = "Sets a hook on a function, emmits an executable state and add the dump to frankenstein"
    xmitstate_parser = argparse.ArgumentParser(description=description)
    xmitstate_parser.add_argument("target",
                                  help="Target function",
                                  type=internalblue.cli.auto_int)

    @cmd2.with_argparser(xmitstate_parser)
    def do_xmitstate(self, args):
        if not args:
            return False

        patch = "projects/%s/gen/xmit_state.patch" % self.internalblue.fw.FW_NAME
        print(patch)
        if not os.path.exists(patch):
            self.logger.warn("Could not find file %s" % patch)
            return False

        entry = self.load_ELF(patch)
        if entry == False:
            self.logger.warn("Failed to load patch ELF %s" % patch)
            return False

        target = struct.pack("I", args.target | 1)
        self.writeMem(symbols["xmit_state_target"], target)

        self.launchRam(entry - 1)

        return False
예제 #14
0
    def xmit_state_hci_callback(self, record):
        hcipkt = record[0]
        if not issubclass(hcipkt.__class__, hci.HCI_Event):
            return

        #State report
        if hcipkt.event_code == 0xfc:
            saved_regs, cont = struct.unpack("II", hcipkt.data[:8])
            if cont != 0:
                self.logger.info(
                    "Receiving firmware state: regs@0x%x cont@0x%x" %
                    (saved_regs, cont))
                self.segment_data = []
                self.segments = {}
                self.succsess = True
                self.saved_regs = saved_regs
                self.cont = cont

            else:
                if not self.succsess:
                    return
                self.logger.info("Received fuill firmware state")

                groupName = datetime.now().strftime(
                    "internalBlue_%m.%d.%Y_%H.%M.%S")
                self.project = Project("projects/" +
                                       self.internalblue.fw.FW_NAME)
                self.project.group_add(groupName)
                self.project.group_deactivate_all()
                self.project.group_set_active(groupName, True)
                self.project.save()
                self.project.add_symbol(groupName, "cont", self.cont | 1)
                self.project.add_symbol(groupName, "get_int",
                                        symbols["get_int"])
                self.project.add_symbol(groupName, "set_int",
                                        symbols["set_int"])
                self.project.add_symbol(groupName, "saved_regs",
                                        self.saved_regs)
                for segment_addr in self.segments:
                    self.project.add_segment(
                        groupName, "", segment_addr,
                        b"".join(self.segments[segment_addr]))

                self.project.save()

        if hcipkt.event_code == 0xfb:
            segment_addr, size, current = struct.unpack(
                "III", hcipkt.data[:12])
            self.segment_data += [hcipkt.data[12:]]

            #Check if we have missed an HCI event
            if segment_addr + len(self.segment_data) * 128 != current + 128:
                if self.succsess:
                    print(hex(segment_addr), hex(len(self.segment_data) * 128),
                          hex(current + 128))
                    self.logger.info("Failed to receive state")
                self.succsess = False

            #Fully received memory dumo
            if len(self.segment_data) * 128 == size:
                self.logger.info("Received segment 0x%x - 0x%x" %
                                 (segment_addr, segment_addr + size))
                self.segments[segment_addr] = self.segment_data
                self.segment_data = []
예제 #15
0
class MainWindow(QMainWindow):
    """Main Class"""

    #Define a QT signal that is emitted when the configuration changes.
    #Connect to this signal if you need to know when the configuration has changed.
    configuration_changed = QtCore.pyqtSignal()

    def __init__(self, app):
        """
        Initialization of the Main window. This is directly called after the
        Logger has been initialized. The Function loads the GUI, creates the
        used Classes and connects the actions to the GUI.
        """
        QMainWindow.__init__(self)

        #Build the configuration window
        self.config_window = ConfigWindow(g.config.makeConfigWindgets(), g.config.var_dict, g.config.var_dict.configspec, self)
        self.config_window.finished.connect(self.updateConfiguration)

        self.app = app

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        self.canvas = self.ui.canvas
        if g.config.mode3d:
            self.canvas_scene = self.canvas
        else:
            self.canvas_scene = None

        self.TreeHandler = TreeHandler(self.ui)
        self.configuration_changed.connect(self.TreeHandler.updateConfiguration)

        self.MyPostProcessor = MyPostProcessor()
        self.d2g = Project(self)

        self.createActions()
        self.connectToolbarToConfig()

        self.filename = ""

        self.valuesDXF = None
        self.shapes = Shapes([])
        self.entityRoot = None
        self.layerContents = Layers([])
        self.newNumber = 1

        self.cont_dx = 0.0
        self.cont_dy = 0.0
        self.cont_rotate = 0.0
        self.cont_scale = 1.0

        # self.readSettings()

    def tr(self, string_to_translate):
        """
        Translate a string using the QCoreApplication translation framework
        @param: string_to_translate: a unicode string
        @return: the translated unicode string if it was possible to translate
        """
        return text_type(QtCore.QCoreApplication.translate('MainWindow',
                                                           string_to_translate))

    def createActions(self):
        """
        Create the actions of the main toolbar.
        @purpose: Links the callbacks to the actions in the menu
        """

        # File
        self.ui.actionOpen.triggered.connect(self.open)
        self.ui.actionReload.triggered.connect(self.reload)
        self.ui.actionSaveProjectAs.triggered.connect(self.saveProject)
        self.ui.actionClose.triggered.connect(self.close)

        # Export
        self.ui.actionOptimizePaths.triggered.connect(self.optimizeTSP)
        self.ui.actionExportShapes.triggered.connect(self.exportShapes)
        self.ui.actionOptimizeAndExportShapes.triggered.connect(self.optimizeAndExportShapes)

        # View
        self.ui.actionShowPathDirections.triggered.connect(self.setShowPathDirections)
        self.ui.actionShowDisabledPaths.toggled.connect(self.setShowDisabledPaths) #We need toggled (and not triggered), otherwise the signal is not emitted when state is changed programmatically
        self.ui.actionLiveUpdateExportRoute.toggled.connect(self.liveUpdateExportRoute)
        self.ui.actionDeleteG0Paths.triggered.connect(self.deleteG0Paths)
        self.ui.actionAutoscale.triggered.connect(self.canvas.autoscale)
        if g.config.mode3d:
            self.ui.actionTopView.triggered.connect(self.canvas.topView)
            self.ui.actionIsometricView.triggered.connect(self.canvas.isometricView)

        # Options
        self.ui.actionConfiguration.triggered.connect(self.config_window.show)
        self.ui.actionTolerances.triggered.connect(self.setTolerances)
        self.ui.actionRotateAll.triggered.connect(self.rotateAll)
        self.ui.actionScaleAll.triggered.connect(self.scaleAll)
        self.ui.actionMoveWorkpieceZero.triggered.connect(self.moveWorkpieceZero)
        self.ui.actionSplitLineSegments.toggled.connect(self.d2g.small_reload)
        self.ui.actionAutomaticCutterCompensation.toggled.connect(self.d2g.small_reload)
        self.ui.actionMilling.triggered.connect(self.setMachineTypeToMilling)
        self.ui.actionDragKnife.triggered.connect(self.setMachineTypeToDragKnife)
        self.ui.actionLathe.triggered.connect(self.setMachineTypeToLathe)

        # Help
        self.ui.actionAbout.triggered.connect(self.about)

    def connectToolbarToConfig(self, project=False):
        # View
        if not project:
            self.ui.actionShowDisabledPaths.blockSignals(True) #Don't emit any signal when changing state of the menu entries
            self.ui.actionShowDisabledPaths.setChecked(g.config.vars.General['show_disabled_paths'])
            self.ui.actionShowDisabledPaths.blockSignals(False)
            self.ui.actionLiveUpdateExportRoute.blockSignals(True)
            self.ui.actionLiveUpdateExportRoute.setChecked(g.config.vars.General['live_update_export_route'])
            self.ui.actionLiveUpdateExportRoute.blockSignals(False)

        # Options
        self.ui.actionSplitLineSegments.blockSignals(True)
        self.ui.actionSplitLineSegments.setChecked(g.config.vars.General['split_line_segments'])
        self.ui.actionSplitLineSegments.blockSignals(False)
        self.ui.actionAutomaticCutterCompensation.blockSignals(True)
        self.ui.actionAutomaticCutterCompensation.setChecked(g.config.vars.General['automatic_cutter_compensation'])
        self.ui.actionAutomaticCutterCompensation.blockSignals(False)
        self.updateMachineType()

    def keyPressEvent(self, event):
        """
        Rewritten KeyPressEvent to get other behavior while Shift is pressed.
        @purpose: Changes to ScrollHandDrag while Control pressed
        @param event:    Event Parameters passed to function
        """
        if event.isAutoRepeat():
            return
        if event.key() == QtCore.Qt.Key_Control:
            self.canvas.isMultiSelect = True
        elif event.key() == QtCore.Qt.Key_Shift:
            if g.config.mode3d:
                self.canvas.isPanning = True
                self.canvas.setCursor(QtCore.Qt.OpenHandCursor)
            else:
                self.canvas.setDragMode(QGraphicsView.ScrollHandDrag)
        elif event.key() == QtCore.Qt.Key_Alt:
            if g.config.mode3d:
                self.canvas.isRotating = True
                self.canvas.setCursor(QtCore.Qt.PointingHandCursor)

    def keyReleaseEvent(self, event):
        """
        Rewritten KeyReleaseEvent to get other behavior while Shift is pressed.
        @purpose: Changes to RubberBandDrag while Control released
        @param event:    Event Parameters passed to function
        """
        if event.key() == QtCore.Qt.Key_Control:
            self.canvas.isMultiSelect = False
        elif event.key() == QtCore.Qt.Key_Shift:
            if g.config.mode3d:
                self.canvas.isPanning = False
                self.canvas.unsetCursor()
            else:
                self.canvas.setDragMode(QGraphicsView.NoDrag)
        elif event.key() == QtCore.Qt.Key_Alt:
            if g.config.mode3d:
                self.canvas.isRotating = False
                if -5 < self.canvas.rotX < 5 and\
                   -5 < self.canvas.rotY < 5 and\
                   -5 < self.canvas.rotZ < 5:
                    self.canvas.rotX = 0
                    self.canvas.rotY = 0
                    self.canvas.rotZ = 0
                    self.canvas.update()
                self.canvas.unsetCursor()

    def enableToolbarButtons(self, status=True):
        # File
        self.ui.actionReload.setEnabled(status)
        self.ui.actionSaveProjectAs.setEnabled(status)

        # Export
        self.ui.actionOptimizePaths.setEnabled(status)
        self.ui.actionExportShapes.setEnabled(status)
        self.ui.actionOptimizeAndExportShapes.setEnabled(status)

        # View
        self.ui.actionShowPathDirections.setEnabled(status)
        self.ui.actionShowDisabledPaths.setEnabled(status)
        self.ui.actionLiveUpdateExportRoute.setEnabled(status)
        self.ui.actionAutoscale.setEnabled(status)
        if g.config.mode3d:
            self.ui.actionTopView.setEnabled(status)
            self.ui.actionIsometricView.setEnabled(status)

        # Options
        self.ui.actionTolerances.setEnabled(status)
        self.ui.actionRotateAll.setEnabled(status)
        self.ui.actionScaleAll.setEnabled(status)
        self.ui.actionMoveWorkpieceZero.setEnabled(status)

    def deleteG0Paths(self):
        """
        Deletes the optimisation paths from the scene.
        """
        self.setCursor(QtCore.Qt.WaitCursor)
        self.app.processEvents()

        self.canvas_scene.delete_opt_paths()
        self.ui.actionDeleteG0Paths.setEnabled(False)
        self.canvas_scene.update()

        self.unsetCursor()

    def exportShapes(self, status=False, saveas=None):
        """
        This function is called by the menu "Export/Export Shapes". It may open
        a Save Dialog if used without LinuxCNC integration. Otherwise it's
        possible to select multiple postprocessor files, which are located
        in the folder.
        """
        self.setCursor(QtCore.Qt.WaitCursor)
        self.app.processEvents()

        logger.debug(self.tr('Export the enabled shapes'))

        # Get the export order from the QTreeView
        self.TreeHandler.updateExportOrder()
        self.updateExportRoute()

        logger.debug(self.tr("Sorted layers:"))
        for i, layer in enumerate(self.layerContents.non_break_layer_iter()):
            logger.debug("LayerContents[%i] = %s" % (i, layer))

        if not g.config.vars.General['write_to_stdout']:

            # Get the name of the File to export
            if not saveas:
                MyFormats = ""
                for i in range(len(self.MyPostProcessor.output_format)):
                    name = "%s " % (self.MyPostProcessor.output_text[i])
                    format_ = "(*%s);;" % (self.MyPostProcessor.output_format[i])
                    MyFormats = MyFormats + name + format_
                filename = self.showSaveDialog(self.tr('Export to file'), MyFormats)
                save_filename = file_str(filename[0])
            else:
                filename = [None, None]
                save_filename = saveas

            # If Cancel was pressed
            if not save_filename:
                self.unsetCursor()
                return

            (beg, ende) = os.path.split(save_filename)
            (fileBaseName, fileExtension) = os.path.splitext(ende)

            pp_file_nr = 0
            for i in range(len(self.MyPostProcessor.output_format)):
                name = "%s " % (self.MyPostProcessor.output_text[i])
                format_ = "(*%s)" % (self.MyPostProcessor.output_format[i])
                MyFormats = name + format_
                if filename[1] == MyFormats:
                    pp_file_nr = i
            if fileExtension != self.MyPostProcessor.output_format[pp_file_nr]:
                if not QtCore.QFile.exists(save_filename):
                    save_filename += self.MyPostProcessor.output_format[pp_file_nr]

            self.MyPostProcessor.getPostProVars(pp_file_nr)
        else:
            save_filename = ""
            self.MyPostProcessor.getPostProVars(0)

        """
        Export will be performed according to LayerContents and their order
        is given in this variable too.
        """

        self.MyPostProcessor.exportShapes(self.filename,
                                          save_filename,
                                          self.layerContents)

        self.unsetCursor()

        if g.config.vars.General['write_to_stdout']:
            self.close()

    def optimizeAndExportShapes(self):
        """
        Optimize the tool path, then export the shapes
        """
        self.optimizeTSP()
        self.exportShapes()

    def updateExportRoute(self):
        """
        Update the drawing of the export route
        """
        self.canvas_scene.delete_opt_paths()

        self.canvas_scene.addexproutest()
        for LayerContent in self.layerContents.non_break_layer_iter():
            if len(LayerContent.exp_order) > 0:
                self.canvas_scene.addexproute(LayerContent.exp_order, LayerContent.nr)
        if len(self.canvas_scene.routearrows) > 0:
            self.ui.actionDeleteG0Paths.setEnabled(True)
            self.canvas_scene.addexprouteen()
        self.canvas_scene.update()

    def optimizeTSP(self):
        """
        Method is called to optimize the order of the shapes. This is performed
        by solving the TSP Problem.
        """
        self.setCursor(QtCore.Qt.WaitCursor)
        self.app.processEvents()

        logger.debug(self.tr('Optimize order of enabled shapes per layer'))
        self.canvas_scene.delete_opt_paths()

        # Get the export order from the QTreeView
        logger.debug(self.tr('Updating order according to TreeView'))
        self.TreeHandler.updateExportOrder()
        self.canvas_scene.addexproutest()

        for LayerContent in self.layerContents.non_break_layer_iter():
            # Initial values for the Lists to export.
            shapes_to_write = []
            shapes_fixed_order = []
            shapes_st_en_points = []

            # Check all shapes of Layer which shall be exported and create List for it.
            logger.debug(self.tr("Nr. of Shapes %s; Nr. of Shapes in Route %s")
                         % (len(LayerContent.shapes), len(LayerContent.exp_order)))
            logger.debug(self.tr("Export Order for start: %s") % LayerContent.exp_order)

            for shape_nr in range(len(LayerContent.exp_order)):
                if not self.shapes[LayerContent.exp_order[shape_nr]].send_to_TSP:
                    shapes_fixed_order.append(shape_nr)

                shapes_to_write.append(shape_nr)
                shapes_st_en_points.append(self.shapes[LayerContent.exp_order[shape_nr]].get_start_end_points())

            # Perform Export only if the Number of shapes to export is bigger than 0
            if len(shapes_to_write) > 0:
                # Errechnen der Iterationen
                # Calculate the iterations
                iter_ = min(g.config.vars.Route_Optimisation['max_iterations'], len(shapes_to_write)*50)

                # Adding the Start and End Points to the List.
                x_st = g.config.vars.Plane_Coordinates['axis1_start_end']
                y_st = g.config.vars.Plane_Coordinates['axis2_start_end']
                start = Point(x_st, y_st)
                ende = Point(x_st, y_st)
                shapes_st_en_points.append([start, ende])

                TSPs = TspOptimization(shapes_st_en_points, shapes_fixed_order)
                logger.info(self.tr("TSP start values initialised for Layer %s") % LayerContent.name)
                logger.debug(self.tr("Shapes to write: %s") % shapes_to_write)
                logger.debug(self.tr("Fixed order: %s") % shapes_fixed_order)

                for it_nr in range(iter_):
                    # Only show each 50th step.
                    if it_nr % 50 == 0:
                        TSPs.calc_next_iteration()
                        new_exp_order = [LayerContent.exp_order[nr] for nr in TSPs.opt_route[1:]]

                logger.debug(self.tr("TSP done with result: %s") % TSPs)

                LayerContent.exp_order = new_exp_order

                self.canvas_scene.addexproute(LayerContent.exp_order, LayerContent.nr)
                logger.debug(self.tr("New Export Order after TSP: %s") % new_exp_order)
                self.app.processEvents()
            else:
                LayerContent.exp_order = []

        if len(self.canvas_scene.routearrows) > 0:
            self.ui.actionDeleteG0Paths.setEnabled(True)
            self.canvas_scene.addexprouteen()

        # Update order in the treeView, according to path calculation done by the TSP
        self.TreeHandler.updateTreeViewOrder()
        self.canvas_scene.update()

        self.unsetCursor()

    def automaticCutterCompensation(self):
        if self.ui.actionAutomaticCutterCompensation.isEnabled() and\
           self.ui.actionAutomaticCutterCompensation.isChecked():
            for layerContent in self.layerContents.non_break_layer_iter():
                if layerContent.automaticCutterCompensationEnabled():
                    new_exp_order = []
                    outside_compensation = True
                    shapes_left = layerContent.shapes
                    while len(shapes_left) > 0:
                        shapes_left = [shape for shape in shapes_left
                                       if not self.ifNotContainedChangeCutCor(shape, shapes_left, outside_compensation, new_exp_order)]
                        outside_compensation = not outside_compensation
                    layerContent.exp_order = list(reversed(new_exp_order))
        self.TreeHandler.updateTreeViewOrder()
        self.canvas_scene.update()

    def ifNotContainedChangeCutCor(self, shape, shapes_left, outside_compensation, new_exp_order):
        if not isinstance(shape, CustomGCode):
            for outerShape in shapes_left:
                if self.isShapeContained(shape, outerShape):
                    return False
            if outside_compensation == shape.cw:
                shape.cut_cor = 41
            else:
                shape.cut_cor = 42
            self.canvas_scene.repaint_shape(shape)
        new_exp_order.append(shape.nr)
        return True

    def isShapeContained(self, shape, outerShape):
        return shape != outerShape and not \
            isinstance(outerShape, CustomGCode) and\
            shape.BB.iscontained(outerShape.BB)

    def showSaveDialog(self, title, MyFormats):
        """
        This function is called by the menu "Export/Export Shapes" of the main toolbar.
        It creates the selection dialog for the exporter
        @return: Returns the filename of the selected file.
        """

        (beg, ende) = os.path.split(self.filename)
        (fileBaseName, fileExtension) = os.path.splitext(ende)

        default_name = os.path.join(g.config.vars.Paths['output_dir'], fileBaseName)

        selected_filter = self.MyPostProcessor.output_format[0]
        filename = getSaveFileName(self,
                                   title, default_name,
                                   MyFormats, selected_filter)

        logger.info(self.tr("File: %s selected") % filename[0])
        logger.info("<a href='%s'>%s</a>" %(filename[0],filename[0]))
        return filename

    def about(self):
        """
        This function is called by the menu "Help/About" of the main toolbar and
        creates the About Window
        """

        message = self.tr("<html>"
                "<h2><center>You are using</center></h2>"
                "<body bgcolor="\
                "<center><img src=':images/dxf2gcode_logo.png' border='1' color='white'></center></body>"
                "<h2>Version:</h2>"
                "<body>%s: %s<br>"
                "Last change: %s<br>"
                "Changed by: %s<br></body>"
                "<h2>Where to get help:</h2>"
                "For more information and updates, "
                "please visit "
                "<a href='http://sourceforge.net/projects/dxf2gcode/'>http://sourceforge.net/projects/dxf2gcode/</a><br>"
                "For any questions on how to use dxf2gcode please use the "
                "<a href='https://groups.google.com/forum/?fromgroups#!forum/dxf2gcode-users'>mailing list</a><br>"
                "To log bugs, or request features please use the "
                "<a href='http://sourceforge.net/projects/dxf2gcode/tickets/'>issue tracking system</a><br>"
                "<h2>License and copyright:</h2>"
                "<body>This program is written in Python and is published under the "
                "<a href='http://www.gnu.org/licenses/'>GNU GPLv3 license.</a><br>"
                "</body></html>") % (c.VERSION, c.REVISION, c.DATE, c.AUTHOR)

        AboutDialog(title=self.tr("About DXF2GCODE"), message=message)

    def setShowPathDirections(self):
        """
        This function is called by the menu "Show all path directions" of the
        main and forwards the call to Canvas.setShow_path_direction()
        """
        flag = self.ui.actionShowPathDirections.isChecked()
        self.canvas.setShowPathDirections(flag)
        self.canvas_scene.update()

    def setShowDisabledPaths(self):
        """
        This function is called by the menu "Show disabled paths" of the
        main and forwards the call to Canvas.setShow_disabled_paths()
        """
        flag = self.ui.actionShowDisabledPaths.isChecked()
        self.canvas_scene.setShowDisabledPaths(flag)
        self.canvas_scene.update()

    def liveUpdateExportRoute(self):
        """
        This function is called by the menu "Live update tool path" of the
        main and forwards the call to TreeHandler.setUpdateExportRoute()
        """
        flag = self.ui.actionLiveUpdateExportRoute.isChecked()
        self.TreeHandler.setLiveUpdateExportRoute(flag)

    def setTolerances(self):
        title = self.tr('Contour tolerances')
        units = "in" if g.config.metric == 0 else "mm"
        label = [self.tr("Tolerance for common points [%s]:") % units,
                 self.tr("Tolerance for curve fitting [%s]:") % units]
        value = [g.config.point_tolerance,
                 g.config.fitting_tolerance]

        logger.debug(self.tr("set Tolerances"))
        SetTolDialog = PopUpDialog(title, label, value)

        if SetTolDialog.result is None:
            return

        g.config.point_tolerance = float(SetTolDialog.result[0])
        g.config.fitting_tolerance = float(SetTolDialog.result[1])

        self.d2g.reload()  # set tolerances requires a complete reload

    def scaleAll(self):
        title = self.tr('Scale Contour')
        label = [self.tr("Scale Contour by factor:")]
        value = [self.cont_scale]
        ScaEntDialog = PopUpDialog(title, label, value)

        if ScaEntDialog.result is None:
            return

        self.cont_scale = float(ScaEntDialog.result[0])
        self.entityRoot.sca = self.cont_scale

        self.d2g.small_reload()

    def rotateAll(self):
        title = self.tr('Rotate Contour')
        label = [self.tr("Rotate Contour by deg:")]  # TODO should we support radians for drawing unit non metric?
        value = [degrees(self.cont_rotate)]
        RotEntDialog = PopUpDialog(title, label, value)

        if RotEntDialog.result is None:
            return

        self.cont_rotate = radians(float(RotEntDialog.result[0]))
        self.entityRoot.rot = self.cont_rotate

        self.d2g.small_reload()

    def moveWorkpieceZero(self):
        """
        This function is called when the Option=>Move WP Zero Menu is clicked.
        """
        title = self.tr('Workpiece zero offset')
        units = "[in]" if g.config.metric == 0 else "[mm]"
        label = [self.tr("Offset %s axis %s:") % (g.config.vars.Axis_letters['ax1_letter'], units),
                 self.tr("Offset %s axis %s:") % (g.config.vars.Axis_letters['ax2_letter'], units)]
        value = [self.cont_dx, self.cont_dy]
        MoveWpzDialog = PopUpDialog(title, label, value, True)

        if MoveWpzDialog.result is None:
            return

        if MoveWpzDialog.result == 'Auto':
            minx = sys.float_info.max
            miny = sys.float_info.max
            for shape in self.shapes:
                if not shape.isDisabled():
                    minx = min(minx, shape.BB.Ps.x)
                    miny = min(miny, shape.BB.Ps.y)
            self.cont_dx = self.entityRoot.p0.x - minx
            self.cont_dy = self.entityRoot.p0.y - miny
        else:
            self.cont_dx = float(MoveWpzDialog.result[0])
            self.cont_dy = float(MoveWpzDialog.result[1])

        self.entityRoot.p0.x = self.cont_dx
        self.entityRoot.p0.y = self.cont_dy

        self.d2g.small_reload()

    def setMachineTypeToMilling(self):
        g.config.machine_type = 'milling'
        self.updateMachineType()
        self.d2g.small_reload()

    def setMachineTypeToDragKnife(self):
        g.config.machine_type = 'drag_knife'
        self.updateMachineType()
        self.d2g.small_reload()

    def setMachineTypeToLathe(self):
        g.config.machine_type = 'lathe'
        self.updateMachineType()
        self.d2g.small_reload()

    def updateMachineType(self):
        if g.config.machine_type == 'milling':
            self.ui.actionAutomaticCutterCompensation.setEnabled(True)
            self.ui.actionMilling.setChecked(True)
            self.ui.actionDragKnife.setChecked(False)
            self.ui.actionLathe.setChecked(False)
            self.ui.label_9.setText(self.tr("Z Infeed depth"))
        elif g.config.machine_type == 'lathe':
            self.ui.actionAutomaticCutterCompensation.setEnabled(False)
            self.ui.actionMilling.setChecked(False)
            self.ui.actionDragKnife.setChecked(False)
            self.ui.actionLathe.setChecked(True)
            self.ui.label_9.setText(self.tr("No Z-Axis for lathe"))
        elif g.config.machine_type == "drag_knife":
            self.ui.actionAutomaticCutterCompensation.setEnabled(False)
            self.ui.actionMilling.setChecked(False)
            self.ui.actionDragKnife.setChecked(True)
            self.ui.actionLathe.setChecked(False)
            self.ui.label_9.setText(self.tr("Z Drag depth"))

    def open(self):
        """
        This function is called by the menu "File/Load File" of the main toolbar.
        It creates the file selection dialog and calls the load function to
        load the selected file.
        """

        self.OpenFileDialog(self.tr("Open file"))

        # If there is something to load then call the load function callback
        if self.filename:
            self.cont_dx = 0.0
            self.cont_dy = 0.0
            self.cont_rotate = 0.0
            self.cont_scale = 1.0

            self.load()

    def OpenFileDialog(self, title):
        self.filename, _ = getOpenFileName(self,
                                           title,
                                           g.config.vars.Paths['import_dir'],
                                           self.tr("All supported files (*.dxf *.ps *.pdf *%s);;"
                                                   "DXF files (*.dxf);;"
                                                   "PS files (*.ps);;"
                                                   "PDF files (*.pdf);;"
                                                   "Project files (*%s);;"
                                                   "All types (*.*)") % (c.PROJECT_EXTENSION, c.PROJECT_EXTENSION))

        # If there is something to load then call the load function callback
        if self.filename:
            self.filename = file_str(self.filename)
            logger.info(self.tr("File: %s selected") % self.filename)

    def load(self, plot=True):
        """
        Loads the file given by self.filename.  Also calls the command to
        make the plot.
        @param plot: if it should plot
        """
        if not QtCore.QFile.exists(self.filename):
            logger.info(self.tr("Cannot locate file: %s") % self.filename)
            self.OpenFileDialog(self.tr("Manually open file: %s") % self.filename)
            if not self.filename:
                return False  # cancelled

        self.setCursor(QtCore.Qt.WaitCursor)
        self.setWindowTitle("DXF2GCODE - [%s]" % self.filename)
        self.canvas.resetAll()
        self.app.processEvents()

        (name, ext) = os.path.splitext(self.filename)

        if ext.lower() == c.PROJECT_EXTENSION:
            self.loadProject(self.filename)
            return True  # kill this load operation - we opened a new one

        if ext.lower() == ".ps" or ext.lower() == ".pdf":
            logger.info(self.tr("Sending Postscript/PDF to pstoedit"))

            # Create temporary file which will be read by the program
            self.filename = os.path.join(tempfile.gettempdir(), 'dxf2gcode_temp.dxf')

            pstoedit_cmd = g.config.vars.Filters['pstoedit_cmd']
            pstoedit_opt = g.config.vars.Filters['pstoedit_opt']
            ps_filename = os.path.normcase(self.filename)
            cmd = [('%s' % pstoedit_cmd)] + pstoedit_opt + [('%s' % ps_filename), ('%s' % self.filename)]
            logger.debug(cmd)
            try:
                subprocess.call(cmd)
            except FileNotFoundError as e:
                logger.error(e.strerror)
                self.unsetCursor()
                QMessageBox.critical(self,
                                     "ERROR",
                                     self.tr("Please make sure you have installed pstoedit, and configured it in the config file."))
                return True
            subprocess.check_output()  # If the return code was non-zero it raises a subprocess.CalledProcessError.

        logger.info(self.tr('Loading file: %s') % self.filename)

        self.valuesDXF = ReadDXF(self.filename)

        # Output the information in the text window
        logger.info(self.tr('Loaded layers: %s') % len(self.valuesDXF.layers))
        logger.info(self.tr('Loaded blocks: %s') % len(self.valuesDXF.blocks.Entities))
        for i in range(len(self.valuesDXF.blocks.Entities)):
            layers = self.valuesDXF.blocks.Entities[i].get_used_layers()
            logger.info(self.tr('Block %i includes %i Geometries, reduced to %i Contours, used layers: %s')
                        % (i, len(self.valuesDXF.blocks.Entities[i].geo), len(self.valuesDXF.blocks.Entities[i].cont), layers))
        layers = self.valuesDXF.entities.get_used_layers()
        insert_nr = self.valuesDXF.entities.get_insert_nr()
        logger.info(self.tr('Loaded %i entity geometries; reduced to %i contours; used layers: %s; number of inserts %i')
                    % (len(self.valuesDXF.entities.geo), len(self.valuesDXF.entities.cont), layers, insert_nr))

        if g.config.metric == 0:
            logger.info(self.tr("Drawing units: inches"))
            distance = self.tr("[in]")
            speed = self.tr("[IPM]")
        else:
            logger.info(self.tr("Drawing units: millimeters"))
            distance = self.tr("[mm]")
            speed = self.tr("[mm/min]")
        self.ui.unitLabel_3.setText(distance)
        self.ui.unitLabel_4.setText(distance)
        self.ui.unitLabel_5.setText(distance)
        self.ui.unitLabel_6.setText(distance)
        self.ui.unitLabel_7.setText(distance)
        self.ui.unitLabel_8.setText(speed)
        self.ui.unitLabel_9.setText(speed)

        self.makeShapes()
        if plot:
            self.plot()
        return True

    def plot(self):
        # Populate the treeViews
        self.TreeHandler.buildEntitiesTree(self.entityRoot)
        self.TreeHandler.buildLayerTree(self.layerContents)

        # Paint the canvas
        if not g.config.mode3d:
            self.canvas_scene = MyGraphicsScene()
            self.canvas.setScene(self.canvas_scene)

        self.canvas_scene.plotAll(self.shapes)
        self.setShowPathDirections()
        self.setShowDisabledPaths()
        self.liveUpdateExportRoute()

        if not g.config.mode3d:
            self.canvas.show()
            self.canvas.setFocus()
        self.canvas.autoscale()

        # After all is plotted enable the Menu entities
        self.enableToolbarButtons()

        self.automaticCutterCompensation()

        self.unsetCursor()

    def reload(self):
        """
        This function is called by the menu "File/Reload File" of the main toolbar.
        It reloads the previously loaded file (if any)
        """
        if self.filename:
            logger.info(self.tr("Reloading file: %s") % self.filename)
            self.load()

    def makeShapes(self):
        self.entityRoot = EntityContent(nr=0, name='Entities', parent=None,
                                        p0=Point(self.cont_dx, self.cont_dy), pb=Point(),
                                        sca=[self.cont_scale, self.cont_scale, self.cont_scale], rot=self.cont_rotate)
        self.layerContents = Layers([])
        self.shapes = Shapes([])

        self.makeEntityShapes(self.entityRoot)

        for layerContent in self.layerContents:
            layerContent.overrideDefaults()
        self.layerContents.sort(key=lambda x: x.nr)
        self.newNumber = len(self.shapes)

    def makeEntityShapes(self, parent, layerNr=-1):
        """
        Instance is called prior to plotting the shapes. It creates
        all shape classes which are plotted into the canvas.

        @param parent: The parent of a shape is always an Entity. It may be the root
        or, if it is a Block, this is the Block.
        """
        if parent.name == "Entities":
            entities = self.valuesDXF.entities
        else:
            ent_nr = self.valuesDXF.Get_Block_Nr(parent.name)
            entities = self.valuesDXF.blocks.Entities[ent_nr]

        # Assigning the geometries in the variables geos & contours in cont
        ent_geos = entities.geo

        # Loop for the number of contours
        for cont in entities.cont:
            # Query if it is in the contour of an insert or of a block
            if ent_geos[cont.order[0][0]].Typ == "Insert":
                ent_geo = ent_geos[cont.order[0][0]]

                # Assign the base point for the block
                new_ent_nr = self.valuesDXF.Get_Block_Nr(ent_geo.BlockName)
                new_entities = self.valuesDXF.blocks.Entities[new_ent_nr]
                pb = new_entities.basep

                # Scaling, etc. assign the block
                p0 = ent_geos[cont.order[0][0]].Point
                sca = ent_geos[cont.order[0][0]].Scale
                rot = ent_geos[cont.order[0][0]].rot

                # Creating the new Entitie Contents for the insert
                newEntityContent = EntityContent(nr=0,
                                                 name=ent_geo.BlockName,
                                                 parent=parent,
                                                 p0=p0,
                                                 pb=pb,
                                                 sca=sca,
                                                 rot=rot)

                parent.append(newEntityContent)

                self.makeEntityShapes(newEntityContent, ent_geo.Layer_Nr)

            else:
                # Loop for the number of geometries
                tmp_shape = Shape(len(self.shapes),
                                  (True if cont.closed else False),
                                  parent)

                for ent_geo_nr in range(len(cont.order)):
                    ent_geo = ent_geos[cont.order[ent_geo_nr][0]]
                    if cont.order[ent_geo_nr][1]:
                        ent_geo.geo.reverse()
                        for geo in ent_geo.geo:
                            geo = copy(geo)
                            geo.reverse()
                            self.append_geo_to_shape(tmp_shape, geo)
                        ent_geo.geo.reverse()
                    else:
                        for geo in ent_geo.geo:
                            self.append_geo_to_shape(tmp_shape, copy(geo))

                if len(tmp_shape.geos) > 0:
                    # All shapes have to be CW direction.
                    tmp_shape.AnalyseAndOptimize()

                    self.shapes.append(tmp_shape)
                    if g.config.vars.Import_Parameters['insert_at_block_layer'] and layerNr != -1:
                        self.addtoLayerContents(tmp_shape, layerNr)
                    else:
                        self.addtoLayerContents(tmp_shape, ent_geo.Layer_Nr)
                    parent.append(tmp_shape)

                    if not g.config.mode3d:
                        # Connect the shapeSelectionChanged and enableDisableShape signals to our treeView,
                        #  so that selections of the shapes are reflected on the treeView
                        tmp_shape.setSelectionChangedCallback(self.TreeHandler.updateShapeSelection)
                        tmp_shape.setEnableDisableCallback(self.TreeHandler.updateShapeEnabling)

    def append_geo_to_shape(self, shape, geo):
        if -1e-5 <= geo.length < 1e-5:  # TODO adjust import for this
            return

        if self.ui.actionSplitLineSegments.isChecked():
            if isinstance(geo, LineGeo):
                diff = (geo.Pe - geo.Ps) / 2.0
                geo_b = deepcopy(geo)
                geo_a = deepcopy(geo)
                geo_b.Pe -= diff
                geo_a.Ps += diff
                shape.append(geo_b)
                shape.append(geo_a)
            else:
                shape.append(geo)
        else:
            shape.append(geo)

        if isinstance(geo, HoleGeo):
            shape.type = 'Hole'
            shape.closed = True  # TODO adjust import for holes?
            if g.config.machine_type == 'drag_knife':
                shape.disabled = True
                shape.allowedToChange = False

    def addtoLayerContents(self, shape, lay_nr):
        # Check if the layer already exists and add shape if it is.
        for LayCon in self.layerContents:
            if LayCon.nr == lay_nr:
                LayCon.shapes.append(shape)
                shape.parentLayer = LayCon
                return

        # If the Layer does not exist create a new one.
        LayerName = self.valuesDXF.layers[lay_nr].name
        self.layerContents.append(LayerContent(lay_nr, LayerName, [shape]))
        shape.parentLayer = self.layerContents[-1]

    def updateConfiguration(self, result):
        """
        Some modification occured in the configuration window, we need to save these changes into the config file.
        Once done, the signal configuration_changed is emitted, so that anyone interested in this information can connect to this signal.
        """
        if result == ConfigWindow.Applied or result == ConfigWindow.Accepted:
            g.config._save_varspace() #Write the configuration into the config file (config.cfg)
            g.config.update_config() #Rebuild the readonly configuration structure

            # Assign changes to the menus (if no change occured, nothing happens / otherwise QT emits a signal for the menu entry that has changed)
            self.ui.actionShowDisabledPaths.setChecked(g.config.vars.General['show_disabled_paths'])
            self.ui.actionLiveUpdateExportRoute.setChecked(g.config.vars.General['live_update_export_route'])
            self.ui.actionSplitLineSegments.setChecked(g.config.vars.General['split_line_segments'])
            self.ui.actionAutomaticCutterCompensation.setChecked(g.config.vars.General['automatic_cutter_compensation'])

            # Inform about the changes into the configuration
            self.configuration_changed.emit()

    def loadProject(self, filename):
        """
        Load all variables from file
        """
        # since Py3 has no longer execfile -  we need to open it manually
        file_ = open(filename, 'r')
        str_ = file_.read()
        file_.close()
        self.d2g.load(str_)

    def saveProject(self):
        """
        Save all variables to file
        """
        prj_filename = self.showSaveDialog(self.tr('Save project to file'), "Project files (*%s)" % c.PROJECT_EXTENSION)
        save_prj_filename = file_str(prj_filename[0])

        # If Cancel was pressed
        if not save_prj_filename:
            return

        (beg, ende) = os.path.split(save_prj_filename)
        (fileBaseName, fileExtension) = os.path.splitext(ende)

        if fileExtension != c.PROJECT_EXTENSION:
            if not QtCore.QFile.exists(save_prj_filename):
                save_prj_filename += c.PROJECT_EXTENSION

        pyCode = self.d2g.export()
        try:
            # File open and write
            f = open(save_prj_filename, "w")
            f.write(str_encode(pyCode))
            f.close()
            logger.info(self.tr("Save project to FILE was successful"))
        except IOError:
            QMessageBox.warning(g.window,
                                self.tr("Warning during Save Project As"),
                                self.tr("Cannot Save the File"))

    def closeEvent(self, e):
        logger.debug(self.tr("Closing"))
        # self.writeSettings()
        e.accept()

    def readSettings(self):
        settings = QtCore.QSettings("dxf2gcode", "dxf2gcode")
        settings.beginGroup("MainWindow")
        self.resize(settings.value("size", QtCore.QSize(800, 600)).toSize())
        self.move(settings.value("pos", QtCore.QPoint(200, 200)).toPoint())
        settings.endGroup()

    def writeSettings(self):
        settings = QtCore.QSettings("dxf2gcode", "dxf2gcode")
        settings.beginGroup("MainWindow")
        settings.setValue("size", self.size())
        settings.setValue("pos", self.pos())
        settings.endGroup()
예제 #16
0
 def test_serialization(self):
     project = Project()
     json = project.serialize()
     project2 = Project.deserialize(json)
     self.assertEqual(project, project2)
예제 #17
0
class Dice(QObject):
    def __init__(self, parent=None):
        super(Dice, self).__init__(parent)

        self.application_dir = QCoreApplication.applicationDirPath()

        self.__project = Project(
            self
        )  # used as an empty default project, replaced by load_project()
        self.__desk = None
        self.__settings = None
        self.__home = None
        qmlRegisterType(Project, "DICE", 1, 0, "Project")

        self.__theme = Theme(self)
        self.__memory = MemoryInfo(self)
        self.__error = ErrorHandler(self)
        qmlRegisterType(MemoryInfo, "DICE", 1, 0, "MemoryInfo")
        qmlRegisterType(ErrorHandler, "DICE", 1, 0, "ErrorHandler")
        qmlRegisterType(BasicWrapper, "DICE", 1, 0, "BasicWrapper")
        qmlRegisterType(Camera, "DICE", 1, 0, "Camera")

        self.__app_log_buffer = {}
        self.__app_log_write_interval = 500
        self.__app_log_writer = self.__init_log_writer()

        self.__qml_engine = None
        self.__qml_context = None
        self.__app_window = None
        self.__main_window = None

        self.__core_apps = CoreAppListModel(self)

        qmlRegisterType(CoreApp, "DICE", 1, 0, "CoreApp")
        qmlRegisterType(BasicApp, "DICE", 1, 0, "BasicApp")

        self.executor = ThreadPoolExecutor(
            max_workers=2)  # TODO: set the max_workers from a configuration

        self.core_app_loaded.connect(self.__insert_core_app,
                                     Qt.QueuedConnection)
        self.__app_candidates = None
        self.__current_loading_core_app_index = 0
        self.__load_next_core_app(
        )  # load the first core app in this thread, but the other in the executor

    core_app_loaded = pyqtSignal(CoreApp)

    def __insert_core_app(self, core_app):
        self.__core_apps.append(core_app)
        self.core_apps_changed.emit()

    def __continue_loading_apps(self):
        self.executor.submit(self.__load_next_core_app)

    def __load_next_core_app(self):
        if self.__app_candidates is None:
            core_apps_json = os.path.join(self.application_dir, "core_apps",
                                          "core_apps.json")
            self.__app_candidates = JsonList(core_apps_json)

        if self.__current_loading_core_app_index == len(self.__app_candidates):
            return

        core_app_name = self.__app_candidates[
            self.__current_loading_core_app_index]
        qDebug("load " + core_app_name)
        self.__current_loading_core_app_index += 1
        core_app = self.__create_core_app(core_app_name)

        if core_app is not None:
            core_app.load()
            core_app.completed.connect(self.__continue_loading_apps)
            self.core_app_loaded.emit(core_app)

            # set really special core apps
            if core_app.name == "Home":
                self.home = core_app
            elif core_app.name == "Desk":
                self.desk = core_app
            elif core_app.name == "Settings":
                self.settings = core_app
        else:
            raise Exception("Could not load " + core_app_name)

    def __create_core_app(self, core_app_name):
        """
        Creates a core app by its name and returns it.
        :param core_app_name:
        :return: CoreApp
        """
        if os.path.exists(
                os.path.join(self.application_dir, "core_apps", core_app_name,
                             "core_app.py")):
            module_name = ".".join(["core_apps", core_app_name, "core_app"])
            module = import_module(module_name)
            class_object = getattr(module, core_app_name)

            core_app = class_object()
            core_app.moveToThread(self.thread())
            core_app.setParent(self)
            return core_app
        else:
            return None

    @pyqtSlot(str, name="loadProject")
    def load_project(self, json_file):
        qDebug("load project " + json_file)
        if not os.path.exists(json_file):
            raise Exception("project.dice not found in " + str(json_file))

        project = Project(self)
        project.path = os.path.abspath(os.path.dirname(json_file))
        project.project_config = JsonOrderedDict(json_file)

        if "projectName" in project.project_config:
            project.name = project.project_config["projectName"]

        self.project = project  # set project before using self.desk, so it can access the project
        self.desk.load_desk(project.project_config)
        project.loaded = True
        self.home.add_recent_project(project.name, json_file)

    @pyqtSlot(str, str, str, name="createNewProject")
    def create_new_project(self, name, path, description):
        name = name.strip()
        if name == "":
            raise Exception("project", "no name given")

        # create folders
        project_path = os.path.join(path, name)
        if os.path.exists(project_path):
            raise Exception("project", "directory already exists")

        if not os.access(path, os.W_OK):
            raise Exception("project", "directory is not writable")

        os.mkdir(project_path)

        # create project.dice
        project_dice = os.path.join(project_path, "project.dice")
        pd = JsonOrderedDict(project_dice)
        conf = {
            "projectName": name,
            "apps": [],
            "groups": [],
            "connections": [],
            "description": description
        }
        pd.update(conf)

        self.load_project(project_dice)

    core_apps_changed = pyqtSignal(name="coreAppsChanged")

    @property
    def core_apps(self):
        return self.__core_apps

    coreApps = pyqtProperty(CoreAppListModel,
                            fget=core_apps.fget,
                            notify=core_apps_changed)

    project_changed = pyqtSignal(name="projectChanged")

    @pyqtProperty(Project, notify=project_changed)
    def project(self):
        return self.__project

    @project.setter
    def project(self, project):
        if self.__project != project:
            if self.__project is not None:
                self.__project.close()
            self.__project = project
            self.project_changed.emit()

    desk_changed = pyqtSignal(name="deskChanged")

    @pyqtProperty(CoreApp, notify=desk_changed)
    def desk(self):
        return self.__desk

    @desk.setter
    def desk(self, desk):
        if self.__desk != desk:
            self.__desk = desk
            self.desk_changed.emit()

    settings_changed = pyqtSignal(name="settingsChanged")

    @pyqtProperty(CoreApp, notify=settings_changed)
    def settings(self):
        return self.__settings

    @settings.setter
    def settings(self, settings):
        if self.__settings != settings:
            self.__settings = settings
            self.settings_changed.emit()

    home_changed = pyqtSignal(name="homeChanged")

    @pyqtProperty(CoreApp, notify=home_changed)
    def home(self):
        return self.__home

    @home.setter
    def home(self, home):
        if self.__home != home:
            self.__home = home
            self.home_changed.emit()

    theme_changed = pyqtSignal(name="themeChanged")

    @pyqtProperty(QObject, notify=theme_changed)
    def theme(self):
        return self.__theme

    @theme.setter
    def theme(self, theme):
        if self.__theme != theme:
            self.__theme = theme
            self.theme_changed.emit()

    app_window_changed = pyqtSignal(name="appWindowChanged")

    @property
    def app_window(self):
        return self.__app_window

    @app_window.setter
    def app_window(self, app_window):
        if self.__app_window != app_window:
            self.__app_window = app_window
            self.app_window_changed.emit()

    appWindow = pyqtProperty(QQuickWindow,
                             fget=app_window.fget,
                             fset=app_window.fset,
                             notify=app_window_changed)

    main_window_changed = pyqtSignal(name="mainWindowChanged")

    @property
    def main_window(self):
        return self.__main_window

    @main_window.setter
    def main_window(self, main_window):
        if self.__main_window != main_window:
            self.__main_window = main_window
            self.main_window_changed.emit()

    mainWindow = pyqtProperty(QQuickItem,
                              fget=main_window.fget,
                              fset=main_window.fset,
                              notify=main_window_changed)

    qml_engine_changed = pyqtSignal(name="qmlEngineChanged")

    @property
    def qml_engine(self):
        return self.__qml_engine

    @qml_engine.setter
    def qml_engine(self, qml_engine):
        if self.__qml_engine != qml_engine:
            self.__qml_engine = qml_engine
            self.qml_engine_changed.emit()

    qmlEngine = pyqtProperty(QQmlApplicationEngine,
                             fget=qml_engine.fget,
                             fset=qml_engine.fset,
                             notify=qml_engine_changed)

    qml_context_changed = pyqtSignal(name="qmlContextChanged")

    @property
    def qml_context(self):
        return self.__qml_context

    @qml_context.setter
    def qml_context(self, qml_context):
        if self.__qml_context != qml_context:
            self.__qml_context = qml_context
            self.qml_context_changed.emit()

    qmlContext = pyqtProperty(QQmlContext,
                              fget=qml_context.fget,
                              fset=qml_context.fset,
                              notify=qml_context_changed)

    memory_changed = pyqtSignal(name="memoryChanged")

    @pyqtProperty(MemoryInfo, notify=memory_changed)
    def memory(self):
        return self.__memory

    error_changed = pyqtSignal(name="errorChanged")

    @pyqtProperty(ErrorHandler, notify=error_changed)
    def error(self):
        return self.__error

    def process_exception(self, exc):
        qDebug("process exception " + str(exc))
        self.error.type = exc.__class__.__name__
        self.error.msg = "\n".join(exc.args)
        self.error.occurred.emit()

    def alert(self, msg):
        self.error.type = "alert"
        self.error.msg = str(msg)
        self.error.occurred.emit()

    new_log = pyqtSignal(BasicApp,
                         str,
                         name="newLog",
                         arguments=["app", "log"])

    def app_log(self, app, log):
        try:
            self.__app_log_buffer[app].append(str(log))
        except KeyError:
            self.__app_log_buffer[app] = []
            self.__app_log_buffer[app].append(str(log))

    def __write_app_log(self):
        for app in self.__app_log_buffer:
            log = self.__app_log_buffer[app]
            if log:
                self.__app_log_buffer[app] = []
                self.new_log.emit(app, ''.join(log))

    def __init_log_writer(self):
        timer = QTimer()
        timer.setSingleShot(False)
        timer.setInterval(self.__app_log_write_interval)
        timer.timeout.connect(self.__write_app_log)
        timer.start()
        return timer
예제 #18
0
class Dice(QObject):
    def __init__(self, parent=None):
        super(Dice, self).__init__(parent)

        self.application_dir = QCoreApplication.applicationDirPath()

        self.__project = Project(self)  # used as an empty default project, replaced by load_project()
        self.__desk = None
        self.__settings = None
        self.__home = None
        qmlRegisterType(Project, "DICE", 1, 0, "Project")

        self.__theme = Theme(self)
        self.__memory = MemoryInfo(self)
        self.__error = ErrorHandler(self)
        qmlRegisterType(MemoryInfo, "DICE", 1, 0, "MemoryInfo")
        qmlRegisterType(ErrorHandler, "DICE", 1, 0, "ErrorHandler")
        qmlRegisterType(BasicWrapper, "DICE", 1, 0, "BasicWrapper")
        qmlRegisterType(Camera, "DICE", 1, 0, "Camera")

        self.__app_log_buffer = {}
        self.__app_log_write_interval = 500
        self.__app_log_writer = self.__init_log_writer()

        self.__qml_engine = None
        self.__qml_context = None
        self.__app_window = None
        self.__main_window = None

        self.__core_apps = CoreAppListModel(self)

        qmlRegisterType(CoreApp, "DICE", 1, 0, "CoreApp")
        qmlRegisterType(BasicApp, "DICE", 1, 0, "BasicApp")

        self.executor = ThreadPoolExecutor(max_workers=2)  # TODO: set the max_workers from a configuration

        self.core_app_loaded.connect(self.__insert_core_app, Qt.QueuedConnection)
        self.__app_candidates = None
        self.__current_loading_core_app_index = 0
        self.__load_next_core_app()  # load the first core app in this thread, but the other in the executor

    core_app_loaded = pyqtSignal(CoreApp)

    def __insert_core_app(self, core_app):
            self.__core_apps.append(core_app)
            self.core_apps_changed.emit()

    def __continue_loading_apps(self):
        self.executor.submit(self.__load_next_core_app)

    def __load_next_core_app(self):
        if self.__app_candidates is None:
            core_apps_json = os.path.join(self.application_dir, "core_apps", "core_apps.json")
            self.__app_candidates = JsonList(core_apps_json)

        if self.__current_loading_core_app_index == len(self.__app_candidates):
            return

        core_app_name = self.__app_candidates[self.__current_loading_core_app_index]
        qDebug("load "+core_app_name)
        self.__current_loading_core_app_index += 1
        core_app = self.__create_core_app(core_app_name)

        if core_app is not None:
            core_app.load()
            core_app.completed.connect(self.__continue_loading_apps)
            self.core_app_loaded.emit(core_app)

            # set really special core apps
            if core_app.name == "Home":
                self.home = core_app
            elif core_app.name == "Desk":
                self.desk = core_app
            elif core_app.name == "Settings":
                self.settings = core_app
        else:
            raise Exception("Could not load "+core_app_name)

    def __create_core_app(self, core_app_name):
        """
        Creates a core app by its name and returns it.
        :param core_app_name:
        :return: CoreApp
        """
        if os.path.exists(os.path.join(self.application_dir, "core_apps", core_app_name, "core_app.py")):
            module_name = ".".join(["core_apps", core_app_name, "core_app"])
            module = import_module(module_name)
            class_object = getattr(module, core_app_name)

            core_app = class_object()
            core_app.moveToThread(self.thread())
            core_app.setParent(self)
            return core_app
        else:
            return None

    @pyqtSlot(str, name="loadProject")
    def load_project(self, json_file):
        qDebug("load project "+json_file)
        if not os.path.exists(json_file):
            raise Exception("project.dice not found in "+str(json_file))

        project = Project(self)
        project.path = os.path.abspath(os.path.dirname(json_file))
        project.project_config = JsonOrderedDict(json_file)

        if "projectName" in project.project_config:
            project.name = project.project_config["projectName"]

        self.project = project  # set project before using self.desk, so it can access the project
        self.desk.load_desk(project.project_config)
        project.loaded = True
        self.home.add_recent_project(project.name, json_file)

    @pyqtSlot(str, str, str, name="createNewProject")
    def create_new_project(self, name, path, description):
        name = name.strip()
        if name == "":
            raise Exception("project", "no name given")

        # create folders
        project_path = os.path.join(path, name)
        if os.path.exists(project_path):
            raise Exception("project", "directory already exists")

        if not os.access(path, os.W_OK):
            raise Exception("project", "directory is not writable")

        os.mkdir(project_path)

        # create project.dice
        project_dice = os.path.join(project_path, "project.dice")
        pd = JsonOrderedDict(project_dice)
        conf = {"projectName": name, "apps": [], "groups": [], "connections": [], "description": description}
        pd.update(conf)

        self.load_project(project_dice)

    core_apps_changed = pyqtSignal(name="coreAppsChanged")

    @property
    def core_apps(self):
        return self.__core_apps

    coreApps = pyqtProperty(CoreAppListModel, fget=core_apps.fget, notify=core_apps_changed)

    project_changed = pyqtSignal(name="projectChanged")

    @pyqtProperty(Project, notify=project_changed)
    def project(self):
        return self.__project

    @project.setter
    def project(self, project):
        if self.__project != project:
            if self.__project is not None:
                self.__project.close()
            self.__project = project
            self.project_changed.emit()

    desk_changed = pyqtSignal(name="deskChanged")

    @pyqtProperty(CoreApp, notify=desk_changed)
    def desk(self):
        return self.__desk

    @desk.setter
    def desk(self, desk):
        if self.__desk != desk:
            self.__desk = desk
            self.desk_changed.emit()

    settings_changed = pyqtSignal(name="settingsChanged")

    @pyqtProperty(CoreApp, notify=settings_changed)
    def settings(self):
        return self.__settings

    @settings.setter
    def settings(self, settings):
        if self.__settings != settings:
            self.__settings = settings
            self.settings_changed.emit()

    home_changed = pyqtSignal(name="homeChanged")

    @pyqtProperty(CoreApp, notify=home_changed)
    def home(self):
        return self.__home

    @home.setter
    def home(self, home):
        if self.__home != home:
            self.__home = home
            self.home_changed.emit()

    theme_changed = pyqtSignal(name="themeChanged")

    @pyqtProperty(QObject, notify=theme_changed)
    def theme(self):
        return self.__theme

    @theme.setter
    def theme(self, theme):
        if self.__theme != theme:
            self.__theme = theme
            self.theme_changed.emit()

    app_window_changed = pyqtSignal(name="appWindowChanged")

    @property
    def app_window(self):
        return self.__app_window

    @app_window.setter
    def app_window(self, app_window):
        if self.__app_window != app_window:
            self.__app_window = app_window
            self.app_window_changed.emit()

    appWindow = pyqtProperty(QQuickWindow, fget=app_window.fget, fset=app_window.fset, notify=app_window_changed)

    main_window_changed = pyqtSignal(name="mainWindowChanged")

    @property
    def main_window(self):
        return self.__main_window

    @main_window.setter
    def main_window(self, main_window):
        if self.__main_window != main_window:
            self.__main_window = main_window
            self.main_window_changed.emit()

    mainWindow = pyqtProperty(QQuickItem, fget=main_window.fget, fset=main_window.fset, notify=main_window_changed)

    qml_engine_changed = pyqtSignal(name="qmlEngineChanged")

    @property
    def qml_engine(self):
        return self.__qml_engine

    @qml_engine.setter
    def qml_engine(self, qml_engine):
        if self.__qml_engine != qml_engine:
            self.__qml_engine = qml_engine
            self.qml_engine_changed.emit()

    qmlEngine = pyqtProperty(QQmlApplicationEngine, fget=qml_engine.fget, fset=qml_engine.fset,
                             notify=qml_engine_changed)

    qml_context_changed = pyqtSignal(name="qmlContextChanged")

    @property
    def qml_context(self):
        return self.__qml_context

    @qml_context.setter
    def qml_context(self, qml_context):
        if self.__qml_context != qml_context:
            self.__qml_context = qml_context
            self.qml_context_changed.emit()

    qmlContext = pyqtProperty(QQmlContext, fget=qml_context.fget, fset=qml_context.fset, notify=qml_context_changed)

    memory_changed = pyqtSignal(name="memoryChanged")

    @pyqtProperty(MemoryInfo, notify=memory_changed)
    def memory(self):
        return self.__memory

    error_changed = pyqtSignal(name="errorChanged")

    @pyqtProperty(ErrorHandler, notify=error_changed)
    def error(self):
        return self.__error

    def process_exception(self, exc):
        qDebug("process exception "+str(exc))
        self.error.type = exc.__class__.__name__
        self.error.msg = "\n".join(exc.args)
        self.error.occurred.emit()

    def alert(self, msg):
        self.error.type = "alert"
        self.error.msg = str(msg)
        self.error.occurred.emit()

    new_log = pyqtSignal(BasicApp, str, name="newLog", arguments=["app", "log"])

    def app_log(self, app, log):
        try:
            self.__app_log_buffer[app].append(str(log))
        except KeyError:
            self.__app_log_buffer[app] = []
            self.__app_log_buffer[app].append(str(log))

    def __write_app_log(self):
        for app in self.__app_log_buffer:
            log = self.__app_log_buffer[app]
            if log:
                self.__app_log_buffer[app] = []
                self.new_log.emit(app, ''.join(log))

    def __init_log_writer(self):
        timer = QTimer()
        timer.setSingleShot(False)
        timer.setInterval(self.__app_log_write_interval)
        timer.timeout.connect(self.__write_app_log)
        timer.start()
        return timer
예제 #19
0
class MainWindow(QMainWindow):
    """Main Class"""
    def __init__(self, app):
        """
        Initialization of the Main window. This is directly called after the
        Logger has been initialized. The Function loads the GUI, creates the
        used Classes and connects the actions to the GUI.
        """
        QMainWindow.__init__(self)

        self.app = app

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        self.canvas = self.ui.canvas
        if g.config.mode3d:
            self.canvas_scene = self.canvas
        else:
            self.canvas_scene = None

        self.TreeHandler = TreeHandler(self.ui)

        self.MyPostProcessor = MyPostProcessor()
        self.d2g = Project(self)

        self.createActions()
        self.connectToolbarToConfig()

        self.filename = ""

        self.valuesDXF = None
        self.shapes = Shapes([])
        self.entityRoot = None
        self.layerContents = Layers([])
        self.newNumber = 1

        self.cont_dx = 0.0
        self.cont_dy = 0.0
        self.cont_rotate = 0.0
        self.cont_scale = 1.0

        # self.readSettings()

    def tr(self, string_to_translate):
        """
        Translate a string using the QCoreApplication translation framework
        @param: string_to_translate: a unicode string
        @return: the translated unicode string if it was possible to translate
        """
        return text_type(
            QtCore.QCoreApplication.translate('MainWindow',
                                              string_to_translate))

    def createActions(self):
        """
        Create the actions of the main toolbar.
        @purpose: Links the callbacks to the actions in the menu
        """

        # File
        self.ui.actionOpen.triggered.connect(self.open)
        self.ui.actionReload.triggered.connect(self.reload)
        self.ui.actionSaveProjectAs.triggered.connect(self.saveProject)
        self.ui.actionClose.triggered.connect(self.close)

        # Export
        self.ui.actionOptimizePaths.triggered.connect(self.optimizeTSP)
        self.ui.actionExportShapes.triggered.connect(self.exportShapes)
        self.ui.actionOptimizeAndExportShapes.triggered.connect(
            self.optimizeAndExportShapes)

        # View
        self.ui.actionShowPathDirections.triggered.connect(
            self.setShowPathDirections)
        self.ui.actionShowDisabledPaths.triggered.connect(
            self.setShowDisabledPaths)
        self.ui.actionLiveUpdateExportRoute.triggered.connect(
            self.liveUpdateExportRoute)
        self.ui.actionDeleteG0Paths.triggered.connect(self.deleteG0Paths)
        self.ui.actionAutoscale.triggered.connect(self.canvas.autoscale)
        if g.config.mode3d:
            self.ui.actionTopView.triggered.connect(self.canvas.topView)
            self.ui.actionIsometricView.triggered.connect(
                self.canvas.isometricView)

        # Options
        self.ui.actionTolerances.triggered.connect(self.setTolerances)
        self.ui.actionRotateAll.triggered.connect(self.rotateAll)
        self.ui.actionScaleAll.triggered.connect(self.scaleAll)
        self.ui.actionMoveWorkpieceZero.triggered.connect(
            self.moveWorkpieceZero)
        self.ui.actionSplitLineSegments.triggered.connect(
            self.d2g.small_reload)
        self.ui.actionAutomaticCutterCompensation.triggered.connect(
            self.d2g.small_reload)
        self.ui.actionMilling.triggered.connect(self.setMachineTypeToMilling)
        self.ui.actionDragKnife.triggered.connect(
            self.setMachineTypeToDragKnife)
        self.ui.actionLathe.triggered.connect(self.setMachineTypeToLathe)
        self.ui.actionLaser_Cutter.triggered.connect(
            self.setMachineTypeToLaserCutter)

        # Help
        self.ui.actionAbout.triggered.connect(self.about)

    def connectToolbarToConfig(self, project=False):
        # View
        if not project:
            self.ui.actionShowDisabledPaths.setChecked(
                g.config.vars.General['show_disabled_paths'])
            self.ui.actionLiveUpdateExportRoute.setChecked(
                g.config.vars.General['live_update_export_route'])

        # Options
        self.ui.actionSplitLineSegments.setChecked(
            g.config.vars.General['split_line_segments'])
        self.ui.actionAutomaticCutterCompensation.setChecked(
            g.config.vars.General['automatic_cutter_compensation'])
        self.updateMachineType()

    def keyPressEvent(self, event):
        """
        Rewritten KeyPressEvent to get other behavior while Shift is pressed.
        @purpose: Changes to ScrollHandDrag while Control pressed
        @param event:    Event Parameters passed to function
        """
        if event.isAutoRepeat():
            return
        if event.key() == QtCore.Qt.Key_Control:
            self.canvas.isMultiSelect = True
        elif event.key() == QtCore.Qt.Key_Shift:
            if g.config.mode3d:
                self.canvas.isPanning = True
                self.canvas.setCursor(QtCore.Qt.OpenHandCursor)
            else:
                self.canvas.setDragMode(QGraphicsView.ScrollHandDrag)
        elif event.key() == QtCore.Qt.Key_Alt:
            if g.config.mode3d:
                self.canvas.isRotating = True
                self.canvas.setCursor(QtCore.Qt.PointingHandCursor)

    def keyReleaseEvent(self, event):
        """
        Rewritten KeyReleaseEvent to get other behavior while Shift is pressed.
        @purpose: Changes to RubberBandDrag while Control released
        @param event:    Event Parameters passed to function
        """
        if event.key() == QtCore.Qt.Key_Control:
            self.canvas.isMultiSelect = False
        elif event.key() == QtCore.Qt.Key_Shift:
            if g.config.mode3d:
                self.canvas.isPanning = False
                self.canvas.unsetCursor()
            else:
                self.canvas.setDragMode(QGraphicsView.NoDrag)
        elif event.key() == QtCore.Qt.Key_Alt:
            if g.config.mode3d:
                self.canvas.isRotating = False
                if -5 < self.canvas.rotX < 5 and\
                   -5 < self.canvas.rotY < 5 and\
                   -5 < self.canvas.rotZ < 5:
                    self.canvas.rotX = 0
                    self.canvas.rotY = 0
                    self.canvas.rotZ = 0
                    self.canvas.update()
                self.canvas.unsetCursor()

    def enableToolbarButtons(self, status=True):
        # File
        self.ui.actionReload.setEnabled(status)
        self.ui.actionSaveProjectAs.setEnabled(status)

        # Export
        self.ui.actionOptimizePaths.setEnabled(status)
        self.ui.actionExportShapes.setEnabled(status)
        self.ui.actionOptimizeAndExportShapes.setEnabled(status)

        # View
        self.ui.actionShowPathDirections.setEnabled(status)
        self.ui.actionShowDisabledPaths.setEnabled(status)
        self.ui.actionLiveUpdateExportRoute.setEnabled(status)
        self.ui.actionAutoscale.setEnabled(status)
        if g.config.mode3d:
            self.ui.actionTopView.setEnabled(status)
            self.ui.actionIsometricView.setEnabled(status)

        # Options
        self.ui.actionTolerances.setEnabled(status)
        self.ui.actionRotateAll.setEnabled(status)
        self.ui.actionScaleAll.setEnabled(status)
        self.ui.actionMoveWorkpieceZero.setEnabled(status)

    def deleteG0Paths(self):
        """
        Deletes the optimisation paths from the scene.
        """
        self.setCursor(QtCore.Qt.WaitCursor)
        self.app.processEvents()

        self.canvas_scene.delete_opt_paths()
        self.ui.actionDeleteG0Paths.setEnabled(False)
        self.canvas_scene.update()

        self.unsetCursor()

    def exportShapes(self, status=False, saveas=None):
        """
        This function is called by the menu "Export/Export Shapes". It may open
        a Save Dialog if used without LinuxCNC integration. Otherwise it's
        possible to select multiple postprocessor files, which are located
        in the folder.
        """
        self.setCursor(QtCore.Qt.WaitCursor)
        self.app.processEvents()

        logger.debug(self.tr('Export the enabled shapes'))

        # Get the export order from the QTreeView
        self.TreeHandler.updateExportOrder()
        self.updateExportRoute()

        logger.debug(self.tr("Sorted layers:"))
        for i, layer in enumerate(self.layerContents.non_break_layer_iter()):
            logger.debug("LayerContents[%i] = %s" % (i, layer))

        if not g.config.vars.General['write_to_stdout']:

            # Get the name of the File to export
            if not saveas:
                MyFormats = ""
                for i in range(len(self.MyPostProcessor.output_format)):
                    name = "%s " % (self.MyPostProcessor.output_text[i])
                    format_ = "(*%s);;" % (
                        self.MyPostProcessor.output_format[i])
                    MyFormats = MyFormats + name + format_
                filename = self.showSaveDialog(self.tr('Export to file'),
                                               MyFormats)
                save_filename = file_str(filename[0])
            else:
                filename = [None, None]
                save_filename = saveas

            # If Cancel was pressed
            if not save_filename:
                self.unsetCursor()
                return

            (beg, ende) = os.path.split(save_filename)
            (fileBaseName, fileExtension) = os.path.splitext(ende)

            pp_file_nr = 0
            for i in range(len(self.MyPostProcessor.output_format)):
                name = "%s " % (self.MyPostProcessor.output_text[i])
                format_ = "(*%s)" % (self.MyPostProcessor.output_format[i])
                MyFormats = name + format_
                if filename[1] == MyFormats:
                    pp_file_nr = i
            if fileExtension != self.MyPostProcessor.output_format[pp_file_nr]:
                if not QtCore.QFile.exists(save_filename):
                    save_filename += self.MyPostProcessor.output_format[
                        pp_file_nr]

            self.MyPostProcessor.getPostProVars(pp_file_nr)
        else:
            save_filename = ""
            self.MyPostProcessor.getPostProVars(0)
        """
        Export will be performed according to LayerContents and their order
        is given in this variable too.
        """

        self.MyPostProcessor.exportShapes(self.filename, save_filename,
                                          self.layerContents)

        self.unsetCursor()

        if g.config.vars.General['write_to_stdout']:
            self.close()

    def optimizeAndExportShapes(self):
        """
        Optimize the tool path, then export the shapes
        """
        self.optimizeTSP()
        self.exportShapes()

    def updateExportRoute(self):
        """
        Update the drawing of the export route
        """
        self.canvas_scene.delete_opt_paths()

        self.canvas_scene.addexproutest()
        for LayerContent in self.layerContents.non_break_layer_iter():
            if len(LayerContent.exp_order) > 0:
                self.canvas_scene.addexproute(LayerContent.exp_order,
                                              LayerContent.nr)
        if len(self.canvas_scene.routearrows) > 0:
            self.ui.actionDeleteG0Paths.setEnabled(True)
            self.canvas_scene.addexprouteen()
        self.canvas_scene.update()

    def optimizeTSP(self):
        """
        Method is called to optimize the order of the shapes. This is performed
        by solving the TSP Problem.
        """
        self.setCursor(QtCore.Qt.WaitCursor)
        self.app.processEvents()

        logger.debug(self.tr('Optimize order of enabled shapes per layer'))
        self.canvas_scene.delete_opt_paths()

        # Get the export order from the QTreeView
        logger.debug(self.tr('Updating order according to TreeView'))
        self.TreeHandler.updateExportOrder()
        self.canvas_scene.addexproutest()

        for LayerContent in self.layerContents.non_break_layer_iter():
            # Initial values for the Lists to export.
            shapes_to_write = []
            shapes_fixed_order = []
            shapes_st_en_points = []

            # Check all shapes of Layer which shall be exported and create List for it.
            logger.debug(
                self.tr("Nr. of Shapes %s; Nr. of Shapes in Route %s") %
                (len(LayerContent.shapes), len(LayerContent.exp_order)))
            logger.debug(
                self.tr("Export Order for start: %s") % LayerContent.exp_order)

            for shape_nr in range(len(LayerContent.exp_order)):
                if not self.shapes[
                        LayerContent.exp_order[shape_nr]].send_to_TSP:
                    shapes_fixed_order.append(shape_nr)

                shapes_to_write.append(shape_nr)
                shapes_st_en_points.append(self.shapes[
                    LayerContent.exp_order[shape_nr]].get_start_end_points())

            # Perform Export only if the Number of shapes to export is bigger than 0
            if len(shapes_to_write) > 0:
                # Errechnen der Iterationen
                # Calculate the iterations
                iter_ = min(g.config.vars.Route_Optimisation['max_iterations'],
                            len(shapes_to_write) * 50)

                # Adding the Start and End Points to the List.
                x_st = g.config.vars.Plane_Coordinates['axis1_start_end']
                y_st = g.config.vars.Plane_Coordinates['axis2_start_end']
                start = Point(x_st, y_st)
                ende = Point(x_st, y_st)
                shapes_st_en_points.append([start, ende])

                TSPs = TspOptimization(shapes_st_en_points, shapes_fixed_order)
                logger.info(
                    self.tr("TSP start values initialised for Layer %s") %
                    LayerContent.name)
                logger.debug(self.tr("Shapes to write: %s") % shapes_to_write)
                logger.debug(self.tr("Fixed order: %s") % shapes_fixed_order)

                for it_nr in range(iter_):
                    # Only show each 50th step.
                    if it_nr % 50 == 0:
                        TSPs.calc_next_iteration()
                        new_exp_order = [
                            LayerContent.exp_order[nr]
                            for nr in TSPs.opt_route[1:]
                        ]

                logger.debug(self.tr("TSP done with result: %s") % TSPs)

                LayerContent.exp_order = new_exp_order

                self.canvas_scene.addexproute(LayerContent.exp_order,
                                              LayerContent.nr)
                logger.debug(
                    self.tr("New Export Order after TSP: %s") % new_exp_order)
                self.app.processEvents()
            else:
                LayerContent.exp_order = []

        if len(self.canvas_scene.routearrows) > 0:
            self.ui.actionDeleteG0Paths.setEnabled(True)
            self.canvas_scene.addexprouteen()

        # Update order in the treeView, according to path calculation done by the TSP
        self.TreeHandler.updateTreeViewOrder()
        self.canvas_scene.update()

        self.unsetCursor()

    def automaticCutterCompensation(self):
        if self.ui.actionAutomaticCutterCompensation.isEnabled() and\
           self.ui.actionAutomaticCutterCompensation.isChecked():
            for layerContent in self.layerContents.non_break_layer_iter():
                if layerContent.automaticCutterCompensationEnabled():
                    outside_compensation = True
                    shapes_left = layerContent.shapes
                    while len(shapes_left) > 0:
                        shapes_left = [
                            shape for shape in shapes_left
                            if not self.ifNotContainedChangeCutCor(
                                shape, shapes_left, outside_compensation)
                        ]
                        outside_compensation = not outside_compensation
        self.canvas_scene.update()

    def ifNotContainedChangeCutCor(self, shape, shapes_left,
                                   outside_compensation):
        for otherShape in shapes_left:
            if shape != otherShape:
                if shape != otherShape and\
                   otherShape.topLeft.x < shape.topLeft.x and shape.bottomRight.x < otherShape.bottomRight.x and\
                   otherShape.bottomRight.y < shape.bottomRight.y and shape.topLeft.y < otherShape.topLeft.y:
                    return False
        if outside_compensation == shape.cw:
            shape.cut_cor = 41
        else:
            shape.cut_cor = 42
        self.canvas_scene.repaint_shape(shape)
        return True

    def showSaveDialog(self, title, MyFormats):
        """
        This function is called by the menu "Export/Export Shapes" of the main toolbar.
        It creates the selection dialog for the exporter
        @return: Returns the filename of the selected file.
        """

        (beg, ende) = os.path.split(self.filename)
        (fileBaseName, fileExtension) = os.path.splitext(ende)

        default_name = os.path.join(g.config.vars.Paths['output_dir'],
                                    fileBaseName)

        selected_filter = self.MyPostProcessor.output_format[0]
        filename = getSaveFileName(self, title, default_name, MyFormats,
                                   selected_filter)

        logger.info(self.tr("File: %s selected") % filename[0])

        return filename

    def about(self):
        """
        This function is called by the menu "Help/About" of the main toolbar and
        creates the About Window
        """

        message = self.tr("<html>"
                "<h2><center>You are using</center></h2>"
                "<body bgcolor="\
                "<center><img src=':images/dxf2gcode_logo.png' border='1' color='white'></center></body>"
                "<h2>Version:</h2>"
                "<body>%s: %s<br>"
                "Last change: %s<br>"
                "Changed by: %s<br></body>"
                "<h2>Where to get help:</h2>"
                "For more information and updates, "
                "please visit "
                "<a href='http://sourceforge.net/projects/dxf2gcode/'>http://sourceforge.net/projects/dxf2gcode/</a><br>"
                "For any questions on how to use dxf2gcode please use the "
                "<a href='https://groups.google.com/forum/?fromgroups#!forum/dxf2gcode-users'>mailing list</a><br>"
                "To log bugs, or request features please use the "
                "<a href='http://sourceforge.net/projects/dxf2gcode/tickets/'>issue tracking system</a><br>"
                "<h2>License and copyright:</h2>"
                "<body>This program is written in Python and is published under the "
                "<a href='http://www.gnu.org/licenses/'>GNU GPLv3 license.</a><br>"
                "</body></html>") % (c.VERSION, c.REVISION, c.DATE, c.AUTHOR)

        AboutDialog(title=self.tr("About DXF2GCODE"), message=message)

    def setShowPathDirections(self):
        """
        This function is called by the menu "Show all path directions" of the
        main and forwards the call to Canvas.setShow_path_direction()
        """
        flag = self.ui.actionShowPathDirections.isChecked()
        self.canvas.setShowPathDirections(flag)
        self.canvas_scene.update()

    def setShowDisabledPaths(self):
        """
        This function is called by the menu "Show disabled paths" of the
        main and forwards the call to Canvas.setShow_disabled_paths()
        """
        flag = self.ui.actionShowDisabledPaths.isChecked()
        self.canvas_scene.setShowDisabledPaths(flag)
        self.canvas_scene.update()

    def liveUpdateExportRoute(self):
        """
        This function is called by the menu "Live update tool path" of the
        main and forwards the call to TreeHandler.setUpdateExportRoute()
        """
        flag = self.ui.actionLiveUpdateExportRoute.isChecked()
        self.TreeHandler.setLiveUpdateExportRoute(flag)

    def setTolerances(self):
        title = self.tr('Contour tolerances')
        units = "in" if g.config.metric == 0 else "mm"
        label = [
            self.tr("Tolerance for common points [%s]:") % units,
            self.tr("Tolerance for curve fitting [%s]:") % units
        ]
        value = [g.config.point_tolerance, g.config.fitting_tolerance]

        logger.debug(self.tr("set Tolerances"))
        SetTolDialog = PopUpDialog(title, label, value)

        if SetTolDialog.result is None:
            return

        g.config.point_tolerance = float(SetTolDialog.result[0])
        g.config.fitting_tolerance = float(SetTolDialog.result[1])

        self.d2g.reload()  # set tolerances requires a complete reload

    def scaleAll(self):
        title = self.tr('Scale Contour')
        label = [self.tr("Scale Contour by factor:")]
        value = [self.cont_scale]
        ScaEntDialog = PopUpDialog(title, label, value)

        if ScaEntDialog.result is None:
            return

        self.cont_scale = float(ScaEntDialog.result[0])
        self.entityRoot.sca = self.cont_scale

        self.d2g.small_reload()

    def rotateAll(self):
        title = self.tr('Rotate Contour')
        label = [
            self.tr("Rotate Contour by deg:")
        ]  # TODO should we support radians for drawing unit non metric?
        value = [degrees(self.cont_rotate)]
        RotEntDialog = PopUpDialog(title, label, value)

        if RotEntDialog.result is None:
            return

        self.cont_rotate = radians(float(RotEntDialog.result[0]))
        self.entityRoot.rot = self.cont_rotate

        self.d2g.small_reload()

    def moveWorkpieceZero(self):
        """
        This function is called when the Option=>Move WP Zero Menu is clicked.
        """
        title = self.tr('Workpiece zero offset')
        units = "[in]" if g.config.metric == 0 else "[mm]"
        label = [
            self.tr("Offset %s axis %s:") %
            (g.config.vars.Axis_letters['ax1_letter'], units),
            self.tr("Offset %s axis %s:") %
            (g.config.vars.Axis_letters['ax2_letter'], units)
        ]
        value = [self.cont_dx, self.cont_dy]
        MoveWpzDialog = PopUpDialog(title, label, value, True)

        if MoveWpzDialog.result is None:
            return

        if MoveWpzDialog.result == 'Auto':
            minx = sys.float_info.max
            miny = sys.float_info.max
            for shape in self.shapes:
                if not shape.isDisabled():
                    minx = min(minx, shape.topLeft.x)
                    miny = min(miny, shape.bottomRight.y)
            self.cont_dx = self.entityRoot.p0.x - minx
            self.cont_dy = self.entityRoot.p0.y - miny
        else:
            self.cont_dx = float(MoveWpzDialog.result[0])
            self.cont_dy = float(MoveWpzDialog.result[1])

        self.entityRoot.p0.x = self.cont_dx
        self.entityRoot.p0.y = self.cont_dy

        self.d2g.small_reload()

    def setMachineTypeToMilling(self):
        g.config.machine_type = 'milling'
        self.updateMachineType()
        self.d2g.small_reload()

    def setMachineTypeToDragKnife(self):
        g.config.machine_type = 'drag_knife'
        self.updateMachineType()
        self.d2g.small_reload()

    def setMachineTypeToLathe(self):
        g.config.machine_type = 'lathe'
        self.updateMachineType()
        self.d2g.small_reload()

    def setMachineTypeToLaserCutter(self):
        g.config.machine_type = 'laser_cutter'
        self.updateMachineType()
        self.d2g.small_reload()

    def updateMachineType(self):
        if g.config.machine_type == 'milling':
            self.ui.actionAutomaticCutterCompensation.setEnabled(True)
            self.ui.actionMilling.setChecked(True)
            self.ui.actionDragKnife.setChecked(False)
            self.ui.actionLathe.setChecked(False)
            self.ui.actionLaser_Cutter.setChecked(False)
            self.ui.label_9.setText(self.tr("Z Infeed depth"))
            self.ui.label_15.setText(self.tr("Not Available"))
            self.ui.label_16.setText(self.tr("Not Available"))
        elif g.config.machine_type == 'lathe':
            self.ui.actionAutomaticCutterCompensation.setEnabled(False)
            self.ui.actionMilling.setChecked(False)
            self.ui.actionDragKnife.setChecked(False)
            self.ui.actionLathe.setChecked(True)
            self.ui.actionLaser_Cutter.setChecked(False)
            self.ui.label_9.setText(self.tr("No Z-Axis for lathe"))
            self.ui.label_15.setText(self.tr("Not Available"))
            self.ui.label_16.setText(self.tr("Not Available"))
        elif g.config.machine_type == "drag_knife":
            self.ui.actionAutomaticCutterCompensation.setEnabled(False)
            self.ui.actionMilling.setChecked(False)
            self.ui.actionDragKnife.setChecked(True)
            self.ui.actionLathe.setChecked(False)
            self.ui.actionLaser_Cutter.setChecked(False)
            self.ui.label_9.setText(self.tr("Z Drag depth"))
            self.ui.label_15.setText(self.tr("Not Available"))
            self.ui.label_16.setText(self.tr("Not Available"))
        if g.config.machine_type == 'laser_cutter':
            self.ui.actionAutomaticCutterCompensation.setEnabled(True)
            self.ui.actionMilling.setChecked(False)
            self.ui.actionDragKnife.setChecked(False)
            self.ui.actionLathe.setChecked(False)
            self.ui.actionLaser_Cutter.setChecked(True)
            self.ui.label_15.setText(self.tr("Laser Power"))
            self.ui.label_16.setText(self.tr("Laser Pulses Per mm"))
            self.ui.label_10.setText(self.tr("Not Available"))
            self.ui.label_9.setText(self.tr("Not Available"))
            self.ui.label_8.setText(self.tr("Not Available"))
            self.ui.label_6.setText(self.tr("Not Available"))
            self.ui.label_5.setText(self.tr("Not Available"))
            self.ui.label_14.setText(self.tr("Not Available"))

    def open(self):
        """
        This function is called by the menu "File/Load File" of the main toolbar.
        It creates the file selection dialog and calls the load function to
        load the selected file.
        """

        self.OpenFileDialog(self.tr("Open file"))

        # If there is something to load then call the load function callback
        if self.filename:
            self.cont_dx = 0.0
            self.cont_dy = 0.0
            self.cont_rotate = 0.0
            self.cont_scale = 1.0

            self.load()

    def OpenFileDialog(self, title):
        self.filename, _ = getOpenFileName(
            self, title, g.config.vars.Paths['import_dir'],
            self.tr("All supported files (*.dxf *.ps *.pdf *%s);;"
                    "DXF files (*.dxf);;"
                    "PS files (*.ps);;"
                    "PDF files (*.pdf);;"
                    "Project files (*%s);;"
                    "All types (*.*)") %
            (c.PROJECT_EXTENSION, c.PROJECT_EXTENSION))

        # If there is something to load then call the load function callback
        if self.filename:
            self.filename = file_str(self.filename)
            logger.info(self.tr("File: %s selected") % self.filename)

    def load(self, plot=True):
        """
        Loads the file given by self.filename.  Also calls the command to
        make the plot.
        @param plot: if it should plot
        """
        if not QtCore.QFile.exists(self.filename):
            logger.info(self.tr("Cannot locate file: %s") % self.filename)
            self.OpenFileDialog(
                self.tr("Manually open file: %s") % self.filename)
            if not self.filename:
                return False  # cancelled

        self.setCursor(QtCore.Qt.WaitCursor)
        self.setWindowTitle("DXF2GCODE - [%s]" % self.filename)
        self.canvas.resetAll()
        self.app.processEvents()

        (name, ext) = os.path.splitext(self.filename)

        if ext.lower() == c.PROJECT_EXTENSION:
            self.loadProject(self.filename)
            return True  # kill this load operation - we opened a new one

        if ext.lower() == ".ps" or ext.lower() == ".pdf":
            logger.info(self.tr("Sending Postscript/PDF to pstoedit"))

            # Create temporary file which will be read by the program
            self.filename = os.path.join(tempfile.gettempdir(),
                                         'dxf2gcode_temp.dxf')

            pstoedit_cmd = g.config.vars.Filters['pstoedit_cmd']
            pstoedit_opt = g.config.vars.Filters['pstoedit_opt']
            ps_filename = os.path.normcase(self.filename)
            cmd = [('%s' % pstoedit_cmd)
                   ] + pstoedit_opt + [('%s' % ps_filename),
                                       ('%s' % self.filename)]
            logger.debug(cmd)
            try:
                subprocess.call(cmd)
            except FileNotFoundError as e:
                logger.error(e.strerror)
                self.unsetCursor()
                QMessageBox.critical(
                    self, "ERROR",
                    self.
                    tr("Please make sure you have installed pstoedit, and configured it in the config file."
                       ))
                return True
            subprocess.check_output(
            )  # If the return code was non-zero it raises a subprocess.CalledProcessError.

        logger.info(self.tr('Loading file: %s') % self.filename)

        self.valuesDXF = ReadDXF(self.filename)

        # Output the information in the text window
        logger.info(self.tr('Loaded layers: %s') % len(self.valuesDXF.layers))
        logger.info(
            self.tr('Loaded blocks: %s') % len(self.valuesDXF.blocks.Entities))
        for i in range(len(self.valuesDXF.blocks.Entities)):
            layers = self.valuesDXF.blocks.Entities[i].get_used_layers()
            logger.info(
                self.
                tr('Block %i includes %i Geometries, reduced to %i Contours, used layers: %s'
                   ) % (i, len(self.valuesDXF.blocks.Entities[i].geo),
                        len(self.valuesDXF.blocks.Entities[i].cont), layers))
        layers = self.valuesDXF.entities.get_used_layers()
        insert_nr = self.valuesDXF.entities.get_insert_nr()
        logger.info(
            self.
            tr('Loaded %i entity geometries; reduced to %i contours; used layers: %s; number of inserts %i'
               ) % (len(self.valuesDXF.entities.geo),
                    len(self.valuesDXF.entities.cont), layers, insert_nr))

        if g.config.metric == 0:
            logger.info(self.tr("Drawing units: inches"))
            distance = self.tr("[in]")
            speed = self.tr("[IPM]")
        else:
            logger.info(self.tr("Drawing units: millimeters"))
            distance = self.tr("[mm]")
            speed = self.tr("[mm/min]")
        self.ui.unitLabel_3.setText(distance)
        self.ui.unitLabel_4.setText(distance)
        self.ui.unitLabel_5.setText(distance)
        self.ui.unitLabel_6.setText(distance)
        self.ui.unitLabel_7.setText(distance)
        self.ui.unitLabel_8.setText(speed)
        self.ui.unitLabel_9.setText(speed)

        self.makeShapes()
        if plot:
            self.plot()
        return True

    def plot(self):
        # Populate the treeViews
        self.TreeHandler.buildEntitiesTree(self.entityRoot)
        self.TreeHandler.buildLayerTree(self.layerContents)

        # Paint the canvas
        if not g.config.mode3d:
            self.canvas_scene = MyGraphicsScene()
            self.canvas.setScene(self.canvas_scene)

        self.canvas_scene.plotAll(self.shapes)
        self.setShowPathDirections()
        self.setShowDisabledPaths()
        self.liveUpdateExportRoute()

        if not g.config.mode3d:
            self.canvas.show()
            self.canvas.setFocus()
        self.canvas.autoscale()

        # After all is plotted enable the Menu entities
        self.enableToolbarButtons()

        self.automaticCutterCompensation()

        self.unsetCursor()

    def reload(self):
        """
        This function is called by the menu "File/Reload File" of the main toolbar.
        It reloads the previously loaded file (if any)
        """
        if self.filename:
            logger.info(self.tr("Reloading file: %s") % self.filename)
            self.load()

    def makeShapes(self):
        self.entityRoot = EntityContent(
            nr=0,
            name='Entities',
            parent=None,
            p0=Point(self.cont_dx, self.cont_dy),
            pb=Point(),
            sca=[self.cont_scale, self.cont_scale, self.cont_scale],
            rot=self.cont_rotate)
        self.layerContents = Layers([])
        self.shapes = Shapes([])

        self.makeEntityShapes(self.entityRoot)

        for layerContent in self.layerContents:
            layerContent.overrideDefaults()
        self.layerContents.sort(key=lambda x: x.nr)
        self.newNumber = len(self.shapes)

    def makeEntityShapes(self, parent, layerNr=-1):
        """
        Instance is called prior to plotting the shapes. It creates
        all shape classes which are plotted into the canvas.

        @param parent: The parent of a shape is always an Entity. It may be the root
        or, if it is a Block, this is the Block.
        """
        if parent.name == "Entities":
            entities = self.valuesDXF.entities
        else:
            ent_nr = self.valuesDXF.Get_Block_Nr(parent.name)
            entities = self.valuesDXF.blocks.Entities[ent_nr]

        # Assigning the geometries in the variables geos & contours in cont
        ent_geos = entities.geo

        # Loop for the number of contours
        for cont in entities.cont:
            # Query if it is in the contour of an insert or of a block
            if ent_geos[cont.order[0][0]].Typ == "Insert":
                ent_geo = ent_geos[cont.order[0][0]]

                # Assign the base point for the block
                new_ent_nr = self.valuesDXF.Get_Block_Nr(ent_geo.BlockName)
                new_entities = self.valuesDXF.blocks.Entities[new_ent_nr]
                pb = new_entities.basep

                # Scaling, etc. assign the block
                p0 = ent_geos[cont.order[0][0]].Point
                sca = ent_geos[cont.order[0][0]].Scale
                rot = ent_geos[cont.order[0][0]].rot

                # Creating the new Entitie Contents for the insert
                newEntityContent = EntityContent(nr=0,
                                                 name=ent_geo.BlockName,
                                                 parent=parent,
                                                 p0=p0,
                                                 pb=pb,
                                                 sca=sca,
                                                 rot=rot)

                parent.append(newEntityContent)

                self.makeEntityShapes(newEntityContent, ent_geo.Layer_Nr)

            else:
                # Loop for the number of geometries
                tmp_shape = Shape(len(self.shapes), cont.closed, parent)

                for ent_geo_nr in range(len(cont.order)):
                    ent_geo = ent_geos[cont.order[ent_geo_nr][0]]
                    if cont.order[ent_geo_nr][1]:
                        ent_geo.geo.reverse()
                        for geo in ent_geo.geo:
                            geo = copy(geo)
                            geo.reverse()
                            self.append_geo_to_shape(tmp_shape, geo)
                        ent_geo.geo.reverse()
                    else:
                        for geo in ent_geo.geo:
                            self.append_geo_to_shape(tmp_shape, copy(geo))

                if len(tmp_shape.geos) > 0:
                    # All shapes have to be CW direction.
                    tmp_shape.AnalyseAndOptimize()

                    self.shapes.append(tmp_shape)
                    if g.config.vars.Import_Parameters[
                            'insert_at_block_layer'] and layerNr != -1:
                        self.addtoLayerContents(tmp_shape, layerNr)
                    else:
                        self.addtoLayerContents(tmp_shape, ent_geo.Layer_Nr)
                    parent.append(tmp_shape)

                    if not g.config.mode3d:
                        # Connect the shapeSelectionChanged and enableDisableShape signals to our treeView,
                        #  so that selections of the shapes are reflected on the treeView
                        tmp_shape.setSelectionChangedCallback(
                            self.TreeHandler.updateShapeSelection)
                        tmp_shape.setEnableDisableCallback(
                            self.TreeHandler.updateShapeEnabling)

    def append_geo_to_shape(self, shape, geo):
        if -1e-5 <= geo.length < 1e-5:  # TODO adjust import for this
            return

        if self.ui.actionSplitLineSegments.isChecked():
            if isinstance(geo, LineGeo):
                diff = (geo.Pe - geo.Ps) / 2.0
                geo_b = deepcopy(geo)
                geo_a = deepcopy(geo)
                geo_b.Pe -= diff
                geo_a.Ps += diff
                shape.append(geo_b)
                shape.append(geo_a)
            else:
                shape.append(geo)
        else:
            shape.append(geo)

        if isinstance(geo, HoleGeo):
            shape.type = 'Hole'
            shape.closed = 1  # TODO adjust import for holes?
            if g.config.machine_type == 'drag_knife':
                shape.disabled = True
                shape.allowedToChange = False

    def addtoLayerContents(self, shape, lay_nr):
        # Check if the layer already exists and add shape if it is.
        for LayCon in self.layerContents:
            if LayCon.nr == lay_nr:
                LayCon.shapes.append(shape)
                shape.parentLayer = LayCon
                return

        # If the Layer does not exist create a new one.
        LayerName = self.valuesDXF.layers[lay_nr].name
        self.layerContents.append(LayerContent(lay_nr, LayerName, [shape]))
        shape.parentLayer = self.layerContents[-1]

    def loadProject(self, filename):
        """
        Load all variables from file
        """
        # since Py3 has no longer execfile -  we need to open it manually
        file_ = open(filename, 'r')
        str_ = file_.read()
        file_.close()
        self.d2g.load(str_)

    def saveProject(self):
        """
        Save all variables to file
        """
        prj_filename = self.showSaveDialog(
            self.tr('Save project to file'),
            "Project files (*%s)" % c.PROJECT_EXTENSION)
        save_prj_filename = file_str(prj_filename[0])

        # If Cancel was pressed
        if not save_prj_filename:
            return

        (beg, ende) = os.path.split(save_prj_filename)
        (fileBaseName, fileExtension) = os.path.splitext(ende)

        if fileExtension != c.PROJECT_EXTENSION:
            if not QtCore.QFile.exists(save_prj_filename):
                save_prj_filename += c.PROJECT_EXTENSION

        pyCode = self.d2g.export()
        try:
            # File open and write
            f = open(save_prj_filename, "w")
            f.write(str_encode(pyCode))
            f.close()
            logger.info(self.tr("Save project to FILE was successful"))
        except IOError:
            QMessageBox.warning(g.window,
                                self.tr("Warning during Save Project As"),
                                self.tr("Cannot Save the File"))

    def closeEvent(self, e):
        logger.debug(self.tr("Closing"))
        # self.writeSettings()
        e.accept()

    def readSettings(self):
        settings = QtCore.QSettings("dxf2gcode", "dxf2gcode")
        settings.beginGroup("MainWindow")
        self.resize(settings.value("size", QtCore.QSize(800, 600)).toSize())
        self.move(settings.value("pos", QtCore.QPoint(200, 200)).toPoint())
        settings.endGroup()

    def writeSettings(self):
        settings = QtCore.QSettings("dxf2gcode", "dxf2gcode")
        settings.beginGroup("MainWindow")
        settings.setValue("size", self.size())
        settings.setValue("pos", self.pos())
        settings.endGroup()
예제 #20
0
from core.project import Project

t = task.Task()
t.task_name = 'Clearing'
t.task_segments[0].duration = 20

for ts in t.task_segments:
    if isinstance(ts, TaskSegment):
        print(ts.start, ts.duration)

print('Duration of Clearing is: ' + str(t.get_duration()))
print('Virtual Duration of Clearing is: ' + str(t.get_virtual_duration()))

print('')

p = Project()
p.add_task(t)

p.tasks[0].set_duration(50)

clearing = p.tasks[0]
clearing1 = clearing.task_segments[0]

clearing.split_task(clearing1, 10)

clearing.split_task(clearing.task_segments[1], 30)

print(clearing.set_duration(40))

for t in p.tasks:
    print('---')
예제 #21
0
 def setUp(self):
     super(TestProject, self).setUp()
     self.project = Project(title="TestProject",
                            fixedData="FixedTest",
                            movingData="MovingTest",
                            isReference=True)
예제 #22
0
# Authentication needs only be done once. To improve processing time, next
# time running the script, comment out the following line. Session will
# automatically scan if there is a need for reauthentication. If so, will
# raise an exception.
if (session.is_valid()):
    session.authenticate(input("Email: ").strip(), input("Password :"******"cs1010s-1920s2", 1821)
#
# If project.mproj is present, or you want to transfer job from previous
# batch, just use Project.load(). It will scan and process the preexisting
# project.mproj.
project = Project.load()  #Project.of(session, "meth-alpha", 1821)

# If starting anew, the following command will delete permanently(!) dumps,
# submissions, logs, templates, and session cookies. Will need to re-login.
project.reset()

# The following command will export and save the current Project into
# project.mproj. Next time, can just load the Project instead of creating a
# new Project.
project.export()

# The following command will download all submissions from all missions in
# the course. The list of missions is stored in project.mproj.
project.dump_all(session)

# The following command will unpack all downloaded zips into submissions.
예제 #23
0
    if args.config is None:
        print("ERROR: Missing path to config file.")
        sys.exit(1)


    config = ProjectConfig(args.config)
    config.parse()

    print("=" * 33 + " CONFIGURATION " + "=" * 32)
    print("REPOSITORY: " + config.get_repository())
    print("BRANCH: " + config.get_repository_branch())
    print("PROJECT ROOT: " + config.get_project_root_path())
    print("WWW DIRECTORY: " + config.get_project_www_path())
    print("COMPOSE PATH: " + config.get_project_compose_path())

    project = Project(config)
    server = Server(config)
    print()

    print("=" * 31 + " STOPPING PROJECT " + "=" * 31)
    server.stop()
    print()

    print("=" * 31 + " CREATING PROJECT " + "=" * 31)
    project.create_project()
    print()

    print("=" * 31 + " CLONING PROJECT " + "=" * 32)
    project.clone_repository()
    print()
예제 #24
0
def getProjectByName(projectName):
    projectPath = "projects/" + os.path.basename(projectName)
    return Project(projectPath)
예제 #25
0
class CmdXmitState(CmdLoadELF):
    keywords = ["xmitstate"]
    description = "Sets a hook on a function, emmits an executable state and add the dump to frankenstein"

    parser = argparse.ArgumentParser(prog=keywords[0], description=description)

    parser.add_argument("target", help="Target function", type=auto_int)

    """
    Receive state dump
    """
    def xmit_state_hci_callback(self, record):
        hcipkt = record[0]
        if not issubclass(hcipkt.__class__, hci.HCI_Event):
            return

        #State report
        if hcipkt.event_code == 0xfc:
            saved_regs, cont = struct.unpack("II", hcipkt.data[:8])
            if cont != 0:
                log.info("Receiving firmware state: regs@0x%x cont@0x%x" % (saved_regs, cont))
                self.segment_data = []
                self.segments = {}
                self.succsess = True
                self.saved_regs = saved_regs
                self.cont = cont

            else:
                if not self.succsess:
                    return
                log.info("Received fuill firmware state")

                groupName = datetime.now().strftime("internalBlue_%m.%d.%Y_%H.%M.%S")
                self.project = Project("projects/"+self.internalblue.fw.FW_NAME)
                self.project.add_group(groupName)
                self.project.deactivate_all_groups()
                self.project.set_active_group(groupName, True)
                self.project.save()
                self.project.add_symbol(groupName, "cont", self.cont|1)
                self.project.add_symbol(groupName, "get_int", symbols["get_int"])
                self.project.add_symbol(groupName, "set_int", symbols["set_int"])
                self.project.add_symbol(groupName, "saved_regs", self.saved_regs)
                for segment_addr in self.segments:
                    self.project.add_segment(groupName, "", segment_addr, "".join(self.segments[segment_addr]))

                self.project.save()

        if hcipkt.event_code == 0xfb:
            segment_addr,size,current = struct.unpack("III", hcipkt.data[:12])
            self.segment_data += [hcipkt.data[12:]]

            #Check if we have missed an HCI event
            if segment_addr + len(self.segment_data)*128 != current + 128:
                if self.succsess:
                    print( hex(segment_addr), hex(len(self.segment_data)*128), hex( current + 128))
                    log.info("Failed to receive state")
                self.succsess = False
                
            #Fully received memory dumo
            if len(self.segment_data)*128 == size:
                log.info("Received segment 0x%x - 0x%x" % (segment_addr, segment_addr+size))
                self.segments[segment_addr] = self.segment_data
                self.segment_data = []

    """
    Command implementation
    """
    def work(self):
        args = self.getArgs()
        if not args:
            return True

        # Initialize callbacks for xmitstate
        global CmdXmitStateInitialized

        if not CmdXmitStateInitialized:

            # disable uart_SetRTSMode if we know its location
            if self.internalblue.fw.FW_NAME == "CYW20735B1":
                self.internalblue.patchRom(0x3d32e, b"\x70\x47\x70\x47")
            elif self.internalblue.fw.FW_NAME == "CYW20819A1":
                self.internalblue.patchRom(0x2330e, b"\x70\x47\x70\x47")

            # and now let's enable the callbacks
            self.internalblue.registerHciCallback(self.debug_hci_callback)
            self.internalblue.registerHciCallback(self.xmit_state_hci_callback)
            CmdXmitStateInitialized = True


        patch = "projects/%s/gen/xmit_state.patch" % self.internalblue.fw.FW_NAME
        print(patch)
        if not os.path.exists(patch):
            log.warn("Could not find file %s" % patch)
            return False

        entry = self.load_ELF(patch)
        if entry == False:
            log.warn("Failed to load patch ELF %s" % patch)
            return False

        target = struct.pack("I", args.target | 1)
        self.writeMem(symbols["xmit_state_target"], target)

        self.launchRam(entry-1)

        return entry != False