コード例 #1
0
    def setUp(self):
        self._download_dir = tempfile.mkdtemp()
        browser = os.getenv("BROWSER_TYPE", 'chrome')
        mode = os.getenv("BROWSER_MODE", '--headless')
        print("...browser: {b}".format(b=browser))
        print("...mode: {m}".format(m=mode))

        if mode == "--headless" and os.getenv("CIRCLECI"):
            print("...starting display since we are running in headless mode")
            display = Display(visible=0, size=(800, 600))
            display.start()

        if browser == 'chrome':
            self.setup_for_chrome(mode)
        elif browser == 'firefox':
            self.setup_for_firefox(mode)

        self.driver.implicitly_wait(self._wait_timeout)
        time.sleep(self._delay)

        utils = JupyterUtils()
        self.server = utils.get_server()
        self.main_page = MainPage(self.driver, self.server)
        self.left_side_bar = VcdatLeftSideBar(self.driver, None)
        self.file_browser = FileBrowser(self.driver, None)
        self.click_on_file_browser_home()

        self._test_notebook_file = "{t}.ipynb".format(t=self._testMethodName)
        self.notebook_page = NoteBookPage(self.driver, None)
        self.notebook_page.rename_notebook(self._test_notebook_file)
コード例 #2
0
    def load_data_file(self, filename):
        left_side_bar = VcdatLeftSideBar(self.driver, None)
        left_side_bar.click_on_jp_vcdat_icon()
        time.sleep(self._delay)
        left_side_bar.click_on_load_variables()

        file_browser = FileBrowser(self.driver, None)
        file_browser.double_click_on_a_file(filename)
        # self.main_page.select_kernel()
        time.sleep(self._delay)

        return left_side_bar
コード例 #3
0
class Save:
    def __init__(self, nodes, connections):
        self.jsonElements = JSONTools().get(nodes, connections)
        self.browser = FileBrowser(self.save,
                                   True,
                                   defaultFilename="project.json")

    def save(self, doSave):
        if doSave:
            self.dlgOverwrite = None
            self.dlgOverwriteShadow = None
            path = self.browser.get()
            path = os.path.expanduser(path)
            path = os.path.expandvars(path)
            if os.path.exists(path):
                self.dlgOverwrite = YesNoDialog(
                    text="File already Exist.\nOverwrite?",
                    relief=DGG.RIDGE,
                    frameColor=(1, 1, 1, 1),
                    frameSize=(-0.5, 0.5, -0.3, 0.2),
                    sortOrder=1,
                    button_relief=DGG.FLAT,
                    button_frameColor=(0.8, 0.8, 0.8, 1),
                    command=self.__executeSave,
                    extraArgs=[path],
                    scale=300,
                    pos=(base.getSize()[0] / 2, 0, -base.getSize()[1] / 2),
                    parent=base.pixel2d)
                self.dlgOverwriteShadow = DirectFrame(
                    pos=(base.getSize()[0] / 2 + 10, 0,
                         -base.getSize()[1] / 2 - 10),
                    sortOrder=0,
                    frameColor=(0, 0, 0, 0.5),
                    frameSize=self.dlgOverwrite.bounds,
                    scale=300,
                    parent=base.pixel2d)
            else:
                self.__executeSave(True, path)
            base.messenger.send("setLastPath", [path])
        self.browser.destroy()
        del self.browser

    def __executeSave(self, overwrite, path):
        if self.dlgOverwrite is not None: self.dlgOverwrite.destroy()
        if self.dlgOverwriteShadow is not None:
            self.dlgOverwriteShadow.destroy()
        if not overwrite: return

        with open(path, 'w') as outfile:
            json.dump(self.jsonElements, outfile, indent=2)
コード例 #4
0
ファイル: fbrv.py プロジェクト: timothyhalim/RVFileBrowser
    def setupUI(self):
        self.dock = QDockWidget()
        self.dock.setWindowTitle("File Browser")

        self.masterWidget = QWidget()
        self.masterLayout = QVBoxLayout(self.masterWidget)
        self.dock.setWidget(self.masterWidget)

        movieExt = ["*.mov", "*.mp4", "*.wmv", "*.movieproc"]
        imgExt = [
            "*.ext", "*.tiff", "*.tif", "*.dpx", "*.iff", "*.jpeg", "*.png",
            "*.ari"
        ]
        rawCam = [
            ".arw", ".cr2", ".crw", ".dng", ".nef", ".orf", ".pef", ".ptx",
            ".raf", ".rdc", ".rmf"
        ]
        self.fileBrowser = FileBrowser(filterExtension=movieExt + imgExt +
                                       rawCam)
        self.fileBrowser.executed.connect(self.play)
        self.masterLayout.addWidget(self.fileBrowser)
コード例 #5
0
  def init(self):
    if self.isInit:
      return

    # add screens
    self.screen = Screen(name=szConsole)
    self.oldScreen = None
    self.oldTouchPrev = None
    self.editorLayout = EditorLayout(self)
    self.tutorialLayout = TutorialLayout(self)
    self.fileBrowser = FileBrowser.instance()
    
    self.repl = REPL(self)
    self.history = ["",]
    self.historyIndex = -1
    self.historyCount = 100
    self.lastIndentSpace = ""
    self.bIndentMode = False
    self.reFocusInputText = False
    self.oldTouchPrev = None
    self.textInputWidth = W * (4.0/5.0)
    
    # console menu layout
    self.consoleMenuLayout = BoxLayout(orientation="horizontal", size_hint=(1, None), height="35dp")
    btn_clear = Button(text="Clear", background_color=darkGray)
    btn_clear.bind(on_release = lambda inst:self.clearOutput())
    btn_prev = Button(text="<<", background_color=darkGray)
    btn_next = Button(text=">>", background_color=darkGray)
    self.consoleMenuLayout.add_widget(btn_clear)
    self.consoleMenuLayout.add_widget(btn_prev)
    self.consoleMenuLayout.add_widget(btn_next)
    self.screen.add_widget(self.consoleMenuLayout)
    
    # screen menu layout
    self.screenMenuLayout = BoxLayout(orientation="horizontal", size_hint=(1, None), height="35dp", pos=(0,0))
    btn_console = Button(text="Console", background_color=[1.5,0.8,0.8,2]) 
    btn_editor = Button(text="Code Editor", background_color=[0.8,1.5,0.8,2])
    btn_tutorial = Button(text="Python Tutotial", background_color=[0.8,0.8,1.5,2])
    btn_editor.bind(on_release=lambda inst:self.setMode(szEditor))
    btn_tutorial.bind(on_release=lambda inst:self.setMode(szTutorial))
    self.screenMenuLayout.add_widget(btn_console)
    self.screenMenuLayout.add_widget(btn_editor)
    self.screenMenuLayout.add_widget(btn_tutorial)
    self.screen.add_widget(self.screenMenuLayout)
    
    # text input
    self.consoleInput = TextInput(text = "text", multiline=False, size_hint=(None, None), auto_indent = True, font_name=defaultFont, 
      background_color=(.1, .1, .1, 1), foreground_color=(1,1,1,1), text_size=(0,0), font_size="14dp", padding_x="20dp", padding_y="15dp")  
    self.consoleInput.size = (W, self.consoleInput.minimum_height)
    self.consoleInput.text = ""
  
    self.consoleInput.bind(on_text_validate = lambda inst:self.onConsoleInput(inst, False, False))
    self.consoleInput.bind(focus = self.inputBoxFocus)
    
    # textinput scroll view
    self.textInputSV = ScrollView(size_hint=(None, None), size = (W, self.consoleInput.minimum_height))
    self.textInputSV.scroll_y = 0
    self.textInputSV.add_widget(self.consoleInput)
    
    # add input widget
    self.screen.add_widget(self.textInputSV)
    
    # run button
    self.btn_run = Button(text="Run", size_hint=(None,None), size =(W-self.consoleInput.size[0], self.consoleInput.size[1]),\
      background_color=(1.3,1.3,2,2))
    self.btn_run.bind(on_release = lambda inst:self.onConsoleInput(self.consoleInput, True, False))
    self.btn_run.pos = (W - self.btn_run.size[0], 0)
    self.screen.add_widget(self.btn_run)
      
    # output
    self.outputSV = ScrollView(size_hint=(None, None))
    self.screen.add_widget(self.outputSV)
    
    self.outputLayout = BoxLayout(orientation="vertical", size_hint=(None,None))
    self.outputSV.add_widget(self.outputLayout)
    
    def func_prev(inst):         
      if len(self.history) > 0:
        self.historyIndex -= 1
        if self.historyIndex < 0:
          self.historyIndex = len(self.history) - 1
        text = self.history[self.historyIndex]
        if text.find("\n") > -1:
          self.bIndentMode = True
        self.setInputText(text)
    btn_prev.bind(on_release = func_prev)
    
    def func_next(inst):
      if len(self.history) > 0:
        self.historyIndex += 1
        if self.historyIndex >= len(self.history):
          self.historyIndex = 0
        text = self.history[self.historyIndex]
        if text.find("\n") > -1:
          self.bIndentMode = True
        self.setInputText(text)
    btn_next.bind(on_release = func_next)    

    # show output layout
    self.displayText("Python " + sys.version.strip(), 0)
    
    self.repl.run_script('input=InputPopup.instance().show', False)
    
    self.isInit = True
コード例 #6
0
class PyInterpreter(Singleton):
  isInit = False
  bExitOnTouchPrev = True
  outputWidth = W
  prevMode = ""
  currentMode = "" # console, tutorial, editor
  emptyWidget = Widget(size_hint=(None,None), size=(0,0))
  
  def init(self):
    if self.isInit:
      return

    # add screens
    self.screen = Screen(name=szConsole)
    self.editorLayout = EditorLayout(self)
    self.tutorialLayout = TutorialLayout(self)
    self.fileBrowser = FileBrowser(self)
    
    self.repl = REPL(self)
    self.history = ["",]
    self.historyIndex = -1
    self.historyCount = 100
    self.lastIndentSpace = ""
    self.bIndentMode = False
    self.reFocusInputText = False
    self.oldTouchPrev = None
    self.textInputWidth = W * (4.0/5.0)
    
    # console menu layout
    self.consoleMenuLayout = BoxLayout(orientation="horizontal", size_hint=(1, None), height="35dp")
    btn_clear = Button(text="Clear", background_color=darkGray)
    btn_clear.bind(on_release = lambda inst:self.clearOutput())
    btn_prev = Button(text="<<", background_color=darkGray)
    btn_next = Button(text=">>", background_color=darkGray)
    self.consoleMenuLayout.add_widget(btn_clear)
    self.consoleMenuLayout.add_widget(btn_prev)
    self.consoleMenuLayout.add_widget(btn_next)
    self.screen.add_widget(self.consoleMenuLayout)
    
    # screen menu layout
    self.screenMenuLayout = BoxLayout(orientation="horizontal", size_hint=(1, None), height="35dp", pos=(0,0))
    btn_console = Button(text="Console", background_color=[1.5,0.8,0.8,2]) 
    btn_editor = Button(text="Code Editor", background_color=[0.8,1.5,0.8,2])
    btn_tutorial = Button(text="Python Tutotial", background_color=[0.8,0.8,1.5,2])
    btn_editor.bind(on_release=lambda inst:self.setMode(szEditor))
    btn_tutorial.bind(on_release=lambda inst:self.setMode(szTutorial))
    self.screenMenuLayout.add_widget(btn_console)
    self.screenMenuLayout.add_widget(btn_editor)
    self.screenMenuLayout.add_widget(btn_tutorial)
    self.screen.add_widget(self.screenMenuLayout)
    
    # text input
    self.consoleInput = TextInput(text = "text", multiline=False, size_hint=(None, None), auto_indent = True, font_name=defaultFont, 
      background_color=(.1, .1, .1, 1), foreground_color=(1,1,1,1), text_size=(0,0), font_size="14dp", padding_x="20dp", padding_y="15dp")  
    self.consoleInput.size = (W, self.consoleInput.minimum_height)
    self.consoleInput.text = ""
  
    self.consoleInput.bind(on_text_validate = lambda inst:self.onConsoleInput(inst, False, False))
    self.consoleInput.bind(focus = self.inputBoxFocus)
    
    # textinput scroll view
    self.textInputSV = ScrollView(size_hint=(None, None), size = (W, self.consoleInput.minimum_height))
    self.textInputSV.scroll_y = 0
    self.textInputSV.add_widget(self.consoleInput)
    
    # add input widget
    self.screen.add_widget(self.textInputSV)
    
    # run button
    self.btn_run = Button(text="Run", size_hint=(None,None), size =(W-self.consoleInput.size[0], self.consoleInput.size[1]),\
      background_color=(1.3,1.3,2,2))
    self.btn_run.bind(on_release = lambda inst:self.onConsoleInput(self.consoleInput, True, False))
    self.btn_run.pos = (W - self.btn_run.size[0], 0)
    self.screen.add_widget(self.btn_run)
      
    # output
    self.outputSV = ScrollView(size_hint=(None, None))
    self.screen.add_widget(self.outputSV)
    
    self.outputLayout = BoxLayout(orientation="vertical", size_hint=(None,None))
    self.outputSV.add_widget(self.outputLayout)
    
    def func_prev(inst):         
      if len(self.history) > 0:
        self.historyIndex -= 1
        if self.historyIndex < 0:
          self.historyIndex = len(self.history) - 1
        text = self.history[self.historyIndex]
        if text.find("\n") > -1:
          self.bIndentMode = True
        self.setInputText(text)
    btn_prev.bind(on_release = func_prev)
    
    def func_next(inst):
      if len(self.history) > 0:
        self.historyIndex += 1
        if self.historyIndex >= len(self.history):
          self.historyIndex = 0
        text = self.history[self.historyIndex]
        if text.find("\n") > -1:
          self.bIndentMode = True
        self.setInputText(text)
    btn_next.bind(on_release = func_next)    

    # show output layout
    self.displayText("Python " + sys.version.strip(), 0)
    
    self.repl.run_script('input=InputPopup.instance().show', False)
    
    self.isInit = True
    
  def setMode(self, mode):
    if mode == self.currentMode:
      return
      
    self.prevMode = self.currentMode
    self.currentMode = mode
    
    # restore..
    if self.prevMode == szConsole:
      self.reFocusInputText = False
      self.inputBoxForceFocus(False)
    
     # set mode layout  
    if mode == szConsole:
      gMyRoot.current_screen(self.screen)
      self.refreshLayout()
    elif mode == szEditor:
      gMyRoot.current_screen(self.editorLayout.screen)
    elif mode == szTutorial:
      gMyRoot.current_screen(self.tutorialLayout.screen)
    elif mode == szFileBrowserOpen:
      self.fileBrowser.showOpenLayout()
    elif mode == szFileBrowserSaveAs:
      self.fileBrowser.showSaveAsLayout()
    
  def setExitOnTouchPrev(self, bValue):
    self.bExitOnTouchPrev = bValue
  
  def start(self):
    self.show()
    
  def update(self, dt):
    pass
  
  def clearOutput(self):
      self.outputLayout.clear_widgets()
      self.outputLayout.size = (W, 0)
      
  def outputLayout_add_widget(self, widget):
    self.outputLayout.add_widget(widget)
    self.outputLayout.height += widget.height + widget.padding[1] + widget.padding[3]

  def displayText(self, text, scroll_y, background_color=(1,1,1,0)):
    if type(text) != str:
      text = str(text)
       
    output = TextInput(markup = True, text="", halign='left', valign='top', readonly=True, font_size="12dp", font_name = defaultFont,
      multiline=True, background_color=background_color, foreground_color=(1,1,1,1), size_hint=(None,None), size = (self.outputWidth, 0))
    output.text = text
    output.size = (self.outputWidth, output.minimum_height)
    
    self.outputLayout.add_widget(output)
    self.outputLayout.size = (self.outputWidth, self.outputLayout.size[1] + output.size[1])
    self.outputSV.scroll_x = 0
    self.outputSV.scroll_y = scroll_y
    
  def onConsoleInput(self, inst, bForceRun, resetGlobals):
    self.reFocusInputText = True
    if inst.text.strip():
      bRunCode = len(inst.text) == self.consoleInput.cursor_index()
      lastLine_nonStrip = inst.text.split("\n")[-1]
      lastLine = lastLine_nonStrip.strip()
      # indent mode - continue input but not run
      if not bForceRun and lastLine and (lastLine[-1] in ("\\", ":") or self.bIndentMode or not bRunCode):
        self.bIndentMode = True
        # get indent space
        self.lastIndentSpace = ""
        if self.bIndentMode:
          for i in lastLine_nonStrip:
            if i in [" ", "\t"]:
              self.lastIndentSpace += i
            else:
              break
        inst.insert_text("\n" + self.lastIndentSpace)
        self.consoleInput.size = (W, self.consoleInput.minimum_height)
        return
      # check indent mode - run code
      self.bIndentMode = False
      # pop input text from history
      if len(self.history) > 0 and self.historyIndex > -1 \
        and self.historyIndex < len(self.history) and self.history[self.historyIndex] == inst.text:
          self.history.pop(self.historyIndex)
      # append item to history
      if self.currentMode == szConsole:
        self.history.append(inst.text.strip())
      # check history count
      if len(self.history) > self.historyCount:
        self.history = self.history[:self.historyCount]
      self.historyIndex = len(self.history)
      # display input text to output widget
      if self.currentMode == szConsole:
        lines = inst.text.split("\n")
        result = []
        for i, line in enumerate(lines):
          line = (">>> " if i == 0 else "... ") + line
          result.append(line)
        result = "\n".join(result)
        self.displayText(result, 0)
      elif self.currentMode == szEditor:
        currentDocument = ">>> Run Untitled.py"
        self.displayText("\n".join(["-" * len(currentDocument), currentDocument + " - " + time.ctime()]), 0)
      # run code
      self.repl.onConsoleInput(inst.text, resetGlobals)
      # end message
      if self.currentMode == szEditor:
        self.displayText("Done.", 0)
        
      # clear text input
      if self.currentMode == szConsole:
        self.setInputText("")
      
  def refreshLayout(self):
    if self.currentMode == szConsole:  
      keyboardHeight = gMyRoot.getKeyboardHeight() if self.consoleInput.focus else 0
      limitHeight = (H - topMargin - keyboardHeight) * 0.5
      if self.consoleInput.minimum_height > limitHeight:
        height = limitHeight
      else:
        height = self.consoleInput.minimum_height
      self.screenMenuLayout.pos = (0, keyboardHeight)
      self.textInputSV.pos = (0, self.screenMenuLayout.top)
      self.textInputSV.size = (self.textInputWidth, height)
      self.consoleInput.size = (self.textInputWidth, self.consoleInput.minimum_height)
      self.btn_run.pos = (self.textInputSV.size[0], self.textInputSV.pos[1])
      self.btn_run.size = (W - self.textInputSV.size[0], self.textInputSV.size[1])
      self.consoleMenuLayout.pos = (0, self.textInputSV.top)
      self.outputSV.pos = (0, self.consoleMenuLayout.top)
      self.outputSV.size = (W, H - self.outputSV.pos[1] - topMargin)
      
  def setInputText(self, text):
    self.consoleInput.text = text
    if self.consoleInput.size[1] != self.consoleInput.minimum_height:
      self.refreshLayout()
  
  def insertInputText(self, text):
    self.consoleInput.insert_text(text)
    if self.consoleInput.size[1] != self.consoleInput.minimum_height:
      self.refreshLayout()
  
  def inputBoxForceFocus(self, bFocus):
    if bFocus != self.consoleInput.focus:
      self.consoleInput.focus = bFocus 
      
  def inputBoxFocus(self, inst, bFocus):
    bAlwaysPreserveFocus = False
    if not bFocus:
      if self.reFocusInputText:
        self.reFocusInputText = bAlwaysPreserveFocus
        inst.focus = True
    self.reFocusInputText = bAlwaysPreserveFocus
    self.refreshLayout()
    
  def update(self, dt):
    pass
    
  def touchPrev(self):
    if self.currentMode == szEditor:
      self.editorLayout.touchPrev()
    elif self.currentMode in (szFileBrowserOpen, szFileBrowserSaveAs):
      self.fileBrowser.touchPrev()
    elif self.currentMode == szTutorial:
      self.tutorialLayout.touchPrev()
    elif self.consoleInput.focus:
      self.reFocusInputText = False
      self.inputBoxForceFocus(False)
    else:
      self.exit()
      
  def toggle(self):
    if not self.isInit:
      self.init()
      
    if self.screen.name == gMyRoot.get_current_screen():
      self.close()
    else:
      self.show()
      
  def show(self):
    if not self.isInit:
      self.init()
      
    gMyRoot.add_screen(self.screen)
    gMyRoot.add_screen(self.editorLayout.screen)
    gMyRoot.add_screen(self.tutorialLayout.screen)
    gMyRoot.current_screen(self.screen)
    self.oldTouchPrev = gMyRoot.getTouchPrev()
    gMyRoot.setTouchPrev(self.touchPrev)
    self.setMode(szConsole)
  
  def close(self):
    gMyRoot.setTouchPrev(self.oldTouchPrev)
    gMyRoot.remove(self)
    gMyRoot.remove_screen(self.screen)
    gMyRoot.remove_screen(self.editorLayout.screen)
    gMyRoot.remove_screen(self.tutorialLayout.screen)
    if self.bExitOnTouchPrev:
      self.editorLayout.exit()
      gMyRoot.exit()
        
  def exit(self, *args):
    self.reFocusInputText = False
    self.inputBoxForceFocus(False)
    gMyRoot.popup("Exit Python?", "", self.close, None)
コード例 #7
0
 def click_on_load_variables_by_file(self):
     element = self.locate_load_variables_by_file()
     self.move_to_click(element)
     file_browser = FileBrowser(self.driver, None)
     return file_browser
コード例 #8
0
    def init(self):
        if self.isInit:
            return

        # add screens
        self.screen = Screen(name=szConsole)
        self.editorLayout = EditorLayout(self)
        self.tutorialLayout = TutorialLayout(self)
        self.fileBrowser = FileBrowser(self)

        self.repl = REPL(self)
        self.history = [
            "",
        ]
        self.historyIndex = -1
        self.historyCount = 100
        self.lastIndentSpace = ""
        self.bIndentMode = False
        self.reFocusInputText = False
        self.oldTouchPrev = None
        self.textInputWidth = W * (4.0 / 5.0)

        # console menu layout
        self.consoleMenuLayout = BoxLayout(orientation="horizontal",
                                           size_hint=(1, None),
                                           height="35dp")
        btn_clear = Button(text="Clear", background_color=darkGray)
        btn_clear.bind(on_release=lambda inst: self.clearOutput())
        btn_prev = Button(text="<<", background_color=darkGray)
        btn_next = Button(text=">>", background_color=darkGray)
        self.consoleMenuLayout.add_widget(btn_clear)
        self.consoleMenuLayout.add_widget(btn_prev)
        self.consoleMenuLayout.add_widget(btn_next)
        self.screen.add_widget(self.consoleMenuLayout)

        # screen menu layout
        self.screenMenuLayout = BoxLayout(orientation="horizontal",
                                          size_hint=(1, None),
                                          height="35dp",
                                          pos=(0, 0))
        btn_console = Button(text="Console",
                             background_color=[1.5, 0.8, 0.8, 2])
        btn_editor = Button(text="Code Editor",
                            background_color=[0.8, 1.5, 0.8, 2])
        btn_tutorial = Button(text="Python Tutotial",
                              background_color=[0.8, 0.8, 1.5, 2])
        btn_editor.bind(on_release=lambda inst: self.setMode(szEditor))
        btn_tutorial.bind(on_release=lambda inst: self.setMode(szTutorial))
        self.screenMenuLayout.add_widget(btn_console)
        self.screenMenuLayout.add_widget(btn_editor)
        self.screenMenuLayout.add_widget(btn_tutorial)
        self.screen.add_widget(self.screenMenuLayout)

        # text input
        self.consoleInput = TextInput(text="text",
                                      multiline=False,
                                      size_hint=(None, None),
                                      auto_indent=True,
                                      font_name=defaultFont,
                                      background_color=(.1, .1, .1, 1),
                                      foreground_color=(1, 1, 1, 1),
                                      text_size=(0, 0),
                                      font_size="14dp",
                                      padding_x="20dp",
                                      padding_y="15dp")
        self.consoleInput.size = (W, self.consoleInput.minimum_height)
        self.consoleInput.text = ""
        '''
    def paste():
      self.consoleInput.insert_text(gMyRoot.getClipboard())
      self.refreshLayout()
    self.consoleInput.paste = paste
    '''
        self.consoleInput.bind(on_text_validate=self.onConsoleInput)
        self.consoleInput.bind(focus=self.inputBoxFocus)

        # textinput scroll view
        self.textInputSV = ScrollView(size_hint=(None, None),
                                      size=(W,
                                            self.consoleInput.minimum_height))
        self.textInputSV.scroll_y = 0
        self.textInputSV.add_widget(self.consoleInput)

        # add input widget
        self.screen.add_widget(self.textInputSV)

        # run button
        self.btn_run = Button(text="Run", size_hint=(None,None), size =(W-self.consoleInput.size[0], self.consoleInput.size[1]),\
          background_color=(1.3,1.3,2,2))
        self.btn_run.bind(on_release=lambda inst: self.onConsoleInput(
            self.consoleInput, True))
        self.btn_run.pos = (W - self.btn_run.size[0], 0)
        self.screen.add_widget(self.btn_run)

        # output
        self.outputSV = ScrollView(size_hint=(None, None))
        self.screen.add_widget(self.outputSV)

        self.outputLayout = BoxLayout(orientation="vertical",
                                      size_hint=(None, None))
        self.outputSV.add_widget(self.outputLayout)

        def func_prev(inst):
            if len(self.history) > 0:
                self.historyIndex -= 1
                if self.historyIndex < 0:
                    self.historyIndex = len(self.history) - 1
                text = self.history[self.historyIndex]
                if text.find("\n") > -1:
                    self.bIndentMode = True
                self.setInputText(text)

        btn_prev.bind(on_release=func_prev)

        def func_next(inst):
            if len(self.history) > 0:
                self.historyIndex += 1
                if self.historyIndex >= len(self.history):
                    self.historyIndex = 0
                text = self.history[self.historyIndex]
                if text.find("\n") > -1:
                    self.bIndentMode = True
                self.setInputText(text)

        btn_next.bind(on_release=func_next)

        # show output layout
        self.displayText("Python " + sys.version.strip(), 0)
        self.isInit = True
コード例 #9
0
class PyInterpreter(Singleton):
    isInit = False
    bExitOnTouchPrev = True
    outputWidth = W
    prevMode = ""
    currentMode = ""  # console, tutorial, editor
    emptyWidget = Widget(size_hint=(None, None), size=(0, 0))

    def init(self):
        if self.isInit:
            return

        # add screens
        self.screen = Screen(name=szConsole)
        self.editorLayout = EditorLayout(self)
        self.tutorialLayout = TutorialLayout(self)
        self.fileBrowser = FileBrowser(self)

        self.repl = REPL(self)
        self.history = [
            "",
        ]
        self.historyIndex = -1
        self.historyCount = 100
        self.lastIndentSpace = ""
        self.bIndentMode = False
        self.reFocusInputText = False
        self.oldTouchPrev = None
        self.textInputWidth = W * (4.0 / 5.0)

        # console menu layout
        self.consoleMenuLayout = BoxLayout(orientation="horizontal",
                                           size_hint=(1, None),
                                           height="35dp")
        btn_clear = Button(text="Clear", background_color=darkGray)
        btn_clear.bind(on_release=lambda inst: self.clearOutput())
        btn_prev = Button(text="<<", background_color=darkGray)
        btn_next = Button(text=">>", background_color=darkGray)
        self.consoleMenuLayout.add_widget(btn_clear)
        self.consoleMenuLayout.add_widget(btn_prev)
        self.consoleMenuLayout.add_widget(btn_next)
        self.screen.add_widget(self.consoleMenuLayout)

        # screen menu layout
        self.screenMenuLayout = BoxLayout(orientation="horizontal",
                                          size_hint=(1, None),
                                          height="35dp",
                                          pos=(0, 0))
        btn_console = Button(text="Console",
                             background_color=[1.5, 0.8, 0.8, 2])
        btn_editor = Button(text="Code Editor",
                            background_color=[0.8, 1.5, 0.8, 2])
        btn_tutorial = Button(text="Python Tutotial",
                              background_color=[0.8, 0.8, 1.5, 2])
        btn_editor.bind(on_release=lambda inst: self.setMode(szEditor))
        btn_tutorial.bind(on_release=lambda inst: self.setMode(szTutorial))
        self.screenMenuLayout.add_widget(btn_console)
        self.screenMenuLayout.add_widget(btn_editor)
        self.screenMenuLayout.add_widget(btn_tutorial)
        self.screen.add_widget(self.screenMenuLayout)

        # text input
        self.consoleInput = TextInput(text="text",
                                      multiline=False,
                                      size_hint=(None, None),
                                      auto_indent=True,
                                      font_name=defaultFont,
                                      background_color=(.1, .1, .1, 1),
                                      foreground_color=(1, 1, 1, 1),
                                      text_size=(0, 0),
                                      font_size="14dp",
                                      padding_x="20dp",
                                      padding_y="15dp")
        self.consoleInput.size = (W, self.consoleInput.minimum_height)
        self.consoleInput.text = ""
        '''
    def paste():
      self.consoleInput.insert_text(gMyRoot.getClipboard())
      self.refreshLayout()
    self.consoleInput.paste = paste
    '''
        self.consoleInput.bind(on_text_validate=self.onConsoleInput)
        self.consoleInput.bind(focus=self.inputBoxFocus)

        # textinput scroll view
        self.textInputSV = ScrollView(size_hint=(None, None),
                                      size=(W,
                                            self.consoleInput.minimum_height))
        self.textInputSV.scroll_y = 0
        self.textInputSV.add_widget(self.consoleInput)

        # add input widget
        self.screen.add_widget(self.textInputSV)

        # run button
        self.btn_run = Button(text="Run", size_hint=(None,None), size =(W-self.consoleInput.size[0], self.consoleInput.size[1]),\
          background_color=(1.3,1.3,2,2))
        self.btn_run.bind(on_release=lambda inst: self.onConsoleInput(
            self.consoleInput, True))
        self.btn_run.pos = (W - self.btn_run.size[0], 0)
        self.screen.add_widget(self.btn_run)

        # output
        self.outputSV = ScrollView(size_hint=(None, None))
        self.screen.add_widget(self.outputSV)

        self.outputLayout = BoxLayout(orientation="vertical",
                                      size_hint=(None, None))
        self.outputSV.add_widget(self.outputLayout)

        def func_prev(inst):
            if len(self.history) > 0:
                self.historyIndex -= 1
                if self.historyIndex < 0:
                    self.historyIndex = len(self.history) - 1
                text = self.history[self.historyIndex]
                if text.find("\n") > -1:
                    self.bIndentMode = True
                self.setInputText(text)

        btn_prev.bind(on_release=func_prev)

        def func_next(inst):
            if len(self.history) > 0:
                self.historyIndex += 1
                if self.historyIndex >= len(self.history):
                    self.historyIndex = 0
                text = self.history[self.historyIndex]
                if text.find("\n") > -1:
                    self.bIndentMode = True
                self.setInputText(text)

        btn_next.bind(on_release=func_next)

        # show output layout
        self.displayText("Python " + sys.version.strip(), 0)
        self.isInit = True

    def setMode(self, mode):
        if mode == self.currentMode:
            return

        self.prevMode = self.currentMode
        self.currentMode = mode

        # restore..
        if self.prevMode == szConsole:
            self.reFocusInputText = False
            self.inputBoxForceFocus(False)

        # set mode layout
        if mode == szConsole:
            gMyRoot.current_screen(self.screen)
            self.refreshLayout()
        elif mode == szEditor:
            gMyRoot.current_screen(self.editorLayout.screen)
        elif mode == szTutorial:
            gMyRoot.current_screen(self.tutorialLayout.screen)
        elif mode == szFileBrowserOpen:
            self.fileBrowser.showOpenLayout()
        elif mode == szFileBrowserSaveAs:
            self.fileBrowser.showSaveAsLayout()

    def setExitOnTouchPrev(self, bValue):
        self.bExitOnTouchPrev = bValue

    def start(self):
        self.show()

    def update(self, dt):
        pass

    def clearOutput(self):
        self.outputLayout.clear_widgets()
        self.outputLayout.size = (W, 0)

    def outputLayout_add_widget(self, widget):
        self.outputLayout.add_widget(widget)
        self.outputLayout.height += widget.height + widget.padding[
            1] + widget.padding[3]

    def displayText(self, text, scroll_y, background_color=(1, 1, 1, 0)):
        if type(text) != str:
            text = str(text)

        output = TextInput(markup=True,
                           text="",
                           halign='left',
                           valign='top',
                           readonly=True,
                           font_size="12dp",
                           font_name=defaultFont,
                           multiline=True,
                           background_color=background_color,
                           foreground_color=(1, 1, 1, 1),
                           size_hint=(None, None),
                           size=(self.outputWidth, 0))
        output.text = text
        output.size = (self.outputWidth, output.minimum_height)

        self.outputLayout.add_widget(output)
        self.outputLayout.size = (self.outputWidth,
                                  self.outputLayout.size[1] + output.size[1])
        self.outputSV.scroll_x = 0
        self.outputSV.scroll_y = scroll_y

    def onConsoleInput(self, inst, bForceRun=False):
        self.reFocusInputText = True
        if inst.text.strip():
            bRunCode = len(inst.text) == self.consoleInput.cursor_index()
            lastLine_nonStrip = inst.text.split("\n")[-1]
            lastLine = lastLine_nonStrip.strip()
            # indent mode - continue input but not run
            if not bForceRun and lastLine and (lastLine[-1] in ("\\", ":")
                                               or self.bIndentMode
                                               or not bRunCode):
                self.bIndentMode = True
                # get indent space
                self.lastIndentSpace = ""
                if self.bIndentMode:
                    for i in lastLine_nonStrip:
                        if i in [" ", "\t"]:
                            self.lastIndentSpace += i
                        else:
                            break
                inst.insert_text("\n" + self.lastIndentSpace)
                self.consoleInput.size = (W, self.consoleInput.minimum_height)
                return
            # check indent mode - run code
            self.bIndentMode = False
            # pop input text from history
            if len(self.history) > 0 and self.historyIndex > -1 \
              and self.historyIndex < len(self.history) and self.history[self.historyIndex] == inst.text:
                self.history.pop(self.historyIndex)
            # append item to history
            if self.currentMode == szConsole:
                self.history.append(inst.text.strip())
            # check history count
            if len(self.history) > self.historyCount:
                self.history = self.history[:self.historyCount]
            self.historyIndex = len(self.history)
            # display input text to output widget
            if self.currentMode == szConsole:
                lines = inst.text.split("\n")
                result = []
                for i, line in enumerate(lines):
                    line = (">>> " if i == 0 else "... ") + line
                    result.append(line)
                result = "\n".join(result)
                self.displayText(result, 0)
            elif self.currentMode == szEditor:
                currentDocument = ">>> Run Untitled.py"
                self.displayText(
                    "\n".join([
                        "-" * len(currentDocument),
                        currentDocument + " - " + time.ctime()
                    ]), 0)
            # run code
            self.repl.onConsoleInput(inst.text)
            # end message
            if self.currentMode == szEditor:
                self.displayText("Done.", 0)

            # clear text input
            if self.currentMode == szConsole:
                self.setInputText("")

    def refreshLayout(self):
        if self.currentMode == szConsole:
            keyboardHeight = gMyRoot.getKeyboardHeight(
            ) if self.consoleInput.focus else 0
            limitHeight = (H - topMargin - keyboardHeight) * 0.5
            if self.consoleInput.minimum_height > limitHeight:
                height = limitHeight
            else:
                height = self.consoleInput.minimum_height
            self.screenMenuLayout.pos = (0, keyboardHeight)
            self.textInputSV.pos = (0, self.screenMenuLayout.top)
            self.textInputSV.size = (self.textInputWidth, height)
            self.consoleInput.size = (self.textInputWidth,
                                      self.consoleInput.minimum_height)
            self.btn_run.pos = (self.textInputSV.size[0],
                                self.textInputSV.pos[1])
            self.btn_run.size = (W - self.textInputSV.size[0],
                                 self.textInputSV.size[1])
            self.consoleMenuLayout.pos = (0, self.textInputSV.top)
            self.outputSV.pos = (0, self.consoleMenuLayout.top)
            self.outputSV.size = (W, H - self.outputSV.pos[1] - topMargin)

    def setInputText(self, text):
        self.consoleInput.text = text
        if self.consoleInput.size[1] != self.consoleInput.minimum_height:
            self.refreshLayout()

    def insertInputText(self, text):
        self.consoleInput.insert_text(text)
        if self.consoleInput.size[1] != self.consoleInput.minimum_height:
            self.refreshLayout()

    def inputBoxForceFocus(self, bFocus):
        if bFocus != self.consoleInput.focus:
            self.consoleInput.focus = bFocus

    def inputBoxFocus(self, inst, bFocus):
        bAlwaysPreserveFocus = True
        if not bFocus:
            if self.reFocusInputText:
                self.reFocusInputText = bAlwaysPreserveFocus
                inst.focus = True
        self.reFocusInputText = bAlwaysPreserveFocus
        self.refreshLayout()

    def update(self, dt):
        pass

    def touchPrev(self):
        if self.currentMode == szEditor:
            self.editorLayout.touchPrev()
        elif self.currentMode in (szFileBrowserOpen, szFileBrowserSaveAs):
            self.fileBrowser.touchPrev()
        elif self.currentMode == szTutorial:
            self.tutorialLayout.touchPrev()
        elif self.consoleInput.focus:
            self.reFocusInputText = False
            self.inputBoxForceFocus(False)
        else:
            self.exit()

    def toggle(self):
        if not self.isInit:
            self.init()

        if self.screen.name == gMyRoot.get_current_screen():
            self.close()
        else:
            self.show()

    def show(self):
        if not self.isInit:
            self.init()

        gMyRoot.add_screen(self.screen)
        gMyRoot.add_screen(self.editorLayout.screen)
        gMyRoot.add_screen(self.tutorialLayout.screen)
        gMyRoot.current_screen(self.screen)
        self.oldTouchPrev = gMyRoot.getTouchPrev()
        gMyRoot.setTouchPrev(self.touchPrev)
        self.setMode(szConsole)

    def close(self):
        gMyRoot.setTouchPrev(self.oldTouchPrev)
        gMyRoot.remove(self)
        gMyRoot.remove_screen(self.screen)
        gMyRoot.remove_screen(self.editorLayout.screen)
        gMyRoot.remove_screen(self.tutorialLayout.screen)
        if self.bExitOnTouchPrev:
            self.editorLayout.exit()
            gMyRoot.exit()

    def exit(self, *args):
        self.reFocusInputText = False
        self.inputBoxForceFocus(False)
        gMyRoot.popup("Exit Python?", "", self.close, None)
コード例 #10
0
class BaseTestCase(unittest.TestCase):
    '''
    Following env variable should be set:
    BROWSER_MODE: '--foreground' or '--headless'
    BROWSER_TYPE: 'chrome' or 'firefox'
    BROWSER_DRIVER: full path to your browser driver (chromedriver or geckodriver)
    If running with firefox on Linux, should also set:
       BROWSER_BINARY: full path to your firefox binary
    '''
    _delay = 0.1
    _wait_timeout = 10

    def setUp(self):
        self._download_dir = tempfile.mkdtemp()
        browser = os.getenv("BROWSER_TYPE", 'chrome')
        mode = os.getenv("BROWSER_MODE", '--headless')
        print("...browser: {b}".format(b=browser))
        print("...mode: {m}".format(m=mode))

        if mode == "--headless" and os.getenv("CIRCLECI"):
            print("...starting display since we are running in headless mode")
            display = Display(visible=0, size=(800, 600))
            display.start()

        if browser == 'chrome':
            self.setup_for_chrome(mode)
        elif browser == 'firefox':
            self.setup_for_firefox(mode)

        self.driver.implicitly_wait(self._wait_timeout)
        time.sleep(self._delay)

        utils = JupyterUtils()
        self.server = utils.get_server()
        self.main_page = MainPage(self.driver, self.server)
        self.left_side_bar = VcdatLeftSideBar(self.driver, None)
        self.file_browser = FileBrowser(self.driver, None)
        self.click_on_file_browser_home()

        self._test_notebook_file = "{t}.ipynb".format(t=self._testMethodName)
        self.notebook_page = NoteBookPage(self.driver, None)
        self.notebook_page.rename_notebook(self._test_notebook_file)

    def tearDown(self):
        print("...BaseTestCase.tearDown()...")
        self.main_page.shutdown_kernel()
        self.notebook_page.save_current_notebook()
        self.notebook_page.close_current_notebook()
        self.driver.quit()
        os.remove(self._test_notebook_file)

    def setup_for_chrome(self, mode):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument(mode)
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("window-size=1200x600")
        self.driver = webdriver.Chrome(
            executable_path=os.getenv("BROWSER_BINARY",
                                      "/usr/local/bin/chromedriver"),
            chrome_options=chrome_options,
            service_args=['--verbose', '--log-path=/tmp/chromedriver.log'])

    def setup_for_firefox(self, mode):
        firefox_profile = FirefoxProfile()
        firefox_profile.set_preference('dom.disable_open_during_load', False)
        firefox_capabilities = DesiredCapabilities().FIREFOX
        firefox_capabilities['marionette'] = True
        firefox_capabilities['moz:firefoxOptions'] = {'args': ['--headless']}

        firefox_binary = FirefoxBinary(
            os.getenv("BROWSER_BINARY", "/usr/bin/firefox"))
        geckodriver_loc = os.getenv("BROWSER_DRIVER",
                                    "/usr/local/bin/geckodriver")
        self.driver = webdriver.Firefox(firefox_profile=firefox_profile,
                                        firefox_binary=firefox_binary,
                                        executable_path=geckodriver_loc,
                                        capabilities=firefox_capabilities)

    #
    # notebook utils
    #

    def close_notebook_if_any(self):
        try:
            note_book = NoteBookPage(self.driver)
            note_book.close()
            time.sleep(self._delay)
        except NoSuchElementException:
            print("No notebook opened")
            pass

    def close_current_notebook(self):
        self.main_page.close_current_notebook()

    #
    # Load a data file
    #

    def load_data_file(self, filename):
        # left_side_bar = VcdatLeftSideBar(self.driver, None)
        self.left_side_bar.click_on_jp_vcdat_icon()
        time.sleep(self._delay)
        self.left_side_bar.click_on_load_variables_by_file()

        # file_browser = FileBrowser(self.driver, None)
        self.file_browser.double_click_on_a_file(filename)
        time.sleep(self._delay)

    def load_sample_data(self, filename):
        # left_side_bar = VcdatLeftSideBar(self.driver, None)
        self.left_side_bar.click_on_jp_vcdat_icon()
        time.sleep(self._delay)
        self.left_side_bar.click_on_load_variables_by_file()

        # file_browser = FileBrowser(self.driver, None)
        self.click_on_file_browser_home()
        print("DEBUG DEBUG...returned from click_on_file_browser_home...")
        time.sleep(5)
        if "/" in filename:
            paths = filename.split('/')
            for f in paths[:-1]:
                print("xxx double clicking on {f}".format(f=f))
                self.file_browser.double_click_on_a_file(f, False)
                time.sleep(self._delay)
            self.file_browser.double_click_on_a_file(paths[-1])
        time.sleep(self._delay)

    #
    #
    #
    def click_on_plot(self):
        self.left_side_bar.click_on_plot()

    def click_on_clear(self):
        self.left_side_bar.click_on_clear()

    def select_plot_type(self, plot_type):
        self.left_side_bar.select_plot_type(plot_type)

    #
    # kernel utils
    #
    def select_kernel(self):
        self.main_page.select_kernel()

    def click_on_file_browser_home(self):
        self.left_side_bar.click_on_file_folder()
        self.file_browser.click_on_home()

    #
    # download_sample_data
    #
    def download_sample_data(self):
        vp = "vcs_egg_path = pkg_resources.resource_filename(pkg_resources.Requirement.parse('vcs'), 'share/vcs')"
        download_code = [
            "import vcs", "import cdms2", "import cdat_info",
            "import pkg_resources", vp,
            "path = vcs_egg_path+'/sample_files.txt'",
            "cdat_info.download_sample_data_files(path,'sample_data')"
        ]
        self.notebook_page.enter_code_list(download_code)
コード例 #11
0
 def __init__(self, nodes, connections):
     self.jsonElements = JSONTools().get(nodes, connections)
     self.browser = FileBrowser(self.save,
                                True,
                                defaultFilename="project.json")
コード例 #12
0
 def __init__(self, nodeMgr):
     self.nodeMgr = nodeMgr
     self.browser = FileBrowser(self.load,
                                True,
                                defaultFilename="project.json")
コード例 #13
0
class Load:
    def __init__(self, nodeMgr):
        self.nodeMgr = nodeMgr
        self.browser = FileBrowser(self.load,
                                   True,
                                   defaultFilename="project.json")

    def load(self, doLoad):
        if doLoad:
            path = self.browser.get()
            path = os.path.expanduser(path)
            path = os.path.expandvars(path)

            self.__executeLoad(path)

        self.browser.destroy()
        del self.browser

    def __executeLoad(self, path):
        fileContent = None
        try:
            with open(path, 'r') as infile:
                fileContent = json.load(infile)
        except Exception as e:
            print("Couldn't load project file {}".format(path))
            print(e)
            return

        if fileContent is None:
            print("Problems reading file: {}".format(infile))
            return

        # 1. Create all nodes
        jsonNodes = fileContent["Nodes"]
        newNodes = []
        for jsonNode in jsonNodes:
            node = self.nodeMgr.createNode(jsonNode["type"])
            node.nodeID = UUID(jsonNode["id"])
            node.setPos(eval(jsonNode["pos"]))
            for i in range(len(jsonNode["inSockets"])):
                inSocket = jsonNode["inSockets"][i]
                node.inputList[i].socketID = UUID(inSocket["id"])
                if "value" in inSocket:
                    node.inputList[i].setValue(inSocket["value"])
            for i in range(len(jsonNode["outSockets"])):
                outSocket = jsonNode["outSockets"][i]
                node.outputList[i].socketID = UUID(outSocket["id"])
            node.show()
            newNodes.append(node)

        # 2. Connect all nodes
        jsonConnections = fileContent["Connections"]
        for jsonConnection in jsonConnections:
            # we have a connection of one of the to be copied nodes
            nodeA = None
            nodeB = None

            for node in newNodes:
                if node.nodeID == UUID(jsonConnection["nodeA_ID"]):
                    nodeA = node
                elif node.nodeID == UUID(jsonConnection["nodeB_ID"]):
                    nodeB = node

            socketA = None
            socketB = None
            for socket in nodeA.inputList + nodeA.outputList + nodeB.inputList + nodeB.outputList:
                if socket.socketID == UUID(jsonConnection["socketA_ID"]):
                    socketA = socket
                elif socket.socketID == UUID(jsonConnection["socketB_ID"]):
                    socketB = socket

            self.nodeMgr.connectPlugs(socketA, socketB)

        # 3. Run logic from all leave nodes down to the end
        self.nodeMgr.updateAllLeaveNodes()
コード例 #14
0
# Local for testing
#root.globalConfig['jobDir'] = os.environ.get('JOBDIR', '/data/atlas/jobs/atlidbs')
#root.globalConfig['taskDb'] = os.environ.get('TASKDB', 'sqlite_file:'+root.globalConfig['jobDir']+'/taskdata.db')
#root.globalConfig['wwwDir'] = os.environ.get('WWWDIR', '/home/jb/ATLAS/BeamSpot/InDetBeamSpotExample/www')
#root.globalConfig['ntDir']  = os.environ.get('NTDIR', '/data/atlas/analysis/BeamSpot/nt')
#root.globalConfig['periodDir'] = os.environ.get('PERIODDIR','/home/jb/analysis/BeamSpot/nt/DataPeriods')
#root.globalConfig['webPlotDir']  = os.environ.get('WEBPLOTDIR', '/data/atlas/analysis/BeamSpot/nt/webplots')

# Page tree
root.addPage('summary', BeamSpotSummary())
root.addPage('t0Summary', BeamSpotSummary(), query='?type=DB_BEAMSPOT')
root.addPage('bcidSummary', BeamSpotSummary(), query='?type=BCID&limit=0')
root.addPage('reprocSummary', BeamSpotSummary(), query='?type=REPR&limit=0')
root.addPage('jobs', JobBrowser())
root.addPage('details', JobDetails())
root.addPage('files', FileBrowser('/jobfiles'))
root.addPage('myplots', MyPlots())
root.addPage('plots', PlotServer())
root.addPage('webplots', WebPlots())
root.addPage('debug', DebugPage())


# Setup for mod_python
def setup_server():
    cherrypy.config.update({
        'environment': 'production',
        'log.screen': False,
        'server.socket_host': '127.0.0.1',
        'log.error_file': '/tmp/site.log',
        'show_tracebacks': False
    })