Example #1
0
    def exportAll(self,
                  file_path: QUrl,
                  notify_progress: Optional["Signal"] = None) -> None:
        """
        Export all materials to a certain file path.
        :param file_path: The path to export the materials to.
        """
        registry = CuraContainerRegistry.getInstance()

        # Create empty archive.
        try:
            archive = zipfile.ZipFile(file_path.toLocalFile(),
                                      "w",
                                      compression=zipfile.ZIP_DEFLATED)
        except OSError as e:
            Logger.log(
                "e",
                f"Can't write to destination {file_path.toLocalFile()}: {type(e)} - {str(e)}"
            )
            error_message = Message(text=catalog.i18nc(
                "@message:text",
                "Could not save material archive to {}:").format(
                    file_path.toLocalFile()) + " " + str(e),
                                    title=catalog.i18nc(
                                        "@message:title",
                                        "Failed to save material archive"),
                                    message_type=Message.MessageType.ERROR)
            error_message.show()
            return

        materials_metadata = registry.findInstanceContainersMetadata(
            type="material")
        for index, metadata in enumerate(materials_metadata):
            if notify_progress is not None:
                progress = index / len(materials_metadata)
                notify_progress.emit(progress)
            if metadata["base_file"] != metadata[
                    "id"]:  # Only process base files.
                continue
            if metadata[
                    "id"] == "empty_material":  # Don't export the empty material.
                continue
            material = registry.findContainers(id=metadata["id"])[0]
            suffix = registry.getMimeTypeForContainer(
                type(material)).preferredSuffix
            filename = metadata["id"] + "." + suffix
            try:
                archive.writestr(filename, material.serialize())
            except OSError as e:
                Logger.log(
                    "e",
                    f"An error has occurred while writing the material \'{metadata['id']}\' in the file \'{filename}\': {e}."
                )
Example #2
0
 def save(self, filename: QUrl) -> None:
     logging.info("Exporting to %s", filename.toLocalFile())
     f = open(filename.toLocalFile(), "wt")
     start_code = self.getSettingValue("start_code").strip()
     if start_code != "":
         f.write(start_code + "\n")
     dialect = PluginRegistry.getInstance().createInstance(GCodeDialect, "CompatibilityDialect")
     assert dialect is not None
     for move in self.getMoves():
         f.write("%s\n" % (dialect.convertMove(move)))
     end_code = self.getSettingValue("end_code").strip()
     if end_code != "":
         f.write(end_code + "\n")
     f.close()
Example #3
0
    def removeBookmark(self, spath):
        if not self.written:
            return

        if not os.path.exists(self.config_path):
            self.written = False
            return

        url = pathlib.Path(spath).as_uri()

        settings_qt5 = QSettings(self.config_path, QSettings.IniFormat)
        shortcuts = ray.getListInSettings(settings_qt5, 'FileDialog/shortcuts')

        for sc in shortcuts:
            sc_url = QUrl(sc)
            if sc_url.isLocalFile() and sc_url.toLocalFile() == spath:
                shortcuts.remove(sc)
                break
        else:
            self.written = False
            return

        settings_qt5.setValue('FileDialog/shortcuts', shortcuts)
        settings_qt5.sync()
        self.written = False
Example #4
0
 def importProfile(self, file_url: QUrl) -> Dict[str, str]:
     if not file_url.isValid():
         return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
     path = file_url.toLocalFile()
     if not path:
         return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
     return self._container_registry.importProfile(path)
Example #5
0
 def dropEvent(self, e):
     if len(e.mimeData().urls()) == 1:
         file = QUrl.toLocalFile(e.mimeData().urls()[0])
         self.load_and_prep_query_mesh(DataSet._read(file))
     else:
         error_dialog = QtWidgets.QErrorMessage(parent=self)
         error_dialog.showMessage("Please drag only one mesh at the time.")
Example #6
0
 def importProfile(self, file_url: QUrl) -> Dict[str, str]:
     if not file_url.isValid():
         return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
     path = file_url.toLocalFile()
     if not path:
         return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
     return cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().importProfile(path)
 def exportProfile(self, instance_id: str, file_url: QUrl, file_type: str) -> None:
     if not file_url.isValid():
         return
     path = file_url.toLocalFile()
     if not path:
         return
     self._container_registry.exportProfile(instance_id, path, file_type)
Example #8
0
 def exportProfile(self, instance_id: str, file_url: QUrl, file_type: str) -> None:
     if not file_url.isValid():
         return
     path = file_url.toLocalFile()
     if not path:
         return
     self._container_registry.exportProfile(instance_id, path, file_type)
Example #9
0
 def importProfile(self, file_url: QUrl):
     if not file_url.isValid():
         return
     path = file_url.toLocalFile()
     if not path:
         return
     return self._container_registry.importProfile(path)
Example #10
0
    def make_bookmark(self, spath):
        if self.written:
            return

        if not os.path.exists(self.config_path):
            #do not write shortcuts if file was not created by Qt5 himself
            return

        url = pathlib.Path(spath).as_uri()

        settings_qt5 = QSettings(self.config_path, QSettings.IniFormat)
        if not settings_qt5.isWritable():
            return

        shortcuts = ray.get_list_in_settings(settings_qt5,
                                             'FileDialog/shortcuts')

        for sc in shortcuts:
            sc_url = QUrl(sc)
            if sc_url.isLocalFile() and sc_url.toLocalFile() == spath:
                return

        shortcuts.append(url)

        settings_qt5.setValue('FileDialog/shortcuts', shortcuts)
        settings_qt5.sync()
        self.written = True
Example #11
0
    def exportQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", file_url: QUrl, file_type: str) -> None:
        if not file_url.isValid():
            return
        path = file_url.toLocalFile()
        if not path:
            return

        container_list = [n.getContainer() for n in quality_changes_group.getAllNodes() if n.getContainer() is not None]
        self._container_registry.exportQualityProfile(container_list, path, file_type)
Example #12
0
    def exportQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", file_url: QUrl, file_type: str) -> None:
        if not file_url.isValid():
            return
        path = file_url.toLocalFile()
        if not path:
            return

        container_list = [n.getContainer() for n in quality_changes_group.getAllNodes() if n.getContainer() is not None]
        self._container_registry.exportQualityProfile(container_list, path, file_type)
Example #13
0
 def _readLocalFile(self, file: QUrl) -> None:
     from UM.FileHandler.ReadFileJob import ReadFileJob
     filename = file.toLocalFile()
     job = ReadFileJob(
         filename,
         handler=self,
         add_to_recent_files=self.getAddToRecentFilesHint(filename))
     job.finished.connect(self._readWorkspaceFinished)
     job.start()
Example #14
0
 def dropEvent(self, event):
     """ Object Method
         Params: QDropEvent event -> the drop object
         Return: None
         This method is called when a drop event occurs.
         The CSS file's path is sent to StyleScreen.addStyle().
     """
     print(type(event))
     url = QUrl(event.mimeData().urls()[0])
     self.screen.addStyle(url.toLocalFile())
Example #15
0
 def _readLocalFile(self,
                    file: QUrl,
                    add_to_recent_files_hint: bool = True):
     # We need to prevent circular dependency, so do some just in time importing.
     from UM.Mesh.ReadMeshJob import ReadMeshJob
     filename = file.toLocalFile()
     job = ReadMeshJob(filename,
                       add_to_recent_files=add_to_recent_files_hint)
     job.finished.connect(self._readMeshFinished)
     job.start()
Example #16
0
 def eemport(self):
     file_name = QFileDialog.getOpenFileUrl(self.centralwidget,
                                            caption="Open image settings as text.",
                                            filter="Text file (*.txt)",
                                            supportedSchemes=["txt"])
     file_name = QUrl.toLocalFile(file_name[0])
     if file_name != "":
         with open(file_name, "r") as f:
             d = literal_eval(f.read())
         self.load_dict(d)
Example #17
0
 def _on_map_dir_chaged(self):
     url = QUrl(self.map_dir)
     map_dir = QDir(url.toLocalFile()).path()
     self.map_info = get_map_info(map_dir)
     self.map_size = round(max(self.map_info.size.w, self.map_info.size.h))
     self.map_name = '{} ({}x{})'.format(self.map_info.name,
                                         self.map_info.size.w,
                                         self.map_info.size.h)
     self.dot_size = self._get_dot_size()
     self.preview = QUrl.fromLocalFile(self.map_info.preview).toString()
Example #18
0
 def _readLocalFile(self,
                    file: QUrl,
                    add_to_recent_files_hint: bool = True) -> None:
     from UM.FileHandler.ReadFileJob import ReadFileJob
     filename = file.toLocalFile()
     job = ReadFileJob(filename,
                       handler=self,
                       add_to_recent_files=add_to_recent_files_hint)
     job.finished.connect(self._readWorkspaceFinished)
     job.start()
    def dropEvent(self, dropEvent):
        filepaths = [
            Path(QUrl.toLocalFile(url)) for url in dropEvent.mimeData().urls()
        ]
        starting_lane_index = self.rowAt(dropEvent.pos().y())
        # Last row is the button.
        if starting_lane_index == self.model().rowCount() - 1:
            starting_lane_index = -1

        self.addFilesRequestedDrop.emit(filepaths, starting_lane_index)
Example #20
0
    def to_local_file(self, url: QUrl) -> str:
        """
        Convert the given QUrl to its local path equivalent.

            >>> to_local_file("file:///home/username/nuxeo")
            /home/username/nuxeo
            >>> to_local_file("file:///C:/Users/username/nuxeo")
            C:\\Users\\username\\nuxeo

        """
        return abspath(url.toLocalFile())
Example #21
0
    def to_local_file(self, url: QUrl) -> str:
        """
        Convert the given QUrl to its local path equivalent.

            >>> to_local_file("file:///home/username/nuxeo")
            /home/username/nuxeo
            >>> to_local_file("file:///C:/Users/username/nuxeo")
            C:\\Users\\username\\nuxeo

        """
        return abspath(url.toLocalFile())
Example #22
0
    def exportQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", file_url: QUrl, file_type: str) -> None:
        if not file_url.isValid():
            return
        path = file_url.toLocalFile()
        if not path:
            return

        container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
        container_list = [cast(InstanceContainer, container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])[0])]  # type: List[InstanceContainer]
        for metadata in quality_changes_group.metadata_per_extruder.values():
            container_list.append(cast(InstanceContainer, container_registry.findContainers(id = metadata["id"])[0]))
        cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().exportQualityProfile(container_list, path, file_type)
Example #23
0
 def _map_to_signal(self, url: QUrl):
     """
     This slot delegates clicked link signal to show the same html as
     before (eg. link to a point in the term has been clicked)
     or to delegates the filename given in the link as emitted
     signal_link_clicked(filename) signal.
     """
     if url.fileName() == "" and url.path() == "/":
         logging.debug(str(url))
         self.ui.contentWebView.setHtml(self._html, url)
     else:
         self.signal_link_clicked.emit(url.toLocalFile().split("/")[-1])
Example #24
0
 def export(self):
     d = self.get_dict()
     default = QUrl(f"file:project.txt")
     file_name = QFileDialog.getSaveFileUrl(self.centralwidget,
                                            caption="Save image settings as text.",
                                            filter="Text file (*.txt)",
                                            directory=default,
                                            supportedSchemes=["txt"])
     file_name = QUrl.toLocalFile(file_name[0])
     if file_name != "":
         with open(file_name, "w") as f:
             f.write(str(d))
Example #25
0
    def urlToLocalFile(self, u: QtCore.QUrl) -> str:
        """Convert QUrl to local file name string

        Parameters
        ----------
        u
            URL to convert

        Returns
        -------
        File name
        """
        return u.toLocalFile()
Example #26
0
    def parentUrl(self, u: QtCore.QUrl) -> QtCore.QUrl:
        """Get URL of directory containing `u`

        Parameters
        ----------
        u
            URL to get parent directory for

        Returns
        -------
        URL to `u`'s parent
        """
        return QtCore.QUrl.fromLocalFile(str(Path(u.toLocalFile()).parent))
Example #27
0
    def dropEvent(self, event):

        #print(event.dropAction() == Qt.CopyAction)

        #url = QUrl()

        links = []
        for url in event.mimeData().urls():
            url = QUrl(url)
            links.append(url.toLocalFile())
        sys.modules['scr.core'].core.copy(sys.modules['scr.core'].core, links,
                                          os.getcwd())
        self.refresh()
Example #28
0
    def pasteCB(self):  #CLIPBOARD
        print("paste")
        print(self.app.clipboard().mimeData().urls())

        links = []
        mimeurls = self.app.clipboard().mimeData().urls()
        for url in mimeurls:
            url = QUrl(url)
            links.append(url.toLocalFile())

        cp = sys.modules['scr.core'].core.copy
        cp(sys.modules['scr.core'].core, self.sourceDir, links, os.getcwd())
        self.refresh()

        pass
Example #29
0
    def requestPixmap(self, id, size):
        url = QUrl(id)
        query = QUrlQuery(url.query())
        map_dir = QDir(url.toLocalFile()).path()
        dot_size = round(float(query.queryItemValue('dot_size')))
        should_flip = query.queryItemValue('flip') in ['True', 'true']
        opacity = round(float(query.queryItemValue('opacity')))

        try:
            img, size = self._generate_heatmap(map_dir, dot_size, opacity)
            if should_flip:
                img = flip(img)
            p = QPixmap.fromImage(img.toqimage())
            return p, size
        except Exception:
            return QPixmap(), QSize(-1, -1)
Example #30
0
    def exportAll(self, file_path: QUrl) -> None:
        """
        Export all materials to a certain file path.
        :param file_path: The path to export the materials to.
        """
        registry = CuraContainerRegistry.getInstance()

        archive = zipfile.ZipFile(file_path.toLocalFile(), "w", compression = zipfile.ZIP_DEFLATED)
        for metadata in registry.findInstanceContainersMetadata(type = "material"):
            if metadata["base_file"] != metadata["id"]:  # Only process base files.
                continue
            if metadata["id"] == "empty_material":  # Don't export the empty material.
                continue
            material = registry.findContainers(id = metadata["id"])[0]
            suffix = registry.getMimeTypeForContainer(type(material)).preferredSuffix
            filename = metadata["id"] + "." + suffix
            archive.writestr(filename, material.serialize())
Example #31
0
    def insertFromMimeData(self, mime):

        if mime.hasImage():
            tag = datetime.datetime.now().time().strftime("%H%M%S")
            url = QUrl("dropped_image_" + str(tag))
            self.dropImage(url, mime.imageData())
            mime.imageData().save("/tmp/" + url.toString(), "png") 
        elif mime.hasUrls():
            for url in mime.urls():
                info = QFileInfo(url.toLocalFile()) 
                ext = info.suffix().lower().encode('latin-1')
                if ext in QImageReader.supportedImageFormats():
                    print(str(info.filePath()))
                    self.dropImage(url, info.filePath())
                else:
                    self.dropTextFile(url)
        else:
            super().insertFromMimeData(mime)
Example #32
0
    def save(self):
        width = self.validate(self.label_18, validate_int, self.widthLineEdit.text(),
                              positive=True)
        height = self.validate(self.label_19, validate_int, self.heightLineEdit.text(),
                               positive=True)

        default = QUrl(f"file:{self.fileNameLineEdit.text()}")
        file_name = QFileDialog.getSaveFileUrl(self.centralwidget,
                                               caption="Save image as PNG or JPEG.",
                                               filter="PNG file (*.png);;JPEG file (*.jpg)",
                                               directory=default,
                                               supportedSchemes=["png", "jpg"])
        file_name = QUrl.toLocalFile(file_name[0])

        if file_name != "":
            img = self.img.copy()
            img.thumbnail((width, height))
            img.save(file_name, quality=self.qualitySlider.value())
Example #33
0
 def importProfile(self, file_url: QUrl) -> Dict[str, str]:
     if not file_url.isValid():
         return {
             "status":
             "error",
             "message":
             catalog.i18nc("@info:status", "Invalid file URL:") + " " +
             str(file_url)
         }
     path = file_url.toLocalFile()
     if not path:
         return {
             "status":
             "error",
             "message":
             catalog.i18nc("@info:status", "Invalid file URL:") + " " +
             str(file_url)
         }
     return self._container_registry.importProfile(path)
Example #34
0
    def convert(self, pathToFile):
        pathToFile = QUrl(pathToFile).toLocalFile()
        images = []
        for i in self._listOfImg:
            url = QUrl()
            url.setUrl(i)

            if url.isLocalFile():
                img = Image.open(url.toLocalFile())
            else:
                img = Image.open(urlopen(i))

            if img.mode == "RGBA":
                img = img.convert('RGB')
            images.append(img)

        images.pop(0).save(pathToFile,
                           "PDF",
                           append_images=images,
                           save_all=True)
Example #35
0
    def _download_blocklist_url(self, url: QUrl) -> None:
        """Take a blocklist url and queue it for download.

        Args:
            url: url to download
        """
        if url.scheme() == "file":
            # The URL describes a local file on disk if the url scheme is
            # "file://". We handle those as a special case.
            filename = url.toLocalFile()
            if os.path.isdir(filename):
                for entry in os.scandir(filename):
                    if entry.is_file():
                        self._import_local(entry.path)
            else:
                self._import_local(filename)
        else:
            download = downloads.download_temp(url)
            self._in_progress.append(download)
            download.finished.connect(
                functools.partial(self._on_download_finished, download))
Example #36
0
	def saveAnalogSignals(self, data, fileurl):
		url = QUrl(fileurl)
		filename = url.toLocalFile()
		signals = data.analog_signals.T
		framerate = data.framerate
		samplerate = data.analogSamplerate
		nsamples = signals.shape[0]
		config = data.config
		
		displacement = signals[:,1] * config.displacement_scale
		load = signals[:,0] * config.force_scale
		
		outdata = np.zeros((nsamples, 4))
		outdata[:, 0] = np.arange(nsamples) / samplerate
		outdata[:, 1] = np.arange(nsamples) * (framerate/samplerate)
		outdata[:, 2] = displacement
		outdata[:, 3] = load
		
		header = 'time(s) video_frame displacement(m) load(N)'
		format = ('%1.8e', '%8d', '%1.8e', '%1.8e')
		np.savetxt(filename, outdata, fmt=format, header = header)
Example #37
0
    def onAnchorClicked(self, url: QUrl):
        from notes.ui.MainWindow import MainWindow
        import webbrowser

        host = url.host()
        scheme = url.scheme()

        if scheme == "http" or scheme == "https":
            webbrowser.open(url.toString())
        elif scheme == "notesmanager":
            url.setScheme("file")

            local_path = url.toLocalFile()
            query = QUrlQuery(url)
            uuid = query.queryItemValue("uuid")

            if local_path == self.notebook.attachment_base.filename:
                self.noteViewManager.openNote(self.noteViewManager.notebook.get_note_by_uuid(uuid))
            else:
                spawn = MainWindow(None, local_path, uuid)
                spawn.show()
Example #38
0
	def saveImageSeries(self, data, analysis_overlay, frames, folder_url, frameRange=True, addAnalogSignalPlot=False):
		url = QUrl(folder_url)
		folder = url.toLocalFile()
		extension = '.png'
		frames = frames.toVariant()
		if frameRange:
			frames = range(*(int(s) for s in frames))
		else:
			frames = [int(s) for s in frames]
		
		if addAnalogSignalPlot:
			width = data.image_width
			plot_height = int(data.image_height * 0.25)
			plot, plot_area = self.get_analog_signals_plot(data, width, plot_height)
			master_image = QImage(width, data.image_height + plot_height, QImage.Format_ARGB32)
			painter = QPainter(master_image)
			
		for frame in frames:
			filename = os.path.join(folder, '{:06d}{}'.format(frame, extension))
			print ('Saving', filename)
			snapshot = self.get_frame_image(data, analysis_overlay, frame)
			if addAnalogSignalPlot:
				painter.drawImage(0,0, snapshot)
				painter.drawImage(0, data.image_height, plot)
				cursor_x = plot_area[0] + frame/data.nFrames * plot_area[2]
				cursor_y1 = data.image_height + plot_area[1]
				cursor_y2 = data.image_height + plot_area[1] + plot_area[3]
				painter.setPen(QColor(0,0,255))
				painter.drawLine(cursor_x, cursor_y1, cursor_x, cursor_y2)
				img = master_image
			else:
				img = snapshot
			if not img.save(filename):
					print('Error saving image.')
		
		if addAnalogSignalPlot:
			painter.end()
Example #39
0
	def saveImage(self, data, analysis_overlay, frame, fileurl):
		url = QUrl(fileurl)
		filename = url.toLocalFile()
		img = self.get_frame_image(data, analysis_overlay, frame)
		if not img.save(filename):
			print('Error saving image.')
Example #40
0
 def _readLocalFile(self, file: QUrl) -> None:
     from UM.FileHandler.ReadFileJob import ReadFileJob
     job = ReadFileJob(file.toLocalFile(), handler = self)
     job.finished.connect(self._readWorkspaceFinished)
     job.start()
Example #41
0
from PyQt5.QtCore import QUrl
url = QUrl("file:///.file/id=6571367.36737433")
f = url.toLocalFile()
print f
#print url.toString()