def __init__(self, interpreter, args, enable_log_replay=False, scene_class=TrackedUsersScene): Window.__init__(self, args) self.args = args self._enable_log_replay = enable_log_replay self.interpreter = interpreter self.frame = None self.floor_y = args.floor_y self._layout = QtGui.QVBoxLayout() self._layout.setSpacing(0) self._layout.setMargin(0) self._layout.setContentsMargins(0, 0, 0, 0) self.setLayout(self._layout) self._scene = scene_class(self) size_policy = QtGui.QSizePolicy( QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) size_policy.setVerticalStretch(2) size_policy.setHorizontalStretch(2) self._scene.setSizePolicy(size_policy) self._layout.addWidget(self._scene) self._log_widget = LogWidget(self) self._layout.addWidget(self._log_widget) self._create_menu() if self.args.fullscreen: self.give_keyboard_focus_to_fullscreen_window() self._fullscreen_action.toggle()
def do_activate(self) -> None: window = Window(self) window.set_position(Gtk.WindowPosition.CENTER) window.set_default_size(Application.WINDOW_WIDTH, Application.WINDOW_HEIGHT) window.set_border_width(20) window.show_all()
def add_parser_arguments(parser): Window.add_parser_arguments(parser) parser.add_argument("--camera", help="posX,posY,posZ,orientY,orientX", default="59.964,-1578.000,2562.016,-188.500,16.000") parser.add_argument("--floor-y", type=float, default=0) parser.add_argument("--joint-size", type=float) parser.add_argument("--show-orientation", action="store_true")
def __enter__(self): self._window = Window(PascalVocAnnotator.WINDOW_TITLE, cv2.WND_PROP_FULLSCREEN).__enter__() self._window.set_property(cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) self._window.set_mouse_callback(self.on_mouse_event) return self
def __init__(self, title, width, height, x, y): self.window = Window(title, width, height, x, y) self.width = width self.window.canvas(width, height) self.detector = MarkDetector() self.capture = WebcamVideoStream(src = 0).start() self.markerList = [] self.prevRead = 0 self.readQty = 0
def pushWindow(self, window: Window) -> None: self._window_stack.append(window) window.closed.connect(self.popWindow) try: self._window_stack[-2].hide() except IndexError: pass window.show()
def main(): app = QApplication(sys.argv) clock = Clock() source = WebSocketSource(Config.get('WS_HOST', '')) window = Window(clock, source) if Config.get('FULLSCREEN', True): window.showFullScreen() else: window.showNormal() sys.exit(app.exec_())
def activate_cb(self, data=None): window = Window(self) self.add_window(window) window.show_all() window.connect('destroy', self.window_destroy_cb) window.connect('key-press-event', self.key_press_event_cb)
def __init__(self, bvh_reader, args): Window.__init__(self, args) self._layout = QtGui.QVBoxLayout() self._layout.setSpacing(0) self._layout.setMargin(0) self._layout.setContentsMargins(0, 0, 0, 0) self._scene = Scene(bvh_reader, args) self._layout.addWidget(self._scene) self._create_menu() self.setLayout(self._layout) if args.fullscreen: self.give_keyboard_focus_to_fullscreen_window() self._fullscreen_action.toggle()
def __init__(self, bvh_reader, args): global transport_controls Window.__init__(self, args) self._main_layout = QtGui.QVBoxLayout() self._main_layout.setSpacing(0) self._main_layout.setMargin(0) self._main_layout.setContentsMargins(0, 0, 0, 0) self._scene = Scene(bvh_reader, args) self._main_layout.addWidget(self._scene) transport_controls = TransportControls() transport.on_updated = transport_controls.on_transport_updated self._main_layout.addWidget(transport_controls.widget) self._create_menu() self.setLayout(self._main_layout)
def __init__(self): assert App._instance is None App._instance = self self.crashed = False try: setproctitle.setproctitle('music-player') self.loop = asyncio.get_event_loop() self.audio = audio.GstAudioBackend() self.window = Window() self.injector = dependency_injection.Injector() from commands import core_commands # noqa plugging.load_plugins() self.commander = commands_runner.CommandsRunner( self.loop, self.injector, ) self.binding_controller = bindings.BindingsController( self.commander, self.window, ) if config['log_level'] == 'DEBUG': self.loop.set_debug(True) db.init() self.setup() plugging.start_plugins() core_providers.register_core_providers(self) except Exception as e: self.crashed = True log_exception(self.window) self.destroy() raise e
def __init__(self, entity, info, **kwargs): global _ACTION_LUT title = str(entity.id) if entity.owner: title += ' (%s)' % entity.owner actions = info['actions'] act = [] tabs = [] if 'MOVE' in actions: act.append(Button(Icon(filename='textures/tiger.svg'), functools.partial(EntityWindow.on_move, self) )) if len(act) > 0: grid = Grid(3, 3, *act) tabs.append(Tab('Act', grid)) if 'BUILD' in actions: build = [] for type in info['Buildlist']: callback = functools.partial(EntityWindow.on_build, self, what=type) build.append(Button(Icon(filename=type_icon.get(type, 'textures/tiger.svg')), callback=callback)) grid = Grid(3, 3, *build) tabs.append(Tab('Build', grid)) if 'SET_CARGO_TYPE' in actions: cargo_types = [] for type in info['Cargo_type_list']: callback = functools.partial(EntityWindow.on_set_cargo_type, self, what=type) cargo_types.append(Button(Icon(filename='textures/tiger.svg'), callback=callback)) grid = Grid(3, 3, *cargo_types) tabs.append(Tab('Set cargo type', grid)) tabs.append(Tab('Stats', EntityStats(info))) tab = TabView(tabs=tabs) Window.__init__(self, widget=tab, position=None, size=Vector2i(300,200), id=entity.id, title=title, **kwargs) self._entity = entity self._info = info
async def open_palette(commands_runner: CommandsRunner, ui: PlayerUI, window: Window): palette = PaletteComponent(size=6) ui.stack_layout.add(palette) window.root_component.update_layout() window.focus(palette) subscription = window.input_component.value.subscribe( lambda value: palette.filter(value)) result = await window.input(">") window.blur_active_component() palette.detach() if result is not None: commands_runner.run_text_command(palette.value) if subscription: subscription.dispose()
class Attendance: def __init__(self, title, width, height, x, y): self.window = Window(title, width, height, x, y) self.width = width self.window.canvas(width, height) self.detector = MarkDetector() self.capture = WebcamVideoStream(src = 0).start() self.markerList = [] self.prevRead = 0 self.readQty = 0 def update(self): self.process() def start(self): while True: self.update() def startLoop(self): self.loopAfter() self.window.mainLoop() def loopAfter(self): try: self.process() self.window.after(target = self.loopAfter) except: self.__del__() def process(self): result = None frame = self.capture.read() if self.capture.grabbed is None or frame is None: return self.detector.setFrame(frame) (result, image) = self.detector.read() if image is not None and result is not None and len(result) > 0: frame = image frame = resize(frame, width=self.width) photo = PhotoImage(image = fromarray(flip(cvtColor(frame, COLOR_BGR2RGB), 1))) self.window.updateImageCanvas(photo) self.window.update() self.report(result) def report(self, result): if result is not None and len(result) > 0: for r in result: if self.prevRead == r[0]: self.readQty += 1 first_or_default = next((x for x in self.markerList if x[0] == r[0]), None) if first_or_default is not None: stdout.write(",".join(str(x) for x in r) + "\n") stdout.flush() elif self.readQty >= 10: self.markerList.append(r) stdout.write(",".join(str(x) for x in r) + "\n") stdout.flush() else: self.readQty = 0 self.prevRead = r[0] def __del__(self): try: self.capture.stop() stdout.write("exit\n") stdout.flush() self.window.remove() except: pass
class PascalVocAnnotator(object): """ Allows a user to annotate images and save data to pascal voc format. """ WINDOW_TITLE = 'Annotator' TEST_DIRECTORY = 'test_images' CONFIG_PATH = 'config.json' SUPPORTED_FILE_EXTENSIONS = ('.jpg', '.png') def __init__(self, path_to_image_folder=TEST_DIRECTORY): ## Read config with open(self.CONFIG_PATH, 'r') as configfile: data = jsonload(configfile) self.controls = data['controls'] self.labels = list(data['labels'].keys()) self.color_map = { key: value['color'] for key, value in data['labels'].items() } ## Read image if not os.path.isdir(path_to_image_folder): raise ValueError( f"The path \'{path_to_image_folder}\' is not a valid directory!" ) self._path_to_image_folder = path_to_image_folder self._paths = [ os.path.join(path_to_image_folder, filename) for filename in os.listdir(self.path_to_image_folder) if os.path.splitext(filename)[1] in PascalVocAnnotator.SUPPORTED_FILE_EXTENSIONS ] self._paths.sort(key=os.path.getmtime) self._current_image = None self._saved_annotations = Annotation.load_annotations( self.path_to_image_folder, self.color_map, annotation_dir=ANNOTATION_DEFAULT_DIR) self._window = None self.tag_index = 0 self._annotations = [] self._annotation_in_progress = None self._changed = False self.index = 0 self._key_events = { self.controls['NEXT']: self._next, self.controls['PREV']: self._prev, self.controls['UNDO']: self._undo, self.controls['CLEAR']: self._clear } def __enter__(self): self._window = Window(PascalVocAnnotator.WINDOW_TITLE, cv2.WND_PROP_FULLSCREEN).__enter__() self._window.set_property(cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) self._window.set_mouse_callback(self.on_mouse_event) return self def __exit__(self, *params): self.index += 1 if self._window is not None: self._window.__exit__() @property def path_to_image_folder(self): return self._path_to_image_folder @property def annotation_dir(self): return ANNOTATION_DEFAULT_DIR @property def paths(self): return self._paths @property def index(self): return self._index @property def current_path(self): return self.paths[self.index] @property def current_image(self): return self._current_image @current_image.setter def current_image(self, value): assert value is not None, 'Cannot read the image at "{}"!'.format( self.current_path) self._current_image = value def _next(self): self.index += 1 def _prev(self): self.index -= 1 def _clear(self): if self._annotations: self._annotations.clear() self._changed = True def _undo(self): if self._annotations: self._annotations.pop(0) self._changed = True def _remove_annotation_file_when_empty(self): if hasattr(self, '_index'): annotation_file_path = os.path.join( self.path_to_image_folder, self.annotation_dir, os.path.basename(os.path.splitext(self.current_path)[0]) + '.xml') if (not self._annotations ) and os.path.isfile(annotation_file_path): os.remove(annotation_file_path) @index.setter def index(self, value): if self.current_image is not None and (self._annotations or self._changed): current_labels = [ annotation.label for annotation in self._annotations ] generate_pascvalvoc_annotation_from_image_file( os.path.abspath(self.current_path), current_labels, self._annotations, self.annotation_dir, True) self._saved_annotations[os.path.basename( self.current_path)] = self._annotations.copy() self._remove_annotation_file_when_empty() value = value % len(self._paths) self._index = value current_path = self._paths[self.index] img = cv2.imread(current_path) self.current_image = img key = os.path.basename(current_path) if key in self._saved_annotations: self._annotations = self._saved_annotations[key] else: self._annotations = [] self._changed = False @property def current_color(self): return self.color_map[self.labels[0]] def show_controls(self, img): """ Display controls in use on top of screen. """ font = cv2.FONT_HERSHEY_SIMPLEX font_scale = 1 / 2 thickness = 1 margin = 5 outline_thickness = 3 text = '' for key, value in self._key_events.items(): text = text + f"{value.__name__}: {key}" + " " (text_w, text_h), _ = cv2.getTextSize(text, font, font_scale, thickness) origin = (margin, margin + text_h) cv2.putText(img, text, origin, font, font_scale, Colors.BLACK.value, thickness + outline_thickness, True) cv2.putText(img, text, origin, font, font_scale, Colors.WHITE.value, thickness, True) def update(self): """ Refresh the whole screen and process actions. """ check_key_press = lambda key: self._window.was_key_pressed(key) frame = self._current_image.copy() for key, event in self._key_events.items(): if check_key_press(key): event() for annotation in self._annotations: annotation.draw(frame) if self._annotation_in_progress is not None: self._annotation_in_progress.draw(frame) self.show_controls(frame) self._window.draw(frame) return not self._window.should_quit def on_mouse_event(self, event, x, y, flags, params): """ Process mouse press events. """ for annotation in self._annotations: processed = annotation.on_mouse_event(event, x, y, flags, params) if processed: self._changed = True return if event == cv2.EVENT_LBUTTONDOWN and ( not self._annotation_in_progress): self._annotation_in_progress = Annotation(x, y, self.current_color, "blob") elif event == cv2.EVENT_LBUTTONUP and self._annotation_in_progress: self._annotations.insert(0, self._annotation_in_progress) self._annotation_in_progress = None elif event == cv2.EVENT_MOUSEMOVE and self._annotation_in_progress: self._annotation_in_progress.box.w = x - self._annotation_in_progress.box.x self._annotation_in_progress.box.h = y - self._annotation_in_progress.box.y self._changed |= bool(self._annotation_in_progress)
#!/bin/python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GLib from ui.window import Window from ui.env import * GLib.set_prgname(PROGRAM_NAME) win = Window() win.connect('destroy', Gtk.main_quit) win.show_all() Gtk.main()
import sys from PyQt5.QtWidgets import QApplication from ui.window import Window if __name__ == '__main__': app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
import os from indexing import index from config import * from ui.window import Window window = Window() window.mainloop()
def dismiss_error(window: Window): if window.active_component: window.active_component.detach() window.blur_active_component()
import sys from PyQt5.QtWidgets import QApplication from ui.window import Window app = QApplication(sys.argv) w = Window() sys.exit(app.exec_())
from ui.window import Window window_object = Window() window_object.main()
class App: _instance: Optional['App'] = None def __init__(self): assert App._instance is None App._instance = self self.crashed = False try: setproctitle.setproctitle('music-player') self.loop = asyncio.get_event_loop() self.audio = audio.GstAudioBackend() self.window = Window() self.injector = dependency_injection.Injector() from commands import core_commands # noqa plugging.load_plugins() self.commander = commands_runner.CommandsRunner( self.loop, self.injector, ) self.binding_controller = bindings.BindingsController( self.commander, self.window, ) if config['log_level'] == 'DEBUG': self.loop.set_debug(True) db.init() self.setup() plugging.start_plugins() core_providers.register_core_providers(self) except Exception as e: self.crashed = True log_exception(self.window) self.destroy() raise e @classmethod def get_instance(cls) -> 'App': return cast(App, cls._instance) def setup(self): raise NotImplementedError def run_forever(self): try: running = True while running: try: running = False self.loop.run_until_complete(self.window.process_input()) except KeyboardInterrupt: running = True keyboard.raw_keys.on_next(curses.KEY_EXIT) except Exception: self.crashed = True log_exception(self.window) finally: self.destroy() def destroy(self): plugging.destroy() if self.window: self.window.destroy() if self.audio: self.audio.destroy() for task in asyncio.Task.all_tasks(): task.cancel() try: if self.loop: self.loop.run_until_complete( asyncio.gather(*asyncio.Task.all_tasks())) except asyncio.CancelledError: pass finally: if self.loop: self.loop.close() if self.crashed: sys.exit(1)
from bvh import bvh_reader as bvh_reader_module from ui.floor_checkerboard import FloorCheckerboard from ui.window import Window FLOOR_ARGS = {"num_cells": 26, "size": 26, "board_color1": (.2, .2, .2, 1), "board_color2": (.3, .3, .3, 1), "floor_color": None, "background_color": (0.0, 0.0, 0.0, 0.0)} CAMERA_Y_SPEED = .01 CAMERA_KEY_SPEED = .1 CAMERA_DRAG_SPEED = .1 FRAME_RATE = 50 parser = argparse.ArgumentParser() Window.add_parser_arguments(parser) parser.add_argument("bvh") parser.add_argument("--camera", help="posX,posY,posZ,orientY,orientX", default="-3.767,-1.400,-3.485,-55.500,18.500") parser.add_argument("--host", default="localhost") parser.add_argument("--port", type=int, default=SERVER_PORT_BVH) parser.add_argument("-speed", type=float, default=1.0) parser.add_argument("-loop", action="store_true") parser.add_argument("--z-up", action="store_true") parser.add_argument("--enable-floor", action="store_true") parser.add_argument("--show-fps", action="store_true") args = parser.parse_args() class MainWindow(Window): def __init__(self, bvh_reader, args): Window.__init__(self, args)
from ui.window import Window Window().run()
def quit(window: Window): window.quit()
app = SingleApplication(sys.argv) if not app.isSingle: QtGui.QMessageBox.information( None, "Hello Word", u"程序已经在运行了哦~", ) app.quit() else: # 显示 splash splash = QtGui.QSplashScreen(QtGui.QPixmap(os.path.join(iconDir, splashIconName))) splash.show() splash.showMessage(u'孵化中...', QtCore.Qt.AlignBottom | QtCore.Qt.AlignHCenter, QtCore.Qt.white) # 主窗体 m = Window() splash.showMessage(u'孵化完成!', QtCore.Qt.AlignBottom | QtCore.Qt.AlignHCenter, QtCore.Qt.white) # 窗体加载完成后释放 splash.finish(m) del splash m.show() app.exec_() # DONE: 只运行一个实例 # TODO: 复习提示 # DONE: 单词发音