def __init__(self, notebook): Editor.__init__(self, notebook) self.buf = ShellBuffer(self.notebook) self.view = ShellView(self.buf) self.config_state = None self.view.connect('notify::sidebar-open', self.on_notify_sidebar_open) global_settings.watch('editor-font-is-custom', self.__update_font) global_settings.watch('editor-font-name', self.__update_font) self.__update_font() self.widget = ViewSidebarLayout() self.widget.set_view(self.view) self.widget.set_sidebar(self.view.sidebar) self.widget.set_sidebar_open(self.view.sidebar_open) self.widget.connect('notify::sidebar-width', self.on_notify_sidebar_width) self.widget.show_all() self.buf.worksheet.sig_filename_changed.connect( lambda *args: self._update_filename()) self.buf.worksheet.sig_file.connect(lambda *args: self._update_file()) self.buf.worksheet.sig_code_modified.connect( lambda *args: self._update_modified()) self.buf.worksheet.sig_state.connect( lambda *args: self._update_state())
def _create_file(self, note): """ Creates file from note """ GeekNote().loadNoteContent(note) # Save images if 'saveImages' in self.imageOptions and self.imageOptions['saveImages']: imageList = Editor.getImages(note.content) if imageList: if 'imagesInSubdir' in self.imageOptions and self.imageOptions['imagesInSubdir']: os.mkdir(os.path.join(self.path, note.title + "_images")) imagePath = os.path.join(self.path, note.title + "_images", note.title) self.imageOptions['baseFilename'] = note.title + "_images/" + note.title else: imagePath = os.path.join(self.path, note.title) self.imageOptions['baseFilename'] = note.title for imageInfo in imageList: filename = "{}-{}.{}".format(imagePath, imageInfo['hash'], imageInfo['extension']) logger.info('Saving image to {}'.format(filename)) binaryHash = binascii.unhexlify(imageInfo['hash']) GeekNote().saveMedia(note.guid, binaryHash, filename) content = Editor.ENMLtoText(note.content, self.imageOptions) path = os.path.join(self.path, note.title + self.extension) open(path, "w").write(content) os.utime(path, (-1, note.updated / 1000)) return True
def do_ABRIR(self, archivo): self.archivo = Archivo(archivo) self.archivo.leer() self.archivo.conversion() self.archivo.agregar_objeto() self.editor = Editor(self.archivo) self.editor.representar_cancion()
def __init__(self, data, out, background_color, size=(1280, 720), delete=False): """ Constructor @param data : The popcorn editor project json blob """ self.delete = delete self.track_edits = [] self.track_items = [] self.track_videos = [] self.current_video = NamedTemporaryFile(suffix='.avi', delete=self.delete) self.background_color = background_color self.size = size self.editor = Editor() self.real_duration = data['media'][0]['duration'] self.duration = data['media'][0]['duration'] self.out = out self.base_videos = [] self.preprocess(data)
def run(self): if self.qpkg_dir is None: error('Cannot find QNAP/changelog anywhere!') error('Are you in the source code tree?') return -1 # read ~/.qdkrc qdkrc = QDKrc() cfg_user = qdkrc.config['user'] control = ControlFile(self.qpkg_dir) changelog = ChangelogFile(self.qpkg_dir) kv = {'package_name': control.source['source']} if self._args.message is not None: kv['messages'] = self._args.message if self._args.version is not None: kv['version'] = self._args.version kv['author'] = cfg_user['name'] if self.author is None else self.author kv['email'] = cfg_user['email'] if self.email is None else self.email if len(kv['author']) == 0 or len(kv['email']) == 0: warning('Environment variable QPKG_NAME or QPKG_EMAIL are empty') info('QPKG_NAME: ' + kv['author']) info('QPKG_EMAIL: ' + kv['email']) yn = raw_input('Continue? (Y/n) ') if yn.lower() == 'n': return 0 kv['author'] = 'noname' kv['email'] = '*****@*****.**' entry = changelog.format(**kv) editor = Editor() editor.insert_content(entry) editor.open(changelog.filename) return 0
def _create_file(self, note): """ Creates file from note """ GeekNote(sleepOnRateLimit=self.sleep_on_ratelimit).loadNoteContent(note) escaped_title = re.sub(os.sep,'-', note.title) # Save images if 'saveImages' in self.imageOptions and self.imageOptions['saveImages']: imageList = Editor.getImages(note.content) if imageList: if 'imagesInSubdir' in self.imageOptions and self.imageOptions['imagesInSubdir']: os.mkdir(os.path.join(self.path, escaped_title + "_images")) imagePath = os.path.join(self.path, escaped_title + "_images", escaped_title) self.imageOptions['baseFilename'] = escaped_title + "_images/" + escaped_title else: imagePath = os.path.join(self.path, escaped_title) self.imageOptions['baseFilename'] = escaped_title for imageInfo in imageList: filename = "{}-{}.{}".format(imagePath, imageInfo['hash'], imageInfo['extension']) logger.info('Saving image to {}'.format(filename)) binaryHash = binascii.unhexlify(imageInfo['hash']) GeekNote(sleepOnRateLimit=self.sleep_on_ratelimit).saveMedia(note.guid, binaryHash, filename) content = Editor.ENMLtoText(note.content.encode('utf-8'), self.imageOptions) path = os.path.join(self.path, escaped_title + self.extension) open(path, "w").write(content) updated_seconds = note.updated / 1000.0 os.utime(path, (updated_seconds, updated_seconds)) return True
def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle(self.tr("Alum Code Editor")) self.setMinimumSize(750,500) self._want_to_close = False #Barra de Menu TOP menu = self.menuBar() self.__crear_acciones() self.__crear_menu(menu) #Widget Cetral self.editor = Editor() self.setCentralWidget(self.editor) self.editor.setStyleSheet("background-color:#1e1e1e;color:white;font-size:18px;border:none;") self.editor.cursorPositionChanged.connect(self._actualizar_status_bar) #ToolBar self.toolbar = QToolBar() self.__crear_Toolbar(self.toolbar) self.addToolBar(Qt.LeftToolBarArea, self.toolbar) #satusBar self.status = StatusBar() self.setStatusBar(self.status) self.status.setStyleSheet("background-color:#252526;") #Conexiones self.abrir.triggered.connect(self._abrir_archivo) self.guardar.triggered.connect(self._guardar_archivo) self.nuevo.triggered.connect(self._nuevo_archivo)
def make_gif(src=None, resize=1, set=None): """Make gif from sequence of images. Saves to media folder. Parameters ------------- src:String, The path or file location of the image sequence resize=1:Integer, Calls on Editor.resize_img to Scale down image by resize. Defaults to 1 which is no change. set=None:List, A list of two integer indices for a set of images to make the GIF. """ images = [] os.chdir('./media/img/' + str(src)) print('{:s} files to be processed in {:s}:'.format(str(len(os.listdir('.'))), src)) for image in os.listdir('.'): # Load image into Editor. new_image = Editor(image) reduced = new_image.resize_img(resize) # print(reduced.filename) images.append(imageio.imread(reduced.filename)) reduced.close() new_gif_name = str(random.randint(1,10000)) print('Saving new GIF: {}.gif'.format(new_gif_name)) imageio.mimwrite('../../{}.gif'.format(new_gif_name), images if set is None else images[slice(set[0], set[1])], duration=1/22, fps=22)
def view_tasks(self): self.__cur_user.subjects = self.__data.get_courses(self.__cur_user) for i, sub in enumerate(self.__cur_user.subjects): print(i + 1, sub[0], sep=" - ") idx = '' while all([str(j) != idx for j in range(1, i + 2)]): idx = input("Enter course ID: ") task = self.__data.get_tasks(self.__cur_user.subjects[int(idx) - 1][0])[0][0] print(task) choice = '' while '1' != choice != '2': choice = input("1 - Submit new file\n" + "2 - Back to menu\n") if choice == '1': tmp = Editor([]) tmp.write_script() sub = self.__cur_user.subjects[int(idx) - 1][0] res = tmp.run_script( f"{self.__cur_user.surname}_{self.__cur_user.name}_" + sub) self.__data.submit_path(self.__cur_user, sub, res[1]) else: pass
def run(self): if self.qpkg_dir is None: error('Cannot find QNAP/control anywhere!') error('Are you in the source code tree?') return -1 if self._args.filename is None: self._args.filename = 'control' cfiles = self._get_support_control_files() if self._args.filename not in cfiles: error('Support control files: {}'.format(', '.join(cfiles))) return -1 filename = pjoin(self.qpkg_dir, Settings.CONTROL_PATH, self._args.filename) editor = Editor() if not pexists(filename): editor.set_template_file( pjoin(Settings.TEMPLATE_PATH, Settings.CONTROL_PATH, '{}{}'.format(Settings.DEFAULT_PACKAGE, filename[filename.rfind('.'):]))) editor.open(filename) return 0
def __init__(self, notebook): Editor.__init__(self, notebook) self.__filename = None self.__modified = False self.__file = None if use_sourceview: self.buf = gtksourceview.SourceBuffer() self.buf.set_highlight(True) language = language_manager.get_language_from_mime_type("text/x-python") if language != None: self.buf.set_language(language) self.view = gtksourceview.SourceView(self.buf) self.view.set_insert_spaces_instead_of_tabs(True) self.view.set_tabs_width(4) else: self.buf = gtk.TextBuffer() self.view = gtk.TextView(self.buf) self.view.modify_font(pango.FontDescription("monospace")) self.buf.connect_after('insert-text', lambda *args: self.__set_modified(True)) self.buf.connect_after('delete-range', lambda *args: self.__set_modified(True)) self.widget = gtk.ScrolledWindow() self.widget.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.widget.add(self.view) self.widget.show_all()
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.mainW = QWidget(self) self.compile = QPushButton(self, text="Compile") self.browse = QPushButton(self, text="Browse") self.editor = Editor() buttonsLau = QHBoxLayout() buttonsLau.addWidget(self.compile) buttonsLau.addWidget(self.browse) self.setCentralWidget(self.mainW) self.mainW.setLayout(QVBoxLayout()) self.mainW.layout().addWidget(self.editor) self.mainW.layout().addLayout(buttonsLau) self.browse.clicked.connect(self._on_browse_clicked) self.compile.clicked.connect(self._on_compile_clicked) def _on_browse_clicked(self): files = QFileDialog.getOpenFileNames(self, "Open File", None, None)[0] if len(files) > 0: path = files[0] f = open(path, "r") content = "".join(f.readlines()) self.editor.setPlainText(content) def _on_compile_clicked(self): try: content = self.editor.toPlainText() compile(content) except: error_dialog = QErrorMessage(self) error_dialog.showMessage('Unknown token')
def run_start(self, events, pressed): self.new_window.display() self.new_window.react_events(events, pressed) if self.new_window.button_done.pushed(events): self.state = 'main' win = self.new_window.create_windows() Editor.set_window(win)
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 __init__(self, notebook): Editor.__init__(self, notebook) self.buf = ShellBuffer(self.notebook) self.view = ShellView(self.buf) self.config_state = None self.view.connect('notify::sidebar-open', self.on_notify_sidebar_open) global_settings.watch('editor-font-is-custom', self.__update_font) global_settings.watch('editor-font-name', self.__update_font) self.__update_font() self.widget = ViewSidebarLayout() self.widget.set_view(self.view) self.widget.set_sidebar(self.view.sidebar) self.widget.set_sidebar_open(self.view.sidebar_open) self.widget.connect('notify::sidebar-width', self.on_notify_sidebar_width) self.widget.show_all() self.buf.worksheet.sig_filename_changed.connect( lambda *args: self._update_filename() ) self.buf.worksheet.sig_file.connect( lambda *args: self._update_file() ) self.buf.worksheet.sig_code_modified.connect( lambda *args: self._update_modified() ) self.buf.worksheet.sig_state.connect( lambda *args: self._update_state() )
def open_tab(self, ndir, itemtext): ndir = os.path.abspath(ndir) if IS_WIN: ndir = ndir.lower() ndir_isfile = os.path.isfile(ndir) if ndir_isfile and os.path.splitext(ndir.lower())[-1] in ('.py', '.html', '.css', '.js', '.load', '.xml', '.json', '.rss'): if ndir in self.notebook: self.notebook.set_selection_by_filename(ndir) else: editor = Editor(self.notebook) editor.page_idx = self.notebook.GetPageCount() editor.filename = ndir self.notebook.AddPage(editor, itemtext) self.notebook.set_selection_by_filename(ndir) pid = editor.openfile(ndir) editor.pid = pid editor.Refresh() editor.SetFocus() elif ndir_isfile and os.path.splitext(ndir.lower())[-1] in ('.png', '.jpg', '.gif', '.ico'): self.open_image(ndir, itemtext) elif os.path.isdir(ndir): if USE_VTE: self.terminal.ctrl.feed_child('\ncd %s\n' % ndir)
def do_REPRODUCIR(self, archivo): '''Este comando reproduce el archivo dado como parametro. Utilizacion: *>>REPRODUCIR nombre_del_archivo.plp''' try: self.editor = Editor(archivo) self.editor.preparar_reproduccion(-1) except IOError: print('No se puede encontrar el archivo.')
def fieldChanged(self, key, field): path = self._path + "." + unicode(key) path = path.replace('__root__.', '') if field == "*": self._throw(Editor.Out.FieldChanged, Editor.translatePath(self._document, path)) else: self._throw(Editor.Out.FieldChanged, Editor.translatePath(self._document, path + "." + field))
def do_ABRIR(self, archivo): '''Toma como parametro un archivo y lo abre en consola''' self.archivo = Archivo(archivo) self.archivo.leer() self.archivo.conversion() self.archivo.agregar_objeto() self.editor = Editor(self.archivo) self.editor.representar_cancion()
def do_REPRODUCIR(self, archivo): '''Este comando reproduce el archivo dado como parametro. Utilizacion: *>>REPRODUCIR nombre_del_archivo.plp''' try: self.editor = Editor(archivo) self.editor.reproducir(-1) except IOError: print(MENSAJE_IOERROR)
def main(): parser = argparse.ArgumentParser() parser.add_argument("--map-editor", help="launch editor for building maps", action="store_true") parser.add_argument("--debug", help="turn on the lights", action="store_true") parser.add_argument("--map-file", help="a json file that specifies a map", required=True) args = parser.parse_args() # IO engine pyg.init() editor = None if args.map_editor: editor = Editor(args) world = World(args) screen = pyg.display.set_mode(screen_size(args)) prev_time_s = time.time() keys = set() while True: # take input events = [] for event in pyg.event.get(): events.append(event) if event.type == pyg.QUIT: return elif event.type == pyg.KEYDOWN: keys.add(event.key) elif event.type == pyg.KEYUP: keys.discard(event.key) # simulate if editor != None: should_reload = editor.handle(events, screen) if should_reload: world = World(args) if world.step(keys): return # draw screen.fill(BLACK) world.draw(screen) if editor != None: editor.draw(screen) pyg.display.flip() # sleep cur_time_s = time.time() elapsed_s = cur_time_s - prev_time_s wait_s = TIME_STEP_S - elapsed_s if wait_s >= 0.0: time.sleep(wait_s) prev_time_s = cur_time_s
def do_ABRIR(self, archivo): '''Este comando abre el archivo dado como parametro y lo prepara para edicion. Utilizacion: *>>ABRIR nombre_del_archivo.plp''' try: self.editor = Editor(archivo) self.editor.representar_cancion() except IOError: print(MENSAJE_IOERROR)
def __init__(self, master=None): super().__init__(master) self.master = master self.grid() self.editor = Editor(master) self.music = Music() self.player = Player() self.parser = Parser(self.music) self.create_widgets()
class Engine: def __init__(self): self.fps = 0 self.running = True self.world = World() self.m_pos = (0, 0) self.L_click = False self.R_click = False self.w_size = (700, 700) self.screen = pygame.display.set_mode(self.w_size, pygame.RESIZABLE) self.hold = False self.mouse_focus = 'window' self.sprites = [] self.sprite_names = [] self.editor = Editor(self) self.clock = pygame.time.Clock() def add_object(self, type_): if type_ == 'square': surf = pygame.Surface((50, 50)) spr = Sprite(self, 'square', [x // 2 for x in self.world.size], surf) self.sprites.append(spr) self.sprite_names.append(type_) def loop(self): while self.running: self.editor.update() for spr in self.sprites: spr.draw() self.clock.tick(self.fps) pygame.display.update() self.Events() def get_sprites(self): return self.sprites def Events(self): self.m_pos = pygame.mouse.get_pos() self.L_click, self.R_click = False, False for e in pygame.event.get(): if e.type == pygame.QUIT: self.running = False break elif e.type == pygame.MOUSEBUTTONDOWN: if e.button == 1: self.L_click = True elif e.button == 3: self.R_click = True self.hold = True elif e.type == pygame.MOUSEBUTTONUP: self.hold = False elif e.type == pygame.VIDEORESIZE: self.w_size = e.size self.screen = pygame.display.set_mode(e.size, pygame.RESIZABLE) self.editor.resize(e.w)
def post(self,request): start = int(float(request.POST['start'])) end = int(float(request.POST['end'])) editor = Editor(settings.MEDIA_ROOT+'/test1.mp4') video = editor.crop_video(start,end) filename = settings.MEDIA_ROOT+'/test1_temp.webm' editor.save_video(video,filename) return HttpResponse(json.dumps({'filename':settings.MEDIA_URL+'/test1_temp.webm?i='+n}), content_type='application/json')
def init(self): # get screen win = self['main_window'] screen = win.get_screen() print screen.get_width(), screen.get_height() self.current_window = None self.move(0,0) #print self.get_position() palette = Palette(self) palette.show() vbox = self['vbox'] hpaned = gtk.HPaned() hpaned.show() win.remove(vbox) hpaned.pack1(vbox, shrink=False) hpaned.pack2(palette.toplevel()) hpaned.set_property('position', 300) vbox0 = gtk.VBox() vbox0.pack_start(hpaned, expand=False) centerbox = gtk.HBox() centerbox.show() vbox0.pack_start(centerbox) vbox0.show() win.add(vbox0) browser = Browser(self) browser.show() centerbox.pack_start(browser.toplevel(), expand=False) self.tree = WidgetTree(self) obtreeview = self.tree['treeview'] self.tree.remove(obtreeview) browser.toplevel().append_page(obtreeview) #self.tree.move(0, self.get_height()+60) self.tree.hide() editor = Editor(self) editor.show() centerbox.pack_start(editor.toplevel()) propertybrowser = PropertyBrowser(self) self.propertybrowser = propertybrowser pbnotebook = propertybrowser['notebook'] propertybrowser.toplevel().remove(pbnotebook) centerbox.pack_start(pbnotebook, expand=False) propertybrowser.hide() self['toolbar'].set_style(gtk.TOOLBAR_ICONS)
def __init__(self, parent=None): super(mainWindow, self).__init__(parent) config.filename = "Untitled" self.tabNum = 0 self.treeVis = True self.termVis = False config.docList = [] self.edit = Editor() self.editDict = {"edit1": self.edit} self.tab = QTabWidget(self) self.initUI()
def post(self, request): start = int(float(request.POST['start'])) end = int(float(request.POST['end'])) editor = Editor(settings.MEDIA_ROOT + '/test1.mp4') video = editor.crop_video(start, end) filename = settings.MEDIA_ROOT + '/test1_temp.webm' editor.save_video(video, filename) return HttpResponse(json.dumps( {'filename': settings.MEDIA_URL + '/test1_temp.webm?i=' + n}), content_type='application/json')
def load(): global editor path = filedialog.askopenfilename() if path: if editor: for child in editor_area.winfo_children(): child.destroy() editor = Editor(path, master=editor_area, bg="black") editor.pack()
def init(self): # get screen win = self['main_window'] screen = win.get_screen() print screen.get_width(), screen.get_height() self.current_window = None self.move(0, 0) #print self.get_position() palette = Palette(self) palette.show() vbox = self['vbox'] hpaned = gtk.HPaned() hpaned.show() win.remove(vbox) hpaned.pack1(vbox, shrink=False) hpaned.pack2(palette.toplevel()) hpaned.set_property('position', 300) vbox0 = gtk.VBox() vbox0.pack_start(hpaned, expand=False) centerbox = gtk.HBox() centerbox.show() vbox0.pack_start(centerbox) vbox0.show() win.add(vbox0) browser = Browser(self) browser.show() centerbox.pack_start(browser.toplevel(), expand=False) self.tree = WidgetTree(self) obtreeview = self.tree['treeview'] self.tree.remove(obtreeview) browser.toplevel().append_page(obtreeview) #self.tree.move(0, self.get_height()+60) self.tree.hide() editor = Editor(self) editor.show() centerbox.pack_start(editor.toplevel()) propertybrowser = PropertyBrowser(self) self.propertybrowser = propertybrowser pbnotebook = propertybrowser['notebook'] propertybrowser.toplevel().remove(pbnotebook) centerbox.pack_start(pbnotebook, expand=False) propertybrowser.hide() self['toolbar'].set_style(gtk.TOOLBAR_ICONS)
def main(): ## load mappings ## try: setup_keymap_folder() except Exception: traceback.print_exc() utils.rpc('GUI.ShowNotification', title="Keymap Editor", message="Failed to remove old keymap file", image='error') return defaultkeymap = utils.read_keymap(default) userkeymap = [] if os.path.exists(gen_file): try: userkeymap = utils.read_keymap(gen_file) except Exception: traceback.print_exc() utils.rpc('GUI.ShowNotification', title="Keymap Editor", message="Failed to load keymap file", image='error') return ## main loop ## confirm_discard = False while True: idx = Dialog().select(tr(30000), [tr(30003), tr(30004), tr(30005)]) if idx == 0: # edit editor = Editor(defaultkeymap, userkeymap) editor.start() confirm_discard = editor.dirty elif idx == 1: # reset confirm_discard = bool(userkeymap) userkeymap = [] elif idx == 2: # save if os.path.exists(gen_file): shutil.copyfile(gen_file, gen_file + ".old") utils.write_keymap(userkeymap, gen_file) xbmc.executebuiltin("action(reloadkeymaps)") break elif idx == -1 and confirm_discard: if Dialog().yesno(tr(30000), tr(30006)) == 1: break else: break sys.modules.clear()
def _editWithEditorInThread(self, inputData, note = None): if note: self.getEvernote().loadNoteContent(note) editor = Editor(note.content) else: editor = Editor('') thread = EditorThread(editor) thread.start() result = True prevChecksum = editor.getTempfileChecksum() while True: if prevChecksum != editor.getTempfileChecksum() and result: newContent = open(editor.tempfile, 'r').read() inputData['content'] = Editor.textToENML(newContent) if not note: result = self.getEvernote().createNote(**inputData) # TODO: log error if result is False or None if result: note = result else: result = False else: result = bool(self.getEvernote().updateNote(guid=note.guid, **inputData)) # TODO: log error if result is False if result: prevChecksum = editor.getTempfileChecksum() if not thread.isAlive(): # check if thread is alive here before sleep to avoid losing data saved during this 5 secs break time.sleep(5) return result
def open_tab(self, ndir, itemtext, lineno=0): wx.BeginBusyCursor() try: if IS_WIN: self.Freeze() ndir = os.path.abspath(ndir) if IS_WIN: ndir = ndir.lower() ndir_isfile = os.path.isfile(ndir) if (ndir_isfile and os.path.splitext(ndir.lower())[-1] in ('.py', '.html', '.css', '.js', '.load', '.xml', '.json', '.rss')): if ndir in self.notebook: self.notebook.set_selection_by_filename(ndir) if lineno > 0: self.notebook.GetCurrentPage().goto_line(lineno) else: editor = Editor(self.notebook) editor.page_idx = self.notebook.GetPageCount() editor.filename = ndir self.notebook.AddPage(editor, itemtext) self.notebook.set_selection_by_filename(ndir) pid = editor.openfile(ndir, lineno) editor.pid = pid editor.Refresh() editor.SetFocus() elif (ndir_isfile and os.path.dirname(ndir).endswith('sessions')): self.open_sessionfile(ndir, itemtext) elif (ndir_isfile and os.path.dirname(ndir).endswith('cache')): self.open_cachefile(ndir, itemtext) elif (ndir_isfile and os.path.dirname(ndir).endswith('errors')): self.open_errorfile(ndir, itemtext) elif (ndir_isfile and os.path.splitext(ndir.lower())[-1] in ('.png', '.jpg', '.gif', '.ico')): self.open_image(ndir, itemtext) elif (ndir_isfile and os.path.dirname(ndir).endswith('databases')): self.open_dbviewer(ndir, itemtext) elif os.path.isdir(ndir): if USE_VTE: self.terminal.ctrl.feed_child('\ncd %s\n' % ndir) finally: if IS_WIN: self.Refresh() self.Thaw() wx.EndBusyCursor()
def open_project(self): folderName = str(QtGui.QFileDialog.getExistingDirectory(self, 'Open Project Directory')) if folderName == '': return editor = Editor() try: f = open(fileName) content = f.readlines() content = ''.join(content) editor.setPlainText(content) self._tabs.addTab(editor, 'New Document') self._tabs.setCurrentIndex(self._tabs.count()-1) editor.setFocus() except: QtGui.QMessageBox.information(self, 'Incorrect File', 'The file does not exist!')
def __init__(self): self.fps = 0 self.running = True self.world = World() self.m_pos = (0, 0) self.L_click = False self.R_click = False self.w_size = (700, 700) self.screen = pygame.display.set_mode(self.w_size, pygame.RESIZABLE) self.hold = False self.mouse_focus = 'window' self.sprites = [] self.sprite_names = [] self.editor = Editor(self) self.clock = pygame.time.Clock()
def _create_file(self, note): """ Creates file from note """ GeekNote( sleepOnRateLimit=self.sleep_on_ratelimit).loadNoteContent(note) escaped_title = re.sub(os.sep, "-", note.title) # Save images if "saveImages" in self.imageOptions and self.imageOptions[ "saveImages"]: imageList = Editor.getImages(note.content) if imageList: if ("imagesInSubdir" in self.imageOptions and self.imageOptions["imagesInSubdir"]): try: os.mkdir( os.path.join(self.path, escaped_title + "_images")) except OSError: # Folder already exists pass imagePath = os.path.join(self.path, escaped_title + "_images", escaped_title) self.imageOptions["baseFilename"] = (escaped_title + "_images/" + escaped_title) else: imagePath = os.path.join(self.path, escaped_title) self.imageOptions["baseFilename"] = escaped_title for imageInfo in imageList: filename = "{}-{}.{}".format(imagePath, imageInfo["hash"], imageInfo["extension"]) logger.info("Saving image to {}".format(filename)) binaryHash = binascii.unhexlify(imageInfo["hash"]) if not GeekNote(sleepOnRateLimit=self. sleep_on_ratelimit).saveMedia( note.guid, binaryHash, filename): logger.warning( "Failed to save image {}".format(filename)) content = Editor.ENMLtoText(note.content, self.imageOptions) path = os.path.join(self.path, escaped_title + self.extension) open(path, "w").write(content) updated_seconds = note.updated / 1000.0 os.utime(path, (updated_seconds, updated_seconds)) return True
def _update_file(self, file_note, note): """ Updates file from note """ GeekNote().loadNoteContent(note) content = Editor.ENMLtoText(note.content) open(file_note['path'], "w").write(content)
def showNote(note, id, shardId): separator("#", "URL") printLine("NoteLink: " + (config.NOTE_LINK % (shardId, id, note.guid))) printLine("WebClientURL: " + (config.NOTE_WEBCLIENT_URL % note.guid)) separator("#", "TITLE") printLine(note.title) separator("=", "META") printLine("Notebook: %s" % note.notebookName) printLine("Created: %s" % printDate(note.created)) printLine("Updated: %s" % printDate(note.updated)) for key, value in note.attributes.__dict__.items(): if value and key not in ("reminderOrder", "reminderTime", "reminderDoneTime"): printLine("%s: %s" % (key, value)) separator("|", "REMINDERS") printLine("Order: %s" % str(note.attributes.reminderOrder)) printLine("Time: %s" % printDate(note.attributes.reminderTime)) printLine("Done: %s" % printDate(note.attributes.reminderDoneTime)) separator("-", "CONTENT") if note.tagNames: printLine("Tags: %s" % ", ".join(note.tagNames)) from editor import Editor printLine(Editor.ENMLtoText(note.content))
def _create_file(self, note): """ Creates file from note """ GeekNote().loadNoteContent(note) # Save images if 'saveImages' in self.imageOptions and self.imageOptions['saveImages']: imageList = Editor.getImages(note.content) if imageList: if 'imagesInSubdir' in self.imageOptions and self.imageOptions['imagesInSubdir']: os.mkdir(os.path.join(self.path, note.title + "_images")) imagePath = os.path.join(self.path, note.title + "_images", note.title) self.imageOptions['baseFilename'] = note.title + "_images/" + note.title else: imagePath = os.path.join(self.path, note.title) self.imageOptions['baseFilename'] = note.title for imageInfo in imageList: filename = "{}-{}.{}".format(imagePath, imageInfo['hash'], imageInfo['extension']) logger.info('Saving image to {}'.format(filename)) binaryHash = binascii.unhexlify(imageInfo['hash']) GeekNote().saveMedia(note.guid, binaryHash, filename) content = Editor.ENMLtoText(note.content, self.imageOptions) path = os.path.join(self.path, note.title + self.extension) open(path, "w").write(content) return True
def __init__(self, root, sample_files, using_audio_out): """ root - main GUI window sample_files - list of relative paths to samples using_audio_out - True if pygame dependency supported, False otherwise """ self.root = root self.model = Model(len(sample_files), DEFAULT_N_BEATS, DEFAULT_BPM, DEFAULT_SWING, DEFAULT_COLUMNS_PER_BEAT) self.model.current_beat.add_callback(self.beat_update_handler) # remove relative path and .wav from filenames sample_names = [sample_file[:-4].rsplit('/', 1)[1] for sample_file in sample_files] self.editor = Editor(root, DEFAULT_N_BEATS, sample_names, DEFAULT_BPM, DEFAULT_SWING) # handle window close self.editor.protocol("WM_DELETE_WINDOW", self.quit) # binds callbacks with corresponding GUI elements self.editor.quit_button.bind("<Button-1>", self.quit_click_handler) self.editor.button_grid.bind("<Button-1>", self.sequencer_click_handler) self.editor.transport_bar.playback_button.bind("<Button-1>", self.playback_click_handler) self.editor.transport_bar.bpm.bind("<Button-1>", self.bpm_setter_click_handler) self.editor.transport_bar.number_beats.bind("<Button-1>", self.number_beats_setter_click_handler) self.editor.transport_bar.swing.bind("<ButtonRelease-1>", self.swing_setter_click_handler) self.editor.sample_boxes.bind("<Button-1>", self.sample_box_click_handler) # intializes audio output if dependencies available, console output otherwise if using_audio_out: from audio import Audio self.output = Audio(sample_files) else: from console_output import ConsoleOutput self.output = ConsoleOutput(sample_names)
def __init__(self, romfile, cdc): self.stdscr = curses.initscr() curses.start_color() curses.use_default_colors() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_YELLOW) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_BLUE) curses.noecho() curses.cbreak() self.stdscr.keypad(1) curses.curs_set(True) self.editor = Editor(romfile, 32, 40, cdc) self.width = self.editor.width # Convenient alias self.height = self.editor.height # Convenient alias self.windows = { 'src': curses.newwin(self.height, self.width, 1, 1), 'dst': curses.newwin(self.height, self.width, 1, self.width + 2), } self.windows['src'].bkgd(' ', curses.color_pair(1)) self.windows['dst'].bkgd(' ', curses.color_pair(3)) self.windows['src'].addstr(0, 0, self.editor.windows['src']) self.windows['dst'].addstr(0, 0, self.editor.windows['dst']) self.textboxes = { 'src': curses.textpad.Textbox(self.windows['src'], insert_mode=False), 'dst': curses.textpad.Textbox(self.windows['dst'], insert_mode=True), } self.textboxes['src'].stripspaces = 0 self.textboxes['dst'].stripspaces = 0 self.windows['dst'].putwin(open('dst.out', 'wb'))
def initUI(self): self.layout = QtGui.QHBoxLayout(self) self.menuLayout = QtGui.QVBoxLayout(self) self.detailLayout = QtGui.QVBoxLayout(self) self.menuLayout.setContentsMargins(8, 8, 8, 8) self.model = model self.view, self.view_selection = self.initView(model) self.viewcontext = self.initContext() self.viewsearch = LineEdit(self) self.viewtoolbar = self.initToolbar() self.editor = Editor(self) self.detailLayout.addWidget(self.editor) self.menuLayout.addWidget(self.viewtoolbar) self.menuLayout.addWidget(self.viewsearch) self.menuLayout.addWidget(self.view) self.layout.addLayout(self.menuLayout) self.layout.addLayout(self.detailLayout) self.layout.setStretchFactor(self.menuLayout, 2) self.layout.setStretchFactor(self.detailLayout, 3) self.setStyleSheet() self.setLayout(self.layout)
def __init__(self): ShowBase.__init__(self) # создаём менеджер карты self.map_manager = MapManager() # создаём контроллер мышки и клавиатуры self.controller = Controller() # создаём редактор self.editor = Editor(self.map_manager) # загружаем картинку курсора pointer = OnscreenImage(image='target.png', pos=(0, 0, 0), scale=0.08) # устанавливаем прозрачность pointer.setTransparency(TransparencyAttrib.MAlpha) # имя файла для сохранения и загрузки карт self.file_name = "my_map.dat" self.accept("f1", self.basicMap) self.accept("f2", self.generateRandomMap) self.accept("f3", self.saveMap) self.accept("f4", self.loadMap) print("'f1' - создать базовую карту") print("'f2' - создать случайную карту") print("'f3' - сохранить карту") print("'f4' - загрузить карту") # генерируем случайный уровень self.generateRandomMap()
def _parseInput(self, title=None, content=None, tags=None, notebook=None, resources=None, note=None): result = {"title": title, "content": content, "tags": tags, "notebook": notebook, "resources": resources} result = tools.strip(result) # if get note without params if note and title is None and content is None and tags is None and notebook is None: content = config.EDITOR_OPEN if title is None and note: result["title"] = note.title if content: if content != config.EDITOR_OPEN: if isinstance(content, str) and os.path.isfile(content): logging.debug("Load content from the file") content = open(content, "r").read() logging.debug("Convert content") content = Editor.textToENML(content) result["content"] = content if tags: result["tags"] = tools.strip(tags.split(",")) if notebook: notepadGuid = Notebooks().getNoteGUID(notebook) if notepadGuid is None: newNotepad = Notebooks().create(notebook) notepadGuid = newNotepad.guid result["notebook"] = notepadGuid logging.debug("Search notebook") return result
def dataChanged(self, sel): path = self._path + ".*" path = path.replace('__root__.', '') self._throw(Editor.Out.FieldChanged, Editor.translatePath(self._document, path)) self._document.select(self._path + '.*', sel) if self._delegate: self._delegate.selectRow(sel)
def __init__(self, dock=None): dbg_print ("AbcEditor.__init__", dock) widgetWithMenu.__init__(self) Editor.__init__(self) #font = QtGui.QFont() font = self.font() font.setPointSize(10) self.setFont(font) self.setCursorWidth(2) self.setWindowTitle('title') self.textChanged.connect(self.handleTextChanged) self.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap) self.dock = dock Common.timer.timeout.connect(self.countDown) self.cursorPositionChanged.connect( self.handleCursorMove) self.originalText = None
def __init__(self, filename): self.filename = filename self.document = Document(self.filename) self.edit = Editor(self) self.edit.set_edit_markup(self.document.lines()) fill = urwid.Filler(self.edit, valign='top') self.statusbar = urwid.Text(u'') super(Window, self).__init__(fill, footer=self.statusbar)
def __init__( self ): Gtk.Application.__init__( self, application_id = "org.pyFrisc.IDE" ) self.connect( "activate", self.on_activate ) self.load_config() self.editor = Editor( self, self.config ) self.console = Console( self, self.config ) self.simulator = SimulatorView( self, self.console, self.config )
class Window(urwid.Frame): def __init__(self, filename): self.filename = filename self.document = Document(self.filename) self.edit = Editor(self) self.edit.set_edit_markup(self.document.lines()) fill = urwid.Filler(self.edit, valign='top') self.statusbar = urwid.Text(u'') super(Window, self).__init__(fill, footer=self.statusbar) def set_status(self, text): self.statusbar.set_text(text) def run(self): loop = urwid.MainLoop(self, palette=[('heading', 'bold', ''), ('span', 'underline', ''), ('current span', 'underline,yellow', ''), ('soft break', '', 'dark red')]) loop.run()
def __init__(self, notebook): Editor.__init__(self, notebook) self.buf = ShellBuffer(self.notebook) self.view = ShellView(self.buf) self.view.modify_font(pango.FontDescription("monospace")) self.widget = gtk.ScrolledWindow() self.widget.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.widget.add(self.view) self.widget.show_all() self.buf.worksheet.connect('notify::filename', lambda *args: self._update_filename()) self.buf.worksheet.connect('notify::file', lambda *args: self._update_file()) self.buf.worksheet.connect('notify::code-modified', lambda *args: self._update_modified()) self.buf.worksheet.connect('notify::state', lambda *args: self._update_state())
def _parseInput(self, title=None, content=None, tags=None, notebook=None, resources=[], note=None, reminder=None): result = { "title": title, "content": content, "tags": tags, "notebook": notebook, "resources": resources, "reminder": reminder, } result = tools.strip(result) # if get note without params if note and title is None and content is None and tags is None and notebook is None: content = config.EDITOR_OPEN if title is None and note: result['title'] = note.title if content: if content != config.EDITOR_OPEN: if isinstance(content, str) and os.path.isfile(content): logging.debug("Load content from the file") content = open(content, "r").read() logging.debug("Convert content") content = Editor.textToENML(content) result['content'] = content if tags: result['tags'] = tools.strip(tags.split(',')) if notebook: notepadGuid = Notebooks().getNoteGUID(notebook) if notepadGuid is None: newNotepad = Notebooks().create(notebook) notepadGuid = newNotepad.guid result['notebook'] = notepadGuid logging.debug("Search notebook") if reminder: then = config.REMINDER_SHORTCUTS.get(reminder) if then: now = int(round(time.time() * 1000)) result['reminder'] = now + then elif reminder not in [config.REMINDER_NONE, config.REMINDER_DONE, config.REMINDER_DELETE]: reminder = tools.strip(reminder.split('-')) try: dateStruct = time.strptime(reminder[0] + " " + reminder[1] + ":00", config.DEF_DATE_AND_TIME_FORMAT) reminderTime = int(round(time.mktime(dateStruct) * 1000)) result['reminder'] = reminderTime except (ValueError, IndexError): out.failureMessage('Incorrect date format in --reminder attribute. ' 'Format: %s' % time.strftime(config.DEF_DATE_FORMAT, time.strptime('199912311422', "%Y%m%d%H%M"))) return tools.exitErr() return result
def __init__(self): super(Window, self).__init__() self.setWindowTitle("Feel2") self.editor = Editor() self.setCentralWidget(self.editor) self.max_recent_projects = 10 self.create_menus() self.create_shortcuts() self.read_settings()
def __init__(self, notebook): Editor.__init__(self, notebook) self.buf = ShellBuffer(self.notebook, edit_only=True) self.view = ShellView(self.buf) self.__font_is_custom_connection = global_settings.watch('editor-font-is-custom', self.__update_font) self.__font_name_connection = global_settings.watch('editor-font-name', self.__update_font) self.__update_font() self.widget = gtk.ScrolledWindow() self.widget.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.widget.add(self.view) self.widget.show_all() self.buf.worksheet.sig_filename_changed.connect( lambda *args: self._update_filename() ) self.buf.worksheet.sig_file.connect(lambda *args: self._update_file()) self.buf.worksheet.sig_code_modified.connect(lambda *args: self._update_modified())
def __init__(self, notebook): Editor.__init__(self, notebook) self.buf = ShellBuffer(self.notebook) self.view = ShellView(self.buf) self.__font_is_custom_connection = global_settings.connect('notify::editor-font-is-custom', self.__update_font) self.__font_name_connection = global_settings.connect('notify::editor-font-name', self.__update_font) self.__update_font() self.widget = gtk.ScrolledWindow() self.widget.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.widget.add(self.view) self.widget.show_all() self.buf.worksheet.connect('notify::filename', lambda *args: self._update_filename()) self.buf.worksheet.connect('notify::file', lambda *args: self._update_file()) self.buf.worksheet.connect('notify::code-modified', lambda *args: self._update_modified()) self.buf.worksheet.connect('notify::state', lambda *args: self._update_state())
def main(): reading_id = int(sys.argv[1]) session = Session() bible_query = BibleQuery() reading = session.query(Reading).filter(Reading.id == reading_id).one() text = reading.text if reading.text is not None else "" editor = Editor() # Fix wrong quotation marks text = re.sub(ur'"([a-zA-ZàòùèéìÒÀÙÈÉÌ0-9])', ur'“\1', text, count=0) text = re.sub(ur'([a-zA-ZàòùèéìÒÀÙÈÉÌ0-9\.?!])"', ur'\1”', text, count=0) # From http://stackoverflow.com/questions/15120346/emacs-setting-comment-character-by-file-extension PrependStream(editor.tempfile, '# ').write(u'-*- coding: utf-8; comment-start: "#"; -*-\n') PrependStream(editor.tempfile, '# ').write(u'Quote: %s\n' % (reading.quote)) editor.tempfile.write(u'\n') editor.tempfile.write(text) editor.tempfile.write(u'\n') PrependStream(editor.tempfile, '# ').write(u'Useful characters: “”–\n\n') try: converted_quote = convert_quote_psalm_numbering(reading.quote, False) bible_text = bible_query.get_text(decode_quote(converted_quote, allow_only_chap=True)) except: PrependStream(editor.tempfile, '# ').write(u'Quote: %s\nCould not retrieve bible text\n' % (reading.quote)) print decode_quote(reading.quote, allow_only_chap=True) raise else: bible_text = "\n".join(map(lambda x: x.strip(), bible_text.split('\n'))) PrependStream(editor.tempfile, '# ').write(u'Quote: %s\nConverted quote: %s\nBible text:\n\n%s' % (reading.quote, converted_quote, bible_text)) editor.edit() new_text = u''.join(filter(lambda x: not x.startswith(u'#'), editor.edited_content)).strip() + u'\n' if editor.confirmation_request(new_text != reading.text): reading.text = new_text session.commit() else: session.rollback()
def _get_file_content(self, path): """ Get file content. """ content = open(path, "r").read() # strip unprintable characters content = remove_control_characters(content.decode("utf-8")).encode("utf-8") content = Editor.textToENML(content=content, raise_ex=True, format=self.format) if content is None: logger.warning("File {0}. Content must be " "an UTF-8 encode.".format(path)) return None return content