Esempio n. 1
0
    def __init__(self, language, user):
        super().__init__(language)
        self.user = user
        self.accountsRowsWidgets = []
        self.showButtons = []
        self.editButtons = []
        self.toDisable = []

        self.titleWidth = 0
        self.loginWidth = 0.2
        self.associatedEmailWidth = 0.37
        self.passwordWidth = 0.6
        self.editWidth = 0.85
        self.deleteWidth = 0.9

        self.scrollframe = ScrollFrame(self.root)
        self.userInfoLabel = tk.Label(
            self.root,
            text=lp[self.language]['logged_as'].format(
                login=self.user['login']),
            bg=self.bg_color)
        self.titleLabel = tk.Label(self.scrollframe.viewPort,
                                   text=lp[self.language]['acc_title'],
                                   bg=self.bg_color)
        self.loginLabel = tk.Label(self.scrollframe.viewPort,
                                   text=lp[self.language]['acc_login'],
                                   bg=self.bg_color)
        self.associatedEmailLabel = tk.Label(
            self.scrollframe.viewPort,
            text=lp[self.language]['acc_associated_email'],
            bg=self.bg_color)
        self.passwordLabel = tk.Label(self.scrollframe.viewPort,
                                      text=lp[self.language]['acc_password'],
                                      bg=self.bg_color)
        self.separationLabel = tk.Label(self.scrollframe.viewPort,
                                        text=' ' * 40,
                                        bg=self.bg_color)
        self.addAccountBtn = tk.Button(self.root,
                                       text=lp[self.language]['add_acc_btn'],
                                       bg='#6bfc03',
                                       command=self.open_add_acc_form)
        self.settingBtn = tk.Button(self.root,
                                    text=lp[self.language]['settings_btn'],
                                    bg='#dedcd1',
                                    command=self.open_settings)
        self.exportBtn = tk.Button(self.root,
                                   text=lp[self.language]['export_btn'],
                                   bg='#dedcd1',
                                   command=self.open_window_to_export)

        self.place_widgets()
        self.display_accounts()
        self.root.mainloop()
Esempio n. 2
0
  def __init__(self,name,tab,root,command, fixedOptions, defaultFileFilter,optionWindow,extraAddButton, tabControl, createGUI=True, copyFrom=None):
    self.lines=[]
    if not createGUI and copyFrom!=None:
      self.name=copyFrom.name
      self.optionWindow=OptionWindow(None,None, None,None, False, copyFrom.optionWindow)
      self.lastPath=copyFrom.lastPath
      for line in copyFrom.lines:
        self.lines.append(Line(None, False,line))
    if createGUI:
      self.name=name
      self.tabControl=tabControl
      self.root=root
      self.tab=tab
      self.lineFrame = tk.Frame(tab)
      self.lineFrame.pack()
      self.scrollFrame=ScrollFrame(self.lineFrame)
      self.scrollFrame.pack(side="top", fill="both", expand=True)
      self.mainFrame=self.scrollFrame.frame
      self.optionWindow=optionWindow
      self.lastPath="."
      self.separateStart=True
      self.subfolder=False
      self.singleEntryCheck=""
      self.extraAddButton=extraAddButton
      # if name == "createUpgradedBuildings":
      #   self.helperFileCheck=True
      # else:
      #   self.helperFileCheck=False
      self.updatePath()
          # print(self.lastPath)
      self.options=[]#options
      self.command=command
      if platform.system()=="Linux":
        if ";" in defaultFileFilter[1]:
          splitList=defaultFileFilter[1].split(";")
          outString=""
          for entry in zip(*splitList):
            equal=1
            for e in entry:
              if e!=entry[0]:
                equal=0
            if equal:
              outString+=entry[0]
            else:
              outString+="["
              for e in entry:
                outString+=e
              outString+="]"
          defaultFileFilter=(defaultFileFilter[0],outString)
            # print(b)
            # if splitList[0][i]=="*" or splitList[0][i]==".":
              # outString+=spltL
      self.defaultFileFilter=defaultFileFilter
      # self.checkVars=[]
      self.fixedOptions=fixedOptions
      
      
      #self.mainFrame=tk.Frame(self.lineFrame)
      #self.mainFrame.pack(side="top", fill="both", expand=True)
      #self.mainFrame.bind( '<Configure>', maxsize )
      self.extraLineMain=tk.Frame(self.mainFrame, height=24)
      self.extraLineMain.pack(side=tk.TOP)
      # for option in options:
      #   self.checkVars.append(IntVar())
      #   check=Checkbutton(self.extraLineMain, text=option[0], variable=self.checkVars[-1])
      #   check.pack(side=tk.RIGHT)
      #   CreateToolTip(check, option[2])
      #b = tk.Button(self.extraLineMain, text="(Un-)check all", command=self.checkAll)
      #b.pack(side=tk.RIGHT)
      #b = tk.Button(self.extraLineMain, text="Add line", command=self.addLine)
      #b.pack(side=tk.RIGHT)

      self.saveImg = ImageTk.PhotoImage(Image.open(resource_path("Save-icon.png")))
      # self.saveImg = PhotoImage(file="Save-icon.gif")
      b = tk.Button(self.extraLineMain,text="",image=self.saveImg, command=self.save)
      b.pack(side=tk.RIGHT,expand=YES, fill="y")
      CreateToolTip(b, "Save Current Tab")

      self.loadImg = ImageTk.PhotoImage(Image.open(resource_path("Load-icon.png")))
      # self.loadImg = PhotoImage(file="Load-icon.gif")
      b = tk.Button(self.extraLineMain,text="",image=self.loadImg, command=lambda : self.load(False,True))
      b.pack(side=tk.RIGHT,expand=YES, fill="y")
      CreateToolTip(b, "Load Tab(s)")

      pathWindow=self.tabControl.pathWindow

      # for img, ( pathName,txt), desc , in zip(pathWindow.imgs.values(), path.items()
      for pathName in pathWindow.txts.keys():
        b = tk.Button(self.extraLineMain,text="",image=pathWindow.imgs[pathName], command=lambda pathName=pathName: self.setPath(pathName))
        b.pack(side=tk.RIGHT,expand=YES, fill="y")
        CreateToolTip(b, pathWindow.descs[pathName])

      # self.DocImg = ImageTk.PhotoImage(Image.open("StellarisDocumentIcon.png"))
      # b = tk.Button(self.extraLineMain,text="",image=self.DocImg, command=lambda : self.setPath("StellarisDocPath"))
      # b.pack(side=tk.RIGHT,expand=YES, fill="y")
      # CreateToolTip(b, "Stellaris Documents Path")

      # self.StellImg = ImageTk.PhotoImage(Image.open("StellarisIcon.png"))
      # b = tk.Button(self.extraLineMain,text="",image=self.StellImg, command=lambda : self.setPath("StellarisPath"))
      # b.pack(side=tk.RIGHT,expand=YES, fill="y")
      # CreateToolTip(b, "Stellaris Main Game Path")

      b = tk.Button(self.extraLineMain,text="Update Path", command=self.updatePath)
      b.pack(side=tk.RIGHT,expand=YES, fill="y")
      if optionWindow:
        b= tk.Button(self.extraLineMain,text="Options", command=self.optionWindow.window.deiconify)
        b.pack(side=tk.RIGHT,expand=YES, fill="y")
      CreateToolTip(b, "Update the Path that is open when adding files to the last used one of any Tab in the GUI. Useful when doing stuff that requires two tabs, like Txt To Ods and Ods To Txt")
      b = tk.Button(self.extraLineMain,text="Add file(s)", command=self.addFiles)
      b.pack(side=tk.RIGHT,expand=YES, fill="y")
      if self.extraAddButton!="":
        b = tk.Button(self.extraLineMain, text=self.extraAddButton, command=self.addMarkedFiles)
        b.pack(side=tk.RIGHT,expand=YES, fill="y")
      b = tk.Button(self.extraLineMain,text="Convert All", command=self.invokeAll)
      b.pack(side=tk.LEFT,expand=YES, fill="y")

      txt_frm = tk.Frame(tab, width=600, height=600)
      txt_frm.pack(fill="both", expand=True)
      # ensure a consistent GUI size
      txt_frm.grid_propagate(False)
      # implement stretchability
      txt_frm.grid_rowconfigure(0, weight=1)
      txt_frm.grid_columnconfigure(0, weight=1)
      
      # create a Text widget
      self.txt = tk.Text(txt_frm, borderwidth=3,bg="light grey", relief="sunken")
      self.txt.config(state=DISABLED)
      #self.txt.config(font=("consolas", 12), undo=True, wrap='word')
      self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)

      # create a Scrollbar and associate it with txt
      scrollb = tk.Scrollbar(txt_frm, command=self.txt.yview)
      scrollb.grid(row=0, column=1, sticky='nsew')
      self.txt['yscrollcommand'] = scrollb.set
Esempio n. 3
0
class TabClass:
  def __init__(self,name,tab,root,command, fixedOptions, defaultFileFilter,optionWindow,extraAddButton, tabControl, createGUI=True, copyFrom=None):
    self.lines=[]
    if not createGUI and copyFrom!=None:
      self.name=copyFrom.name
      self.optionWindow=OptionWindow(None,None, None,None, False, copyFrom.optionWindow)
      self.lastPath=copyFrom.lastPath
      for line in copyFrom.lines:
        self.lines.append(Line(None, False,line))
    if createGUI:
      self.name=name
      self.tabControl=tabControl
      self.root=root
      self.tab=tab
      self.lineFrame = tk.Frame(tab)
      self.lineFrame.pack()
      self.scrollFrame=ScrollFrame(self.lineFrame)
      self.scrollFrame.pack(side="top", fill="both", expand=True)
      self.mainFrame=self.scrollFrame.frame
      self.optionWindow=optionWindow
      self.lastPath="."
      self.separateStart=True
      self.subfolder=False
      self.singleEntryCheck=""
      self.extraAddButton=extraAddButton
      # if name == "createUpgradedBuildings":
      #   self.helperFileCheck=True
      # else:
      #   self.helperFileCheck=False
      self.updatePath()
          # print(self.lastPath)
      self.options=[]#options
      self.command=command
      if platform.system()=="Linux":
        if ";" in defaultFileFilter[1]:
          splitList=defaultFileFilter[1].split(";")
          outString=""
          for entry in zip(*splitList):
            equal=1
            for e in entry:
              if e!=entry[0]:
                equal=0
            if equal:
              outString+=entry[0]
            else:
              outString+="["
              for e in entry:
                outString+=e
              outString+="]"
          defaultFileFilter=(defaultFileFilter[0],outString)
            # print(b)
            # if splitList[0][i]=="*" or splitList[0][i]==".":
              # outString+=spltL
      self.defaultFileFilter=defaultFileFilter
      # self.checkVars=[]
      self.fixedOptions=fixedOptions
      
      
      #self.mainFrame=tk.Frame(self.lineFrame)
      #self.mainFrame.pack(side="top", fill="both", expand=True)
      #self.mainFrame.bind( '<Configure>', maxsize )
      self.extraLineMain=tk.Frame(self.mainFrame, height=24)
      self.extraLineMain.pack(side=tk.TOP)
      # for option in options:
      #   self.checkVars.append(IntVar())
      #   check=Checkbutton(self.extraLineMain, text=option[0], variable=self.checkVars[-1])
      #   check.pack(side=tk.RIGHT)
      #   CreateToolTip(check, option[2])
      #b = tk.Button(self.extraLineMain, text="(Un-)check all", command=self.checkAll)
      #b.pack(side=tk.RIGHT)
      #b = tk.Button(self.extraLineMain, text="Add line", command=self.addLine)
      #b.pack(side=tk.RIGHT)

      self.saveImg = ImageTk.PhotoImage(Image.open(resource_path("Save-icon.png")))
      # self.saveImg = PhotoImage(file="Save-icon.gif")
      b = tk.Button(self.extraLineMain,text="",image=self.saveImg, command=self.save)
      b.pack(side=tk.RIGHT,expand=YES, fill="y")
      CreateToolTip(b, "Save Current Tab")

      self.loadImg = ImageTk.PhotoImage(Image.open(resource_path("Load-icon.png")))
      # self.loadImg = PhotoImage(file="Load-icon.gif")
      b = tk.Button(self.extraLineMain,text="",image=self.loadImg, command=lambda : self.load(False,True))
      b.pack(side=tk.RIGHT,expand=YES, fill="y")
      CreateToolTip(b, "Load Tab(s)")

      pathWindow=self.tabControl.pathWindow

      # for img, ( pathName,txt), desc , in zip(pathWindow.imgs.values(), path.items()
      for pathName in pathWindow.txts.keys():
        b = tk.Button(self.extraLineMain,text="",image=pathWindow.imgs[pathName], command=lambda pathName=pathName: self.setPath(pathName))
        b.pack(side=tk.RIGHT,expand=YES, fill="y")
        CreateToolTip(b, pathWindow.descs[pathName])

      # self.DocImg = ImageTk.PhotoImage(Image.open("StellarisDocumentIcon.png"))
      # b = tk.Button(self.extraLineMain,text="",image=self.DocImg, command=lambda : self.setPath("StellarisDocPath"))
      # b.pack(side=tk.RIGHT,expand=YES, fill="y")
      # CreateToolTip(b, "Stellaris Documents Path")

      # self.StellImg = ImageTk.PhotoImage(Image.open("StellarisIcon.png"))
      # b = tk.Button(self.extraLineMain,text="",image=self.StellImg, command=lambda : self.setPath("StellarisPath"))
      # b.pack(side=tk.RIGHT,expand=YES, fill="y")
      # CreateToolTip(b, "Stellaris Main Game Path")

      b = tk.Button(self.extraLineMain,text="Update Path", command=self.updatePath)
      b.pack(side=tk.RIGHT,expand=YES, fill="y")
      if optionWindow:
        b= tk.Button(self.extraLineMain,text="Options", command=self.optionWindow.window.deiconify)
        b.pack(side=tk.RIGHT,expand=YES, fill="y")
      CreateToolTip(b, "Update the Path that is open when adding files to the last used one of any Tab in the GUI. Useful when doing stuff that requires two tabs, like Txt To Ods and Ods To Txt")
      b = tk.Button(self.extraLineMain,text="Add file(s)", command=self.addFiles)
      b.pack(side=tk.RIGHT,expand=YES, fill="y")
      if self.extraAddButton!="":
        b = tk.Button(self.extraLineMain, text=self.extraAddButton, command=self.addMarkedFiles)
        b.pack(side=tk.RIGHT,expand=YES, fill="y")
      b = tk.Button(self.extraLineMain,text="Convert All", command=self.invokeAll)
      b.pack(side=tk.LEFT,expand=YES, fill="y")

      txt_frm = tk.Frame(tab, width=600, height=600)
      txt_frm.pack(fill="both", expand=True)
      # ensure a consistent GUI size
      txt_frm.grid_propagate(False)
      # implement stretchability
      txt_frm.grid_rowconfigure(0, weight=1)
      txt_frm.grid_columnconfigure(0, weight=1)
      
      # create a Text widget
      self.txt = tk.Text(txt_frm, borderwidth=3,bg="light grey", relief="sunken")
      self.txt.config(state=DISABLED)
      #self.txt.config(font=("consolas", 12), undo=True, wrap='word')
      self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)

      # create a Scrollbar and associate it with txt
      scrollb = tk.Scrollbar(txt_frm, command=self.txt.yview)
      scrollb.grid(row=0, column=1, sticky='nsew')
      self.txt['yscrollcommand'] = scrollb.set
#def maxsize( event=None ):
    #if(event.height>200):
      #print(event.height)
      #event.widget.grid_propagate(False)
      #event.widget.grid_rowconfigure(0, weight=1)
      #event.widget.grid_columnconfigure(0, weight=1)
    #scrollbar.ScrolledWindow(self.mainFrame)
  @classmethod
  def copyNonGUI(cls, copyFrom):
    return cls(copyFrom.name,copyFrom.tab,copyFrom.root,copyFrom.command, copyFrom.fixedOptions, copyFrom.defaultFileFilter,copyFrom.optionWindow,copyFrom.extraAddButton, copyFrom.tabControl,False, copyFrom)
      # return cls(randint(0, 100))
  def addLine(self):
    self.lines.append(Line(self))
  def addFile(self):
    self.lines.append(Line(self))
    self.lines[-1].bFile.invoke()
  def addFiles(self):
    files=filedialog.askopenfilenames(initialdir = self.lastPath,title = "Select file(s)",filetypes = (self.defaultFileFilter, ("all files","*")))
    if files:
      self.lastPath=os.path.dirname(files[0].strip())
      outPreviousPath(self.lastPath)
      # with open(".GUI_last_path",'a+') as file:
      #   file.write("\n"+self.lastPath)
    for fileName in files:
      self.lines.append(Line(self))
      self.lines[-1].setNewFileAndDoTestRun(fileName)
    #print (root.filename)
  # def redoTabOrder(self):
    # for line in self.lines:
      # print(line.txt.get())
      # line.txt.lower()  
    # if self.subfolder:
      # for line in self.lines:
        # print(line.subfolderTxt.get())
        # line.subfolderTxt.lower()
  def updatePath(self):
    if os.path.exists(".GUI_last_path"):
      with open(".GUI_last_path") as file:
        self.lastPath=file.readlines()[-1].strip()
  def setPath(self, key):
    self.lastPath=self.tabControl.pathWindow.txts[key].get().strip()
  def addMarkedFiles(self):
    curLine=len(self.lines)
    self.addFiles()
    for line in self.lines[curLine:]:
      line.lineCheckVar.set(1)
  def removeLineByIndex(self, index):
    self.lines[index].lineFrame.pack_forget()
    del self.lines[index]
    #del self.buttons[index]
  def removeLineByReference(self, line):
    lineFrames=[a.lineFrame for a in self.lines]
    index=lineFrames.index(line)
    self.removeLineByIndex(index)
  def setSize(self):
    if len(self.lines)>0:
      lineWidth=self.lines[-1].lineFrame.winfo_height()
      # print(lineWidth)
      if lineWidth>1: #make sure we do not kill the init!
        self.scrollFrame.canvas.config(width=self.lines[-1].lineFrame.winfo_width())
      self.scrollFrame.canvas.config(height=min(-self.mainFrame.winfo_rooty()+self.lines[-1].lineFrame.winfo_rooty() + self.lines[-1].lineFrame.winfo_height(),self.tab.winfo_height()//3*2))
    else:
      elements=self.extraLineMain.winfo_children()
      lineWidth=0
      for element in elements:
        lineWidth=max(lineWidth,-self.mainFrame.winfo_rootx()+element.winfo_rootx() + element.winfo_width())
      # print(lineWidth)
      if lineWidth>10: #make sure we do not kill the init!
        self.scrollFrame.canvas.config(width=lineWidth)
  def checkAll(self):
    for line in self.lines:
      if line.checkvar.get()==0:
        for line in self. lines:
          line.checkvar.set(1)
        return 0
    for line in self. lines:
      line.checkvar.set(0)
  def invokeAll(self):
    if self.separateStart:
      for line in self.lines:
        line.bConv.invoke()
    elif self.singleEntryCheck=="Source File":
      argList=[]
      self.addArguments(argList)
      sourceFiles=[]
      for line in self.lines:
        if line.lineCheckVar.get():  #Source File check
          sourceFiles.append(line.getTxt())
      for line in self.lines:
        if not line.lineCheckVar.get():  #Source File check
          args=self.command.parse([line.getTxt()]+sourceFiles+argList)
          line.result=self.command.main(args,[line.getTxt()]+sourceFiles+argList)

    else:
      argList=[]
      for line in self.lines:
        argList.append(line.getTxt())
      self.addArguments(argList)
      args=self.command.parse(argList)
      self.command.main(args,argList)
  def addArguments(self, argList,line=0):
    argList+=self.fixedOptions   
    if self.optionWindow:
      argList+=self.optionWindow.getOptions(line)
    # for i in range(len(self.options)):
    #   if self.checkVars[i].get():
    #     argList+=self.options[i][1].split()
    if self.singleEntryCheck!="":
      if self.singleEntryCheck=="Helper File":
        argList.append("--helper_file_list")
        argList.append("")
        for line in self.lines:
          if line.lineCheckVar.get():
            argList[-1]+="1"
          else:
            argList[-1]+="0"
      elif self.singleEntryCheck!="Source File":
        if line.lineCheckVar.get():
          argList.append("--"+self.singleEntryCheck.replace(" ","_").lower())
  def checkValid(self):
    self.setSize()
    for line in self.lines:
      sourceR=1
      filterR=1
      resultR=1
      resultW=1
      if not os.access(line.getTxt(),os.R_OK):
        sourceR=0
      #if os.path.exists(line.result):
        #try:
          #open(line.result)
        #except IOError:
          #resultW=0
          
        ##and not os.access(line.result,os.W_OK):
        ##resultW=0
      if not os.access(line.result,os.W_OK):
        resultR=0
      #if not os.access(line.getTxt().replace(".txt","_filter.txt"),os.W_OK):
        #filterR=0
      if resultW and sourceR:
        line.bConv.config(state="normal")
        line.bConvTooltip.update("Start script")
      else:
        line.bConv.config(state="disabled")
        if not sourceR:
          line.bConvTooltip.update("Invalid source file")
        elif not resultW:
          line.bConvTooltip.update("Result file access problem. Might be locked by program that has it open")
      if sourceR:
        line.bEditS.config(state="normal")
        line.bEditSTooltip.update("Open source file in default editor")
      else:
        line.bEditS.config(state="disabled")
        line.bEditSTooltip.update("Invalid source file")
      if filterR:
        line.bEditF.config(state="normal")
        line.bEditFTooltip.update("Open or create and open filter file. Comma separated list of tags")
      else:
        line.bEditF.config(state="disabled")
        line.bEditFTooltip.update("Invalid")
      if resultR and resultW:
        line.bEditR.config(state="normal")
        line.bEditRTooltip.update("Open result file.")
      else:
        line.bEditR.config(state="disabled")
        line.bEditRTooltip.update("Missing result file. You probably need to create it first via 'Convert'")
        
    #os.F_OK − Value to pass as the mode parameter of access() to test the existence of path.
    #os.R_OK − Value to include in the mode parameter of access() to test the readability of path.
    #os.W_OK Value to include in the mode parameter of access() to test the writability of path.
    #os.X_OK Value to include in the mode parameter of access() to determine if path can be executed.
  def askForPkl(self, type="asksaveasfilename", titleInput="Select file to save to"):
    fileName=getattr(filedialog, type)(defaultextension=".pkl",initialdir = self.tabControl.menuBar.lastPklFolder,title = titleInput,filetypes = (("pickle files","*.pkl"), ("all files","*")))
    if fileName:
      self.tabControl.menuBar.lastPklFolder=os.path.dirname(fileName.strip())
      self.tabControl.menuBar.storeData()
    return fileName
  def save(self, appendToFile=False):
    fileKey="wb"
    if appendToFile:
      fileKey="a+b"
    fileName=self.askForPkl("asksaveasfilename","Select file to save to")
    if fileName:
      with open(fileName, fileKey) as f:
        pickle.dump(TabClass.copyNonGUI(self),f)


    # filedialog.asksaveasfilename(defaultextension=".pkl",initialdir = self.tabControl.menuBar.lastPklFolder,title = "Select file to save to",filetypes = (("pickle files","*.pkl"), ("all files","*")))
    # if fileName:
    #   self.tabControl.menuBar.lastPklFolder=os.path.dirname(fileName.strip())
    #   self.tabControl.menuBar.storeData()
    #   with open(fileName, 'wb') as f:
    #     pickle.dump([],f) #empty stop for old checkVars
    #     if self.optionWindow:
    #       pickle.dump([var.get() for var in self.optionWindow.vals],f)
    #     else:
    #       pickle.dump([],f)
    #     pickle.dump([line.txt.get() for line in self.lines], f)
    #     pickle.dump([line.subfolderTxt.get() for line in self.lines], f)
    #     pickle.dump([line.lineCheckVar.get() for line in self.lines], f)
        # pickle.dump(test(),f)
      # print("save")
  def newLoadingMethod(self, tabClassLoaded, onlyAddLines):
    if not onlyAddLines:
      self.optionWindow.setVals(tabClassLoaded.optionWindow.options, tabClassLoaded.optionWindow.vals)
    for line in tabClassLoaded.lines:
      self.lines.append(Line(self, True, line))
  def load(self, onlyAddLines=False, fittingTabs=False):
    fileName=self.askForPkl("askopenfilename","Select file to load from")
    if fileName:
      if not onlyAddLines:
        for i in range(len(self.lines)):
          self.removeLineByIndex(0)
      with open(fileName, 'rb') as f:
        tabClassLoaded=pickle.load(f)
        if isinstance(tabClassLoaded, TabClass):
          if fittingTabs:
            while 1:
              try:
                self.tabControl.getTabByName(tabClassLoaded.name).newLoadingMethod(tabClassLoaded, onlyAddLines)
              except:
                print("Skipping tab for load")
                pass
              try:
                tabClassLoaded=pickle.load(f)
              except EOFError:
                break
          else:
            if tabClassLoaded.name==self.name or messagebox.askquestion("Different Tab", "The data you are trying to load is created form a different Tab. Only identical options will be loaded and lines may be incomplete. It should work though. Continue?", icon='warning') == 'yes':
              # print("Warning:")
              self.newLoadingMethod(tabClassLoaded, onlyAddLines)
        else: #old format. the first entry is useless anyway since it was even there not used anymore
          if fittingTabs:
            print("Error: This only works with the new save format! Doing normal load instead!")
          if self.optionWindow:
            for i,val in enumerate(pickle.load(f)):
              if not onlyAddLines:
                self.optionWindow.vals[i].set(val)
          else:
            pickle.load(f)
          self.loadLines(f)
  def loadLines(self,f): #old format only!
    try:
      i=len(self.lines)
      for entry in pickle.load(f):
        self.addLine()
        self.lines[-1].setNewFileAndDoTestRun(entry)
      iLoc=i
      for entry in pickle.load(f):
        if self.subfolder:
          self.lines[iLoc].subfolderTxt.insert(0,entry)
          iLoc+=1
      iLoc=i
      for entry in pickle.load(f):
        self.lines[iLoc].lineCheckVar.set(entry)
        iLoc+=1
    except EOFError:
      print("Warning: File ended earlir than expected. File might be older version but still work perfectly or stuff is actually missing")
Esempio n. 4
0
    def __init__(self,
                 tab,
                 root,
                 command,
                 fixedOptions,
                 defaultFileFilter,
                 options=[]):
        self.root = root
        self.tab = tab
        self.lines = []
        self.lineFrame = tk.Frame(tab)
        self.lineFrame.pack()
        self.scrollFrame = ScrollFrame(self.lineFrame)
        self.scrollFrame.pack(side="top", fill="both", expand=True)
        self.mainFrame = self.scrollFrame.frame
        self.lastPath = "."
        if os.path.exists(".GUI_last_path"):
            with open(".GUI_last_path") as file:
                self.lastPath = file.read().strip()
                #print(self.lastPath)
        self.options = options
        self.command = command
        self.defaultFileFilter = defaultFileFilter
        self.checkVars = []
        self.fixedOptions = fixedOptions

        #self.mainFrame=tk.Frame(self.lineFrame)
        #self.mainFrame.pack(side="top", fill="both", expand=True)
        #self.mainFrame.bind( '<Configure>', maxsize )
        self.extraLineMain = tk.Frame(self.mainFrame)
        self.extraLineMain.pack(side=tk.TOP)
        for option in options:
            self.checkVars.append(IntVar())
            check = Checkbutton(self.extraLineMain,
                                text=option,
                                variable=self.checkVars[-1])
            check.pack(side=tk.RIGHT)
        #b = tk.Button(self.extraLineMain, text="(Un-)check all", command=self.checkAll)
        #b.pack(side=tk.RIGHT)
        b = tk.Button(self.extraLineMain,
                      text="Add line",
                      command=self.addLine)
        b.pack(side=tk.RIGHT)
        b = tk.Button(self.extraLineMain,
                      text="Add file(s)",
                      command=self.addFiles)
        b.pack(side=tk.RIGHT)
        b = tk.Button(self.extraLineMain,
                      text="Convert All",
                      command=self.invokeAll)
        b.pack(side=tk.LEFT)

        txt_frm = tk.Frame(tab, width=600, height=600)
        txt_frm.pack(fill="both", expand=True)
        # ensure a consistent GUI size
        txt_frm.grid_propagate(False)
        # implement stretchability
        txt_frm.grid_rowconfigure(0, weight=1)
        txt_frm.grid_columnconfigure(0, weight=1)

        # create a Text widget
        self.txt = tk.Text(txt_frm, borderwidth=3, relief="sunken")
        self.txt.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)

        # create a Scrollbar and associate it with txt
        scrollb = tk.Scrollbar(txt_frm, command=self.txt.yview)
        scrollb.grid(row=0, column=1, sticky='nsew')
        self.txt['yscrollcommand'] = scrollb.set
Esempio n. 5
0
class TabClass:
    def addLine(self):
        self.lines.append(Line(self))

    def addFile(self):
        self.lines.append(Line(self))
        self.lines[-1].bFile.invoke()

    def addFiles(self):
        files = filedialog.askopenfilenames(initialdir=self.lastPath,
                                            title="Select file",
                                            filetypes=(self.defaultFileFilter,
                                                       ("all files", "*")))
        if files:
            self.lastPath = os.path.dirname(files[0].strip())
            with open(".GUI_last_path", 'w') as file:
                file.write(self.lastPath)
        for fileName in files:
            self.lines.append(Line(self))
            self.lines[-1].setTxt(fileName)
        #print (root.filename)
    def removeLineByIndex(self, index):
        self.lines[index].lineFrame.pack_forget()
        del self.lines[index]
        #del self.buttons[index]
    def removeLineByReference(self, line):
        lineFrames = [a.lineFrame for a in self.lines]
        index = lineFrames.index(line)
        self.removeLineByIndex(index)

    def setSize(self):
        if len(self.lines) > 0:
            lineWidth = self.lines[-1].lineFrame.winfo_height()
            if lineWidth > 1:  #make sure we do not kill the init!
                self.scrollFrame.canvas.config(
                    width=self.lines[-1].lineFrame.winfo_width())
            self.scrollFrame.canvas.config(height=min(
                -self.mainFrame.winfo_rooty() +
                self.lines[-1].lineFrame.winfo_rooty() +
                self.lines[-1].lineFrame.winfo_height(),
                self.tab.winfo_height() // 3 * 2))
        else:
            elements = self.extraLineMain.winfo_children()
            lineWidth = 0
            for element in elements:
                lineWidth = max(
                    lineWidth, -self.mainFrame.winfo_rootx() +
                    element.winfo_rootx() + element.winfo_width())
            if lineWidth > 10:  #make sure we do not kill the init!
                self.scrollFrame.canvas.config(width=lineWidth)

    def checkAll(self):
        for line in self.lines:
            if line.checkvar.get() == 0:
                for line in self.lines:
                    line.checkvar.set(1)
                return 0
        for line in self.lines:
            line.checkvar.set(0)

    def invokeAll(self):
        for line in self.lines:
            line.bConv.invoke()

    def checkValid(self):
        self.setSize()
        for line in self.lines:
            sourceR = 1
            filterR = 1
            resultR = 1
            resultW = 1
            if not os.access(line.getTxt(), os.R_OK):
                sourceR = 0
            #if os.path.exists(line.result):
            #try:
            #open(line.result)
            #except IOError:
            #resultW=0

            ##and not os.access(line.result,os.W_OK):
            ##resultW=0
            #if not os.access(line.result,os.W_OK):
            #resultR=0
            #if not os.access(line.getTxt().replace(".txt","_filter.txt"),os.W_OK):
            #filterR=0
            if resultW and sourceR:
                line.bConv.config(state="normal")
                line.bConvTooltip.update("Valid")
            else:
                line.bConv.config(state="disabled")
                if not sourceR:
                    line.bConvTooltip.update("Invalid source file")
                elif not resultW:
                    line.bConvTooltip.update(
                        "Result file access problem. Might be locked by program that has it open"
                    )
            if sourceR:
                line.bEditS.config(state="normal")
                line.bEditSTooltip.update("Valid")
            else:
                line.bEditS.config(state="disabled")
                line.bEditSTooltip.update("Invalid")
            if filterR:
                line.bEditF.config(state="normal")
                line.bEditFTooltip.update("Valid")
            else:
                line.bEditF.config(state="disabled")
                line.bEditFTooltip.update("Invalid")
            if resultR and resultW:
                line.bEditR.config(state="normal")
                line.bEditRTooltip.update("Valid")
            else:
                line.bEditR.config(state="disabled")
                line.bEditRTooltip.update("Invalid")

        #os.F_OK − Value to pass as the mode parameter of access() to test the existence of path.
        #os.R_OK − Value to include in the mode parameter of access() to test the readability of path.
        #os.W_OK Value to include in the mode parameter of access() to test the writability of path.
        #os.X_OK Value to include in the mode parameter of access() to determine if path can be executed.

    def __init__(self,
                 tab,
                 root,
                 command,
                 fixedOptions,
                 defaultFileFilter,
                 options=[]):
        self.root = root
        self.tab = tab
        self.lines = []
        self.lineFrame = tk.Frame(tab)
        self.lineFrame.pack()
        self.scrollFrame = ScrollFrame(self.lineFrame)
        self.scrollFrame.pack(side="top", fill="both", expand=True)
        self.mainFrame = self.scrollFrame.frame
        self.lastPath = "."
        if os.path.exists(".GUI_last_path"):
            with open(".GUI_last_path") as file:
                self.lastPath = file.read().strip()
                #print(self.lastPath)
        self.options = options
        self.command = command
        self.defaultFileFilter = defaultFileFilter
        self.checkVars = []
        self.fixedOptions = fixedOptions

        #self.mainFrame=tk.Frame(self.lineFrame)
        #self.mainFrame.pack(side="top", fill="both", expand=True)
        #self.mainFrame.bind( '<Configure>', maxsize )
        self.extraLineMain = tk.Frame(self.mainFrame)
        self.extraLineMain.pack(side=tk.TOP)
        for option in options:
            self.checkVars.append(IntVar())
            check = Checkbutton(self.extraLineMain,
                                text=option,
                                variable=self.checkVars[-1])
            check.pack(side=tk.RIGHT)
        #b = tk.Button(self.extraLineMain, text="(Un-)check all", command=self.checkAll)
        #b.pack(side=tk.RIGHT)
        b = tk.Button(self.extraLineMain,
                      text="Add line",
                      command=self.addLine)
        b.pack(side=tk.RIGHT)
        b = tk.Button(self.extraLineMain,
                      text="Add file(s)",
                      command=self.addFiles)
        b.pack(side=tk.RIGHT)
        b = tk.Button(self.extraLineMain,
                      text="Convert All",
                      command=self.invokeAll)
        b.pack(side=tk.LEFT)

        txt_frm = tk.Frame(tab, width=600, height=600)
        txt_frm.pack(fill="both", expand=True)
        # ensure a consistent GUI size
        txt_frm.grid_propagate(False)
        # implement stretchability
        txt_frm.grid_rowconfigure(0, weight=1)
        txt_frm.grid_columnconfigure(0, weight=1)

        # create a Text widget
        self.txt = tk.Text(txt_frm, borderwidth=3, relief="sunken")
        self.txt.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)

        # create a Scrollbar and associate it with txt
        scrollb = tk.Scrollbar(txt_frm, command=self.txt.yview)
        scrollb.grid(row=0, column=1, sticky='nsew')
        self.txt['yscrollcommand'] = scrollb.set
Esempio n. 6
0
class MainWindow(Window):
    def __init__(self, language, user):
        super().__init__(language)
        self.user = user
        self.accountsRowsWidgets = []
        self.showButtons = []
        self.editButtons = []
        self.toDisable = []

        self.titleWidth = 0
        self.loginWidth = 0.2
        self.associatedEmailWidth = 0.37
        self.passwordWidth = 0.6
        self.editWidth = 0.85
        self.deleteWidth = 0.9

        self.scrollframe = ScrollFrame(self.root)
        self.userInfoLabel = tk.Label(
            self.root,
            text=lp[self.language]['logged_as'].format(
                login=self.user['login']),
            bg=self.bg_color)
        self.titleLabel = tk.Label(self.scrollframe.viewPort,
                                   text=lp[self.language]['acc_title'],
                                   bg=self.bg_color)
        self.loginLabel = tk.Label(self.scrollframe.viewPort,
                                   text=lp[self.language]['acc_login'],
                                   bg=self.bg_color)
        self.associatedEmailLabel = tk.Label(
            self.scrollframe.viewPort,
            text=lp[self.language]['acc_associated_email'],
            bg=self.bg_color)
        self.passwordLabel = tk.Label(self.scrollframe.viewPort,
                                      text=lp[self.language]['acc_password'],
                                      bg=self.bg_color)
        self.separationLabel = tk.Label(self.scrollframe.viewPort,
                                        text=' ' * 40,
                                        bg=self.bg_color)
        self.addAccountBtn = tk.Button(self.root,
                                       text=lp[self.language]['add_acc_btn'],
                                       bg='#6bfc03',
                                       command=self.open_add_acc_form)
        self.settingBtn = tk.Button(self.root,
                                    text=lp[self.language]['settings_btn'],
                                    bg='#dedcd1',
                                    command=self.open_settings)
        self.exportBtn = tk.Button(self.root,
                                   text=lp[self.language]['export_btn'],
                                   bg='#dedcd1',
                                   command=self.open_window_to_export)

        self.place_widgets()
        self.display_accounts()
        self.root.mainloop()

    def place_widgets(self):
        self.userInfoLabel.place(relx=0, rely=0)
        self.addAccountBtn.place(relx=0, rely=0.05)
        self.exportBtn.place(relx=0.12, rely=0.05)
        self.settingBtn.place(relx=0.9, rely=0.05)
        self.scrollframe.place(relx=0, rely=0.15, relwidth=1, relheight=0.80)
        self.titleLabel.grid(row=0, column=0)
        self.loginLabel.grid(row=0, column=1)
        self.associatedEmailLabel.grid(row=0, column=2)
        self.passwordLabel.grid(row=0, column=3)
        self.separationLabel.grid(row=0, column=4)

    def disable_buttons(self):
        for btn in self.toDisable:
            btn.config(state='disabled')

    def open_add_acc_form(self):
        self.disable_buttons()
        form_window = AccountFormWindow(self,
                                        mode='Add',
                                        language=self.language)

    def delete_account(self, acc_id):
        if messagebox.askokcancel(
                title='Delete account',
                message='Are you sure you want to delete this account?'):
            DbManager.delete('Accounts', 'id', acc_id)
            self.display_accounts()

    def edit_account(self, acc_id):
        self.disable_buttons()
        form_window = AccountFormWindow(self,
                                        mode='Edit',
                                        language=self.language)
        form_window.load_account_data(acc_id)

    def check_pin(self, pin, btn):
        if pin.get() != DbManager.get_column_value_where(
                'Users', 'pin', 'id', self.user['id']):
            messagebox.showerror('Error', 'Invalid PIN.')
            pin.delete(0, 'end')
            return
        btn['btn'].destroy()
        pin.destroy()

        password = tk.Label(self.scrollframe.viewPort,
                            text=DbManager.get_column_value_where(
                                'Accounts', 'password', 'id', btn['acc_id']),
                            bg=self.bg_color)
        password.grid(row=btn['y'], column=3)

        # % same here, adding shown password label to accountsRowsWidgets eliminates the bug
        self.accountsRowsWidgets.append({'shown_password': password})

    def show_password(self, btn):
        btn['btn']['text'] = lp[self.language]['show']
        pin_entry = tk.Entry(self.scrollframe.viewPort, width=17, show='*')
        pin_entry.grid(row=btn['y'], column=4)
        # pin_entry.place(relx=btn['x'] + 0.05, rely=btn['y'])

        btn['btn']['command'] = lambda: self.check_pin(pin_entry, btn)

        # % accountsRowsWidgets is cleared every time display_accounts is called so adding these
        # widgets gets rid of the bug which caused show btn and pin entry to be left
        # after add/delete account
        self.accountsRowsWidgets.append({
            'show_btn': btn['btn'],
            'pin_entry': pin_entry
        })

    def display_accounts(self):
        self.showButtons.clear()
        self.toDisable.clear()
        for row in self.accountsRowsWidgets:
            for widget in row.values():
                widget.destroy()

        self.accountsRowsWidgets.clear()
        accounts = DbManager.get_user_accounts(self.user['id'])

        for i in range(len(accounts)):
            title = tk.Label(self.scrollframe.viewPort,
                             text=accounts[i]['title'],
                             bg=self.bg_color)
            title.grid(row=i + 1, column=0)

            login = tk.Label(self.scrollframe.viewPort,
                             text=accounts[i]['login'],
                             bg=self.bg_color)
            login.grid(row=i + 1, column=1)

            associated_email = tk.Label(self.scrollframe.viewPort,
                                        text=accounts[i]['associated_email'],
                                        bg=self.bg_color)
            associated_email.grid(row=i + 1, column=2)

            # SHOW BTN
            show_btn = tk.Button(self.scrollframe.viewPort,
                                 text=lp[self.language]['enter_pin_to_show'],
                                 bg='white')
            show_btn.grid(row=i + 1, column=3)
            self.showButtons.append({
                'btn': show_btn,
                'y': i + 1,
                'x': self.passwordWidth,
                'acc_id': accounts[i]['id']
            })
            self.showButtons[i]['btn'][
                'command'] = lambda btn=self.showButtons[
                    i]: self.show_password(btn)

            # EDIT BTN
            edit_btn = tk.Button(self.scrollframe.viewPort,
                                 text=lp[self.language]['edit'],
                                 bg='white',
                                 command=lambda index=i: self.edit_account(
                                     accounts[index]['id']))
            edit_btn.grid(row=i + 1, column=99)
            self.editButtons.append({
                'btn': edit_btn,
                'x': self.editWidth,
                'y': 0.05 * i
            })

            # DELETE BTN
            delete_btn = tk.Button(self.scrollframe.viewPort,
                                   text=lp[self.language]['delete'],
                                   bg='red',
                                   fg='white',
                                   command=lambda index=i: self.delete_account(
                                       accounts[index]['id']))
            delete_btn.grid(row=i + 1, column=100)

            row = {
                'title': title,
                'login': login,
                'associated_email': associated_email,
                'show_btn': show_btn,
                'edit_btn': edit_btn,
                'delete_btn': delete_btn
            }

            self.accountsRowsWidgets.append(row)

            self.toDisable.append(edit_btn)
            self.toDisable.append(delete_btn)

        self.toDisable.append(self.addAccountBtn)

    def open_window_to_export(self):
        export_security_check_window = AskValuesWindow(
            self.root, lp[self.language]['Export data'],
            ['PIN', lp[self.language]['Password']], self.user,
            self.toDisable + [self.exportBtn, self.settingBtn], self.bg_color,
            self.language)

    def open_settings(self):
        self.root.destroy()
        settings_window = SettingsWindow(self.language, self.user, self)
        settings_window.root.mainloop()
Esempio n. 7
0
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)

        self.controller = parent
        self.TILE_X = 0
        self.TILE_Y = 0

        self.ROW_LEN = None

        # Widget Defintions

        self.collection_frame = tk.Frame(self)
        self.tileset_button = tk.Button(self.collection_frame,
                                        text="Create Level",
                                        font=self.controller.font,
                                        command=self.selectTileSet)
        self.export_button = tk.Button(self.collection_frame,
                                       text="Export Level",
                                       font=self.controller.font,
                                       command=self.exportLevel)
        self.mode_label = tk.Label(self.collection_frame,
                                   text="MODE: floor",
                                   font=self.controller.font)

        self.tile_ribbon = ScrollFrame(self)
        self.tile_ribbon.scroll_canvas.configure(height=100)
        self.tile_ribbon.hideVerticalScrollBar()

        self.selected_tile_frame = tk.Frame(self)

        self.selected_tile_label = tk.Label(self.selected_tile_frame,
                                            text="Current Tile:",
                                            font=self.controller.font)
        self.selected_tile = ToolbarTile(self.selected_tile_frame)
        self.selected_tile.setImage(createTransparentRect((0, 0, 0)))

        # Widget Placement

        self.collection_frame.pack(side="left", fill="both")
        self.tileset_button.pack(side="top",
                                 fill="y",
                                 expand=True,
                                 padx=5,
                                 pady=5)
        self.export_button.pack(side="top",
                                fill="y",
                                expand=True,
                                padx=5,
                                pady=5)
        self.mode_label.pack(side="top", fill="y", expand=True, padx=5, pady=5)
        self.selected_tile_frame.pack(side="right", padx=5, pady=5)
        self.selected_tile_label.pack(side="top",
                                      fill="y",
                                      expand=True,
                                      padx=2,
                                      pady=2)
        self.selected_tile.pack(side="top",
                                fill="y",
                                expand=True,
                                padx=2,
                                pady=2)
        self.tile_ribbon.pack(side="right",
                              fill="x",
                              expand=True,
                              padx=5,
                              pady=5)

        for i in range(2):
            for j in range(32):
                tile = ToolbarTile(self.tile_ribbon.inner_frame)
                tile.grid(row=i, column=j)
                tile.bind("<Button-1>", self.selectTile)
Esempio n. 8
0
class ToolBarFrame(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)

        self.controller = parent
        self.TILE_X = 0
        self.TILE_Y = 0

        self.ROW_LEN = None

        # Widget Defintions

        self.collection_frame = tk.Frame(self)
        self.tileset_button = tk.Button(self.collection_frame,
                                        text="Create Level",
                                        font=self.controller.font,
                                        command=self.selectTileSet)
        self.export_button = tk.Button(self.collection_frame,
                                       text="Export Level",
                                       font=self.controller.font,
                                       command=self.exportLevel)
        self.mode_label = tk.Label(self.collection_frame,
                                   text="MODE: floor",
                                   font=self.controller.font)

        self.tile_ribbon = ScrollFrame(self)
        self.tile_ribbon.scroll_canvas.configure(height=100)
        self.tile_ribbon.hideVerticalScrollBar()

        self.selected_tile_frame = tk.Frame(self)

        self.selected_tile_label = tk.Label(self.selected_tile_frame,
                                            text="Current Tile:",
                                            font=self.controller.font)
        self.selected_tile = ToolbarTile(self.selected_tile_frame)
        self.selected_tile.setImage(createTransparentRect((0, 0, 0)))

        # Widget Placement

        self.collection_frame.pack(side="left", fill="both")
        self.tileset_button.pack(side="top",
                                 fill="y",
                                 expand=True,
                                 padx=5,
                                 pady=5)
        self.export_button.pack(side="top",
                                fill="y",
                                expand=True,
                                padx=5,
                                pady=5)
        self.mode_label.pack(side="top", fill="y", expand=True, padx=5, pady=5)
        self.selected_tile_frame.pack(side="right", padx=5, pady=5)
        self.selected_tile_label.pack(side="top",
                                      fill="y",
                                      expand=True,
                                      padx=2,
                                      pady=2)
        self.selected_tile.pack(side="top",
                                fill="y",
                                expand=True,
                                padx=2,
                                pady=2)
        self.tile_ribbon.pack(side="right",
                              fill="x",
                              expand=True,
                              padx=5,
                              pady=5)

        for i in range(2):
            for j in range(32):
                tile = ToolbarTile(self.tile_ribbon.inner_frame)
                tile.grid(row=i, column=j)
                tile.bind("<Button-1>", self.selectTile)

    def selectTile(self, event):
        tile = event.widget
        self.selected_tile.setImage(tile.getImage())
        self.selected_tile.setX(tile.getX())
        self.selected_tile.setY(tile.getY())

    def selectTileSet(self):
        new_tileset = TileSetSelectionDialog(self, self.controller)
        # self.controller.setTileSet("C:\\Users\\Teks Viler\\Documents\\PYGAMESTUFF\\test1\\tileset2.png")
        # self.loadTileSet()
        # self.controller.createMap()
        # self.controller.drawGround()

    def loadTileSet(self):
        self.TILE_X = 0
        self.TILE_Y = 0
        self.ROW_LEN = None

        for tile in self.tile_ribbon.inner_frame.winfo_children():
            tile.setImage(None)

        loaded_tileset = loadImage(self.controller.getTileSet())
        self.controller.setTileSet(loaded_tileset)

        tileset_width, tileset_height = loaded_tileset.size
        self.controller.setTileSetWidth(tileset_width)
        self.controller.setTileSetHeight(tileset_height)

        self.loadNewTiles()

    def loadNewTiles(self):
        tileset = self.controller.getTileSet()
        tileset_width = self.controller.getTileSetWidth()

        limit = int(tileset_width / 32)

        for tile in self.tile_ribbon.inner_frame.winfo_children():
            if (self.TILE_Y > limit - 1):
                break

            image = getTileFromImage(self.TILE_X, self.TILE_Y, tileset)
            tile.setImage(image)
            tile.setX(self.TILE_X)
            tile.setY(self.TILE_Y)

            self.TILE_X += 1
            if self.TILE_X == limit:
                self.TILE_Y += 1
                self.TILE_X = 0

    def shiftTiles(self, key):
        tileset_height = self.controller.getTileSetHeight()
        if tileset_height is None:
            return

        limit = ((tileset_height / 32)**2) / 64
        if limit <= 1:
            return

        if self.ROW_LEN is None:
            self.ROW_LEN = self.TILE_Y

        if key == "LEFT":
            if self.TILE_Y <= self.ROW_LEN: return
            self.TILE_Y -= (self.ROW_LEN * 2)
        else:
            if self.TILE_Y >= int(tileset_height / 32) - 1: return

        self.TILE_X = 0
        self.loadNewTiles()

    def exportLevel(self):
        self.controller.exportLevel()
Esempio n. 9
0
 def __init__(self, master=None):
     super().__init__(master)
     self.scroll_frame = ScrollFrame(self)
     self.pack()
     # Row number for the schedules. This is used to call grid() method.
     self.row = 0
Esempio n. 10
0
class ScheduleDrawing(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.scroll_frame = ScrollFrame(self)
        self.pack()
        # Row number for the schedules. This is used to call grid() method.
        self.row = 0

    def finalize(self):
        self.scroll_frame.pack(fill="both", expand=True)
        
    # This and other drawing methods in this class are meant to be called by outside code.
    def draw_proposed_sched(self, num_subtasks, num_procs, subtask_to_frags, deadline):
        self.num_subtasks = num_subtasks
        self.num_procs = num_procs
        self.subtask_to_frags = subtask_to_frags
        self.deadline = deadline
        # Scale out the schedule.
        self.scale = 1
        if 1000 > int(self.deadline):
            self.scale = 1000//int(self.deadline)
        self.width = self.scale * int(self.deadline) + 100
        # The height of the proposed schedule.
        self.height = (self.num_procs + 1) * 50
        # Each schedule is put within a canvas.
        #self.canvas = Canvas(self, width=self.width, height=self.height)
        self.canvas = Canvas(self.scroll_frame.viewPort, width=self.width, height=self.height)
        self.canvas.grid(row=self.row, column=0)
        self.canvas.pack()
        self.row += 1 # Compute the row number for the next canvas.
        # Gap between lines.
        gap = 50
        x_start = 40
        x_end = self.width - 10
        # y-coordinate of the bottom line.
        bottom = self.height - 20
        lines = list()
        # Each line corresponds to a processor's timeline.
        for i in range(0, self.num_procs):
            y_coor = bottom - i * gap
            line_id = self.canvas.create_line(x_start, y_coor, x_end, y_coor, arrow=LAST)
            lines.append(line_id)
            label = "P" + str(i)
            self.canvas.create_text(x_start-20, y_coor-15, text=label)

        # Add a line for the DAG task's deadline.
        x_dln = x_start + self.scale * int(self.deadline)
        self.canvas.create_line(x_dln, 10, x_dln, bottom, arrow=LAST)
        self.canvas.create_text(x_dln, bottom + 15, text=self.deadline)
        
        # Set of time ticks.
        tick_set = set()
        
        # Draw schedule for the subtasks.
        rect_height = gap - 15
        for sub_id, fragments in self.subtask_to_frags.items():
            frag_no = 0
            for frag in fragments:
                proc_id = int(frag[0])
                scaled_start_time = int(frag[1]) * self.scale + x_start
                scaled_exe_time = int(frag[2]) * self.scale
                scaled_deadline = int(frag[3]) * self.scale
                # Top left coordinate.
                x_1 = scaled_start_time
                y_1 = bottom - proc_id * gap - rect_height
                # Bottom right coordinate.
                x_2 = x_1 + scaled_exe_time
                y_2 = y_1 + rect_height
                self.canvas.create_rectangle(x_1, y_1, x_2, y_2, fill='sky blue')
                # Add label to the rectangles.
                label = "v" + str(sub_id) + "_" + str(frag_no)
                frag_no += 1
                self.canvas.create_text((x_1+x_2)/2, (y_1+y_2)/2, text=label, width=scaled_exe_time)
                # Add time ticks to the bottom line.
                start_time = int(frag[1])
                end_time = int(frag[1]) + int(frag[2])
                if start_time not in tick_set:
                    self.canvas.create_text(scaled_start_time, bottom + 15, text=str(start_time))
                    tick_set.add(start_time)
                if end_time not in tick_set:
                    self.canvas.create_text(scaled_start_time + scaled_exe_time, bottom + 15, text=str(end_time))
                    tick_set.add(end_time)
        # Add label to this frame.
        l = Label(self.scroll_frame.viewPort, text="Proposed Schedule", font=("Helvetica", 20))
        l.grid(row=self.row, column=0)
        l.pack()
        self.row += 1


    # Common method to draw both the naive schedule and the improved schedule by Baruah.
    # NOTE: call draw_proposed_sched() before this method since it needs some instance
    # variables to be initialized.
    def draw_greedy_sched(self, proc_to_subtasks, algo="baruah"):
        self.num_procs_greedy = len(proc_to_subtasks)
        greedy_height = (self.num_procs_greedy + 1) * 50
        #canvas = Canvas(self, width=self.width, height=greedy_height)
        canvas = Canvas(self.scroll_frame.viewPort, width=self.width, height=greedy_height)
        canvas.grid(row=self.row, column=0)
        canvas.pack()
        self.row += 1
        bottom = greedy_height - 20
        gap = 50
        x_start = 40
        x_end = self.width - 10
        rect_height = gap - 15
        # Add a line for the DAG task's deadline.
        x_dln = x_start + self.scale * int(self.deadline)
        canvas.create_line(x_dln, 10, x_dln, bottom, arrow=LAST)
        canvas.create_text(x_dln, bottom + 15, text=self.deadline)
        # Set of time ticks.
        tick_set = set()
        # Draw the rectangles for the subtask executions.
        for i in range(0, self.num_procs_greedy):
            y_coor = bottom - i * gap
            line_id = canvas.create_line(x_start, y_coor, x_end, y_coor, arrow=LAST)
            label = "P" + str(i)
            canvas.create_text(x_start-20, y_coor-15, text=label)
            subtasks = proc_to_subtasks[i]
            for subtask in subtasks:
                sub_id = int(subtask[0])
                scaled_start_time = self.scale * int(subtask[1]) + x_start
                scaled_wcet = self.scale * int(subtask[2])
                x_1 = scaled_start_time
                y_1 = bottom - i * gap - rect_height
                x_2 = x_1 + scaled_wcet
                y_2 = y_1 + rect_height
                canvas.create_rectangle(x_1, y_1, x_2, y_2, fill="sky blue")
                # Add label to the rectangles.
                label = "v" + str(sub_id)
                canvas.create_text((x_1+x_2)/2, (y_1+y_2)/2, text=label, width=scaled_wcet)
                # Add time ticks to the bottom line (i.e., processor 0's line).
                if int(subtask[1]) not in tick_set:
                    canvas.create_text(scaled_start_time, bottom + 15, text=subtask[1])
                    tick_set.add(int(subtask[1]))
                end_time = int(subtask[1]) + int(subtask[2])
                if end_time not in tick_set:
                    canvas.create_text(scaled_start_time + scaled_wcet, bottom + 15, \
                                       text=str(end_time))
                    tick_set.add(end_time)

        if algo == "baruah":
            l = Label(self.scroll_frame.viewPort, text="Baruah Greedy Schedule", font=("Helvetica", 20))
            l.grid(row=self.row, column=0)
            l.pack()
        else:
            l = Label(self.scroll_frame.viewPort, text="Naive Greedy Schedule", font=("Helvetica", 20))
            l.grid(row=self.row, column=0)
            l.pack()
        self.row += 1