def setup_app(self): self.setupActions() splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) self.tree = Tree() self.editor = Editor() self.tab_widget = QtGui.QTabWidget() self.preview = Preview() self.pdf_pane = PDFPane() self.tab_widget.addTab(self.preview, "HTML") self.tab_widget.addTab(self.pdf_pane, "PDF") self.file_path = None self.output_html_path = None self.setCentralWidget(splitter) splitter.addWidget(self.tree) splitter.addWidget(self.editor) splitter.addWidget(self.tab_widget) self.setWindowTitle("Sphinx Docs Editor") self.createMenus() self.createToolBars() self.showMaximized()
def _setup_view(self) -> None: """ Set up components of the GUI """ self._navigator = Navigator(self._master, self.handle_move_callback, self.handle_jump_callback, bg=self._bg) self._navigator.pack(side=tk.TOP) frame = tk.Frame(self._master, bg=self._bg) frame.pack(side=tk.TOP) self._classifier = Classifier(frame, self.handle_select_callback, bg=self._bg) self._classifier.pack(side=tk.LEFT) self._preview = Preview(frame, PREVIEW_WIDTH, PREVIEW_HEIGHT, callback=self._handle_preview_click) self._preview.pack(side=tk.LEFT) self._master.config(bg=self._bg) self._master.title("poprev") self._master.protocol("WM_DELETE_WINDOW", self._exit)
def __init__(self, master, callback: Callable[[int], None], bg: str = "#ffffff"): """ Initialise this Classifier :param master: parent container of this Classifier :param callback: function to call when the ColourSelector sub-component of this Classifier is clicked :param bg: the background colour of this Classifier """ super().__init__(master, bg=bg, padx=5) self._callback = callback self._preview = Preview(self, REF_CANVAS_WIDTH, REF_CANVAS_HEIGHT) self._preview.pack(side=tk.TOP) self._selector = ColourSelector( self, ["#000000", "#555555", "#aaaaaa", "#ffffff"], ["#ffffff", "#aaaaaa", "#555555", "#000000"], self._callback, bg=bg) self._selector.pack(side=tk.TOP) self._img = None
def __init__(self): # init pygame components pygame.init() pygame.display.set_caption(GAME_TITLE) self._screen = pygame.display.set_mode(SCREEN_RESOLUTION) self._background = pygame.Surface(self._screen.get_size()).convert() self._background.fill(colors.WHITE) self._font = pygame.font.SysFont(None, 24) self._set_message("Press PAUSE key to start!", colors.GREEN) # init game components rect_pixel_length = 20 self._field = GameField(self._screen, GRID_COLUMNS, GRID_ROWS, rect_pixel_length) self._preview = Preview(self._screen, SCREEN_RESOLUTION[0] - 100, 20, Brick.DIMENSION, int(rect_pixel_length / 2)) self._figure_factory = FigureFactory(self._field) self._figure = next(self._figure_factory) self._next_figure = next(self._figure_factory) self._score = Score() self._control = Control(START_FPS) # init speed and game state self._stepover = START_GAME_STEPOVER self._nostep = self._stepover self._looping = True self._was_started = False self._has_stopped = False self._is_paused = True
def getPreviewXML(self, sources=None): # Preview returns an empty preview tag if it fails preview = Preview() raw_preview_xml = preview.preview(sources) if raw_preview_xml: try: preview_xml = etree.fromstring(raw_preview_xml) except SyntaxError, ex: # FIX ME This is going to go bad at some point logger.error('Error with xml from preview:\n %s' % str(ex)) pass
def simple(sites, main_index): # simple test without cleanup: assert len(sites) > 1 d = Delaunay(test = True) d.include(sites[main_index]) for site in sites: if site == sites[main_index]: continue d.include(site) if not d.fail_site is None: Preview.voronoi(d, title = "Fail") VoronoiDiagram.show(d, title = "Without cleanup")
def main(self, filename): self.config = _config audio_producer = mod.Decoder(self.config.audio, filename) header_view = ModHeaderView(audio_producer) pattern_view = ModPatternView(audio_producer) root_view = Framer() root_view.add(header_view, makerect(0, 0, self.config.video.width, self.config.video.height / 30)) root_view.add(pattern_view, makerect(0, self.config.video.height / 30, self.config.video.width, self.config.video.height - (self.config.video.height / 30))) video_producer = SurfaceHandler(self.config.video, root_view) state = {'video': {'frames_produced': 0}, 'audio': {'frames_produced': 0}, 'frame': 0, 'elapsed_sec': 0.0} preview = Preview(self.config.video) def get_frames(): # TODO: Move this function into a sequencer video = video_producer.render(state) preview.update_image(video) audio_frames_required = self._audio_frames_to_next_video_frame(state) audio = audio_producer.render(audio_frames_required) state['video']['frames_produced'] += 1 state['audio']['frames_produced'] += audio_frames_required state['frame'] += 1 state['elapsed_sec'] = state['frame'] / self.config.video.fps if video is None or audio is None or preview.is_stop_requested(): return None else: return video, audio preview.show_preview_ui() try: ffmpegger = VideoRunner(self.config) ffmpegger.start(get_frames) finally: preview.destroy_preview_ui()
def show(diagram, title = ''): preview = Preview(title = title, lines=1, columns=1) preview.add_view(diagram, VoronoiDiagram, title) preview.interactive(True) preview.start() while preview.step(): pass
def show(view, title = '', lines = 1, columns = 1): preview = Preview(title = title, lines = lines, columns = columns, painter_class = self.painter_class) preview.add_view(view, title) preview.interactive(True) preview.start() while preview.step(): pass
def update(self, dt): for i in self.buttons: i.update(dt) if i.path is not None: self.root = i.path i.path = None self.LoadImagePaths() if self.is_imagesloaded[2] is not None: self.LoadImagesLabel() self.preview = Preview(self.image_paths, 280, 100) self.is_imagesloaded[2] = None if self.preview is not None: self.preview.update(dt)
def __init__(self, element, composition, timeline): goocanvas.Group.__init__(self) View.__init__(self) Zoomable.__init__(self) self.element = element self.comp = composition self.timeline = timeline self.bg = goocanvas.Rect(height=self.__HEIGHT__, fill_color_rgba=self.__NORMAL__, line_width=0) self.content = Preview(self.element) self.name = goocanvas.Text(x=10, text=os.path.basename( unquote(element.factory.name)), font="Sans 9", fill_color_rgba=0x000000FF, alignment=pango.ALIGN_LEFT) self.start_handle = StartHandle(element, timeline, height=self.__HEIGHT__) self.end_handle = EndHandle(element, timeline, height=self.__HEIGHT__) for thing in (self.bg, self.content, self.start_handle, self.end_handle, self.name): self.add_child(thing) if element: self.zoomChanged() self.normal()
def spawn_shape(self): # new_shape = random.choice([F, L, Z, I, O])() self._shapes.append(self.next_shape) self.cur_shape = self.next_shape self.can_turbo = False self.next_shape = random.choice([F, L, Z, I, O])() self.preview = Preview(self.next_shape)
def createDockWidgets(self): # Palette widget self.palette = QtWidgets.QDockWidget( self.context.getText("dock_widgets", "palette"), self) self.palette.setAllowedAreas(Qt.RightDockWidgetArea) self.palette.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures) paletteWidget = Palette(self.context, self.signals) self.palette.setWidget(paletteWidget) self.palette.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) self.addDockWidget(Qt.RightDockWidgetArea, self.palette) # Tool Properties widget self.toolProperties = ToolProperties( self.context.getText("dock_widgets", "tool_properties"), self.context, self.signals) self.addDockWidget(Qt.RightDockWidgetArea, self.toolProperties) self.toolProperties.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) # Preview self.preview = Preview(self.context.getText("dock_widgets", "preview"), self.context, self.signals, self) self.addDockWidget(Qt.RightDockWidgetArea, self.preview)
def set_sizes(self, h_res, v_res, size): if h_res == "auto": screen = self.screen() self.ppix = screen.physicalDotsPerInchX() self.ppiy = screen.physicalDotsPerInchY() h_res = screen.geometry().width() v_res = screen.geometry().height() #if self.ppix != self.ppiy: # print("WARNING! due to the properties of your screen angles are slightly distorted and length of diagonals are approximations") else: diagonal_res = math.sqrt(int(h_res)**2 + int(v_res)**2) self.ppix = diagonal_res / float(size) # Pixels per inch self.ppiy = self.ppix self.preview = Preview(h_res, v_res, self) self.preview.show() self.h_res, self.v_res = h_res, v_res
def _initEmptyBoard(self): """ :return: the initialized board """ board = [[Square(None, i, j) for j in range(5)] for i in range(5)] board[0][0] = Square(Note(False), 0, 0) board[0][1] = Square(Governance(False), 0, 1) board[0][2] = Square(Relay(False), 0, 2) board[0][3] = Square(Shield(False), 0, 3) board[0][4] = Square(Drive(False), 0, 4) board[1][4] = Square(Preview(False), 1, 4) board[3][0] = Square(Preview(True), 3, 0) board[4][0] = Square(Drive(True), 4, 0) board[4][1] = Square(Shield(True), 4, 1) board[4][2] = Square(Relay(True), 4, 2) board[4][3] = Square(Governance(True), 4, 3) board[4][4] = Square(Note(True), 4, 4) return board
class Classifier(tk.Frame): """ A GUI component that displays an image and allows users to classify the image as one of four colours. """ def __init__(self, master, callback: Callable[[int], None], bg: str = "#ffffff"): """ Initialise this Classifier :param master: parent container of this Classifier :param callback: function to call when the ColourSelector sub-component of this Classifier is clicked :param bg: the background colour of this Classifier """ super().__init__(master, bg=bg, padx=5) self._callback = callback self._preview = Preview(self, REF_CANVAS_WIDTH, REF_CANVAS_HEIGHT) self._preview.pack(side=tk.TOP) self._selector = ColourSelector( self, ["#000000", "#555555", "#aaaaaa", "#ffffff"], ["#ffffff", "#aaaaaa", "#555555", "#000000"], self._callback, bg=bg) self._selector.pack(side=tk.TOP) self._img = None def display_image(self, arr: np.ndarray): """ Display an image on the Preview component of this Classifier. :param arr: the image to display """ self._preview.display_image(arr) def get_selector(self) -> ColourSelector: """ :return: the ColourSelector component of this Classifier. """ return self._selector def display_no_image_warning(self) -> None: """ Display a warning that no reference image is loaded. """ self._preview.delete(tk.ALL) self._preview.create_text(REF_CANVAS_WIDTH / 2, REF_CANVAS_HEIGHT / 2, text="Please load a reference image\n " "by going to File > Load Reference")
def painter_test(n, lines, columns, fps = 25000): # test main-thread execution (previewer run as main thread): preview = Preview(title = "Main-thread test without diagram", lines = lines, columns = columns, fps_limit = fps, painter_class = TestPainter) preview.interactive(True) preview.start() # create tests in different threads for i in xrange(0,n): preview.add_view(i) if not preview.step(): break while preview.step(): pass
def do_test(self, file_name, s = 1, d = 0, mx = 0, my = 0): self.set_cenario(file_name) self.transform(s, s, d, d, mx, my) self.set_limits() label = "Multithread test : " + file_name import platform if platform.system() == "Linux": label += " (Linux)" self.preview_control.start(title = label, lines = self.lines, columns = self.columns, fps_limit = self.fps, painter_class = ArtGalleryPainter) threads = self.thread(self._polygon, self.preview_control) # waiting until previewer terminates while self.preview_control.in_state(Preview.RUNNING): pass else: label += " (Windows)" preview = Preview(title = label, lines = self.lines, columns = self.columns, fps_limit = self.fps, painter_class = ArtGalleryPainter) preview.interactive(True) preview.start() threads = self.thread(self._polygon, preview) while preview.step(): pass # stop tests threads for t in threads: t.stop()
def __init__(self, instance, element, track, timeline): goocanvas.Group.__init__(self) View.__init__(self) Zoomable.__init__(self) self.app = instance self.track = track self.timeline = timeline self.namewidth = 0 self.nameheight = 0 self.bg = goocanvas.Rect(height=self.height, line_width=0) self.content = Preview(element) self.name = goocanvas.Text(x=NAME_HOFFSET + NAME_PADDING, y=NAME_VOFFSET + NAME_PADDING, operator=cairo.OPERATOR_ADD, alignment=pango.ALIGN_LEFT) self.namebg = goocanvas.Rect(radius_x=2, radius_y=2, x=NAME_HOFFSET, y=NAME_VOFFSET, line_width=0) self.start_handle = StartHandle(self.app, element, timeline, height=self.height) self.end_handle = EndHandle(self.app, element, timeline, height=self.height) self.selection_indicator = goocanvas.Rect( visibility=goocanvas.ITEM_INVISIBLE, line_width=0.0, height=self.height) for thing in (self.bg, self.content, self.selection_indicator, self.start_handle, self.end_handle, self.namebg, self.name): self.add_child(thing) for prop, interpolator in element.getInterpolators().itervalues(): self.add_child(Curve(instance, element, interpolator, 50)) self.element = element self.settings = instance.settings self.normal()
def setup_app(self): self.setupActions() splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal) self.tree = Tree() self.editor = Editor() self.highlighter = Highlighter(self.editor.document(), 'rst') self.tab_widget = QtWidgets.QTabWidget() self.preview = Preview() self.pdf_pane = PDFPane() self.tab_widget.addTab(self.preview, "HTML") self.tab_widget.addTab(self.pdf_pane, "PDF") self.file_path = None self.output_html_path = None self.setCentralWidget(splitter) splitter.addWidget(self.tree) splitter.addWidget(self.editor) splitter.addWidget(self.tab_widget) splitter.setSizes([300, 950, 1350]) self.setWindowTitle("Sphinx Docs Editor") self.createMenus() self.createToolBars() self.resize(300 + 950 + 1350, 1400) try: with open('./config.json', 'r') as f: c = json.load(f) path = c['last_folder'] self.openFolder(path) except: pass
def _create_widgets(self): editor_frame = tk.LabelFrame(self, text="Editor") editor_frame.grid(row=0, column=0, sticky="NEWS") editor_frame.columnconfigure(0, weight=1) editor_frame.rowconfigure(0, weight=1) preview_frame = tk.LabelFrame(self, text="Preview") preview_frame.grid(row=0, column=1, sticky="NEWS") preview_frame.columnconfigure(0, weight=1) preview_frame.rowconfigure(0, weight=1) self.__text_field = tk.Text( editor_frame, undo=True, wrap=tk.WORD, font="fixed", ) self.__text_field.grid(sticky="NEWS") self.__text_field.tag_config(self._syntax_error_tag, background="red", foreground="white") self.__preview = Preview(preview_frame, self._on_new_figure_created, self._on_figure_updated)
def main_thread(points, delay, n, lines, columns, fps = 250, test_class = DiagramTest): # test main-thread execution (previewer run as main thread): preview = Preview(title = test_class.__name__ + " - Main-thread test", lines = lines, columns = columns, fps_limit = fps, painter_class = VoronoiDiagram) preview.interactive(True) preview.start() threads = [] # create tests in different threads for i in xrange(0,n): test = test_class(points, delay) threads.append(test) preview.add_view(test.diagram) test.start() if not preview.step(): break while preview.step(): pass # stop tests threads for t in threads: t.stop()
def __init__(self, parent): super(DetailFrame, self).__init__(parent) layout = QVBoxLayout(self) layout.setContentsMargins(20, 15, 20, 20) self.title = Title('', 23) titleLayout = QHBoxLayout() titleLayout.setAlignment(Qt.AlignTop) titleLayout.addWidget(QLabel(' ' * 5)) titleLayout.addWidget(self.title, 1) layout.addLayout(titleLayout, 0) detailLayout = QGridLayout() detailLayout.setColumnStretch(0, self.width() * 0.618) detailLayout.setColumnStretch(1, self.width() * (1 - 0.618)) self.preview = Preview() self.info = Info() detailLayout.addWidget(self.preview, 0, 0) detailLayout.addWidget(self.info, 0, 1) layout.addLayout(detailLayout, 1)
def __initUI(self): """ Initialize the GUI """ # Layout layout = QtGui.QHBoxLayout() self.__mainWidget = QtGui.QWidget() self.__mainWidget.setLayout(layout) self.setCentralWidget(self.__mainWidget) # Kinect image vLayout = QtGui.QVBoxLayout() self.__previewImage = Preview(self.__kinect) vLayout.addWidget(QtGui.QLabel(u"Image directe :")) vLayout.addWidget(self.__previewImage) layout.addLayout(vLayout) # Object image vLayout = QtGui.QVBoxLayout() self.__objectImage = QtGui.QLabel() vLayout.addWidget(QtGui.QLabel(u"Objet à imprimer :")) vLayout.addWidget(self.__objectImage) vLayout.addStretch(1) self.__captureButton = QtGui.QPushButton(u"Photographier") vLayout.addWidget(self.__captureButton) self.__exportButton = QtGui.QPushButton(u"Exporter") vLayout.addWidget(self.__exportButton) layout.addLayout(vLayout) self.__refreshObjectImage() # Center the window geo = self.frameGeometry() geo.moveCenter(QtGui.QDesktopWidget().availableGeometry().center()) self.move(geo.topLeft()) # Title self.setWindowTitle("Photomaton")
class RulerWindow(QWidget): def __init__(self, *args, **kwargs): super(RulerWindow, self).__init__(*args, **kwargs) self.setWindowTitle("Screen Ruler") self.setWindowIcon(QIcon("ruler.ico")) self.initial_dots = [] self.final_dots = [] self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.WindowSystemMenuHint) self.setAttribute(Qt.WA_TranslucentBackground) self.ignored = False self.setMouseTracking(True) self.custom_cursor = self.generate_custom_cursor() #self.setCursor(Qt.BlankCursor) self.setCursor(self.custom_cursor) def set_sizes(self, h_res, v_res, size): if h_res == "auto": screen = self.screen() self.ppix = screen.physicalDotsPerInchX() self.ppiy = screen.physicalDotsPerInchY() h_res = screen.geometry().width() v_res = screen.geometry().height() #if self.ppix != self.ppiy: # print("WARNING! due to the properties of your screen angles are slightly distorted and length of diagonals are approximations") else: diagonal_res = math.sqrt(int(h_res)**2 + int(v_res)**2) self.ppix = diagonal_res / float(size) # Pixels per inch self.ppiy = self.ppix self.preview = Preview(h_res, v_res, self) self.preview.show() self.h_res, self.v_res = h_res, v_res def paintEvent(self, event): painter = QPainter() painter.begin(self) if not self.ignored: self.paint_background(painter) painter.setPen(QColor(255, 0, 255)) painter.setBrush(QColor(0, 0, 0)) for index, i in enumerate(self.initial_dots): painter.setPen(QColor(255, 0, 255)) painter.drawRect(i.x() - 1, i.y() - 1, 2, 2) try: end_point = self.final_dots[index] painter.setPen(QColor(0, 0, 255)) moving = False except IndexError: # There is no end point, so cursor is end point end_point = self.cursor().pos() painter.setPen(QColor(0, 0, 255, 64)) moving = True mid_point = QPoint(end_point.x(), i.y()) painter.drawPolyline(i, mid_point, end_point, i) painter.setPen(QColor(255, 0, 255)) halfx = (mid_point.x() - i.x()) / 2 + i.x() halfy = (end_point.y() - mid_point.y()) / 2 + mid_point.y() # Draw perpendicular magenta lines in each of the triangle's sides' center top_horizontal_half = QPoint(halfx, i.y() + 10) bot_horizontal_half = QPoint(halfx, i.y() - 10) left_vertical_half = QPoint(end_point.x() - 10, halfy) right_vertical_half = QPoint(end_point.x() + 10, halfy) try: hipotenuse = math.sqrt((2 * (halfx - i.x()))**2 + (2 * (halfy - mid_point.y()))**2) scaling_factor = hipotenuse / 10 # To ensure line length = 10 y_change = (2 * (halfx - i.x()) / scaling_factor) x_change = (2 * (halfy - mid_point.y()) / scaling_factor) except ZeroDivisionError: y_change = 0 x_change = 0 top_hipotenuse_half = QPoint(halfx - x_change, halfy + y_change) bot_hipotenuse_half = QPoint(halfx + x_change, halfy - y_change) if hipotenuse >= 20 and moving: # To not be in the way while looking for a second point painter.drawLine(top_horizontal_half, bot_horizontal_half) painter.drawLine(left_vertical_half, right_vertical_half) painter.drawLine(top_hipotenuse_half, bot_hipotenuse_half) painter.setPen(QColor(255, 255, 255)) x_px = abs(int((halfx - i.x()) * 2)) + 1 y_px = abs(int((halfy - mid_point.y()) * 2)) + 1 hipotenuse = abs(hipotenuse) inch_to_cm = 2.54 x_inches = x_px / self.ppix y_inches = y_px / self.ppiy hip_inches = hipotenuse / ((self.ppiy + self.ppix) / 2) x_cm = x_inches * inch_to_cm y_cm = y_inches * inch_to_cm hip_cm = hip_inches * inch_to_cm x_text = str( x_px ) + "px | " + f"{x_cm:7.2f}" + "cm | " + f"{x_inches:7.2f}" + "inch" y_text = str( y_px ) + "px | " + f"{y_cm:7.2f}" + "cm | " + f"{y_inches:7.2f}" + "inch" hip_text = f"{abs(hipotenuse):7.2f}" + "px | " + f"{hip_cm:7.2f}" + "cm | " + f"{hip_inches:7.2f}" + "inch" # in 7.2f -> 7 = max char, 2 = max floating point precision if moving and hipotenuse >= 20: # To not be in the way while looking for a second point painter.drawText(QPoint(halfx, i.y()), x_text) painter.drawText(QPoint(end_point.x(), halfy), y_text) painter.drawText( QPoint(halfx, halfy - 12), hip_text) # 7 = max char, 2 = max floating point precision elif not moving: # drawStaticText is more optimized if it rarely updates painter.drawStaticText(QPoint(halfx, i.y()), QStaticText(x_text)) painter.drawStaticText(QPoint(end_point.x(), halfy), QStaticText(y_text)) painter.drawStaticText(QPoint(halfx, halfy - 12), QStaticText(hip_text)) painter.setPen(QColor(255, 0, 255)) for i in self.final_dots: painter.drawRect(i.x() - 1, i.y() - 1, 2, 2) """if not self.ignored: self.paint_cursor(painter)""" painter.end() def paint_background(self, painter): painter.setBrush(QColor(0, 0, 0, 120)) # Semitransparent brush painter.setPen(Qt.NoPen) corners = self.preview.screen_corners # drawRect(left margin, top margin, width, height) # corners[0] = top left corner # corners[1] = bot right corner # corners[][0] = x component # corners[][1] = y component # black rectangle # topleft corner = (screen left, screen top) # botright corner = (preview left, screen bottom) painter.drawRect(0, 0, corners[0][0], self.v_res) # black rectangle # topleft corner = (preview left, screen top) # botright corner = (preview right, preview top) painter.drawRect(corners[0][0], 0, corners[1][0] - corners[0][0], corners[0][1]) # black rectangle # topleft corner = (preview left, preview bottom) # botright corner = (preview right, screen bottom) painter.drawRect(corners[0][0], corners[1][1], corners[1][0] - corners[0][0], self.v_res - corners[1][1]) # black rectangle # topleft corner = (preview right, screen top) # botright corner = (preview right, screen bot) painter.drawRect(corners[1][0], 0, self.h_res - corners[1][0], self.v_res) painter.setPen(QColor( 255, 255, 255, 1)) # Almost transparent brush, just so there is something there painter.setBrush(QColor( 0, 0, 0, 1)) # Almost transparent brush, just so there is something there # transparent rectangle with blue border # topleft corner = (preview left, preview top) # botright corner = (preview right, preview bottom) painter.drawRect(corners[0][0] - 1, corners[0][1] - 1, corners[1][0] - corners[0][0] + 1, corners[1][1] - corners[0][1] + 1) """painter.setBrush(QColor(255, 255, 255, 255)) painter.drawRect(corners[0][0]+10, # 1 white dot where the cursor is corners[0][1]+10, 1, 1 )""" def mousePressEvent(self, event): if len(self.initial_dots) == len(self.final_dots): self.initial_dots.append(event.pos()) else: self.final_dots.append(event.pos()) self.repaint() self.preview.update() def mouseDoubleClickEvent(self, event): self.final_dots = [] self.initial_dots = [] self.update() self.preview.update() def mouseMoveEvent(self, event): self.preview.update_pos() self.repaint() self.preview.update() def keyPressEvent(self, event): key = event.key() if key in [16777234, 16777235, 16777236, 16777237]: # Arrows cursor = self.cursor() x = cursor.pos().x() y = cursor.pos().y() if key == 16777234: # Left arrow new_x, new_y = (x - 1, y) if key == 16777235: # Up arrow new_x, new_y = (x, y - 1) if key == 16777236: # Right arrow new_x, new_y = (x + 1, y) if key == 16777237: # Down arrow new_x, new_y = (x, y + 1) cursor.setPos(new_x, new_y) elif key == 80: # P key self.ignore_input(not self.ignored) elif key == 16777220: # Enter key # Simulate click self.mousePressEvent(self.cursor()) self.preview.repaint() def ignore_input(self, ignore=True): self.ignored = ignore self.setMouseTracking(not ignore) flags = Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.WindowSystemMenuHint if ignore: flags = flags | Qt.WindowTransparentForInput self.setWindowFlags(flags) self.showFullScreen() if ignore: cursor = Qt.ArrowCursor self.preview.hide() else: self.preview.show() cursor = Qt.BlankCursor self.setCursor(cursor) def generate_custom_cursor(self): print(QPixmap.defaultDepth()) bitmap = QPixmap(QSize(32, 32)) mask = QPixmap(QSize(32, 32)) bitmap.fill(QColor("#ffffff")) mask.fill(QColor("#ffffff")) x, y = Preview.M_SIZE painter = QPainter(bitmap) painter.setPen(QColor("#000000")) painter.drawRect(0, 0, x + 2, y + 2) painter.drawLine(x / 2 + 2, 1, x / 2 + 2, y + 1) painter.drawLine(1, y / 2 + 2, x + 1, y / 2 + 2) painter.end() return QCursor(QBitmap(bitmap), QBitmap(mask), (x + 2) / 2, (y + 2) / 2)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): # super(MainWindow, self).__init__(parent) if sys.platform == 'darwin': # Workaround for Qt issue on OS X that causes QMainWindow to # hide when adding QToolBar, see # https://bugreports.qt-project.org/browse/QTBUG-4300 super(MainWindow, self).__init__(parent, QtCore.Qt.MacWindowToolBarButtonHint) else: super(MainWindow, self).__init__(parent) def setup_app(self): self.setupActions() splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal) self.tree = Tree() self.editor = Editor() self.highlighter = Highlighter(self.editor.document(), 'rst') self.tab_widget = QtWidgets.QTabWidget() self.preview = Preview() self.pdf_pane = PDFPane() self.tab_widget.addTab(self.preview, "HTML") self.tab_widget.addTab(self.pdf_pane, "PDF") self.file_path = None self.output_html_path = None self.setCentralWidget(splitter) splitter.addWidget(self.tree) splitter.addWidget(self.editor) splitter.addWidget(self.tab_widget) splitter.setSizes([300, 950, 1350]) self.setWindowTitle("Sphinx Docs Editor") self.createMenus() self.createToolBars() self.resize(300 + 950 + 1350, 1400) try: with open('./config.json', 'r') as f: c = json.load(f) path = c['last_folder'] self.openFolder(path) except: pass def setupActions(self): """ Set up the top menu actions and keyboard shortcuts. """ # File Menu -------------------------------------------------- self.openAction = QtWidgets.QAction( # QtWidgets.QIcon(":/images/open.png"), "&Open File", self, shortcut="Ctrl+O", statusTip="Open File", triggered=self.openFile) self.openFolderAction = QtWidgets.QAction( # QtWidgets.QIcon(":/images/open.png"), "Open Folder", self, shortcut="Ctrl+Shift+O", statusTip="Open Folder", triggered=self.openFolder) self.saveAction = QtWidgets.QAction( # QtWidgets.QIcon(":/images/save.png"), "&Save File", self, shortcut="Ctrl+S", statusTip="Save File", triggered=self.saveFile) self.saveAsAction = QtWidgets.QAction( # QtWidgets.QIcon(":/images/save.png"), "Save As File", self, shortcut="Ctrl+Shift+S", statusTip="Save File As...", triggered=self.saveFileAs) self.quitAction = QtWidgets.QAction( # QtWidgets.QIcon(':/images/save.png'), "&Quit", self, shortcut="Ctrl+Q", statusTip="Quit", triggered=self.close) # Build Menu -------------------------------------------------- self.buildHTMLAction = QtWidgets.QAction("Build &HTML", self, shortcut="Ctrl+B", statusTip="Build HTML", triggered=self.buildHTML) self.buildPDFAction = QtWidgets.QAction("Build &PDF", self, shortcut="Ctrl+Shift+B", statusTip="Build PDF", triggered=self.buildPDF) self.selectFontAction = QtWidgets.QAction( "Select Font", self, triggered=self.openFontDialog) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.openAction) self.fileMenu.addAction(self.openFolderAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.saveAction) self.fileMenu.addAction(self.saveAsAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.quitAction) self.buildMenu = self.menuBar().addMenu("&Build") self.buildMenu.addAction(self.buildHTMLAction) self.buildMenu.addAction(self.buildPDFAction) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.openAction) self.fileToolBar.addAction(self.openFolderAction) self.fileToolBar.addAction(self.saveAction) self.fileToolBar.addAction(self.selectFontAction) # self.fileToolBar.addAction(self.saveAsAction) # self.fileToolBar.addAction(self.quitAction) self.buildToolBar = self.addToolBar("Build") self.buildToolBar.addAction(self.buildHTMLAction) self.buildToolBar.addAction(self.buildPDFAction) def openFile(self, path=None): """ Ask the user to open a file via the Open File dialog. Then open it in the tree, editor, and HTML preview windows. """ if not path: dialog = OpenDialog() dialog.set_folders_only(False) path = dialog.getOpenFileName( self, "Open File", '', "ReStructuredText Files (*.rst *.txt)") if path: file_path = Path(path[0]) filename = file_path.name tree_dir = file_path.parent.absolute() self.handleFileChanged(tree_dir, filename) def saveFile(self): if self.file_path: text = self.editor.toPlainText() try: f = open(self.tree.get_current_item_path(), "w") f.write(text) f.close() self.buildHTML() except IOError: QtWidgets.QMessageBox.information( self, "Unable to open file: %s" % self.file_path.absolute()) def saveFileAs(self): filename, _ = QtWidgets.QFileDialog.getSaveFileName( self, 'Save File As', '', "ReStructuredText Files (*.rst *.txt)") if filename: text = self.editor.toPlainText() try: f = open(filename, "w") f.write(text) f.close() self.buildHTML() except IOError: QtWidgets.QMessageBox.information( self, "Unable to open file: %s" % filename) def openFolder(self, path=None): """ Ask the user to open a folder (directory) via the Open Folder dialog. Then open it in the tree, editor, and HTML preview windows. """ if not path: dialog = OpenDialog() dialog.set_folders_only(True) path = dialog.getExistingDirectory(self, "Open Folder", '') if path: self.handleFileChanged(path) #, filename='index.rst') with open('./config.json', 'r') as f: c = json.load(f) c['last_folder'] = path with open('./config.json', 'w') as f: json.dump(c, f) def openFontDialog(self): font = QtWidgets.QFontDialog.getFont(self.editor.font()) if font[1]: font = font[0] font.setFixedPitch(True) self.editor.setFont(font) with open('./config.json', 'r') as f: c = json.load(f) c['font_family'] = font.family() c['font_size'] = font.pointSize() with open('./config.json', 'w') as f: json.dump(c, f) def handleFileChanged(self, dir, filename=None): """ This is called whenever the active file is changed. It sets the tree, editor, and preview panes to the new file. """ if not filename: # TODO: find first rst file if index.rst doesn't exist. filename = "index.rst" self.file_path = Path(dir, filename) file_stem = str(self.file_path.stem) #html_str = "build/html/{0}.html".format(file_stem) #self.output_html_path = Path(dir, html_str).absolute() # Load the directory containing the file into the tree. self.tree.load_from_dir(dir) if not self.file_path.endswith('.rst'): try: html_path = os.path.dirname( os.path.relpath(self.tree.get_current_item_path(), dir + '/source')) self.output_html_path = "{0}/build/html/{1}/{2}".format( dir, html_path, filename) print(self.output_html_path) self.preview.load_html(self.output_html_path) except: print(traceback.format_exc()) return # Load the file into the editor self.editor.open_file(self.tree.get_current_item_path()) try: html_path = os.path.dirname( os.path.relpath(self.tree.get_current_item_path(), dir + '/source')) self.output_html_path = "{0}/build/html/{1}/{2}.html".format( dir, html_path, file_stem) except: pass #print(self.tree.get_current_item_path()) # Load corresponding HTML file from pre-built Sphinx docs self.preview.load_html(self.output_html_path) def buildHTML(self): """ Builds the .html version of the active file and reloads it in the preview pane. """ # TODO: make this configurable via a dialog os.chdir(self.file_path.parent) proc = subprocess.Popen(["make", "clean"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in proc.stdout: print("stdout: " + str(line.rstrip(), encoding='utf8')) print('----------------') proc = subprocess.Popen(["make", "html"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) proc.wait() for line in proc.stdout: print("stdout: " + str(line.rstrip(), encoding='utf8')) # Load corresponding HTML file from newly-built Sphinx docs self.preview.load_html(self.output_html_path) def buildPDF(self): """ Builds the .pdf version of the active file. """ # TODO: get this working # TODO: make this configurable via a dialog os.chdir(self.file_path.parent) proc = subprocess.Popen(["make", "latexpdf"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) proc.wait() for line in proc.stdout: print("stdout: " + line.rstrip())
class Menu: root = None is_imagesloaded = [False, False, None] text = None label = pyglet.text.Label("Images Loaded:", font_name='Times New Roman', font_size=12, x=70, y=640, anchor_x='center', anchor_y='center') image_paths = [] buttons = [] preview = None loader_idle = pyglet.image.load_animation("./resources/images/loading.gif") loader_green = pyglet.image.load_animation( "./resources/images/loading2.gif") bin = pyglet.image.atlas.TextureBin() bin_green = pyglet.image.atlas.TextureBin() loader_idle.add_to_texture_bin(bin) loader_green.add_to_texture_bin(bin) loader_sprite = pyglet.sprite.Sprite(img=loader_idle) loader_sprite_green = pyglet.sprite.Sprite(img=loader_green) folder_button_image = pyglet.image.load( './resources/images/button_orange.png') folder_button = Button(70, 170, 125, 100, folder_button_image, "Open folder") exit_button = Button(70, 50, 125, 100, folder_button_image, "Exit") def __init__(self): self.loader_sprite.scale = 0.2 self.loader_sprite.x = 0 self.loader_sprite.y = 700 self.loader_sprite_green.scale = 0.2 self.loader_sprite_green.x = 0 self.loader_sprite_green.y = 700 self.exit_button.SetMouseCallback(ExitCallback) self.folder_button.SetMouseCallback(OpenFolderCallback) self.buttons.append(self.folder_button) self.buttons.append(self.exit_button) def draw(self): pyglet.graphics.draw_indexed(4, pyglet.gl.GL_TRIANGLES, [0, 1, 2, 0, 2, 3], ('v2i', (0, 0, 140, 0, 140, 1080, 0, 1080)), ('c3B', (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))) for i in self.buttons: i.render() if self.is_imagesloaded[1]: self.loader_sprite_green.draw() else: self.loader_sprite.draw() if self.text is not None: self.text.draw() self.label.draw() if self.preview is not None: self.preview.render() def update(self, dt): for i in self.buttons: i.update(dt) if i.path is not None: self.root = i.path i.path = None self.LoadImagePaths() if self.is_imagesloaded[2] is not None: self.LoadImagesLabel() self.preview = Preview(self.image_paths, 280, 100) self.is_imagesloaded[2] = None if self.preview is not None: self.preview.update(dt) def CheckClicks(self, xc, yc): for i in self.buttons: i.clicked(xc, yc) def CheckFocus(self, xc, yc): for i in self.buttons: i.focused(xc, yc) if self.preview is not None: self.preview.onFocus(xc, yc) def LoadImagePaths(self): x = threading.Thread(target=LoadImagesPaths, args=( self.root, self.image_paths, self.is_imagesloaded, )) x.start() def LoadImagesLabel(self): self.text = pyglet.text.Label(str(self.is_imagesloaded[2]), font_name='Times New Roman', font_size=12, x=70, y=620, anchor_x='center', anchor_y='center')
# -*- coding: utf-8 -*- import sys import os from PyQt5.QtCore import QCoreApplication, QSettings, QResource from PyQt5.QtGui import QGuiApplication, QIcon from PyQt5.QtQml import QQmlApplicationEngine from preview import Preview QResource.registerResource("_ninjapreview_resource.rcc") qApp = QGuiApplication(sys.argv) QCoreApplication.setOrganizationName("Deuteronomy Works") QCoreApplication.setApplicationName("Ninja-Preview") settings = QSettings() qApp.setWindowIcon(QIcon(":icons/logo.png")) engine = QQmlApplicationEngine() preview = Preview() engine.load("qrc:///UI/main.qml") engine.rootObjects()[0].setProperty('preview', preview) engine.quit.connect(qApp.quit) sys.exit(qApp.exec_())
def main_thread_fps(points, delay, n, lines, columns, fps = 250, max_threads = 10, test_class = DiagramTest): # test main-thread execution (previewer run as main thread): preview = Preview(title = test_class.__name__ + " - Main-thread test mixed with diagram (FPS limit)", lines = lines, columns = columns, fps_limit = fps) preview.interactive(True) preview.start() # create tests threads = [] for i in xrange(0,n): if len(threads) < max_threads and random.randint(1, 5) == 1: test = test_class(points, delay) threads.append(test) preview.add_view(test.diagram, VoronoiDiagram) test.start() elif random.randint(1, 2) == 1: preview.add_view(i, TestFpsPainter) else: preview.add_view(i, TestPainter) if not preview.step(): break while preview.step(): pass # stop tests threads for t in threads: t.stop()
class Application(tk.Frame): _syntax_error_tag = "syntax_error" def __init__(self, master, title: str): super().__init__(master) self._master = master self.grid(sticky="NEWS") self.columnconfigure(0, weight=1, uniform="app_column") self.columnconfigure(1, weight=1, uniform="app_column") self.rowconfigure(0, weight=1) self.winfo_toplevel().title(title) self._create_widgets() self._bind_event_handlers() def _create_widgets(self): editor_frame = tk.LabelFrame(self, text="Editor") editor_frame.grid(row=0, column=0, sticky="NEWS") editor_frame.columnconfigure(0, weight=1) editor_frame.rowconfigure(0, weight=1) preview_frame = tk.LabelFrame(self, text="Preview") preview_frame.grid(row=0, column=1, sticky="NEWS") preview_frame.columnconfigure(0, weight=1) preview_frame.rowconfigure(0, weight=1) self.__text_field = tk.Text( editor_frame, undo=True, wrap=tk.WORD, font="fixed", ) self.__text_field.grid(sticky="NEWS") self.__text_field.tag_config(self._syntax_error_tag, background="red", foreground="white") self.__preview = Preview(preview_frame, self._on_new_figure_created, self._on_figure_updated) def _bind_event_handlers(self): self.__text_field.bind("<Leave>", lambda _: self._on_update_text()) self.__text_field.bind("<FocusOut>", lambda _: self._on_update_text()) self.__text_field.bind("<Key-Return>", lambda _: self._on_update_text()) def _on_update_text(self): self._remove_syntax_errors() text = self.__text_field.get("1.0", tk.END) figures, errs = GeometrySyntax.parse(text) failed_line_no = self.__preview.draw_figures(figures) errs += list(map(lambda l: ParseError(line=l), failed_line_no)) self._display_errors(errs) def _display_errors(self, errors: List[ParseError]): self._remove_syntax_errors() for err in errors: self.__text_field.tag_add( self._syntax_error_tag, f"{err.line}.0", f"{err.line}.0 + 1l - 1c", ) def _remove_syntax_errors(self): x = self.__text_field.tag_ranges(self._syntax_error_tag) for start, end in zip(x[::2], x[1::2]): self.__text_field.tag_remove(self._syntax_error_tag, start, end) def _on_new_figure_created(self, params: OvalParameters): new_text = GeometrySyntax.serialize([params]) line_count = self._count_lines() if (len( self.__text_field.get(f"{line_count}.0", f"{line_count}.0 + 1l - 1c")) > 0): new_text = "\n" + new_text self.__text_field.insert(tk.END, new_text) self._on_update_text() def _on_figure_updated(self, params: OvalParameters): new_text = GeometrySyntax.serialize([params]) edited_line = params.id line_count = self._count_lines() if line_count >= edited_line: start = f"{edited_line}.0" end = f"{edited_line}.0 + 1l - 1c" self.__text_field.delete(start, end) self.__text_field.insert(start, new_text) self._on_update_text() def _count_lines(self) -> int: return int(self.__text_field.index(tk.END + "-1c").split(".")[0]) def _on_exit(self): self._master.destroy()
class PopRevApp(object): """ The Picture of Picture Reverser application. """ def __init__(self, master, bg: str = BACKGROUND_COLOUR): """ Initialise the application. :param master: parent container of this application :param bg: background colour of this application """ self._master = master self._bg = bg self._file_menu = None self._poprev = PopRev() self._x = 0 self._y = 0 self._classifier = None self._preview = None self._navigator = None self._setup_menu() self._setup_view() self.refresh_components() def _smart_ask_save_before_doing(self, do_fn: Callable[[], None], title: str, message: str) -> None: """ If the current drawing has unsaved changes, ask the user if they would like to save before performing the action specified by do_fn. Otherwise, just execute do_fn. :param do_fn: function to execute :param title: title of dialog prompting save :param message: save prompt message """ if self._poprev.unsaved_changes(): ask_save_before_doing(lambda: self._smart_save(), do_fn, title, message) else: do_fn() def _setup_view(self) -> None: """ Set up components of the GUI """ self._navigator = Navigator(self._master, self.handle_move_callback, self.handle_jump_callback, bg=self._bg) self._navigator.pack(side=tk.TOP) frame = tk.Frame(self._master, bg=self._bg) frame.pack(side=tk.TOP) self._classifier = Classifier(frame, self.handle_select_callback, bg=self._bg) self._classifier.pack(side=tk.LEFT) self._preview = Preview(frame, PREVIEW_WIDTH, PREVIEW_HEIGHT, callback=self._handle_preview_click) self._preview.pack(side=tk.LEFT) self._master.config(bg=self._bg) self._master.title("poprev") self._master.protocol("WM_DELETE_WINDOW", self._exit) def _exit(self) -> None: """ Exit the application after confirmation """ title = "Save Before Exiting?" message = "Would you like to save this drawing before exiting?" self._smart_ask_save_before_doing(lambda: self._master.destroy(), title, message) def _setup_menu(self) -> None: """ Set up the menu bar """ menu_bar = tk.Menu(self._master) self._master.config(menu=menu_bar) file_menu = tk.Menu(menu_bar) menu_bar.add_cascade(label="File", menu=file_menu) reference_menu = tk.Menu(file_menu) file_menu.add_cascade(label="Reference", menu=reference_menu) drawing_menu = tk.Menu(file_menu) file_menu.add_cascade(label="Drawing", menu=drawing_menu) reference_menu.add_command(label="Load Reference", command=self.load_reference) drawing_menu.add_command(label="New Drawing", command=self.try_new_drawing) drawing_menu.add_command(label="Load Drawing", command=self.try_load_drawing) drawing_menu.add_command(label="Save Drawing", command=self._smart_save) drawing_menu.add_command(label="Save Drawing As", command=self.save_drawing_as) drawing_menu.add_command(label="Export Drawing", command=self.export_drawing) self._file_menu = file_menu def _smart_save(self) -> None: """ If the current drawing has a save file name, save it to that file. Otherwise, bring up the save as dialog. """ if self._poprev.get_save_name() is None: self.save_drawing_as() else: self.save_drawing() def _handle_preview_click(self, x: int, y: int) -> None: """ Handle the event when the drawing preview is clicked. :param x: the x coordinate that was clicked :param y: the y coordinate that was clicked """ jumpx = int(x * DRAW_WIDTH / PREVIEW_WIDTH) jumpy = int(y * DRAW_HEIGHT / PREVIEW_HEIGHT) self.jump_to(jumpx, jumpy) def load_reference(self) -> None: """ Load a reference image """ filename = filedialog.askopenfilename( title="Open Reference Image", filetypes=(("jpeg files", "*.jpg"), ("jpeg files", "*.jpeg"), ("png files", "*.png"))) if filename != "": self._poprev.load_reference(filename) self.refresh_components() def next_pixel(self) -> None: """ Go to the 'next' pixel i.e. right neighbour of current pixel, or left-most pixel in the next row down if the former does not apply (or go back to top left if current is bottom right) """ self._x = (self._x + 1) % DRAW_WIDTH if self._x == 0: self._y = (self._y + 1) % DRAW_HEIGHT self.refresh_components() def move_to(self, direction: str) -> None: """ Move to the next pixel in the specified direction. :param direction: the direction to move """ if direction == "up": self._y = (self._y - 1) % DRAW_HEIGHT elif direction == "right": self._x = (self._x + 1) % DRAW_WIDTH elif direction == "down": self._y = (self._y + 1) % DRAW_HEIGHT elif direction == "left": self._x = (self._x - 1) % DRAW_WIDTH self.refresh_components() def jump_to(self, x: int, y: int) -> None: """ Jump to the pixel specified by the given (x, y) coordinate :param x: x coordinate of position to jump to :param y: y coordinate of position to jump to """ self._x = x self._y = y self.refresh_components() def refresh_components(self) -> None: """ Refresh appearance of GUI components """ self.refresh_selector() self.refresh_preview() self.refresh_title() self.refresh_navigator() def refresh_preview(self) -> None: """ Refresh the appearance of the drawing preview """ self._preview.display_image(self._poprev.get_preview(self._x, self._y)) if self._poprev.has_reference(): image = self._poprev.get_ref_context(self._x, self._y, REF_CANVAS_WIDTH, REF_CANVAS_HEIGHT, 1) self._classifier.display_image(image) else: self._classifier.display_no_image_warning() def refresh_selector(self) -> None: """ Refresh the appearance of the colour selector """ selector = self._classifier.get_selector() colour = self._poprev.get_selection(self._x, self._y) if not (0 <= colour < 4): colour = None selector.set_selected(colour) def refresh_navigator(self) -> None: """ Refresh the appearance of the navigator """ self._navigator.display_position(self._x + 1, self._y + 1) def handle_select_callback(self, identifier: int) -> None: """ Handle the event when a colour is selected :param identifier: the id of the colour that was selected """ self._poprev.edit_drawing(self._x, self._y, identifier) self.next_pixel() def export_drawing(self) -> None: """ Display a dialog allowing user to export the current drawing as an image. """ filename = filedialog.asksaveasfilename(title="Export Drawing", filetypes=(("png files", "*.png"), )) if filename != "": self._poprev.export_drawing(filename) def save_drawing(self) -> None: """ Save changes to the current drawing. """ self._poprev.save_drawing() self.refresh_title() def save_drawing_as(self) -> None: """ Display a dialog allowing the user to save the current drawing to a particular file """ filename = filedialog.asksaveasfilename(title="Save Drawing As", filetypes=(("poprev drawing", ".poprev"), )) if filename != "": self._poprev.save_drawing_as(filename) self.refresh_title() def load_drawing(self) -> None: """ Display a dialog allowing the user to load a drawing """ filename = filedialog.askopenfilename(title="Select Drawing", filetypes=(("poprev drawing", ".poprev"), )) if filename != "": self._poprev.load_drawing(filename) self.refresh_components() def try_load_drawing(self) -> None: """ If there are unsaved changes to the current drawing, ask the user if they would like to save before loading another drawing. """ title = "Save Before Loading?" message = "Would you like to save this drawing before loading " \ "another?" self._smart_ask_save_before_doing(lambda: self.load_drawing(), title, message) def new_drawing(self) -> None: """ Clear the current drawing and start a new one. """ self._poprev.new_drawing() self.refresh_components() def try_new_drawing(self) -> None: """ If there are unsaved changes to the current drawing, ask the user if they would like to save before starting a new drawing. """ title = "Save Before Starting Over?" message = "Would you like to save this drawing before starting " \ "another?" self._smart_ask_save_before_doing(lambda: self.new_drawing(), title, message) def handle_move_callback(self, direction: str) -> None: """ Handle the event when one of the up, down, left, or right buttons in the navigator are clicked. :param direction: the direction that was clicked """ self.move_to(direction) def handle_jump_callback(self, x: int, y: int) -> None: """ Handle the event when the jump button of the navigator is clicked. :param x: the x coordinate to jump to :param y: the y coordinate to jump to """ self.jump_to(x - 1, y - 1) def refresh_title(self) -> None: """ Refresh the title of the application window """ unsaved_changes = "" if self._poprev.unsaved_changes(): unsaved_changes = "*" name = "untitled" if self._poprev.get_save_name() is not None: name = self._poprev.get_save_name() self._master.title("poprev ({}){}".format(name, unsaved_changes))
def random_points_test(min, max, delay, n, lines, columns, max_count, fps, test_class = DiagramTest): # test main-thread execution (previewer run as main thread): preview = Preview(title = test_class.__name__ + " - Main-thread test with random points", lines = lines, columns = columns, fps_limit = fps, painter_class = VoronoiDiagram) x, y = preview.panel_dimensions() preview.interactive(True) preview.start() # create tests threads = [] remove = None while True: if len(threads) < n: test = test_class(TestCases.random_points(min, max, x, y), delay) threads.append(test) test.start() preview.add_view(test.diagram) for i in xrange(0, len(threads)): if threads[i].counter >= max_count: preview.del_view(threads[i].diagram) threads[i].stop() del threads[i] break if not preview.step(): break # stop tests threads for t in threads: t.stop()
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): # super(MainWindow, self).__init__(parent) if sys.platform == 'darwin': # Workaround for Qt issue on OS X that causes QMainWindow to # hide when adding QToolBar, see # https://bugreports.qt-project.org/browse/QTBUG-4300 super(MainWindow, self).__init__( parent, QtCore.Qt.MacWindowToolBarButtonHint ) else: super(MainWindow, self).__init__(parent) def setup_app(self): self.setupActions() splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) self.tree = Tree() self.editor = Editor() self.tab_widget = QtGui.QTabWidget() self.preview = Preview() self.pdf_pane = PDFPane() self.tab_widget.addTab(self.preview, "HTML") self.tab_widget.addTab(self.pdf_pane, "PDF") self.file_path = None self.output_html_path = None self.setCentralWidget(splitter) splitter.addWidget(self.tree) splitter.addWidget(self.editor) splitter.addWidget(self.tab_widget) self.setWindowTitle("Sphinx Docs Editor") self.createMenus() self.createToolBars() self.showMaximized() def setupActions(self): """ Set up the top menu actions and keyboard shortcuts. """ # File Menu -------------------------------------------------- self.openAction = QtGui.QAction( # QtGui.QIcon(":/images/open.png"), "&Open File", self, shortcut="Ctrl+O", statusTip="Open File", triggered=self.openFile ) self.openFolderAction = QtGui.QAction( # QtGui.QIcon(":/images/open.png"), "Open Folder", self, shortcut="Ctrl+Shift+O", statusTip="Open Folder", triggered=self.openFolder ) self.saveAction = QtGui.QAction( # QtGui.QIcon(":/images/save.png"), "&Save File", self, shortcut="Ctrl+S", statusTip="Save File", triggered=self.saveFile ) self.saveAsAction = QtGui.QAction( # QtGui.QIcon(":/images/save.png"), "Save As File", self, shortcut="Ctrl+Shift+S", statusTip="Save File As...", triggered=self.saveFileAs ) self.quitAction = QtGui.QAction( # QtGui.QIcon(':/images/save.png'), "&Quit", self, shortcut="Ctrl+Q", statusTip="Quit", triggered=self.close ) # Build Menu -------------------------------------------------- self.buildHTMLAction = QtGui.QAction( "Build &HTML", self, shortcut="Ctrl+B", statusTip="Build HTML", triggered=self.buildHTML ) self.buildPDFAction = QtGui.QAction( "Build &PDF", self, shortcut="Ctrl+Shift+B", statusTip="Build PDF", triggered=self.buildPDF ) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.openAction) self.fileMenu.addAction(self.openFolderAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.saveAction) self.fileMenu.addAction(self.saveAsAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.quitAction) self.buildMenu = self.menuBar().addMenu("&Build") self.buildMenu.addAction(self.buildHTMLAction) self.buildMenu.addAction(self.buildPDFAction) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.openAction) self.fileToolBar.addAction(self.openFolderAction) self.fileToolBar.addAction(self.saveAction) # self.fileToolBar.addAction(self.saveAsAction) # self.fileToolBar.addAction(self.quitAction) self.buildToolBar = self.addToolBar("Build") self.buildToolBar.addAction(self.buildHTMLAction) self.buildToolBar.addAction(self.buildPDFAction) def openFile(self, path=None): """ Ask the user to open a file via the Open File dialog. Then open it in the tree, editor, and HTML preview windows. """ if not path: dialog = OpenDialog() dialog.set_folders_only(False) path = dialog.getOpenFileName( self, "Open File", '', "ReStructuredText Files (*.rst *.txt)" ) if path: file_path = Path(path[0]) filename = file_path.name tree_dir = file_path.parent.absolute() self.handleFileChanged(tree_dir, filename) def saveFile(self): if self.file_path: text = self.editor.toPlainText() try: f = open(self.file_path.absolute(), "wb") f.write(text) f.close() # self.rebuildHTML() except IOError: QtGui.QMessageBox.information( self, "Unable to open file: %s" % self.file_path.absolute() ) def saveFileAs(self): filename, _ = QtGui.QFileDialog.getSaveFileName( self, 'Save File As', '', "ReStructuredText Files (*.rst *.txt)" ) if filename: text = self.editor.toPlainText() try: f = open(filename, "wb") f.write(text) f.close() # self.rebuildHTML() except IOError: QtGui.QMessageBox.information( self, "Unable to open file: %s" % filename ) def openFolder(self, path=None): """ Ask the user to open a folder (directory) via the Open Folder dialog. Then open it in the tree, editor, and HTML preview windows. """ if not path: dialog = OpenDialog() dialog.set_folders_only(True) path = dialog.getExistingDirectory(self, "Open Folder", '') if path: self.handleFileChanged(path) def handleFileChanged(self, dir, filename=None): """ This is called whenever the active file is changed. It sets the tree, editor, and preview panes to the new file. """ if not filename: # TODO: find first rst file if index.rst doesn't exist. filename = "index.rst" self.file_path = Path(dir, filename) file_stem = str(self.file_path.stem) html_str = "_build/html/{0}.html".format(file_stem) self.output_html_path = Path(dir, html_str).absolute() # Load the file into the editor self.editor.open_file(self.file_path) # Load the directory containing the file into the tree. self.tree.load_from_dir(dir) # Load corresponding HTML file from pre-built Sphinx docs self.preview.load_html(self.output_html_path) def buildHTML(self): """ Builds the .html version of the active file and reloads it in the preview pane. """ # TODO: make this configurable via a dialog os.chdir(self.file_path.parent) proc = subprocess.Popen( ["make", "clean"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) for line in proc.stdout: print("stdout: " + line.rstrip()) print('----------------') proc = subprocess.Popen( ["make", "html"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) proc.wait() for line in proc.stdout: print("stdout: " + line.rstrip()) # Load corresponding HTML file from newly-built Sphinx docs self.preview.load_html(self.output_html_path) def buildPDF(self): """ Builds the .pdf version of the active file. """ # TODO: get this working # TODO: make this configurable via a dialog os.chdir(self.file_path.parent) proc = subprocess.Popen( ["make", "latexpdf"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) proc.wait() for line in proc.stdout: print("stdout: " + line.rstrip())
class Game: def __init__(self): # init pygame components pygame.init() pygame.display.set_caption(GAME_TITLE) self._screen = pygame.display.set_mode(SCREEN_RESOLUTION) self._background = pygame.Surface(self._screen.get_size()).convert() self._background.fill(colors.WHITE) self._font = pygame.font.SysFont(None, 24) self._set_message("Press PAUSE key to start!", colors.GREEN) # init game components rect_pixel_length = 20 self._field = GameField(self._screen, GRID_COLUMNS, GRID_ROWS, rect_pixel_length) self._preview = Preview(self._screen, SCREEN_RESOLUTION[0] - 100, 20, Brick.DIMENSION, int(rect_pixel_length / 2)) self._figure_factory = FigureFactory(self._field) self._figure = next(self._figure_factory) self._next_figure = next(self._figure_factory) self._score = Score() self._control = Control(START_FPS) # init speed and game state self._stepover = START_GAME_STEPOVER self._nostep = self._stepover self._looping = True self._was_started = False self._has_stopped = False self._is_paused = True def _set_message(self, text, color): self._text_image = self._font.render( text, True, colors.GRAY if color is None else color) def _display_score(self): if self._has_stopped: score_text = self._score.get_final_score() self._set_message( score_text + " Game finished. Press Q to quit!", colors.RED) else: score_text = self._score.get_current_score() self._set_message(score_text, colors.CYAN) print(score_text) def _adjust_speed(self, delta): old_stepover = self._stepover self._stepover = max(self._stepover + delta, 1) if self._stepover != old_stepover: print("[DEBUG] game_stepover = " + str(self._stepover)) def _check_states(self): # game speed if self._control.speed_up(): self._adjust_speed(-1) if self._control.speed_down(): self._adjust_speed(+1) # game state if self._control.pause() and not self._has_stopped: self._is_paused = not self._is_paused if self._is_paused: self._set_message("Press PAUSE key to continue.", colors.BLUE) else: self._was_started = True self._set_message("Press PAUSE key to pause.", colors.BLUE) if self._control.quit(): print("Quitting...") self._looping = False def _move_figure(self): if self._control.step_left(): self._figure.step_left() if self._control.step_right(): self._figure.step_right() if self._control.step_down(): self._figure.step_down() if self._control.fall_down(): self._figure.fall_down() if self._control.rotate(): self._figure.rotate() def _resolve_lines(self): lines = self._field.resolve_lines() if lines: self._score.add_lines(lines) self._display_score() # increase game speed self._stepover = max(self._stepover - 1, 1) print("[DEBUG] game_stepover = " + str(self._stepover)) def _spawn_new_figure(self): if self._figure.is_freezed(): self._figure = self._next_figure if self._field.collides(self._figure): self._has_stopped = True self._display_score() else: self._next_figure = next(self._figure_factory) print("Next figure: " + self._next_figure.get_name()) def _draw(self): self._screen.blit(self._background, (0, 0)) self._field.draw_grid() if self._was_started: if not self._has_stopped: self._field.draw_figure(self._figure) self._preview.draw_figure(self._next_figure) else: # hack in some flickering self._nostep = (self._nostep + 1) % 3 if not self._nostep: self._field.draw_figure(self._figure, colors.GRAY) if self._text_image is not None: rect = self._text_image.get_rect() rect.topleft = (20, 20) self._screen.blit(self._text_image, rect) pygame.display.update() def loop(self): while self._looping: self._control.process_events() self._check_states() if not self._is_paused and not self._has_stopped: self._move_figure() self._nostep = (self._nostep + 1) % self._stepover if not self._nostep: # advance game self._figure.step_down() self._resolve_lines() self._spawn_new_figure() self._draw() if not self._has_stopped: print(self._score.get_final_score()) pygame.quit()
def painter_test2(n, lines, columns, fps = 25000): # test main-thread execution (previewer run as main thread): preview = Preview(title = "Main-thread test without diagram", lines = lines, columns = columns, fps_limit = fps, painter_class = TestPainter) timer = Timer(0.1) preview.interactive(True) preview.start() step = 0 # create tests in different threads while True: step += 1 preview.set_title("Test #" + str(step) + " ADD-del inverse order") painters = [] for i in xrange(0,n): painters.append(preview.add_view(i)) while timer.idle(): if not preview.step(): return preview.set_title("Test #" + str(step) + " add-DEL inverse order") while len(painters) > 0: preview.del_view(painters.pop()) while timer.idle(): if not preview.step(): return preview.set_title("Test #" + str(step) + " ADD-del direct order") painters = [] for i in xrange(0,n): painters.append(preview.add_view(i)) while timer.idle(): if not preview.step(): return preview.set_title("Test #" + str(step) + " add-DEL direct order") for i in xrange(0,n): preview.del_view(painters[i]) while timer.idle(): if not preview.step(): return preview.set_title("Test #" + str(step) + " ADD-del random order") painters = [] for i in xrange(0,n): painters.append(preview.add_view(i)) while timer.idle(): if not preview.step(): return preview.set_title("Test #" + str(step) + " add-DEL random order") while len(painters) > 0: i = random.randint(0, len(painters) - 1) preview.del_view(painters[i]) del painters[i] while timer.idle(): if not preview.step(): return
Point2D(100, 10), Point2D(100, 190), Point2D(30, 30), Point2D(170, 170), Point2D(170, 30), Point2D(30, 170) ] # test manual cleanup: d = Delaunay() #d.add_as_main(Point2D(100, 100)) d.add(Point2D(100, 100)) for site in sites: d.add(site) #d.clear_far_sites() Preview.voronoi(d, title = "Manual 'main site' cleanup mode") # test automatic cleanup: d = Delaunay() d.add_as_main(Point2D(100, 100)) d.add(Point2D(100, 100)) for site in sites: d.add_near(site) Preview.voronoi(d, title = "Automatic 'main site' cleanup mode") d = Delaunay(10000) d.add(Point2D(100, 100)) for site in sites: d.add(site) # test site deletion: