def combinedTest(): document = Document() editor = Editor() print("adding new editor states") editor.setContent("a") history.push(editor.createState()) print(str(editor)) editor.setContent("b") print(str(editor)) print("adding new document states") document.setContent("Hello World!") document.setFont("Times-New-Roman", 12) history.push(deepcopy(document)) print(str(document)) document.setContent("foo bar baz") document.setFont("Arial", 14) print(str(document)) print("restoring from history") editor.restore(history.pop(editor.createState())) print(str(editor)) document = history.pop(document) print(str(document))
def __add_edit(self, file_path=""): editor = Editor(file_path, self) #on garde le nom des fichiers avec leur chemins pour ne pas ouvrir plusieurs fois le même if file_path != "": self.opened_files[editor.get_name()] = editor.get_path() #Add Tab with Editor self.add_tab(editor)
def main(): """the main function""" print("==================================================") print("Green Editor v%i.%i.%i" % (major, minor, tiny)) print("==================================================") ed = Editor(project, path) ed.start()
def __init__(self, parent=None): super(mainWindow, self).__init__(parent) config.filename = "Untitled" self.tabNum = 0 self.treeVis = False self.termVis = False config.docList = [] self.edit = Editor() self.editDict = {"edit1": self.edit} self.tab = QTabWidget(self) self.initUI()
def newTab(self): self.tabNum += 1 # Add a new entry to the dict and map it to an editor object self.editDict["edit" + str(self.tabNum)] = Editor() self.tab.addTab(self.getEditor(self.tabNum), "Untitled") self.guessLexer() self.getEditor(self.tab.currentIndex() + 1).lexer.setFont(config.font)
def __init__(self): self.config = Config() self.config.load() self.icon = pygame.Surface((32, 32)) self.icon.set_colorkey((0, 0, 0)) pygame.draw.polygon(self.icon, (150, 150, 150), [[8, 0], [8, 32], [24, 32], [24, 0]]) self.window = Window(self, "GreyRectangle", WINDOW_SIZE, SURFACE_SIZE, flags=Frame.RESIZABLE, icon=self.icon, fullscreen=self.config.config["Fullscreen"]) self.player = Player(self) self.menuHandler = MenuHandler(self) self.menuHandler.show(self.menuHandler.loadScreen) self.setProgress(0) self.blocks = Blocks(self) self.editor = Editor(self) self.camera = Camera(self) self.menuHandler.create() self.warningHandler = WarningHandler(self.window) self.keyBindingsMenu = KeyBindingsMenu(self) self.levelPreview = View(self) self.levelHandler = LevelHandler(self) self.levelSelection = LevelSelection(self) self.debugScreen = DebugScreen(self.window) self.window.guiChanger = self.config.config["Controls"]["GuiChanger"] self.window.guiPresser = self.config.config["Controls"]["GuiPresser"] self.window.guiEscape = self.config.config["Controls"]["Escape"] self.debugScreenActive = self.config.config["DebugScreenActive"] self.window.fpsLimit = self.config.config["FPSLimit"] self.window.useBusyLoop = self.config.config["UseBusyLoop"] self.menuHandler.getVolume(self.config.config["Volume"]) self.window.disableGuiAnimations = not self.config.config[ "GuiStaticAnimations"] self.window.disableGuiComeInAnimations = not self.config.config[ "GuiComeInAnimations"] self.playing = False self.editing = False if failedSDL2Import: self.warningHandler.createWarning("Unable to import pygame_sdl2 !", 2) self.setProgress(100) self.window.updateClock() self.loop()
def editExcludesFile(self): self.Parent.setTabsState(False) mode = 0 if self.mode.currentIndex() else 1 if mode : path_ = os.path.expanduser('~/.config/thrifty/thrifty.excludes') else : path_ = '/etc/thrifty.excludes' self.editor = Editor(path_, mode, self) self.editor.show()
def __init__(self, main_window): QtGui.QVBoxLayout.__init__(self) main_window.vbox_layout = self self.main_window = main_window self.setSpacing(0) toolbar = ToolBar(main_window) self.addWidget(toolbar) editor = Editor(main_window) self.addWidget(editor)
def __init__(self, parent = None): super(mainWindow, self).__init__(parent) config.filename = "Untitled" self.tabNum = 0 self.treeVis = False self.termVis = False config.docList = [] self.edit = Editor() self.editDict = {"edit1":self.edit} self.tab = QTabWidget(self) self.initUI()
def run_Editor(self): # check if metadata file exists if not self.checkMetadata(): return standard = MetaInfoStandard.tryDetermineStandard(self.metaProvider) if standard != MetaInfoStandard.ISO19115: QMessageBox.critical(self.iface.mainWindow(),u"Μεταδεδομένα",u"Τα μεταδεδομένα δεν είναι συμβατά με Inspire!") return self.IsRunning=True dlg = Editor(self.iface,self.metaFilePath) dlg.setContent(self.metaProvider) dlg.exec_() self.IsRunning=False dlg.removetemplayer()
def main(stdscr, args): quit = False ch = -1 init_colors() file = None if len(args.files) > 0: file = args.files[0] editor = Editor(file, curses.LINES, curses.COLS, 0, 0) while not editor.shouldClose(): editor.refresh() editor.update(ch)
def main(): app = QApplication(sys.argv) translator = QTranslator() if translator.load('editor_'+ QLocale.system().name()+'.qm',":/translations/"): app.installTranslator(translator) translator_qt = QTranslator() if translator_qt.load('qt_'+ QLocale.system().name()+'.qm',":/translations/"): # print('i found qt') app.installTranslator(translator_qt) mainwindow = Editor() mainwindow.setWindowTitle('simple text editor') mainwindow.setWindowIcon(QIcon(':/icons/editor.ico')) mainwindow.show() sys.exit(app.exec_())
def run(): """ Esegue l'emulatore del pdp8 """ CD = pdp8() principale = Tk() principale.title("Pdp8 Emulator : Assembly Editor") emulatore = Toplevel() emulatore.title("Pdp8 Emulator") emulatore.geometry("1015x589") edit = Editor(principale, CD) scrollbar1 = AutoScrollbar(emulatore) scrollbar1.grid(row=0, column=1, sticky=N + S) scrollbar2 = AutoScrollbar(emulatore, orient=HORIZONTAL) scrollbar2.grid(row=1, column=0, sticky=E + W) finestra = Canvas(emulatore, yscrollcommand=scrollbar1.set, xscrollcommand=scrollbar2.set) finestra.grid(row=0, column=0, sticky=N + S + E + W) scrollbar1.config(command=finestra.yview) scrollbar2.config(command=finestra.xview) emulatore.grid_rowconfigure(0, weight=1) emulatore.grid_columnconfigure(0, weight=1) emul = Emulatore(finestra, edit, CD, emulatore) finestra.create_window(0, 0, anchor=NW, window=emul.master) emul.master.update_idletasks() finestra.config(scrollregion=finestra.bbox("all")) principale.protocol("WM_DELETE_WINDOW", edit.exit) emulatore.protocol("WM_DELETE_WINDOW", emul.exit) principale.mainloop() emulatore.mainloop()
class BackUp(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) self.Parent = parent self.tr = Translator('Thrifty') self.runned = False self.trChunk0 = self.tr._translate('backs up own $HOME only') self.trChunk1 = self.tr._translate('without Excludes path.') self.trChunk2 = self.tr._translate('backs up catalogs:') self.trChunk3 = self.tr._translate('all real $HOMEs in system') self.layout = QGridLayout() self.layout.setAlignment(Qt.AlignLeft) self.buttonLayout = QVBoxLayout() self.buttonLayout.setAlignment(Qt.AlignCenter) self.mode = QComboBox() self.mode.setIconSize(QSize(32,32)) #self.mode.addItems(QStringList() << 'User' << 'Root') self.mode.addItem (QIcon('/usr/share/thrifty/icons/user.png'), '') self.mode.addItem (QIcon('/usr/share/thrifty/icons/admin.png'), '') self.mode.setToolTip(self.tr._translate('User Mode')) self.speed = QComboBox() self.speed.setIconSize(QSize(32,32)) #self.speed.addItems(QStringList() << 'Slow' << 'Normal' << 'Fast' << 'Fast+') self.speed.addItem (QIcon('/usr/share/thrifty/icons/slow.png'), '') self.speed.addItem (QIcon('/usr/share/thrifty/icons/normal.png'), '') self.speed.addItem (QIcon('/usr/share/thrifty/icons/fast.png'), '') self.speed.addItem (QIcon('/usr/share/thrifty/icons/fast+.png'), '') self.speed.setToolTip(self.tr._translate('Slow')) self.editExcludes = QPushButton(QIcon('/usr/share/thrifty/icons/edit.png'), '') self.editExcludes.setIconSize(QSize(32,32)) self.editExcludes.setToolTip(self.tr._translate('Edit Excludes file for current regime')) self.editExcludes.clicked.connect(self.editExcludesFile) self.start = QPushButton(QIcon('/usr/share/thrifty/icons/start.png'), '') self.start.setIconSize(QSize(32,32)) self.start.clicked.connect(self.runBackUp) self.start.setToolTip(self.tr._translate('Start task')) self.buttonLayout.addWidget(self.mode) self.buttonLayout.addWidget(self.speed) self.buttonLayout.addWidget(self.editExcludes) self.buttonLayout.addWidget(self.start) self.descriptionTask = QLabel('') self.descriptionTask.setAlignment(Qt.AlignLeft) self.progress = QProgressBar() self.progress.setOrientation(Qt.Vertical) self.progress.hide() self.progress.setRange(0, 0) self.logIn = QLabel('') self.logIn.setToolTip(self.tr._translate('Log of processed task')) self.logIn.setOpenExternalLinks(True) self.layout.addItem(self.buttonLayout, 0, 0) self.layout.addWidget(self.progress, 0, 1) self.layout.addWidget(self.descriptionTask, 0, 2) self.layout.addWidget(self.logIn, 1, 0) self.setLayout(self.layout) self.mode.currentIndexChanged.connect(self.changeModeContent) self.speed.currentIndexChanged.connect(self.changeSpeedContent) self.mode.currentIndexChanged.emit(0) def changeModeContent(self, i = 0): if i : self.mode.setToolTip(self.tr._translate('Root Mode')) self.descriptionTask.setText(ROOT_DESCRIPTION(self.trChunk2, self.trChunk3, self.trChunk1)) self.editExcludes.setToolTip(self.tr._translate('Edit Excludes file for ') + \ '<font color=red><b>ROOT</b></font> ' + \ self.tr._translate('mode')) else : self.mode.setToolTip(self.tr._translate('User Mode')) self.descriptionTask.setText(USER_DESCRIPTION(self.trChunk0, self.trChunk1)) self.editExcludes.setToolTip(self.tr._translate('Edit Excludes file for ') + \ '<font color=green><b>USER</b></font> ' + \ self.tr._translate('mode')) def changeSpeedContent(self, i = 0): if i == 3 : self.speed.setToolTip(self.tr._translate('Fast+')) elif i == 2 : self.speed.setToolTip(self.tr._translate('Fast')) elif i == 1 : self.speed.setToolTip(self.tr._translate('Normal')) else : self.speed.setToolTip(self.tr._translate('Slow')) def runBackUp(self): self.Parent.setTabsState(False) self.progress.show() self.runned = True mode = 0 if self.mode.currentIndex() else 1 speed = SPEED[self.speed.currentIndex()] print 'BackUp running in %i mode and %i speed ...' % (mode, speed) self.t = QProcess() Data = QStringList() Data.append('/usr/share/thrifty/thrifty.py') opt = ''.join(('G:', str(USER_UID), '/', str(USER_GID), '::', str(speed))) Data.append(opt) self.t.finished.connect(self.showResult) if mode : self.t.start('python', Data) else : self.t.start('pkexec', Data) if self.t.waitForStarted() : self.runned = True #print self.t.state() else : self.showResult() def setState(self, state): self.mode.setEnabled(state) self.speed.setEnabled(state) self.editExcludes.setEnabled(state) self.start.setEnabled(state) self.descriptionTask.setEnabled(state) def showResult(self): self.runned = False self.Parent.setTabsState(True) self.progress.hide() name_ = '/dev/shm/thrifty.lastTask' if os.path.isfile(name_) : with open(name_, 'rb') as f : pathToLog = f.read() os.remove(name_) else : pathToLog = 'ERROR' self.logIn.setText('<a href="%s">Log in $TEMP<a>' % pathToLog) def editExcludesFile(self): self.Parent.setTabsState(False) mode = 0 if self.mode.currentIndex() else 1 if mode : path_ = os.path.expanduser('~/.config/thrifty/thrifty.excludes') else : path_ = '/etc/thrifty.excludes' self.editor = Editor(path_, mode, self) self.editor.show() def enableEditorButton(self): self.Parent.setTabsState(True)
class Main: def __init__(self): self.config = Config() self.config.load() self.icon = pygame.Surface((32, 32)) self.icon.set_colorkey((0, 0, 0)) pygame.draw.polygon(self.icon, (150, 150, 150), [[8, 0], [8, 32], [24, 32], [24, 0]]) self.window = Window(self, "GreyRectangle", WINDOW_SIZE, SURFACE_SIZE, flags=Frame.RESIZABLE, icon=self.icon, fullscreen=self.config.config["Fullscreen"]) self.player = Player(self) self.menuHandler = MenuHandler(self) self.menuHandler.show(self.menuHandler.loadScreen) self.setProgress(0) self.blocks = Blocks(self) self.editor = Editor(self) self.camera = Camera(self) self.menuHandler.create() self.warningHandler = WarningHandler(self.window) self.keyBindingsMenu = KeyBindingsMenu(self) self.levelPreview = View(self) self.levelHandler = LevelHandler(self) self.levelSelection = LevelSelection(self) self.debugScreen = DebugScreen(self.window) self.window.guiChanger = self.config.config["Controls"]["GuiChanger"] self.window.guiPresser = self.config.config["Controls"]["GuiPresser"] self.window.guiEscape = self.config.config["Controls"]["Escape"] self.debugScreenActive = self.config.config["DebugScreenActive"] self.window.fpsLimit = self.config.config["FPSLimit"] self.window.useBusyLoop = self.config.config["UseBusyLoop"] self.menuHandler.getVolume(self.config.config["Volume"]) self.window.disableGuiAnimations = not self.config.config[ "GuiStaticAnimations"] self.window.disableGuiComeInAnimations = not self.config.config[ "GuiComeInAnimations"] self.playing = False self.editing = False if failedSDL2Import: self.warningHandler.createWarning("Unable to import pygame_sdl2 !", 2) self.setProgress(100) self.window.updateClock() self.loop() def setProgress(self, progress): self.progress = progress self.menuHandler.loadScreen.createdGuis[0].setProgress(progress) self.menuHandler.update() self.window.update() self.window.surface.fill((255, 255, 255)) self.menuHandler.render() self.window.updateDisplay() def loop(self): while self.window.isOpen: if self.window.key == self.config.config["Controls"]["FullScreen"]: self.window.toggleFullscreen() if self.window.key == self.config.config["Controls"]["ScreenShot"]: if pygame.K_F11 > 1000: self.warningHandler.createWarning( "Screenshots are not supported in SDL2 !", 3) else: if not os.path.exists("Screenshots"): os.makedirs("Screenshots") currentTime = time.localtime() count = "" name = "Screenshots/screenshot-" + str( currentTime.tm_hour) + ":" + str( currentTime.tm_min) + ":" + str(currentTime.tm_sec) while os.path.exists(name + str(count) + ".png"): if count == "": count = 0 count -= 1 pygame.image.save(self.window.surface, name + str(count) + ".png") if self.window.key == self.config.config["Controls"][ "DebugScreen"]: self.debugScreenActive = not self.debugScreenActive self.window.update() self.menuHandler.update() self.warningHandler.update() self.window.surface.fill((255, 255, 255)) if self.playing and not self.levelPreview.shouldRender: self.camera.update() self.player.update() self.camera.render() self.player.render() if self.editing and not self.levelPreview.shouldRender: self.editor.update() self.camera.update() self.camera.render() self.editor.render() updatedPreview = False if self.levelPreview.shouldRender: self.levelPreview.update() self.levelPreview.render() updatedPreview = True if self.menuHandler.levelSelection.createdGuis != [] or self.menuHandler.levelSelectionEdit.createdGuis != [] or not self.levelSelection.closed or \ self.menuHandler.goToPlay: self.player.update(False) self.player.render() if not updatedPreview: self.levelPreview.update() self.levelSelection.update() self.levelPreview.render() self.levelSelection.render() if not self.config.config["GuiComeInAnimations"]: self.player.activeCount = 2 if self.menuHandler.keyBindings.createdGuis != []: self.keyBindingsMenu.update() self.keyBindingsMenu.render() self.menuHandler.render() if self.warningHandler.isActive: self.warningHandler.render() if self.debugScreenActive: self.debugScreen.render() self.window.updateDisplay() self.window.exit()
class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setWindowTitle('MIPS') # 窗口标题 # 设置各项菜单 self.setupFileMenu() self.setupAssembleMenu() self.setupDebugMenu() self.setupHelpMenu() self.setupEditor() # 设置编辑器 self.setCentralWidget(self.editor) self.setupDock() # 设置Dock栏 def setupEditor(self): self.editor = Editor() # 创建编辑器对象 def setupFileMenu(self): fileMenu = QMenu('文件(&F)', self) self.menuBar().addMenu(fileMenu) self.currentFile = '' # 设置当前文件路径为空值 fileMenu.addAction('新建(&N)', self.newFile, 'Ctrl+N') # 新建立一个文件 fileMenu.addAction('打开(&O)...', self.openFile, 'Ctrl+O') # 打开已有的文件 fileMenu.addAction('保存(&S)', self.saveFile, 'Ctrl+S') # 将当前文件保存 fileMenu.addAction('另存为(&A)...', self.saveAnotherFile, 'Ctrl+Alt+S') # 将当前文件保存到指定路径 fileMenu.addAction('退出(&X)', self.close, 'Ctrl+F4') # 退出MIPS汇编器 def setupAssembleMenu(self): assembleMenu = QMenu('汇编(&A)', self) self.menuBar().addMenu(assembleMenu) self.assembler = Assembler() # 创建汇编器对象 assembleMenu.addAction('汇编(&A)', self.assemble, 'F10') # 对当前代码实行汇编操作 assembleMenu.addAction('反汇编(&D)', self.disassemble, 'F11') # 对当前代码实行反汇编操作 def setupDebugMenu(self): assembleMenu = QMenu('调试(&D)', self) self.menuBar().addMenu(assembleMenu) self.isStart = False # 设置是否开始调试布尔值为否 assembleMenu.addAction('启动调试(&S)', self.startDebug, 'F5') # 启动调试 assembleMenu.addAction('继续调试(&C)', self.contiuneDebug, 'F5') # 将调试进行到最后一步 assembleMenu.addAction('单步执行(&I)', self.nextDebug, 'F11') # 单步进行调试 assembleMenu.addAction('停止调试(&S)', self.stopDebug, 'Shift+F5') # 停止调试过程 assembleMenu.addAction('重启调试(&R)', self.resetDebug, 'Ctrl+Shift+F5') # 重新启动调试过程 def setupHelpMenu(self): helpMenu = QMenu("帮助(&H)", self) self.menuBar().addMenu(helpMenu) helpMenu.addAction('关于(&A)', self.about) # 本程序的小介绍 def setupDock(self): # 建立输出运行结果的窗口 self.rightBrowser = Browser() # 建立在窗口右端 self.rightDock = QDockWidget('运行结果/内存', self) self.rightDock.setFeatures(QDockWidget.DockWidgetClosable) self.rightDock.setWidget(self.rightBrowser) self.addDockWidget(Qt.RightDockWidgetArea, self.rightDock) self.rightDock.hide() # 窗口自动隐藏 # 建立输出调试过程的窗口 self.bottomBrowser = Browser() # 建立在窗口底端 self.bottomDock = QDockWidget('调试窗口', self) self.bottomDock.setFeatures(QDockWidget.DockWidgetClosable) self.bottomDock.setWidget(self.bottomBrowser) self.addDockWidget(Qt.BottomDockWidgetArea, self.bottomDock) self.bottomDock.hide() def newFile(self): self.editor.clear() # 清空当前屏幕 self.rightDock.hide() # 隐藏Dock栏 self.bottomDock.hide() self.currentFile = '' return True def openFile(self): # 打开汇编文件或二进制文件 path, _ = QFileDialog.getOpenFileName( self, '打开', '', '汇编文件 (*.asm);;二进制文件(*.coe *.bin)') if path: file = open(path, 'r') self.editor.setPlainText(file.read()) file.close() self.rightDock.hide() self.bottomDock.hide() self.currentFile = path return True return False def saveFile(self): # 如果没有文件名则跳转到另存为 if not self.currentFile: return self.saveAnotherFile() # 将编辑器内容写入到当前路径文件 file = open(self.currentFile, 'w') file.write(self.editor.toPlainText()) file.close() return True def saveAnotherFile(self): # 选择存入文件路径 path, _ = QFileDialog.getSaveFileName( self, '另存为', self.currentFile if self.currentFile else '', '汇编文件 (*.asm);;二进制文件(*.coe *.bin)') # 路径存在则将编辑器内容写入 if path: file = open(path, 'w') file.write(self.editor.toPlainText()) file.close() self.currentFile = path return True return False def assemble(self): self.saveFile() # 执行前保存文件 try: self.rightBrowser.setText(self.assembler.assembly( self.currentFile)) # 执行汇编并在右侧输出结果 except: self.rightBrowser.setText( 'error!!! \ncheck your code!!!') # 代码有误不能正确汇编 return self.rightDock.show() def disassemble(self): self.saveFile() try: self.rightBrowser.setText( self.assembler.disassembly(self.currentFile)) # 执行反汇编并在右侧输出结果 except: self.rightBrowser.setText( 'error!!! \ncheck your code!!!') # 代码有误不能正确反汇编 return self.rightDock.show() def startDebug(self): self.saveFile() self.assembler.step = 0 # 初始化执行步数 self.debugStr = '' # 初始化结果字符 self.isStart = True # 设定已经开始 # 初始化寄存器内容 for k in self.assembler.registers: self.assembler.registers[k] = '00000000' self.assembler.memory = {} # 初始化内存 try: self.assembler.debug(self.currentFile) self.debugStr = str(self.assembler.memory).strip("{}").replace( "'", '').replace(':', ' ').replace(',', ' ') # 执行单步模拟操作 except: self.debugStr += '\nthe debug is over\nnow check your code' # 模拟完成或代码有误则停止 return False # 将寄存器内容展示在底部,结果展示在右部 self.bottomBrowser.setText(' ' + str(self.assembler.registers).strip( "{},").replace(':', '\t').replace(',', '\t').replace("'", '')) self.rightBrowser.setText(self.debugStr) self.rightDock.show() self.bottomDock.show() return True def contiuneDebug(self): # 如果没有开始则开始调试 if not self.isStart: self.startDebug() # 模拟进行到最后一步 while self.nextDebug(): continue self.bottomBrowser.setText( str(self.assembler.registers).strip("{},").replace( ':', '\t').replace(',', '\t').replace("'", '')) self.rightBrowser.setText(self.debugStr) self.rightDock.show() self.bottomDock.show() return True def nextDebug(self): if not self.isStart: return self.startDebug() try: self.assembler.debug(self.currentFile) self.debugStr = str(self.assembler.memory).strip("{}").replace( "'", '').replace(':', ' ').replace(',', ' ') except: self.debugStr += '\nthe debug is over\nnow check your code' self.rightBrowser.setText(self.debugStr) self.rightDock.show() return False self.bottomBrowser.setText( str(self.assembler.registers).strip("{},").replace( ':', '\t').replace(',', '\t').replace("'", '')) self.rightBrowser.setText(self.debugStr) self.rightDock.show() self.bottomDock.show() return True def stopDebug(self): self.isStart = False # 结束调试并将开始置否 self.bottomDock.hide() self.rightDock.hide() return True def resetDebug(self): self.stopDebug() return self.startDebug() def about(self): # 简短介绍本程序 QMessageBox.about( self, '关于本MIPS汇编器', '<p style="font-size: 16px;">Made By Aaron</p>' '<p style="font-size: 16px;">可实现MIPS汇编器(支持伪码),反汇编器,调试器</p>' '<p style="font-size: 16px;">介绍请见README.md</p>' '<p style="font-size: 16px;">具体细节请参考实验报告')
def newEditor(self, path, tabGroup = None, line_no = None, prev_file = None, currentLine = False, fileIndex=None, tempfile = False, currentText=None): """ Create a tab group if both don't exist, then add an editor in the correct tab widget. """ if self.deviceManager is None: self.deviceManager = self.main._deviceManager path = str(path) name = os.path.basename(str(path)) editor = Editor(self, None) editor.tempfile = tempfile editor.fileIndex = fileIndex #closedTab = None closedTab = [] # Default to opening in the first tab group tabGroup = 0 nTabGroups = len(self.editorGroups) # If there is already one tab group, create a new one in split view and open the file there if 0 == nTabGroups: self.tab = self.EditorTabWidget(self.splitter) self.editorGroups.append(self.tab) # If the file is already open, just use the open document if self.editors.has_key(path): for k in self.editors: if not str(k) in self.tab.paths: #closedTab = k closedTab.append(k) #if closedTab != None: if len(closedTab) > 0 : #self.editors.pop(closedTab) for c_idx in range (0, len(closedTab)): self.editors.pop(closedTab[c_idx]) for k in self.tab.paths: self.editors[k][1] = self.tab.paths.index(k) if editor.tempfile == False: if currentText is None: editor.readFile(path) else: editor.setText(currentText) #if closedTab != path: if not path in closedTab : for k in self.editors: if path == k: curIndex = self.editors[k][1] self.editorGroups[tabGroup].setCurrentIndex(curIndex) if line_no != None: self.currentEditor = self.tab.editors[curIndex] self.currentEditor.SendScintilla(QsciScintilla.SCI_GOTOLINE, int(line_no)) # -1 if currentLine == True : if self.currentEditor.current_line > -1 : if not self.currentEditor.line_click.has_key(self.currentEditor.current_line) or self.currentEditor.line_click[self.currentEditor.current_line] == 0 : self.currentEditor.markerDelete(self.currentEditor.current_line, Editor.ARROW_MARKER_NUM) elif self.currentEditor.line_click[self.currentEditor.current_line] == 1 : self.currentEditor.markerDelete(self.currentEditor.current_line, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) self.currentEditor.markerAdd(self.currentEditor.current_line, Editor.ACTIVE_BREAK_MARKER_NUM) elif self.currentEditor.line_click[self.currentEditor.current_line] == 2 : self.currentEditor.markerDelete(self.currentEditor.current_line, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) self.currentEditor.markerAdd(self.currentEditor.current_line, Editor.DEACTIVE_BREAK_MARKER_NUM) elif prev_file != None: #if closedTab != prev_file: if not prev_file in closedTab : for j in self.editors: if prev_file == j: prevIndex = self.editors[j][1] curLine = self.tab.editors[prevIndex].current_line prevEditor = self.tab.editors[prevIndex] if not prevEditor.line_click.has_key(curLine) or prevEditor.line_click[curLine] == 0: prevEditor.markerDelete( curLine, Editor.ARROW_MARKER_NUM) elif prevEditor.line_click[curLine] == 1: prevEditor.markerDelete( curLine, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) prevEditor.markerAdd( curLine, Editor.ACTIVE_BREAK_MARKER_NUM) elif prevEditor.line_click[curLine] == 2: prevEditor.markerDelete( curLine, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) prevEditor.markerAdd( curLine, Editor.DEACTIVE_BREAK_MARKER_NUM) self.tab.editors[prevIndex].current_line = -1 if path == k: nextCurLine = int(line_no) -1 if not self.currentEditor.line_click.has_key(nextCurLine) or self.currentEditor.line_click[nextCurLine] == 0: self.currentEditor.markerAdd(nextCurLine, Editor.ARROW_MARKER_NUM) elif self.currentEditor.line_click[nextCurLine] == 1: self.currentEditor.markerDelete(nextCurLine, Editor.ACTIVE_BREAK_MARKER_NUM) self.currentEditor.markerAdd(nextCurLine, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) elif self.currentEditor.line_click[nextCurLine] == 2: self.currentEditor.markerDelete(nextCurLine, Editor.DEACTIVE_BREAK_MARKER_NUM) self.currentEditor.markerAdd(nextCurLine, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) self.currentEditor.current_line = nextCurLine #print ("return here - opened tab") return self.currentEditor elif tempfile == False: path = os.path.join (self.deviceManager.path(), path) if currentText is None: editor.readFile(path) else: editor.setText(currentText) if 0 == nTabGroups: seperatorAction = self.windowsMenu.addSeparator() if not self.editors.has_key(path): self.tab.paths.append(path) #self.tab.textBefores.append(editor.text()) #self.editors[path][2] = editor.text() self.tab.editors.append(editor) index = self.editorGroups[tabGroup].addTab(editor, name) editor.tabIndex = index if not self.editors.has_key(path): self.editors[path] = [editor, index, editor.text()] self.editorGroups[tabGroup].setCurrentIndex(index) editor.setFocus() editor.path = path if len(self.bp_info[1]) > 0: editor.show_marker() n = re.search("[/]+\S+[/]+", editor.path).end() fileName = editor.path[n:] editorAction = QAction(self.windowsMenu) editorAction.setText(fileName) editorAction.setIconText(editor.path) editorAction.setShortcut(QApplication.translate("MainWindow", "Ctrl+"+str(index+1), None, QApplication.UnicodeUTF8)) self.windowsMenu.addAction(editorAction) QObject.connect(editorAction , SIGNAL("triggered()"), self, SLOT("moveToThisEditor()")) editor.windowsAction = editorAction if not line_no == None: editor.SendScintilla(QsciScintilla.SCI_GOTOLINE, int(line_no)) self.currentEditor = editor if currentLine == True : if editor.current_line > -1 : if not editor.line_click.has_key(editor.current_line) or editor.line_click[editor.current_line] == 0: editor.markerDelete( editor.current_line, Editor.ARROW_MARKER_NUM) if editor.line_click[editor.current_line] == 1: editor.markerDelete( editor.current_line, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) editor.markerAdd( editor.current_line, Editor.ACTIVE_BREAK_MARKER_NUM) if editor.line_click[editor.current_line] == 2: editor.markerDelete( editor.current_line, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) editor.markerAdd( editor.current_line, Editor.DEACTIVE_BREAK_MARKER_NUM) elif prev_file != None: for l in self.editors: if prev_file == l: prevEditor = self.tab.editors[self.editors[l][1]] curLine = self.tab.editors[self.editors[l][1]].current_line if not prevEditor.line_click.has_key(curLine) or prevEditor.line_click[curLine] == 0 : prevEditor.markerDelete(curLine, Editor.ARROW_MARKER_NUM) elif prevEditor.line_click[curLine] == 1 : prevEditor.markerDelete(curLine, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) prevEditor.markerAdd(curLine, Editor.ACTIVE_BREAK_MARKER_NUM) elif prevEditor.line_click[curLine] == 0 : prevEditor.markerDelete(curLine, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) prevEditor.markerAdd(curLine, Editor.DEACTIVE_BREAK_MARKER_NUM) self.tab.editors[self.editors[l][1]].current_line = -1 if not editor.line_click.has_key(int(line_no) -1) or editor.line_click[int(line_no) -1] == 0: editor.markerAdd(int(line_no) -1, Editor.ARROW_MARKER_NUM) elif editor.line_click[int(line_no) -1] == 1: editor.markerDelete(int(line_no) -1, Editor.ACTIVE_BREAK_MARKER_NUM) editor.markerAdd(int(line_no) -1, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) elif editor.line_click[int(line_no) -1] == 2: editor.markerDelete(int(line_no) -1, Editor.DEACTIVE_BREAK_MARKER_NUM) editor.markerAdd(int(line_no) -1, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) editor.current_line = int(line_no) -1 if self.tab.count() > 0: self.main.editorMenuEnabled() if self.currentEditor is not None : if self.currentEditor.isRedoAvailable() == True: self.main.ui.actionRedo.setEnabled(True) else : self.main.ui.actionRedo.setEnabled(False) if self.currentEditor.isUndoAvailable() == True: self.main.ui.actionUndo.setEnabled(True) else : self.main.ui.actionUndo.setEnabled(False) #print ("return there - new tab") return editor
class Ide(QWidget): def __init__(self, sequencePath, browser, errline=0, parent=None): super().__init__(parent) self.sequencePath = sequencePath self.browser = browser self.playSpeed = 1 hbox = QHBoxLayout(self) self.splitter = QSplitter() self.editor = Editor(sequencePath, errline, None) self.splitter.addWidget(self.editor) self.rpanel = QWidget(None) grid = QGridLayout() self.reloadButton = QPushButton('Save script and load sequence', self.rpanel) self.reloadButton.clicked.connect(self.reload) grid.addWidget(self.reloadButton, 1, 2, 1, 8) self.discardButton = QPushButton('Discard changes', self.rpanel) self.discardButton.clicked.connect(self.discard) grid.addWidget(self.discardButton, 5, 2, 1, 8) self.preview = Preview(self.rpanel, self.editor) grid.addWidget(self.preview, 2, 2, 1, 8) self.seeker = QSlider(Qt.Horizontal, self.rpanel) self.seeker.setTickPosition(QSlider.TicksBelow) self.seeker.setMinimum(0) seq = gears.getSequence() if seq: self.seeker.setMaximum(seq.getDuration()) self.seeker.sliderPressed.connect(self.seekerPressed) self.seeker.sliderReleased.connect(self.seekerReleased) self.seeker.valueChanged.connect(self.seekerChanged) self.seeking = False grid.addWidget(self.seeker, 3, 2, 1, 8) self.pauseButton = QPushButton('\u275a\u275a', self.rpanel) self.pauseButton.clicked.connect(self.pause) grid.addWidget(self.pauseButton, 4, 2, 1, 1) self.play1button = QPushButton('\u25b6', self.rpanel) self.play1button.clicked.connect(self.play1) grid.addWidget(self.play1button, 4, 3, 1, 1) self.play2button = QPushButton('\u25b6\u25b6', self.rpanel) self.play2button.clicked.connect(self.play2) grid.addWidget(self.play2button, 4, 4, 1, 1) self.rpanel.setLayout(grid) self.splitter.addWidget(self.rpanel) hbox.addWidget(self.splitter) self.setLayout(hbox) self.setGeometry(100, 100, 1600, 900) self.timer = QTimer(self) self.timer.setInterval(16) self.timer.timeout.connect(self.onTimer) self.timer.start() def onTimer(self): self.seeker.setValue(self.preview.sFrame) if not self.seeking: self.preview.sFrame += self.playSpeed self.preview.update() def reload(self, e): self.editor.save() self.close() if loadSequence(self.sequencePath, self.browser, False): self.browser.launcherWindow.start(self.browser.browserWindow, self.sequencePath) QApplication.instance().processEvents() self.browser.browserWindow.hide() def discard(self, e): self.close() def seekerPressed(self): self.seeking = True def seekerReleased(self): self.seeking = False def seekerChanged(self): self.preview.sFrame = self.seeker.value() def pause(self, e): self.playSpeed = 0 def play1(self, e): self.playSpeed = 1 def play2(self, e): self.playSpeed = 2
def newEditor(self): self.tabNum += 1 # Add a new entry to the dict and map it an editor object self.editDict["edit" + str(self.tabNum)] = Editor() self.tab.addTab(self.getEditor(self.tabNum), os.path.basename(str(self.file)))
def editorTest(): editor = Editor() print("adding new states \n") editor.setContent("a") history.push(editor.createState()) print(str(editor)) editor.setContent("b") history.push(editor.createState()) print(str(editor)) editor.setContent("c") history.push(editor.createState()) print(str(editor)) editor.setContent("d") print(str(editor)) print("\nrestoring states \n") editor.restore(history.pop()) print(str(editor)) editor.restore(history.pop()) print(str(editor)) editor.restore(history.pop()) print(str(editor)) return
infile) except IOError: pass # process each image individually for im in images: print(f'Accessing {im}...') # prompt user for destination platform pSelect = PlatformSelect(platform_list, im) for platform, isSelected in pSelect.selectedPlatforms.items(): if isSelected.get(): if len(templates[platform]): print(f'Processing templates for {platform}...') # create editor and write output to disk for every template for t in templates[platform]: a = Editor(t, im) merge(t, im, a.mergeData, a.fName.get()) else: tempDisplay = tk.Tk() warnings.warn(f'No templates found for {platform}') if not tkinter.messagebox.askokcancel( 'No templates found', f'No templates were found in templates/ for {platform}. Press OK to continue processing other images, or press CANCEL to stop the program now.' ): raise SystemExit('User requested termination') tempDisplay.destroy() tkinter.messagebox.showinfo('Templating finished', 'All images have been processed.') print("--- All images processed. ---")
def startEditor(self): self.launchLayer(lambda: Editor(self.engine))
def onComponentDoubleClick(self, event): self.getDraggedItemData(event) selected = self.circuitElementDict[self.dragData['dataKey']] if(not isinstance(selected, Wire)):#Wires cannot be edited edit = Editor(selected, self.root) edit.displayPopup()
def newEditor(self, path, tabGroup=None, line_no=None, prev_file=None, currentLine=False, fileIndex=None, tempfile=False, currentText=None): """ Create a tab group if both don't exist, then add an editor in the correct tab widget. """ if self.deviceManager is None: self.deviceManager = self.main._deviceManager path = str(path) name = os.path.basename(str(path)) editor = Editor(self, None) editor.tempfile = tempfile editor.fileIndex = fileIndex #closedTab = None closedTab = [] # Default to opening in the first tab group tabGroup = 0 nTabGroups = len(self.editorGroups) # If there is already one tab group, create a new one in split view and open the file there if 0 == nTabGroups: self.tab = self.EditorTabWidget(self.splitter) self.editorGroups.append(self.tab) # If the file is already open, just use the open document if self.editors.has_key(path): for k in self.editors: if not str(k) in self.tab.paths: #closedTab = k closedTab.append(k) #if closedTab != None: if len(closedTab) > 0: #self.editors.pop(closedTab) for c_idx in range(0, len(closedTab)): self.editors.pop(closedTab[c_idx]) for k in self.tab.paths: self.editors[k][1] = self.tab.paths.index(k) if editor.tempfile == False: if currentText is None: editor.readFile(path) else: editor.setText(currentText) #if closedTab != path: if not path in closedTab: for k in self.editors: if path == k: curIndex = self.editors[k][1] self.editorGroups[tabGroup].setCurrentIndex(curIndex) if line_no != None: self.currentEditor = self.tab.editors[curIndex] self.currentEditor.SendScintilla( QsciScintilla.SCI_GOTOLINE, int(line_no)) # -1 if currentLine == True: if self.currentEditor.current_line > -1: if not self.currentEditor.line_click.has_key( self.currentEditor.current_line ) or self.currentEditor.line_click[ self.currentEditor. current_line] == 0: self.currentEditor.markerDelete( self.currentEditor.current_line, Editor.ARROW_MARKER_NUM) elif self.currentEditor.line_click[ self.currentEditor. current_line] == 1: self.currentEditor.markerDelete( self.currentEditor.current_line, Editor. ARROW_ACTIVE_BREAK_MARKER_NUM) self.currentEditor.markerAdd( self.currentEditor.current_line, Editor.ACTIVE_BREAK_MARKER_NUM) elif self.currentEditor.line_click[ self.currentEditor. current_line] == 2: self.currentEditor.markerDelete( self.currentEditor.current_line, Editor. ARROW_DEACTIVE_BREAK_MARKER_NUM) self.currentEditor.markerAdd( self.currentEditor.current_line, Editor.DEACTIVE_BREAK_MARKER_NUM) elif prev_file != None: #if closedTab != prev_file: if not prev_file in closedTab: for j in self.editors: if prev_file == j: prevIndex = self.editors[j][1] curLine = self.tab.editors[ prevIndex].current_line prevEditor = self.tab.editors[ prevIndex] if not prevEditor.line_click.has_key( curLine ) or prevEditor.line_click[ curLine] == 0: prevEditor.markerDelete( curLine, Editor. ARROW_MARKER_NUM) elif prevEditor.line_click[ curLine] == 1: prevEditor.markerDelete( curLine, Editor. ARROW_ACTIVE_BREAK_MARKER_NUM ) prevEditor.markerAdd( curLine, Editor. ACTIVE_BREAK_MARKER_NUM ) elif prevEditor.line_click[ curLine] == 2: prevEditor.markerDelete( curLine, Editor. ARROW_DEACTIVE_BREAK_MARKER_NUM ) prevEditor.markerAdd( curLine, Editor. DEACTIVE_BREAK_MARKER_NUM ) self.tab.editors[ prevIndex].current_line = -1 if path == k: nextCurLine = int(line_no) - 1 if not self.currentEditor.line_click.has_key( nextCurLine ) or self.currentEditor.line_click[ nextCurLine] == 0: self.currentEditor.markerAdd( nextCurLine, Editor.ARROW_MARKER_NUM) elif self.currentEditor.line_click[ nextCurLine] == 1: self.currentEditor.markerDelete( nextCurLine, Editor.ACTIVE_BREAK_MARKER_NUM) self.currentEditor.markerAdd( nextCurLine, Editor. ARROW_ACTIVE_BREAK_MARKER_NUM) elif self.currentEditor.line_click[ nextCurLine] == 2: self.currentEditor.markerDelete( nextCurLine, Editor.DEACTIVE_BREAK_MARKER_NUM) self.currentEditor.markerAdd( nextCurLine, Editor. ARROW_DEACTIVE_BREAK_MARKER_NUM) self.currentEditor.current_line = nextCurLine #print ("return here - opened tab") return self.currentEditor elif tempfile == False: path = os.path.join(self.deviceManager.path(), path) if currentText is None: editor.readFile(path) else: editor.setText(currentText) if 0 == nTabGroups: seperatorAction = self.windowsMenu.addSeparator() if not self.editors.has_key(path): self.tab.paths.append(path) #self.tab.textBefores.append(editor.text()) #self.editors[path][2] = editor.text() self.tab.editors.append(editor) index = self.editorGroups[tabGroup].addTab(editor, name) editor.tabIndex = index if not self.editors.has_key(path): self.editors[path] = [editor, index, editor.text()] self.editorGroups[tabGroup].setCurrentIndex(index) editor.setFocus() editor.path = path if len(self.bp_info[1]) > 0: editor.show_marker() n = re.search("[/]+\S+[/]+", editor.path).end() fileName = editor.path[n:] editorAction = QAction(self.windowsMenu) editorAction.setText(fileName) editorAction.setIconText(editor.path) editorAction.setShortcut( QApplication.translate("MainWindow", "Ctrl+" + str(index + 1), None, QApplication.UnicodeUTF8)) self.windowsMenu.addAction(editorAction) QObject.connect(editorAction, SIGNAL("triggered()"), self, SLOT("moveToThisEditor()")) editor.windowsAction = editorAction if not line_no == None: editor.SendScintilla(QsciScintilla.SCI_GOTOLINE, int(line_no)) self.currentEditor = editor if currentLine == True: if editor.current_line > -1: if not editor.line_click.has_key( editor.current_line) or editor.line_click[ editor.current_line] == 0: editor.markerDelete(editor.current_line, Editor.ARROW_MARKER_NUM) if editor.line_click[editor.current_line] == 1: editor.markerDelete( editor.current_line, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) editor.markerAdd(editor.current_line, Editor.ACTIVE_BREAK_MARKER_NUM) if editor.line_click[editor.current_line] == 2: editor.markerDelete( editor.current_line, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) editor.markerAdd(editor.current_line, Editor.DEACTIVE_BREAK_MARKER_NUM) elif prev_file != None: for l in self.editors: if prev_file == l: prevEditor = self.tab.editors[self.editors[l][1]] curLine = self.tab.editors[self.editors[l] [1]].current_line if not prevEditor.line_click.has_key( curLine ) or prevEditor.line_click[curLine] == 0: prevEditor.markerDelete( curLine, Editor.ARROW_MARKER_NUM) elif prevEditor.line_click[curLine] == 1: prevEditor.markerDelete( curLine, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) prevEditor.markerAdd( curLine, Editor.ACTIVE_BREAK_MARKER_NUM) elif prevEditor.line_click[curLine] == 0: prevEditor.markerDelete( curLine, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) prevEditor.markerAdd( curLine, Editor.DEACTIVE_BREAK_MARKER_NUM) self.tab.editors[self.editors[l] [1]].current_line = -1 if not editor.line_click.has_key( int(line_no) - 1) or editor.line_click[int(line_no) - 1] == 0: editor.markerAdd(int(line_no) - 1, Editor.ARROW_MARKER_NUM) elif editor.line_click[int(line_no) - 1] == 1: editor.markerDelete( int(line_no) - 1, Editor.ACTIVE_BREAK_MARKER_NUM) editor.markerAdd( int(line_no) - 1, Editor.ARROW_ACTIVE_BREAK_MARKER_NUM) elif editor.line_click[int(line_no) - 1] == 2: editor.markerDelete( int(line_no) - 1, Editor.DEACTIVE_BREAK_MARKER_NUM) editor.markerAdd( int(line_no) - 1, Editor.ARROW_DEACTIVE_BREAK_MARKER_NUM) editor.current_line = int(line_no) - 1 if self.tab.count() > 0: self.main.editorMenuEnabled() if self.currentEditor is not None: if self.currentEditor.isRedoAvailable() == True: self.main.ui.actionRedo.setEnabled(True) else: self.main.ui.actionRedo.setEnabled(False) if self.currentEditor.isUndoAvailable() == True: self.main.ui.actionUndo.setEnabled(True) else: self.main.ui.actionUndo.setEnabled(False) #print ("return there - new tab") return editor
class mainWindow(QMainWindow): """Class for the main window that contains the tabs, editor, terminal, etc.""" def __init__(self, parent=None): super(mainWindow, self).__init__(parent) config.filename = "Untitled" self.tabNum = 0 self.treeVis = False self.termVis = False config.docList = [] self.edit = Editor() self.editDict = {"edit1": self.edit} self.tab = QTabWidget(self) self.initUI() def writeSettings(self): settings = QSettings() font = settings.setValue("Editor/font", QVariant(config.font.toString())) term = settings.setValue("mainWindow/term", QVariant(self.termVis)) tree = settings.setValue("mainWindow/tree", QVariant(self.treeVis)) pDir = settings.setValue("fileTree/proDir", QVariant(config.proDir)) def readSettings(self): # The default fonts represented as a toString() list DEFAULT_FONT = str(config.font.family()) + ",12,-1,5,50,0,0,0,0,0" settings = QSettings() if config.font.fromString( settings.value("Editor/font", QVariant(DEFAULT_FONT), type=str)): #config.lexer.setDefaultColor(QColor("Black")) config.lexer.setFont(config.font) self.termVis = settings.value("mainWindow/term", QVariant(False), type=bool) self.treeVis = settings.value("mainWindow/tree", QVariant(False), type=bool) config.proDir = settings.value("fileTree/proDir", type=str) def initActions(self): self.newAction = QAction("New Window", self) self.newAction.setShortcut("Ctrl+N") self.newAction.triggered.connect(self.new) self.newTabAction = QAction("New Tab", self) self.newTabAction.setShortcut("Ctrl+T") self.newTabAction.triggered.connect(self.newTab) self.openAction = QAction("Open file", self) self.openAction.setShortcut("Ctrl+O") self.openAction.triggered.connect(self.openFile) self.saveAction = QAction("Save", self) self.saveAction.setShortcut("Ctrl+S") self.saveAction.triggered.connect(self.saveFile) self.saveasAction = QAction("Save As", self) self.saveasAction.setShortcut("Ctrl+Shift+S") self.saveasAction.triggered.connect(self.saveFileAs) self.cutAction = QAction("Cut", self) self.cutAction.setShortcut("Ctrl+X") self.cutAction.triggered.connect( lambda cut: self.getEditor(self.tab.currentIndex()).cut) self.copyAction = QAction("Copy", self) self.copyAction.setShortcut("Ctrl+C") self.copyAction.triggered.connect( lambda copy: self.getEditor(self.tab.currentIndex()).copy) self.pasteAction = QAction("Paste", self) self.pasteAction.setShortcut("Ctrl+V") self.pasteAction.triggered.connect( lambda paste: self.getEditor(self.tab.currentIndex()).paste) self.undoAction = QAction("Undo", self) self.undoAction.setShortcut("Ctrl+Z") self.undoAction.triggered.connect( lambda undo: self.getEditor(self.tab.currentIndex()).undo) self.redoAction = QAction("Redo", self) self.redoAction.setShortcut("Ctrl+Y") self.redoAction.triggered.connect( lambda redo: self.getEditor(self.tab.currentIndex()).redo) self.aboutAction = QAction("About Codex", self) self.aboutAction.triggered.connect(self.about) self.noLexAct = QAction("Plain Text", self) self.noLexAct.triggered.connect(lambda noLex: self.getEditor(self.tab.currentIndex()).\ setLexer(QsciLexerText())) self.termAct = QAction("Terminal", self) self.termAct.setCheckable(True) self.termAct.triggered.connect(self.toggleTerm) self.treeAct = QAction("File Tree", self) self.treeAct.setCheckable(True) self.treeAct.triggered.connect(self.toggleTree) self.toggleIntAct = QAction("Indentation Guides", self) self.toggleIntAct.triggered.connect(self.toggleIntGuide) self.toggleIntAct.setCheckable(True) self.toggleIntAct.setChecked(True) self.toggleLNAct = QAction("Line Numbers", self) self.toggleLNAct.triggered.connect(self.toggleLN) self.toggleLNAct.setCheckable(True) self.toggleLNAct.setChecked(True) self.FRAct = QAction("Find and Replace", self) self.FRAct.triggered.connect(self.fr) self.FRAct.setShortcut("Ctrl+F") self.fontAct = QAction("Choose Font", self) self.fontAct.triggered.connect(self.chooseFont) self.dirAct = QAction("Choose Project Directory", self) self.dirAct.triggered.connect(self.setProDir) def getEditor(self, index): if index == 0: return self.editDict.get("edit1") else: return self.editDict.get(("edit" + str(index))) def getCurrentFile(self): return config.docList[self.tab.currentIndex()] # returns tuple (?) def initMenubar(self): menubar = self.menuBar() file = menubar.addMenu("File") edit = menubar.addMenu("Edit") self.lang = menubar.addMenu("Languages") view = menubar.addMenu("View") about = menubar.addMenu("About") self.initLexers() file.addAction(self.newAction) file.addAction(self.newTabAction) file.addAction(self.openAction) file.addAction(self.saveAction) file.addAction(self.saveasAction) file.addSeparator() file.addAction(self.fontAct) file.addAction(self.dirAct) edit.addAction(self.undoAction) edit.addAction(self.redoAction) edit.addSeparator() edit.addAction(self.copyAction) edit.addAction(self.cutAction) edit.addAction(self.pasteAction) edit.addAction(self.FRAct) view.addAction(self.termAct) view.addAction(self.toggleIntAct) view.addAction(self.toggleLNAct) view.addAction(self.treeAct) about.addAction(self.aboutAction) def lessTabs(self): self.tabNum = self.tabNum - 1 try: #print config.docList config.docList.remove(config.docList[self.tab.currentIndex() - 1]) except: if len(config.docList) == 0: pass finally: if self.tabNum < 1: self.newTab() else: self.tab.removeTab(self.tab.currentIndex() - 1) #print self.tabNum def initTabs(self): # Set up the tabs self.tab.tabCloseRequested.connect(self.tab.removeTab) self.tab.tabCloseRequested.connect(self.lessTabs) self.tab.setMovable(True) # Needed for Mac self.tab.setDocumentMode(True) self.setUnifiedTitleAndToolBarOnMac(True) # Automatically make new tabs contain an editor widget self.tab.addTab(self.editDict.get("edit1"), config.filename) self.termSplit.addWidget(self.tab) self.tab.setTabsClosable(True) def initUI(self): # Create first qsplitter for sidebar self.treeSplit = QSplitter() self.treeSplit.setOrientation(Qt.Horizontal) # Create second qsplitter (Allows split screen for terminal) self.termSplit = QSplitter() self.termSplit.setOrientation(Qt.Vertical) # Add a termSplit to the treeSplit self.treeSplit.addWidget(self.termSplit) self.setCentralWidget(self.treeSplit) # Create everything else self.initTabs() self.initActions() self.initMenubar() # Create terminal widget and automatically hide it because otherwise # it will awkwardly hover in the corner self.term = Terminal() #self.term.hide() # x and y coordinates on the screen, width, height self.setGeometry(100, 100, 800, 630) self.setWindowTitle("Codex") # Move up to the parent directory and set the window icons. # Without os.path it will look for icons in src/ self.setWindowIcon( QIcon( os.path.join(os.path.dirname(__file__)) + "/icons/256x256/codex.png")) # Open any documents that were open before closing and restore settings QTimer.singleShot(0, self.loadDocs) self.readSettings() # Show the terminal/tree if necessary. self.loadTermAndTree() # If there are no documents to load set the language as plain text # If there are documents to load guess lexers for them if len(config.docList) == 0: self.getEditor(self.tabNum).setLang(QsciLexerText()) self.noLexAct.setChecked(True) else: self.guessLexer() # Set font self.getEditor(self.tab.currentIndex()).lexer.setFont(config.font) def initLexers(self): # Dict that maps lexer actions to their respective strings self.lexActs = {} langGrp = QActionGroup(self.lang) langGrp.setExclusive(True) self.lang.addAction(self.noLexAct) self.noLexAct.setCheckable(True) #self.noLexAct.setChecked(True) self.noLexAct.setActionGroup(langGrp) self.lang.addSeparator() languages = sorted(config.LEXERS.keys()) for i in languages: langAct = self.lang.addAction(i) langAct.setCheckable(True) langAct.setActionGroup(langGrp) self.lexActs[langAct] = i langGrp.triggered.connect(lambda lex: self.getEditor(self.tabNum + 1). setLang(self.lexActs.get(lex))) def guessLexer(self): try: x = config.docList[self.tab.currentIndex() + 1] n, e = os.path.basename(x).lower().split(".") if e == "sh" or e == "bsh": self.getEditor(self.tabNum).setLang("Bash") elif e == "cmd" or e == "bat" or e == "btm" or e == "nt": self.getEditor(self.tabNum).setLang("Batch") elif e == "cmake" or e == "cmakelists": self.getEditor(self.tabNum).setLang("CMake") elif e == "cpp" or e == "cxx" or e == "cc" or e == "c" or e == "h"\ or e == "hh" or e == "hpp": self.getEditor(self.tabNum).setLang("C++") elif e == "cs": self.getEditor(self.tabNum).setLang("C#") elif e == "css": self.getEditor(self.tabNum).setLang("CSS") elif e == "d": self.getEditor(self.tabNum).setLang("D") elif e == "diff" or e == "patch": self.getEditor(self.tabNum).setLang("Diff") elif e == "f90" or e == "f95" or e == "f2k" or e == "f03" or e == "f15": self.getEditor(self.tabNum).setLang("Fortran") elif e == "f" or e == "for": self.getEditor(self.tabNum).setLang("Fortran77") elif e == "html" or e == "htm": self.getEditor(self.tabNum).setLang("HTML") elif e == "java": self.getEditor(self.tabNum).setLang("Java") elif e == "js": self.getEditor(self.tabNum).setLang("JavaScript") elif e == "lua": self.getEditor(self.tabNum).setLang("Lua") elif e == "mak" or n == "gnumakefile" or n == "makefile": self.getEditor(self.tabNum).setLang("Makefile") elif e == "m": self.getEditor(self.tabNum).setLang("MATLAB") elif e == "pas" or e == "inc": self.getEditor(self.tabNum).setLang("Pascal") elif e == "ps": self.getEditor(self.tabNum).setLang("PostScript") elif e == "pov" or e == "tga": self.getEditor(self.tabNum).setLang("POV-Ray") elif e == "py" or e == "pyw": self.getEditor(self.tabNum).setLang("Python") #print "p" elif e == "rb" or e == "rbw": self.getEditor(self.tabNum).setLang("Ruby") elif e == "cir": self.getEditor(self.tabNum).setLang("Spice") elif e == "sql": self.getEditor(self.tabNum).setLang("SQL") elif e == "tcl": self.getEditor(self.tabNum).setLang("TCL") elif e == "tex": self.getEditor(self.tabNum).setLang("TeX") elif e == "v" or e == "sv" or e == "vh" or e == "svh": self.getEditor(self.tabNum).setLang("Verilog") elif e == "vhd" or e == "vhdl": self.getEditor(self.tabNum).setLang("VHDL") elif e == "xml" or e == "xsl" or e == "xsml" or e == "xsd" or \ e == "kml" or e == "wsdl" or e == "xlf" or e == "xliff": self.getEditor(self.tabNum).setLang("XML") elif e == "yml": self.getEditor(self.tabNum).setLang("YML") except (ValueError, IndexError): self.lexer = QsciLexerText() self.lexer.setDefaultFont(config.font) self.lexer.setDefaultColor(QColor("Black")) self.getEditor(self.tabNum).setLexer(self.lexer) self.noLexAct.setChecked(True) def new(self): main = mainWindow() main.show() def open(self): index = self.tab.currentIndex() if (self.file != ('', '')): with open(self.file, "rt") as f: if self.tabNum >= 1: self.newEditor() #print "t" self.tab.setTabText(index + 1, os.path.basename(str(self.file))) self.getEditor(self.tabNum).setText(f.read()) self.tab.setCurrentIndex(index + 1) if self.tabNum == 0: self.tabNum = 1 self.tab.setTabText(index, os.path.basename(str(self.file))) #print(self.tabNum) self.getEditor(self.tabNum).setText(f.read()) self.tab.setCurrentIndex(index + 1) # Try to guess the lexer based on extension self.guessLexer() # Not really sure where else to put this self.getEditor(self.tab.currentIndex() + 1).setModified(False) self.getEditor(self.tabNum).textChanged.connect(self.unsaved) def newEditor(self): self.tabNum += 1 # Add a new entry to the dict and map it an editor object self.editDict["edit" + str(self.tabNum)] = Editor() self.tab.addTab(self.getEditor(self.tabNum), os.path.basename(str(self.file))) #print "o" def openFile(self): self.file = QFileDialog.getOpenFileName(self, 'Open File', ".")[0] try: config.docList.append(str(self.file)) #print "k" self.open() except AttributeError: config.docList.append(str(self.file)) self.open() #print "h" def loadDocs(self): fh = None if not os.access(".open.p", os.F_OK): return else: try: fh = gzip.open(".open.p", "rb") config.docList = pickle.load(fh) for x in config.docList: self.file = x self.open() except (IOError, OSError): #print e return finally: if fh is not None: fh.close() def save(self): # Save the file as plain text with open(self.getCurrentFile(), "wt") as file: file.write(self.getEditor(self.tab.currentIndex() + 1).text()) # Note that changes to the document are saved self.edit.setModified(False) # Set the tab title to filename self.tab.setTabText(self.tab.currentIndex(), os.path.basename(str(self.getCurrentFile()))) def saveDocs(self): try: fh = gzip.open(".open.p", "wb") pickle.dump(config.docList, fh, 2) except (IOError, OSError) as e: raise e finally: if fh: fh.close() def saveFile(self): # Only open if it hasn't previously been saved if len(config.docList) != 0: if self.getCurrentFile() == "Untitled": config.docList[self.tab.currentIndex()] = \ QFileDialog.getSaveFileName(self, 'Save File') self.save() else: config.docList.append( QFileDialog.getSaveFileName(self, 'Save File')) self.save() def saveFileAs(self): config.filename = QFileDialog.getSaveFileName(self, 'Save File') self.save() def unsaved(self): if self.getEditor(self.tab.currentIndex() + 1).isModified: self.tab.setTabText(self.tab.currentIndex(), os.path.basename(self.getCurrentFile() + "*")) def about(self): QMessageBox.about(self, "About Codex", "<p>Codex is a text editor for programmers " \ "made with PyQt5 and QScintilla.</p>" ) def toggleTabs(self): state = self.tab.isVisible() self.tab.setVisible(not state) def newTab(self): self.tabNum += 1 # Add a new entry to the dict and map it to an editor object self.editDict["edit" + str(self.tabNum)] = Editor() self.tab.addTab(self.getEditor(self.tabNum), "Untitled") self.guessLexer() self.getEditor(self.tab.currentIndex() + 1).lexer.setFont(config.font) def showTerm(self): self.termVis = True self.termSplit.addWidget(self.term) self.term.resize(800, 40) self.term.setFont(config.font) self.term.show() def hideTerm(self): self.termVis = False self.term.hide() def toggleTerm(self): self.hideTerm() if self.termVis else self.showTerm() def showTree(self): self.ftree = Tree(self) self.treeVis = True self.ftree.resize(80, 430) self.treeSplit.addWidget(self.ftree) self.ftree.show() def hideTree(self): self.treeVis = False self.ftree.close() def toggleTree(self): self.hideTree() if self.treeVis else self.showTree() def loadTermAndTree(self): if self.treeVis: self.showTree() self.treeAct.setChecked(True) else: self.treeVis = False self.treeAct.setChecked(False) if self.termVis: self.showTerm() self.termAct.setChecked(True) else: self.termVis = False self.termAct.setChecked(False) def toggleIntGuide(self): state = self.edit.indentationGuides() self.edit.setIndentationGuides(not state) def toggleLN(self): state = self.edit.marginLineNumbers(0) self.edit.setMarginLineNumbers(0, not state) self.edit.setMarginWidth(0,0) if state == True else self.edit. \ setMarginWidth(0,self.edit.metrics.width("00000")) def fr(self): frwin = Find(self) frwin.show() def chooseFont(self): font, ok = QFontDialog.getFont() if ok: config.font = font try: self.getEditor(self.tab.currentIndex()).lexer().setFont( config.font) except AttributeError: self.getEditor(self.tab.currentIndex()).setLang( QsciLexerText()) #print self.getEditor(self.tab.currentIndex()).lexer() self.getEditor(self.tab.currentIndex()).lexer().setFont( config.font) def setProDir(self): pdir, ok = QInputDialog.getText(self, "Set Project Directory", "Enter absolute path (i.e. "\ "/home/steve/Documents)") if ok: config.proDir = pdir #print config.proDir # This method adapted from Peter Goldsborough's Writer. # Save settings and alerts the user if they are saving an edited file. def closeEvent(self, event): self.writeSettings() self.saveDocs() if not self.edit.isModified(): event.accept() else: dialog = QMessageBox(self) dialog.setIcon(QMessageBox.Warning) dialog.setText(config.filename + " has unsaved changes.") dialog.setInformativeText("Do you want to save your changes?") dialog.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard) dialog.setDefaultButton(QMessageBox.Save) response = dialog.exec_() if response == QMessageBox.Save: self.save() elif response == QMessageBox.Discard: event.accept() else: event.ignore() def resizeEvent(self, event): # Don't try to resize a non-existant file tree try: self.ftree.treeView.resize(self.ftree.treeView.width(), self.height()) except: pass try: self.term.resize(self.width(), self.term.height()) except: pass def keyPressEvent(self, event): key = event.key() if (self.getEditor(self.tab.currentIndex()).text() == "bee movie"): with open("bee_movie.txt", "r") as file: script = file.read() self.getEditor(self.tab.currentIndex()).setText(script)
def __new_editor(self, uri=None, encoding="utf-8", stdin=None): if uri is None: uri = "" from Editor import Editor Editor(self, str(uri), encoding, stdin) return False
LoadGame() def MovePlayer(): for block in maps.new_blocks: if block.ID == 2: start = block.rect.x, block.rect.y player.rect.x, player.rect.y = start player2.rect.x, player2.rect.y = start if not reloadGame: MovePlayer() maps.all_block_types = maps.allTypes from Editor import Editor edit = Editor() if editing == True: edit.editing = True clock = pygame.time.Clock() entities = [] import SettingUp
def showTargetsList(self): self.Parent.setTabsState(False) path_ = '' if self.pathToLog is None else self.pathToLog task = 0 if self.mode.currentIndex() else 1 self.editor = Editor(path_, 0, self, task) self.editor.show()
def __init__(self, sequencePath, browser, errline=0, parent=None): super().__init__(parent) self.sequencePath = sequencePath self.browser = browser self.playSpeed = 1 hbox = QHBoxLayout(self) self.splitter = QSplitter() self.editor = Editor(sequencePath, errline, None) self.splitter.addWidget(self.editor) self.rpanel = QWidget(None) grid = QGridLayout() self.reloadButton = QPushButton('Save script and load sequence', self.rpanel) self.reloadButton.clicked.connect(self.reload) grid.addWidget(self.reloadButton, 1, 2, 1, 8) self.discardButton = QPushButton('Discard changes', self.rpanel) self.discardButton.clicked.connect(self.discard) grid.addWidget(self.discardButton, 5, 2, 1, 8) self.preview = Preview(self.rpanel, self.editor) grid.addWidget(self.preview, 2, 2, 1, 8) self.seeker = QSlider(Qt.Horizontal, self.rpanel) self.seeker.setTickPosition(QSlider.TicksBelow) self.seeker.setMinimum(0) seq = gears.getSequence() if seq: self.seeker.setMaximum(seq.getDuration()) self.seeker.sliderPressed.connect(self.seekerPressed) self.seeker.sliderReleased.connect(self.seekerReleased) self.seeker.valueChanged.connect(self.seekerChanged) self.seeking = False grid.addWidget(self.seeker, 3, 2, 1, 8) self.pauseButton = QPushButton('\u275a\u275a', self.rpanel) self.pauseButton.clicked.connect(self.pause) grid.addWidget(self.pauseButton, 4, 2, 1, 1) self.play1button = QPushButton('\u25b6', self.rpanel) self.play1button.clicked.connect(self.play1) grid.addWidget(self.play1button, 4, 3, 1, 1) self.play2button = QPushButton('\u25b6\u25b6', self.rpanel) self.play2button.clicked.connect(self.play2) grid.addWidget(self.play2button, 4, 4, 1, 1) self.rpanel.setLayout(grid) self.splitter.addWidget(self.rpanel) hbox.addWidget(self.splitter) self.setLayout(hbox) self.setGeometry(100, 100, 1600, 900) self.timer = QTimer(self) self.timer.setInterval(16) self.timer.timeout.connect(self.onTimer) self.timer.start()
class Broken(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) self.Parent = parent self.tr = Translator('Thrifty') self.runned = False self.pathToLog = None self.layout = QGridLayout() self.layout.setAlignment(Qt.AlignCenter) self.dirList = QListWidget() #self.dirList.setMaximumHeight(150) self.dirList.setToolTip(self.tr._translate('A list of directories processed')) self.buttonLayout = QVBoxLayout() self.buttonLayout.setAlignment(Qt.AlignCenter) self.addPath = QPushButton(QIcon('/usr/share/thrifty/icons/plus.png'), '') self.addPath.setIconSize(QSize(32,32)) self.delPath = QPushButton(QIcon('/usr/share/thrifty/icons/delete.png'), '') self.delPath.setIconSize(QSize(32,32)) self.showTargets = QPushButton(QIcon('/usr/share/thrifty/icons/show.png'), '') self.showTargets.setIconSize(QSize(32,32)) self.mode = QComboBox() self.mode.setIconSize(QSize(32,32)) self.mode.setToolTip(self.tr._translate('Packages')) self.mode.addItem (QIcon('/usr/share/thrifty/icons/packages.png'), '') self.mode.addItem (QIcon('/usr/share/thrifty/icons/files.png'), '') self.start = QPushButton(QIcon('/usr/share/thrifty/icons/start.png'), '') self.start.setIconSize(QSize(32,32)) self.addPath.setToolTip(self.tr._translate('Add to List')) self.delPath.setToolTip(self.tr._translate('Delete from List')) self.showTargets.setToolTip(self.tr._translate('show Targets file')) self.start.setToolTip(self.tr._translate('Start task')) self.addPath.clicked.connect(self.addDirPath) self.delPath.clicked.connect(self.delDirPath) self.showTargets.clicked.connect(self.showTargetsList) self.start.clicked.connect(self.runSearchBroken) self.buttonLayout.addWidget(self.addPath) self.buttonLayout.addWidget(self.delPath) self.buttonLayout.addWidget(self.start) self.buttonLayout.addWidget(self.mode) self.buttonLayout.addWidget(self.showTargets) self.progress = QProgressBar() self.progress.setOrientation(Qt.Vertical) self.progress.hide() self.progress.setRange(0, 0) self.logIn = QLabel('') self.logIn.setToolTip(self.tr._translate('Log of processed task')) self.logIn.setOpenExternalLinks(True) self.layout.addWidget(self.dirList, 0, 0) self.layout.addItem(self.buttonLayout, 0, 1) self.layout.addWidget(self.progress, 0, 2) self.layout.addWidget(self.logIn, 1, 0) self.setLayout(self.layout) self.mode.currentIndexChanged.connect(self.changeModeContent) def addDirPath(self): _nameDir = QFileDialog.getExistingDirectory(self, self.tr._translate('Path_to_'), '~', QFileDialog.ShowDirsOnly) nameDir = _nameDir.toLocal8Bit().data() if os.path.isdir(nameDir) and \ os.access(nameDir, os.R_OK) and os.access(nameDir, os.X_OK) : self.dirList.addItem(_nameDir) else : msg = QMessageBox.information(self, 'ERROR', self.tr._translate('error'), QMessageBox.Ok) def delDirPath(self): item = self.dirList.takeItem(self.dirList.currentRow()) def changeModeContent(self, i = 0): if i : self.mode.setToolTip(self.tr._translate('Files')) else : self.mode.setToolTip(self.tr._translate('Packages')) def runSearchBroken(self): self.Parent.setTabsState(False) self.progress.show() self.runned = True self.pathToLog = None print 'Search broken running ...' self.t = QProcess() Data = QStringList() Data.append('--user') Data.append('root') Data.append('/usr/share/thrifty/thrifty.py') mode = '-b' value = str(self.Parent.Parent.Settings.value('checkFileOwners', 'False').toString()) if value.lower() == 'true' : mode += 'O' value = str(self.Parent.Parent.Settings.value('checkFileMode', 'False').toString()) if value.lower() == 'true' : mode += 'M' value = str(self.Parent.Parent.Settings.value('checkFileMtime', 'False').toString()) if value.lower() == 'true' : mode += 'T' opt = ''.join(('G:', str(USER_UID), '/', str(USER_GID), '::', mode)) Data.append(opt) for i in xrange(self.dirList.count()) : item_ = self.dirList.item(i) Data.append(item_.text()) #for i in xrange(Data.count()) : # print Data[i], self.t.finished.connect(self.showResult) self.t.start('pkexec', Data) if self.t.waitForStarted() : self.runned = True #print self.t.state() else : self.showResult() def setState(self, state): self.dirList.setEnabled(state) self.addPath.setEnabled(state) self.delPath.setEnabled(state) self.mode.setEnabled(state) self.showTargets.setEnabled(state) self.start.setEnabled(state) def showResult(self): self.runned = False self.Parent.setTabsState(True) self.progress.hide() name_ = '/dev/shm/thrifty.lastTask' if os.path.isfile(name_) : with open(name_, 'rb') as f : pathToLog = f.read() os.remove(name_) self.pathToLog = pathToLog else : pathToLog = 'ERROR' self.logIn.setText('<a href="%s">Log in $TEMP<a>' % pathToLog + '</a>') def showTargetsList(self): self.Parent.setTabsState(False) path_ = '' if self.pathToLog is None else self.pathToLog task = 0 if self.mode.currentIndex() else 1 self.editor = Editor(path_, 0, self, task) self.editor.show() def enableEditorButton(self): self.Parent.setTabsState(True)
class mainWindow(QMainWindow): """Class for the main window that contains the tabs, editor, terminal, etc.""" def __init__(self, parent = None): super(mainWindow, self).__init__(parent) config.filename = "Untitled" self.tabNum = 0 self.treeVis = False self.termVis = False config.docList = [] self.edit = Editor() self.editDict = {"edit1":self.edit} self.tab = QTabWidget(self) self.initUI() def writeSettings(self): settings = QSettings() font = settings.setValue("Editor/font", QVariant(config.font.toString())) term = settings.setValue("mainWindow/term", QVariant(self.termVis)) tree = settings.setValue("mainWindow/tree", QVariant(self.treeVis)) pDir = settings.setValue("fileTree/proDir", QVariant(config.proDir)) def readSettings(self): # The default fonts represented as a toString() list DEFAULT_FONT = str(config.font.family())+",12,-1,5,50,0,0,0,0,0" settings = QSettings() if config.font.fromString(settings.value("Editor/font", QVariant(DEFAULT_FONT),type=str)): #config.lexer.setDefaultColor(QColor("Black")) config.lexer.setFont(config.font) self.termVis = settings.value("mainWindow/term", QVariant(False),type=bool) self.treeVis = settings.value("mainWindow/tree", QVariant(False),type=bool) config.proDir = settings.value("fileTree/proDir",type=str) def initActions(self): self.newAction = QAction("New Window",self) self.newAction.setShortcut("Ctrl+N") self.newAction.triggered.connect(self.new) self.newTabAction = QAction("New Tab",self) self.newTabAction.setShortcut("Ctrl+T") self.newTabAction.triggered.connect(self.newTab) self.openAction = QAction("Open file",self) self.openAction.setShortcut("Ctrl+O") self.openAction.triggered.connect(self.openFile) self.saveAction = QAction("Save",self) self.saveAction.setShortcut("Ctrl+S") self.saveAction.triggered.connect(self.saveFile) self.saveasAction = QAction("Save As",self) self.saveasAction.setShortcut("Ctrl+Shift+S") self.saveasAction.triggered.connect(self.saveFileAs) self.cutAction = QAction("Cut",self) self.cutAction.setShortcut("Ctrl+X") self.cutAction.triggered.connect(lambda cut: self.getEditor(self.tab.currentIndex()).cut) self.copyAction = QAction("Copy",self) self.copyAction.setShortcut("Ctrl+C") self.copyAction.triggered.connect(lambda copy: self.getEditor(self.tab.currentIndex()).copy) self.pasteAction = QAction("Paste",self) self.pasteAction.setShortcut("Ctrl+V") self.pasteAction.triggered.connect(lambda paste: self.getEditor(self.tab.currentIndex()).paste) self.undoAction = QAction("Undo",self) self.undoAction.setShortcut("Ctrl+Z") self.undoAction.triggered.connect(lambda undo: self.getEditor(self.tab.currentIndex()).undo) self.redoAction = QAction("Redo",self) self.redoAction.setShortcut("Ctrl+Y") self.redoAction.triggered.connect(lambda redo: self.getEditor(self.tab.currentIndex()).redo) self.aboutAction = QAction("About Codex",self) self.aboutAction.triggered.connect(self.about) self.noLexAct = QAction("Plain Text",self) self.noLexAct.triggered.connect(lambda noLex: self.getEditor(self.tab.currentIndex()).\ setLexer(QsciLexerText())) self.termAct = QAction("Terminal",self) self.termAct.setCheckable(True) self.termAct.triggered.connect(self.toggleTerm) self.treeAct = QAction("File Tree",self) self.treeAct.setCheckable(True) self.treeAct.triggered.connect(self.toggleTree) self.toggleIntAct = QAction("Indentation Guides",self) self.toggleIntAct.triggered.connect(self.toggleIntGuide) self.toggleIntAct.setCheckable(True) self.toggleIntAct.setChecked(True) self.toggleLNAct = QAction("Line Numbers",self) self.toggleLNAct.triggered.connect(self.toggleLN) self.toggleLNAct.setCheckable(True) self.toggleLNAct.setChecked(True) self.FRAct = QAction("Find and Replace",self) self.FRAct.triggered.connect(self.fr) self.FRAct.setShortcut("Ctrl+F") self.fontAct = QAction("Choose Font",self) self.fontAct.triggered.connect(self.chooseFont) self.dirAct = QAction("Choose Project Directory",self) self.dirAct.triggered.connect(self.setProDir) def getEditor(self, index): if index == 0: return self.editDict.get("edit1") else: return self.editDict.get(("edit"+str(index))) def getCurrentFile(self): return config.docList[self.tab.currentIndex()] # returns tuple (?) def initMenubar(self): menubar = self.menuBar() file = menubar.addMenu("File") edit = menubar.addMenu("Edit") self.lang = menubar.addMenu("Languages") view = menubar.addMenu("View") about = menubar.addMenu("About") self.initLexers() file.addAction(self.newAction) file.addAction(self.newTabAction) file.addAction(self.openAction) file.addAction(self.saveAction) file.addAction(self.saveasAction) file.addSeparator() file.addAction(self.fontAct) file.addAction(self.dirAct) edit.addAction(self.undoAction) edit.addAction(self.redoAction) edit.addSeparator() edit.addAction(self.copyAction) edit.addAction(self.cutAction) edit.addAction(self.pasteAction) edit.addAction(self.FRAct) view.addAction(self.termAct) view.addAction(self.toggleIntAct) view.addAction(self.toggleLNAct) view.addAction(self.treeAct) about.addAction(self.aboutAction) def lessTabs(self): self.tabNum = self.tabNum - 1 try: #print config.docList config.docList.remove(config.docList[self.tab.currentIndex()-1]) except: if len(config.docList) == 0: pass finally: if self.tabNum < 1: self.newTab() else: self.tab.removeTab(self.tab.currentIndex()-1) #print self.tabNum def initTabs(self): # Set up the tabs self.tab.tabCloseRequested.connect(self.tab.removeTab) self.tab.tabCloseRequested.connect(self.lessTabs) self.tab.setMovable(True) # Needed for Mac self.tab.setDocumentMode(True) self.setUnifiedTitleAndToolBarOnMac(True) # Automatically make new tabs contain an editor widget self.tab.addTab(self.editDict.get("edit1"), config.filename) self.termSplit.addWidget(self.tab) self.tab.setTabsClosable(True) def initUI(self): # Create first qsplitter for sidebar self.treeSplit = QSplitter() self.treeSplit.setOrientation(Qt.Horizontal) # Create second qsplitter (Allows split screen for terminal) self.termSplit = QSplitter() self.termSplit.setOrientation(Qt.Vertical) # Add a termSplit to the treeSplit self.treeSplit.addWidget(self.termSplit) self.setCentralWidget(self.treeSplit) # Create everything else self.initTabs() self.initActions() self.initMenubar() # Create terminal widget and automatically hide it because otherwise # it will awkwardly hover in the corner self.term = Terminal() #self.term.hide() # x and y coordinates on the screen, width, height self.setGeometry(100,100,800,630) self.setWindowTitle("Codex") # Move up to the parent directory and set the window icons. # Without os.path it will look for icons in src/ self.setWindowIcon(QIcon(os.path.join( os.path.dirname(__file__)) + "/icons/256x256/codex.png")) # Open any documents that were open before closing and restore settings QTimer.singleShot(0,self.loadDocs) self.readSettings() # Show the terminal/tree if necessary. self.loadTermAndTree() # If there are no documents to load set the language as plain text # If there are documents to load guess lexers for them if len(config.docList) == 0: self.getEditor(self.tabNum).setLang(QsciLexerText()) self.noLexAct.setChecked(True) else: self.guessLexer() # Set font self.getEditor(self.tab.currentIndex()).lexer.setFont(config.font) def initLexers(self): # Dict that maps lexer actions to their respective strings self.lexActs = {} langGrp = QActionGroup(self.lang) langGrp.setExclusive(True) self.lang.addAction(self.noLexAct) self.noLexAct.setCheckable(True) #self.noLexAct.setChecked(True) self.noLexAct.setActionGroup(langGrp) self.lang.addSeparator() languages = sorted(config.LEXERS.keys()) for i in languages: langAct = self.lang.addAction(i) langAct.setCheckable(True) langAct.setActionGroup(langGrp) self.lexActs[langAct] = i langGrp.triggered.connect(lambda lex: self.getEditor(self.tabNum+1).setLang(self.lexActs.get(lex))) def guessLexer(self): try: x = config.docList[self.tab.currentIndex()+1] n, e = os.path.basename(x).lower().split(".") if e == "sh" or e == "bsh": self.getEditor(self.tabNum).setLang("Bash") elif e == "cmd" or e == "bat" or e == "btm" or e == "nt": self.getEditor(self.tabNum).setLang("Batch") elif e == "cmake" or e == "cmakelists": self.getEditor(self.tabNum).setLang("CMake") elif e == "cpp" or e == "cxx" or e == "cc" or e == "c" or e == "h"\ or e == "hh" or e == "hpp": self.getEditor(self.tabNum).setLang("C++") elif e == "cs": self.getEditor(self.tabNum).setLang("C#") elif e == "css": self.getEditor(self.tabNum).setLang("CSS") elif e == "d": self.getEditor(self.tabNum).setLang("D") elif e == "diff" or e == "patch": self.getEditor(self.tabNum).setLang("Diff") elif e == "f90" or e == "f95" or e == "f2k" or e == "f03" or e == "f15": self.getEditor(self.tabNum).setLang("Fortran") elif e == "f" or e == "for": self.getEditor(self.tabNum).setLang("Fortran77") elif e == "html" or e == "htm": self.getEditor(self.tabNum).setLang("HTML") elif e == "java": self.getEditor(self.tabNum).setLang("Java") elif e == "js": self.getEditor(self.tabNum).setLang("JavaScript") elif e == "lua": self.getEditor(self.tabNum).setLang("Lua") elif e == "mak" or n == "gnumakefile" or n == "makefile": self.getEditor(self.tabNum).setLang("Makefile") elif e == "m": self.getEditor(self.tabNum).setLang("MATLAB") elif e == "pas" or e == "inc": self.getEditor(self.tabNum).setLang("Pascal") elif e == "ps": self.getEditor(self.tabNum).setLang("PostScript") elif e == "pov" or e == "tga": self.getEditor(self.tabNum).setLang("POV-Ray") elif e == "py" or e == "pyw": self.getEditor(self.tabNum).setLang("Python") #print "p" elif e == "rb" or e == "rbw": self.getEditor(self.tabNum).setLang("Ruby") elif e == "cir": self.getEditor(self.tabNum).setLang("Spice") elif e == "sql": self.getEditor(self.tabNum).setLang("SQL") elif e == "tcl": self.getEditor(self.tabNum).setLang("TCL") elif e == "tex": self.getEditor(self.tabNum).setLang("TeX") elif e == "v" or e == "sv" or e == "vh" or e == "svh": self.getEditor(self.tabNum).setLang("Verilog") elif e == "vhd" or e == "vhdl": self.getEditor(self.tabNum).setLang("VHDL") elif e == "xml" or e == "xsl" or e == "xsml" or e == "xsd" or \ e == "kml" or e == "wsdl" or e == "xlf" or e == "xliff": self.getEditor(self.tabNum).setLang("XML") elif e == "yml": self.getEditor(self.tabNum).setLang("YML") except (ValueError, IndexError): self.lexer = QsciLexerText() self.lexer.setDefaultFont(config.font) self.lexer.setDefaultColor(QColor("Black")) self.getEditor(self.tabNum).setLexer(self.lexer) self.noLexAct.setChecked(True) def new(self): main = mainWindow() main.show() def open(self): index = self.tab.currentIndex() if(self.file != ('', '')): with open(self.file, "rt") as f: if self.tabNum >= 1: self.newEditor() #print "t" self.tab.setTabText(index+1, os.path.basename(str(self.file))) self.getEditor(self.tabNum).setText(f.read()) self.tab.setCurrentIndex(index+1) if self.tabNum == 0: self.tabNum = 1 self.tab.setTabText(index, os.path.basename(str(self.file))) #print(self.tabNum) self.getEditor(self.tabNum).setText(f.read()) self.tab.setCurrentIndex(index+1) # Try to guess the lexer based on extension self.guessLexer() # Not really sure where else to put this self.getEditor(self.tab.currentIndex()+1).setModified(False) self.getEditor(self.tabNum).textChanged.connect(self.unsaved) def newEditor(self): self.tabNum+=1 # Add a new entry to the dict and map it an editor object self.editDict["edit"+str(self.tabNum)] = Editor() self.tab.addTab(self.getEditor(self.tabNum), os.path.basename(str(self.file))) #print "o" def openFile(self): self.file = QFileDialog.getOpenFileName(self, 'Open File',".")[0] try: config.docList.append(str(self.file)) #print "k" self.open() except AttributeError: config.docList.append(str(self.file)) self.open() #print "h" def loadDocs(self): fh = None if not os.access(".open.p", os.F_OK): return else: try: fh = gzip.open(".open.p", "rb") config.docList = pickle.load(fh) for x in config.docList: self.file = x self.open() except (IOError, OSError): #print e return finally: if fh is not None: fh.close() def save(self): # Save the file as plain text with open(self.getCurrentFile(), "wt") as file: file.write(self.getEditor(self.tab.currentIndex()+1).text()) # Note that changes to the document are saved self.edit.setModified(False) # Set the tab title to filename self.tab.setTabText(self.tab.currentIndex(), os.path.basename(str(self.getCurrentFile()))) def saveDocs(self): try: fh = gzip.open(".open.p", "wb") pickle.dump(config.docList, fh, 2) except (IOError, OSError) as e: raise e finally: if fh: fh.close() def saveFile(self): # Only open if it hasn't previously been saved if len(config.docList) != 0: if self.getCurrentFile() == "Untitled": config.docList[self.tab.currentIndex()] = \ QFileDialog.getSaveFileName(self, 'Save File') self.save() else: config.docList.append(QFileDialog.getSaveFileName (self, 'Save File')) self.save() def saveFileAs(self): config.filename = QFileDialog.getSaveFileName(self, 'Save File') self.save() def unsaved(self): if self.getEditor(self.tab.currentIndex()+1).isModified: self.tab.setTabText(self.tab.currentIndex(), os.path.basename(self.getCurrentFile()+"*")) def about(self): QMessageBox.about(self, "About Codex", "<p>Codex is a text editor for programmers " \ "made with PyQt5 and QScintilla.</p>" ) def toggleTabs(self): state = self.tab.isVisible() self.tab.setVisible(not state) def newTab(self): self.tabNum+=1 # Add a new entry to the dict and map it to an editor object self.editDict["edit"+str(self.tabNum)] = Editor() self.tab.addTab(self.getEditor(self.tabNum), "Untitled") self.guessLexer() self.getEditor(self.tab.currentIndex()+1).lexer.setFont(config.font) def showTerm(self): self.termVis = True self.termSplit.addWidget(self.term) self.term.resize(800,40) self.term.setFont(config.font) self.term.show() def hideTerm(self): self.termVis = False self.term.hide() def toggleTerm(self): self.hideTerm() if self.termVis else self.showTerm() def showTree(self): self.ftree = Tree(self) self.treeVis = True self.ftree.resize(80,430) self.treeSplit.addWidget(self.ftree) self.ftree.show() def hideTree(self): self.treeVis = False self.ftree.close() def toggleTree(self): self.hideTree() if self.treeVis else self.showTree() def loadTermAndTree(self): if self.treeVis: self.showTree() self.treeAct.setChecked(True) else: self.treeVis = False self.treeAct.setChecked(False) if self.termVis: self.showTerm() self.termAct.setChecked(True) else: self.termVis = False self.termAct.setChecked(False) def toggleIntGuide(self): state = self.edit.indentationGuides() self.edit.setIndentationGuides(not state) def toggleLN(self): state = self.edit.marginLineNumbers(0) self.edit.setMarginLineNumbers(0, not state) self.edit.setMarginWidth(0,0) if state == True else self.edit. \ setMarginWidth(0,self.edit.metrics.width("00000")) def fr(self): frwin = Find(self) frwin.show() def chooseFont(self): font, ok = QFontDialog.getFont() if ok: config.font = font try: self.getEditor(self.tab.currentIndex()).lexer().setFont(config.font) except AttributeError: self.getEditor(self.tab.currentIndex()).setLang(QsciLexerText()) #print self.getEditor(self.tab.currentIndex()).lexer() self.getEditor(self.tab.currentIndex()).lexer().setFont(config.font) def setProDir(self): pdir, ok = QInputDialog.getText(self, "Set Project Directory", "Enter absolute path (i.e. "\ "/home/steve/Documents)") if ok: config.proDir = pdir #print config.proDir # This method adapted from Peter Goldsborough's Writer. # Save settings and alerts the user if they are saving an edited file. def closeEvent(self,event): self.writeSettings() self.saveDocs() if not self.edit.isModified(): event.accept() else: dialog = QMessageBox(self) dialog.setIcon(QMessageBox.Warning) dialog.setText(config.filename+" has unsaved changes.") dialog.setInformativeText("Do you want to save your changes?") dialog.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard) dialog.setDefaultButton(QMessageBox.Save) response = dialog.exec_() if response == QMessageBox.Save: self.save() elif response == QMessageBox.Discard: event.accept() else: event.ignore() def resizeEvent(self,event): # Don't try to resize a non-existant file tree try: self.ftree.treeView.resize(self.ftree.treeView.width(), self.height()) except: pass try: self.term.resize(self.width(), self.term.height()) except: pass def keyPressEvent(self,event): key = event.key() if (self.getEditor(self.tab.currentIndex()).text() == "bee movie"): with open("bee_movie.txt", "r") as file: script = file.read() self.getEditor(self.tab.currentIndex()).setText(script)
def setupEditor(self): self.editor = Editor() # 创建编辑器对象
def OnClick(self, event): ID = event.GetId() if ID == self.NEW_ID: self.parent.ShowAction(self.parent.geometryActionsNew) if ID == self.ADD_ID: self.parent.ShowAction(self.parent.geometryActionsAdd) if ID == self.DEL_ID: # inspector = self.parent wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry geoItem = wk.inspector.currentGeometryItem geo_id = wk.list_geo.index(geo) wk.remove_geometry(geoItem, geo) # macro recording if wk.macroRecording: macro_script = wk.macro_script macro_script.new_line() macro_script.append("# ... delete geometry") macro_script.append("geo_id = " + str(geo_id)) macro_script.append("geo = geometries[geo_id]") macro_script.append("geoItem = geo.treeItem") macro_script.append("wk.remove_geometry(geoItem, geo)") macro_script.append("# ...") if ID == self.DUP_ID: # inspector = self.parent wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry geo_new = wk.inspector.currentGeometry.copy() geo_newItem = wk.add_geometry(geo_new) # macro recording if wk.macroRecording: macro_script = wk.macro_script macro_script.new_line() macro_script.append("# ... copy geometry") geo_id = wk.list_geo.index(geo) macro_script.append("geo_id = " + str(geo_id)) macro_script.append("geo = geometries[geo_id]") macro_script.append("_geo = geo.copy()") macro_script.append("wk.add_geometry(geometry(_geo))") macro_script.append("# ...") if ID == self.PLJ_ID: # inspector = self.parent wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry import matplotlib.pyplot as plt try: MeshResolution = geo.list_patchInfo[0].steps[0] except: MeshResolution = 10 geo.plotJacobians(MeshResolution=MeshResolution) plt.colorbar() plt.show() if ID == self.PLM_ID: # inspector = self.parent wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry import matplotlib.pyplot as plt MeshResolution = geo.list_patchInfo[0].steps[0] geo.plotMesh(MeshResolution=MeshResolution) plt.show() if ID == self.EXP_ID: from global_vars import CAIDwildcard # Create a save file dialog dialog = wx.FileDialog(None, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT, wildcard=CAIDwildcard) # Show the dialog and get user input if dialog.ShowModal() == wx.ID_OK: ls_file = dialog.GetPath() wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry geo.save(ls_file) # macro recording if wk.macroRecording: macro_script = wk.macro_script macro_script.new_line() macro_script.append("# ... export geometry") geo_id = wk.list_geo.index(geo) macro_script.append("geo_id = " + str(geo_id)) macro_script.append("geo = geometries[geo_id]") macro_script.append("filename = \"" + ls_file + "\"") macro_script.append("geo.save(filename)") macro_script.append("# ...") # Destroy the dialog dialog.Destroy() if ID == self.EDT_ID: from Editor import Editor # inspector = self.parent wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry edt = Editor(wk.parent, -1, 'Editor') filename = edt.DoOpenGeometryAsFile(geo) # wait until the editor is closed createNewGeo = False while edt: if edt.modify: createNewGeo = True wx.MilliSleep(10) wx.GetApp().Yield() if createNewGeo: newgeo = cad_geometry(filename) geo_new = geometry(newgeo) geo_newItem = wk.add_geometry(geo_new) try: os.remove(filename) except: pass if ID == self.TRS_ID: self.parent.objectActionsTranslate.asGeometry() self.parent.ShowAction(self.parent.objectActionsTranslate) if ID == self.ROT_ID: self.parent.objectActionsRotate.asGeometry() self.parent.ShowAction(self.parent.objectActionsRotate) if ID == self.SCL_ID: self.parent.objectActionsScale.asGeometry() self.parent.ShowAction(self.parent.objectActionsScale) if ID == self.REF_ID: self.parent.ShowAction(self.parent.geometryActionsRefine) if ID == self.PEX_ID: self.parent.objectActionsPolarExtrude.asGeometry() self.parent.ShowAction(self.parent.objectActionsPolarExtrude) if ID == self.EXD_ID: # inspector = self.parent wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry geoItem = wk.inspector.currentGeometryItem list_geo = geo.expand() for _geo in list_geo: geo_new = geometry(_geo) geo_newItem = wk.add_geometry(geo_new) # macro recording if wk.macroRecording: macro_script = wk.macro_script macro_script.new_line() macro_script.append("# ... expand geometry") geo_id = wk.list_geo.index(geo) macro_script.append("geo_id = " + str(geo_id)) macro_script.append("geo = geometries[geo_id]") macro_script.append("list_geo = geo.expand()") macro_script.append("for _geo in list_geo:") macro_script.append("\twk.add_geometry(geometry(_geo))") macro_script.append("# ...") if ID == self.IMP_ID: # Create an open file dialog dialog = wx.FileDialog(None, style=wx.FD_OPEN) # Show the dialog and get user input if dialog.ShowModal() == wx.ID_OK: filename = dialog.GetPath() # TODO update recent files # self.UpdateRecentFiles(filename) geo = cad_geometry(filename) wk = self.parent.WorkGroup wk.add_geometry(geometry(geo)) # macro recording if wk.macroRecording: macro_script = wk.macro_script macro_script.new_line() macro_script.append("# ... import geometry") macro_script.append("filename = \"" + filename + "\"") macro_script.append("_geo = cad_geometry(filename)") macro_script.append("wk.add_geometry(geometry(_geo))") macro_script.append("# ...") # Destroy the dialog dialog.Destroy() if ID == self.REI_ID: # inspector = self.parent wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry geoItem = wk.inspector.currentGeometryItem geo.initialize_info() # macro recording if wk.macroRecording: macro_script = wk.macro_script macro_script.new_line() macro_script.append("# ... initialize info geometry") geo_id = wk.list_geo.index(geo) macro_script.append("geo_id = " + str(geo_id)) macro_script.append("geo = geometries[geo_id]") macro_script.append("geo.initialize_info()") macro_script.append("wk.Refresh(inspector=True)") macro_script.append("# ...") wk.Refresh(inspector=True) if ID == self.UPI_ID: # inspector = self.parent wk = self.parent.WorkGroup geo = wk.inspector.currentGeometry geoItem = wk.inspector.currentGeometryItem geo.update() # macro recording if wk.macroRecording: macro_script = wk.macro_script macro_script.new_line() macro_script.append("# ... update geometry") geo_id = wk.list_geo.index(geo) macro_script.append("geo_id = " + str(geo_id)) macro_script.append("geo = geometries[geo_id]") macro_script.append("geo.update()") macro_script.append("wk.Refresh(inspector=True)") macro_script.append("# ...") wk.Refresh(inspector=True) if ID == self.T5P_ID: # inspector = self.parent wk = self.parent.WorkGroup item = wk.inspector.tree.GetSelection() geo_bnd = wk.inspector.tree.GetItemData(item) face = geo_bnd.face faceItem = wk.inspector.tree.GetItemParent(item) patchItem = wk.inspector.tree.GetItemParent(faceItem) geoItem = wk.inspector.tree.GetItemParent(patchItem) geo = wk.inspector.tree.GetItemData(geoItem) _geo = cad_geometry() _geo.append(geo[0]) geo_new = geometry(_geo.to5patchs(face)) geo_newItem = wk.add_geometry(geo_new) # macro recording if wk.macroRecording: macro_script = wk.macro_script macro_script.new_line() macro_script.append("# ... to-5-patchs geometry") geo_id = wk.list_geo.index(geo) macro_script.append("geo_id = " + str(geo_id)) macro_script.append("geo = geometries[geo_id]") macro_script.append("_geo = cad_geometry()") macro_script.append("_geo.append(geo[0])") macro_script.append("face = " + str(face)) macro_script.append("_geo = _geo.to5patchs(face)") macro_script.append("wk.add_geometry(geometry(_geo))") macro_script.append("wk.Refresh()") macro_script.append("# ...") wk.Refresh()
def page_editor(Username): global count_menu, v_num_canvas editor = Editor() with open("static/resourses/version_num", "w") as file: file.write(str(v_num_canvas)) if request.method == "GET": print("Hello") v_num_canvas += 1 return render_template("editor.html", name=Username, hidden="hidden", v_num_canvas=v_num_canvas) else: if list(request.form.keys())[0] == "Sett": if count_menu % 2 == 0: count_menu += 1 return render_template("editor.html", hidden="", name=Username, v_num_canvas=v_num_canvas) else: count_menu += 1 return render_template("editor.html", hidden="hidden", name=Username, v_num_canvas=v_num_canvas) elif list(request.form.keys())[0] == "Name": return redirect(f"/{Username}/") elif list(request.form.keys())[-1] == "but5": if request.form.get("List") == "Начало": with open("static/js/editor-script.js", "w") as file: start = Start((275, 50)) editor.add_figure(start) file.write(editor.get_code()) elif request.form.get("List") == "Конец": with open("static/js/editor-script.js", "w") as file: end = End((275, 50)) editor.add_figure(end) file.write(editor.get_code()) elif request.form.get("List") == "Условие": with open("static/js/editor-script.js", "w") as file: cond = Condition((275, 50)) editor.add_figure(cond) file.write(editor.get_code()) elif request.form.get("List") == "Цикл": with open("static/js/editor-script.js", "w") as file: cycle = Cycle((275, 50)) editor.add_figure(cycle) file.write(editor.get_code()) elif request.form.get("List") == "Ввод/вывод": with open("static/js/editor-script.js", "w") as file: inp = Input((275, 50)) editor.add_figure(inp) file.write(editor.get_code()) elif request.form.get("List") == "Объявление": with open("static/js/editor-script.js", "w") as file: decl = Declar((275, 50)) editor.add_figure(decl) file.write(editor.get_code()) elif request.form.get("List") == "Функция": with open("static/js/editor-script.js", "w") as file: func = Func((275, 50)) editor.add_figure(func) file.write(editor.get_code()) return redirect(f"/{Username}/profile/Editor") elif list(request.form.keys())[-1] == "but4": editor.scheme[-1].move_right() with open("static/js/editor-script.js", "w") as file: file.write(editor.get_code()) return redirect(f"/{Username}/profile/Editor") elif list(request.form.keys())[-1] == "but3": editor.scheme[-1].move_left() with open("static/js/editor-script.js", "w") as file: file.write(editor.get_code()) return redirect(f"/{Username}/profile/Editor") elif list(request.form.keys())[-1] == "but1": editor.scheme[-1].move_up() with open("static/js/editor-script.js", "w") as file: file.write(editor.get_code()) return redirect(f"/{Username}/profile/Editor") elif list(request.form.keys())[-1] == "but2": editor.scheme[-1].move_down() with open("static/js/editor-script.js", "w") as file: file.write(editor.get_code()) return redirect(f"/{Username}/profile/Editor")
for block in maps.new_blocks: if block.ID == 2: start = block.rect.x, block.rect.y player.rect.x, player.rect.y = start player2.rect.x, player2.rect.y = start if not reloadGame: MovePlayer() maps.all_block_types = maps.allTypes from Editor import Editor edit = Editor() if editing == True: edit.editing = True clock = pygame.time.Clock() entities = [] import SettingUp
def __init__(self, sequencePath, browser, errline=0, parent=None): super().__init__(parent) self.sequencePath = sequencePath self.browser = browser #self.polyMaskGenWnd = PolymaskGeneratorWindow() self.playSpeed = 1 hbox = QHBoxLayout(self) self.splitter = QSplitter() self.editor = Editor(sequencePath, errline, None) self.splitter.addWidget(self.editor) self.rpanel = QWidget(None) grid = QGridLayout() self.reloadButton = QPushButton('Save script and load sequence', self.rpanel) self.reloadButton.clicked.connect(self.reload) grid.addWidget(self.reloadButton, 1, 2, 1, 8) self.discardButton = QPushButton('Discard changes', self.rpanel) self.discardButton.clicked.connect(self.discard) grid.addWidget(self.discardButton, 5, 2, 1, 8) self.prevview = QWidget() self.prevview.setAttribute(Qt.WA_TranslucentBackground, True) self.prevview.setAttribute(Qt.WA_NoSystemBackground, True) self.prevview.setAutoFillBackground(False) self.prevview.setFixedSize(400, 400) grid.addWidget(self.prevview, 2, 2, 1, 8) self.surfaceHandle = gears.CreateSurface( self.prevview.winId().__int__()) gears.SetCurrentSurface(self.surfaceHandle) gears.RenderFrame(600) #self.preview = Preview(self.rpanel, self.editor, self.winId()) #grid.addWidget(self.preview, 2, 2, 1, 8) self.seeker = QSlider(Qt.Horizontal, self.rpanel) self.seeker.setTickPosition(QSlider.TicksBelow) self.seeker.setMinimum(0) seq = gears.getSequence() if seq: self.seeker.setMaximum(seq.getDuration()) self.seeker.sliderPressed.connect(self.seekerPressed) self.seeker.sliderReleased.connect(self.seekerReleased) self.seeker.valueChanged.connect(self.seekerChanged) self.seeking = False grid.addWidget(self.seeker, 3, 2, 1, 8) self.pauseButton = QPushButton('\u275a\u275a', self.rpanel) self.pauseButton.clicked.connect(self.pause) grid.addWidget(self.pauseButton, 4, 2, 1, 1) self.play1button = QPushButton('\u25b6', self.rpanel) self.play1button.clicked.connect(self.play1) grid.addWidget(self.play1button, 4, 3, 1, 1) self.play2button = QPushButton('\u25b6\u25b6', self.rpanel) self.play2button.clicked.connect(self.play2) grid.addWidget(self.play2button, 4, 4, 1, 1) self.rpanel.setLayout(grid) self.splitter.addWidget(self.rpanel) hbox.addWidget(self.splitter) self.setLayout(hbox) self.setGeometry(100, 100, 1600, 900) self.timer = QTimer(self) self.timer.setInterval(16) self.timer.timeout.connect(self.onTimer) self.timer.start()