Ejemplo n.º 1
0
def readSave():
    save = open("chess.save", "r")
    startData = save.readline().strip('\n')
    if startData == "True":
        st = True
    else:
        st = False

    if st:
        # read board
        readBoard(save)
        # read global variables
        readGlobal(save)
        # read w_pieces and b_pieces
        readPiecesArrays(save, "W")
        readPiecesArrays(save, "b")
        # read deleted pieces
        read_r_PiecesArrays(save, "W")
        read_r_PiecesArrays(save, "b")
        # read r_avail
        read_r_avail(save)
        # read p_moves
        read_p_moves(save)
        # read firstPawns
        read_firstPawns(save)

    if not globVar.ready:
        Canvas.not_ready_error()
Ejemplo n.º 2
0
def Ccircle(args):  # Command called when circle is called
    print 'draw a circle with radius %d' % (args[0])  #debug
    # If the cursor is the centre then to draw it we need to find
    # the corners of the containg box, so just remove/add the radius
    # to the x and y axis
    Canvas.create_oval(cpos[0] - args[0], cpos[1] - args[0], cpos[0] + args[0],
                       cpos[1] + args[0])
Ejemplo n.º 3
0
 def init(self):
     if self.fInit: return
     self.fInit = 1
     print "init", self
     # line
     self.fLineToOwner = Canvas.Line(self.fCanvas,
                                     0,
                                     0,
                                     0,
                                     0,
                                     fill='gray30',
                                     width=1)
     # disc
     self.fDisc = Canvas.Oval(self.fCanvas, 0, 0, 0, 0)
     self.fDisc.config(width=1)
     outlineColor, fillColor = Node.kColors[self.xType]
     self.fDisc.config(outline=outlineColor, fill=fillColor)
     Node.DiscToNode[self.fDisc] = self
     outlineColor, fillColor = Node.kColors[self.xType]
     self.fDisc.config(outline=outlineColor, fill=fillColor)
     # label
     self.fLabel = Canvas.CanvasText(self.fCanvas,
                                     0,
                                     0,
                                     font=('helvetica', 8),
                                     justify='center',
                                     anchor='s',
                                     text='')
Ejemplo n.º 4
0
 def draw(self, canvas: Canvas):
     data = numpy.fromstring(self.fig.canvas.tostring_rgb(),
                             dtype=numpy.uint8,
                             sep='')
     data = data.reshape(self.fig.canvas.get_width_height()[::-1] + (3, ))
     print("k")
     canvas.draw_numpy(0, 0, data, max_color_value=255)
Ejemplo n.º 5
0
def checkWin():
    won = False
    potenial_moves()

    if (globVar.p_w_Num == 0 or len(globVar.p_w_moves) == 0
            or len(globVar.w_pieces) == 1 or globVar.no_w_king):
        # Canvas.clear()
        won = True
        globVar.checkmate = True
        Canvas.drawBoard()
        print(" Black wins!")
        print("\n Press Enter to exit.")
        input("")
        delete_save()

    elif (globVar.p_b_Num == 0 or len(globVar.p_b_moves) == 0
          or len(globVar.b_pieces) == 1 or globVar.no_b_king):
        # Canvas.clear()
        won = True
        globVar.checkmate = True
        Canvas.drawBoard()
        print(" White wins!")
        print("\n Press Enter to exit.")
        input("")
        delete_save()

    return won
Ejemplo n.º 6
0
 def GetTrsr(self):  ################################### GETTRSR
     ''' This class won't win a Design Award! '''
     Mz = self.ry
     # convyort left fog squares to wall
     for r in np.ndindex(Mz.shape):
         if Mz[r] == Sqr.Fog:
             Mz[r] = Sqr.Wall
             self.DrawSqr(r)
     trsr = np.unravel_index(self.path.argmax(), self.path.shape)
     y = self.offset[1] + trsr[0]
     x = self.offset[0] + trsr[1]
     Canvas.Display(x, y, [5], [100, 100, 0], [200, 200, 0], 'T')
     r = Coor(trsr)
     while self.path[r] > 0:
         for dr in Globus.ls():
             r1 = r + dr
             if self.path[r1] == self.path[r] - 1:
                 y = self.offset[1] + r1[0]
                 x = self.offset[0] + r1[1]
                 Canvas.Display(x, y, [5], [10, 100, 240], [50, 30, 80],
                                '»')
                 sys.stdout.flush()
                 time.sleep(args.s)
                 r = r1
                 break
     return trsr
Ejemplo n.º 7
0
def begin(n):
    set_globals()
    global N
    N = n
    W_v = multiprocessing.Value('i', 0)
    b_v = multiprocessing.Value('i', 0)
    total_num_moves = multiprocessing.Value('i', 0)
    games_played = multiprocessing.Value('i', 0)
    num = multiprocessing.Value('i', int(n))
    lock = multiprocessing.Lock()

    procs = []
    for i in range(int(n)):
        procs.append(
            multiprocessing.Process(target=run,
                                    args=(total_num_moves, games_played, W_v,
                                          b_v, lock, i, num)))

    progress(games_played, num)

    done = 0
    while done < int(N):
        for i in range(multiprocessing.cpu_count()):
            if done + i < int(N):
                procs[done + i].start()
        for i in range(multiprocessing.cpu_count()):
            if done + i < int(N):
                procs[done + i].join()
        done += multiprocessing.cpu_count()

    Canvas.clear()
    print("\n Done! Below is the final score.")
    draw_score(int(n), W_v, b_v, total_num_moves, games_played, num)
    Canvas.pressEnter()
Ejemplo n.º 8
0
 def show(self):
     self.tk.wm_title(self.title)
     self.board = Canvas(self.tk,relief=SUNKEN, bd=2, width=self.ww, height=self.wh)
     self.board.pack(fill=BOTH)
     Rectangle(self.board, (0,0), (self.ww,self.wh), fill="white", width=1)
     b = Button(self.tk, text="Close", font=self.font, command = self.close )
     b.pack()
Ejemplo n.º 9
0
def checkWin():
    won = False
    potenial_moves()

    if (globVar.p_w_Num == 0 or len(globVar.p_w_moves) == 0
            or len(globVar.w_pieces) == 1 or globVar.no_w_king):
        won = True
        globVar.checkmate = True
        if not globVar.simulation:
            Canvas.drawBoard()
            print(" Black wins!")
            print("\n Press Enter to exit.")
            input("")
            delete_save()
        else:
            simulate.b_victories += 1

    elif (globVar.p_b_Num == 0 or len(globVar.p_b_moves) == 0
          or len(globVar.b_pieces) == 1 or globVar.no_b_king):
        won = True
        globVar.checkmate = True
        if not globVar.simulation:
            Canvas.drawBoard()
            print(" White wins!")
            print("\n Press Enter to exit.")
            input("")
            delete_save()
        else:
            simulate.W_victories += 1

    return won
 def _remakeOutline(self):
     if not self.mapped:
         return
     import Canvas
     if self.outline:
         self.outline.delete()
     if not self.points:
         self.outline = None
     elif len(self.points) < 2:
         pt = self._mapToCanvas(self.points[0])
         ul = (pt[0] - 1, pt[1] - 1)
         lr = (pt[0] + 1, pt[1] + 1)
         self.outline = Canvas.Rectangle(self.canvas, [ul, lr],
                                         fill="black")
     else:
         coords = []
         for pt in self.points:
             coords.append(self._mapToCanvas(pt))
         if "closed" in self.opt.getvalue():
             if self.points[0] != self.points[-1]:
                 coords.append(self._mapToCanvas(self.points[0]))
             else:
                 del self.points[-1]
         self.outline = Canvas.Line(self.canvas,
                                    coords,
                                    fill="black",
                                    width=3)
Ejemplo n.º 11
0
def Cline(args):  # Command called when line is called
    next_pos = [cpos[0] + args[0],
                cpos[1] + args[1]]  # Evalutate next position
    print 'draw a line from : %d, %d to : %d, %d' % (cpos[0], cpos[1],
                                                     next_pos[0], next_pos[1])
    Canvas.create_line(cpos[0], cpos[1], next_pos[0],
                       next_pos[1])  # Draw the line on the canvas
    Cposition(next_pos)  # Change the cursor position
Ejemplo n.º 12
0
 def showCrossover(self):
     self.GenerCanvas = [
         Canvas.Canvas(self.population, 1),
         Canvas.Canvas(self.population, 1)
     ]
     self.vboxc[0].addWidget(self.GenerCanvas[0])
     self.vboxc[1].addWidget(self.GenerCanvas[1])
     self.GenerCanvas[0].drawImage()
     self.GenerCanvas[1].drawImage()
Ejemplo n.º 13
0
 def init(self):
     self.fHighlight = Canvas.Oval(self.fCanvas, 0, 0, 0, 0)
     self.fHighlight.config(outline="#FF0000", width="1")
     self.fLabel = Canvas.CanvasText(self.fCanvas,
                                     7,
                                     7,
                                     font=('courier', 8),
                                     justify='left',
                                     anchor='nw',
                                     text='')
Ejemplo n.º 14
0
 def Render(self, canvas, obj):
     if obj:
         if self.Attribute(0) == '':
             obj.at = Canvas.Position()
         else:
             obj.at = Canvas.Position(float(self.Attribute(0)),
                                      float(self.Attribute(1)))
             if self.Attribute(2) != '':
                 obj.at.angle = float(self.Attribute(2))
     super(KicadAt, self).Render(canvas, obj)
Ejemplo n.º 15
0
 def __init__(self, mastr, sq, *a, **k):
     self.highlight = 0
     Frame.__init__(self, mastr, border=0, *a, **k)
     self.ca = Canvas(master=self, border=0, width=48, height=48)
     self.ca.pack(expand=1, fill=BOTH)
     self.l = ImageItem(self.ca, 0, 16, anchor=NW)
     self.t = ImageItem(self.ca, 16, 0, anchor=NW)
     self.c = ImageItem(self.ca, 16, 16, anchor=NW)
     self.b = ImageItem(self.ca, 16, 32, anchor=NW)
     self.r = ImageItem(self.ca, 32, 16, anchor=NW)
     self.seq = sq
Ejemplo n.º 16
0
def parse_args(args):
    args.pop(0)  # remove script arg
    s = "".join(args)
    globVar.show_all_menus = ("m" in s)

    ## GRAPHICS
    if ("a" in s):
        globVar.unicode = False
        globVar.limited_unicode = False

    if ("l" in s):
        globVar.unicode = False
        globVar.limited_unicode = True

    if ("u" in s):
        globVar.unicode = True
        globVar.limited_unicode = False

    if globVar.limited_unicode:
        colors.limited_pieces()

    # Game speed
    globVar.slow_speed = not ("f" in s)
    if ("s" in s):
        globVar.slow_speed = True

    # AI
    if ("n" in s):
        globVar.chill = False
        globVar.aggressive = False
    if ("c" in s):
        globVar.chill = True
        globVar.aggressive = False
    if ("g" in s):
        globVar.chill = False
        globVar.aggressive = True

    # GAME MODES
    if ("0" in s):
        globVar.numPlayers = 0
    elif ("1" in s):
        globVar.numPlayers = 1
    elif ("2" in s):
        globVar.numPlayers = 2

    if ("i" in s):
        globVar.simulation = True
        globVar.numPlayers = 0
        Canvas.simulateMenu()
        exit()

    if ("h" in s):
        Canvas.help()
        exit()
Ejemplo n.º 17
0
def main():
    path = pathlib.Path("chess.save")
    if path.exists():
        Canvas.loadSave()
        running = True
    else:
        running = Canvas.startScreen()

    while(running):
        running = state()

    utils.delete_save()
Ejemplo n.º 18
0
def r_c(x):
    if x == 'c':  # col
        choice = Canvas.chooseCol()
        choice = choice.upper()
        choice = ord(choice)
        choice -= 65

    else:  # row
        choice = Canvas.chooseRow()
        choice = (8 - choice)

    return int(choice)
Ejemplo n.º 19
0
def begin(n):
    set_globals()
    global N
    N = n
    W_v = multiprocessing.Value('i', 0)
    b_v = multiprocessing.Value('i', 0)
    total_num_moves = multiprocessing.Value('i', 0)
    games_played = multiprocessing.Value('i', 0)
    num = multiprocessing.Value('i', int(n))
    lock = multiprocessing.Lock()

    counts = []
    for i in range(int(multiprocessing.cpu_count())):
        counts.append(0)

    dist = int(N)
    i = 0
    while dist > 0:
        counts[i % len(counts)] += 1
        i += 1
        dist -= 1

    procs = []
    for i in range(len(counts)):
        games_to_play = counts[i]
        p = multiprocessing.Process(target=run_games,
                                    args=(total_num_moves, games_played, W_v,
                                          b_v, lock, i, num, games_to_play))
        procs.append(p)

    progress(games_played, num)

    for p in procs:
        p.start()
    for p in procs:
        p.join()

    #  done = 0
    #  while done < int(N):
    #  for i in range(multiprocessing.cpu_count()):
    #  if done + i < int(N):
    #  procs[done + i].start()
    #  for i in range(multiprocessing.cpu_count()):
    #  if done + i < int(N):
    #  procs[done + i].join()
    #  done += multiprocessing.cpu_count()

    Canvas.clear()
    print("\n Done! Below is the final score.")
    draw_score(int(n), W_v, b_v, total_num_moves, games_played, num)
    Canvas.pressEnter()
Ejemplo n.º 20
0
    def __init__(self, app):
        """
        Create a main window for the given application.
        """

        defaultOptions["palette"] = app.palette()
        Systray.__init__(self)

        self.expansions = 0
        self.client = None
        self.server = None
        self.running = False
        self.recovery = False
        mainWidgets["main"] = self
        mainWidgets["app"] = app

        self.canvas = Canvas(self)
        mainWidgets["canvas"] = self.canvas

        self.tabWidget = TabWidget(self)
        mainWidgets["tab"] = self.tabWidget

        self.setCentralWidget(self.tabWidget)
        #self.setCentralWidget(self.canvas)

        self.createActions()
        self.createMenus()
        self.createToolBars()
        self.createStatusBar()
        self.createDockWindows()
        self.createConfigWindows()
        self.createPopupWindows()
        self.createProgressBar()

        self.newScene()

        self.debugWindow.hide()
        self.tm.hide()
        self.routes.hide()

        self.setVisible(True)
        self.center()
        self.saveLayout(environ["config"] + "defaultLayout")

        self.defaultLayout = True
        if options["restore"]:
            self.loadLayout()
            self.defaultLayout = False

        self.loadProject()
        atexit.register(self.cleanup)
Ejemplo n.º 21
0
def select():
    print(" Select which piece to move.")
    selecting = True
    while selecting:
        col = utils.r_c('c')
        row = utils.r_c('r')

        if board.Grid(row,col).piece.color != globVar.player:
            Canvas.selectError()
        else:
            board.Grid(row,col).piece.selected = True # display fromSqr as selected
            selecting = False

    return board.Grid(row,col)
Ejemplo n.º 22
0
def setGconmember(self,member,value):
     # If the VCS Canvas is displayed, then bring the canvas to the front before 
     # redisplaying the updated contents.
     if (self.parent.mode == 1) and (self.parent.iscanvasdisplayed()):
        Canvas.finish_queued_X_server_requests( self.parent )
        self.parent.canvas.BLOCK_X_SERVER()
        self.parent.canvasraised()

     _vcs.setGconmember(self, member, value, self.parent.mode)

     # If the VCS Canvas is displayed, then update the backing store
     if (self.parent.mode == 1) and (self.parent.iscanvasdisplayed()):
        self.parent.flush()
        self.parent.backing_store()
        self.parent.canvas.UNBLOCK_X_SERVER()
Ejemplo n.º 23
0
    def initUI(self):
        self.canvas = Canvas()
        self.setCentralWidget(self.canvas)

        self.initActions()
        self.initMenu()

        self.setWindowTitle("Draw Pixel")
        self.resize(800, 600)

        self.toolbar = QToolBar("Size Bar", self)
        self.toolbar.addAction("PlaceHolder")

        self.sizeSlider = QSlider(self)
        self.toolbar.addWidget(self.sizeSlider)
Ejemplo n.º 24
0
def turn():
    utils.potenial_moves()
    Canvas.drawBoard()

    if (globVar.noPlayers or globVar.numPlayers == 0):
        ai_turn()

    elif (globVar.numPlayers == 1 and globVar.player == "b"):
        ai_turn()

    elif (globVar.numPlayers == 2 or globVar.player == "W" and
    globVar.numPlayers == 1):
        human_turn()

    globVar.removed = False
Ejemplo n.º 25
0
def setGfimember(self, member, value):
    # If the VCS Canvas is displayed, then bring the canvas to the front before
    # redisplaying the updated contents.
    if (self.parent.mode == 1) and (self.parent.iscanvasdisplayed()):
        Canvas.finish_queued_X_server_requests(self.parent)
        self.parent.canvas.BLOCK_X_SERVER()
        self.parent.canvasraised()

    _vcs.setGfimember(self, member, value, self.parent.mode)

    # If the VCS Canvas is displayed, then update the backing store
    if (self.parent.mode == 1) and (self.parent.iscanvasdisplayed()):
        self.parent.flush()
        self.parent.backing_store()
        self.parent.canvas.UNBLOCK_X_SERVER()
Ejemplo n.º 26
0
def init(gui = 0, mode=1, pause_time=0, call_from_gui=0, size=None, backend="vtk"):
    '''
 Function: init                 # Initialize, Construct a VCS Canvas Object

 Description of Function:
    Construct the VCS Canas object. There can only be at most 8 VCS
    Canvases open at any given time.

    Graphics User Interface Mode:                                         
            gui = 0|1    if ==1, create the canvas with GUI controls       
                         (Default setting is *not* to display GUI controls)

 Example of Use:
    import vcs,cu

    file=cu.open('filename.nc')
    slab=file.getslab('variable')
    a=vcs.init()                        # This examples constructs 4 VCS Canvas 
    a.plot(slab)                        # Plot slab using default settings
    b=vcs.init()                        # Construct VCS object
    template=b.gettemplate('AMIP')      # Get 'example' template object
    b.plot(slab,template)               # Plot slab using template 'AMIP'
    c=vcs.init()                        # Construct new VCS object
    isofill=c.getisofill('quick')       # Get 'quick' isofill graphics method
    c.plot(slab,template,isofill)       # Plot slab using template and isofill objects
    d=vcs.init()                        # Construct new VCS object
    isoline=c.getisoline('quick')       # Get 'quick' isoline graphics method
    c.plot(isoline,slab,template)       # Plot slab using isoline and template objects
'''
    canvas = Canvas.Canvas(gui=gui, mode=mode, pause_time=pause_time, call_from_gui=call_from_gui, size=size, backend=backend)
    global canvaslist
    canvaslist.append(canvas)
    return canvas
Ejemplo n.º 27
0
    def startTutorial(self):
        """
        Start the interactive tutorial.
        """
        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append(
                "You are already doing the tutorial!  If you would like to stop or restart, select 'Close' from the File menu now."
            )
            return

        if not self.closeTopology():
            return

        self.project = "Tutorial"
        self.filename = ""

        self.canvas = Tutorial(self)
        mainWidgets["canvas"] = self.canvas

        self.tabWidget.removeTab(0)
        self.tabWidget.addTab(self.canvas, "Tutorial")
        self.canvas.start()

        for nodeType in nodeTypes.keys():
            itemTypes = nodeTypes[nodeType]
            itemTypes[nodeType] = 0

        self.properties.clear()
        self.interfaces.clear()
        self.routes.clear()

        self.resetLayout(True)
        self.lockDocks()
    def __init__(self, parent):
        QtGui.QMainWindow.__init__(self)
        UI_DrawingWindow.__init__(self)
        self.setupUi(self)

        self.parent = parent

        self.canvas = Canvas.Canvas(self.drawing_panel)

        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)

        self.register_buttons()
        # set max counts in progresss bar
        self.count_progress_bar.setMaximum(
            config.Settings.SAMPLE_COUNT_PER_DIGIT)
        self.count_progress_bar.setValue(
            config.Settings.SAMPLE_COUNT_PER_DIGIT)
        # Attach this window to the Server
        globals.device_server.attach_active_drawing_window(self)

        # Panel Updater timer
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(config.Settings.REFRESH_INTERVAL)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.update_panel)
        self.timer.start()
Ejemplo n.º 29
0
 def __init__(self, master, frame, sw, sh):
     '''
     Constructor for the plot area.
     '''
     # initialization of 
     self.sw = sw
     self.sh = sh
     self.frame = frame
     
     # empty value list
     self.value_list = []
     
     # canvas area where the value lines and the coordinate system
     self.canvas = Canvas(self.frame, bg = "white")
     self.canvas.pack(expand = YES, fill = BOTH)
     
     #if the used os is a windows or a mac, they need a factor 1.5 for the y-axis
     if os.name == "nt":
         self.win_osx_factor = 1.5
     elif os.name == "mac":
         self.win_osx_factor = 1.5
         
     # if its a linux machine factor is 1           
     else:
         self.win_osx_factor = 1
Ejemplo n.º 30
0
 def showSelection(self):
     self.GenerCanvas = [Canvas.Canvas(self.population, 1)]
     self.warning1.setText(
         "<div style='color: rgb(255, 255, 255); text-align: center;'>Расставьте уникальное значение для каждого изображения, где 1 - наименее подходящее изображение, "
         + str(self.population.size) + " - наиболее подходящее.</div>")
     self.hboxs.addWidget(self.GenerCanvas[0])
     self.GenerCanvas[0].drawImage()
Ejemplo n.º 31
0
    def startTutorial(self):
        """
        Start the interactive tutorial.
        """
        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append("You are already doing the tutorial!  If you would like to stop or restart, select 'Close' from the File menu now.")
            return

        if not self.closeTopology():
            return
        
        self.project = "Tutorial"
        self.filename = ""
        
        self.canvas = Tutorial(self)
        mainWidgets["canvas"] = self.canvas

        self.tabWidget.removeTab(0)
        self.tabWidget.addTab(self.canvas, "Tutorial")
        self.canvas.start()

        for nodeType in nodeTypes.keys():
            itemTypes = nodeTypes[nodeType]
            itemTypes[nodeType] = 0

        self.properties.clear()
        self.interfaces.clear()
        self.routes.clear()

        self.resetLayout(True)
        self.lockDocks()
Ejemplo n.º 32
0
 def load_painter(self):
     # Загружаем холст
     self.paint_page.setLayout(self.paint_page_lay)
     # Текущий цвет - черный, ширина кисти - 10
     self.now_col = QColor(0, 0, 0)
     self.now_width = 10
     self.point_width.setValue(10)
     # Подвязываем кнопку с изменением ширины кисти к соответсвующему слоту
     self.point_width.valueChanged.connect(self.change_width)
     # Создаем холст как экземпляр класса Canvas из доп.модуля Canvas
     self.canvas = Canvas.Canvas(self.main_paint_widg)
     self.canvas.move(1, 1)
     self.canvas.resize(self.main_paint_widg.width() - 1,
                        self.main_paint_widg.height() - 1)
     print(self.main_paint_widg.size(), self.canvas.size(),
           self.border_lab.size())
     # Устанавливаем границы рамки
     self.border_lab.setStyleSheet(
         'border-style: solid; border-width: 2px; border-color: black;')
     self.canvas.setStyleSheet('background-color: white;')
     # Устанавливаем сильный фокус для перехвата всех событий
     # клавиатуры и мыши
     self.setFocusPolicy(Qt.StrongFocus)
     # Подвязываем действия из меню к слотам
     self.actionSave.triggered.connect(self.save_file)
     self.actionSave_as.triggered.connect(self.save_as_file)
     self.actionOpen.triggered.connect(self.open_file)
     self.actionReference.triggered.connect(self.open_reference)
     # и кнопку очистки холста, а также задания цвета кисти
     self.bt_clear.clicked.connect(self.clear_canvas)
     self.bt_set_color.clicked.connect(self.set_color_with_bt)
     # Имя файла изначально не задано, файл не сохранен
     self.file_name = ''
     self.saved = False
     self.resizeEvent(QResizeEvent(self.size(), self.size()))
Ejemplo n.º 33
0
def check_pawn(pc):
    W_success = (pc.type == "pawn") and (globVar.player == "W") and (pc.row
                                                                     == 0)
    b_success = (pc.type == "pawn") and (globVar.player == "b") and (pc.row
                                                                     == 7)

    if W_success or b_success:
        if ((globVar.numPlayers == 1 and globVar.player == "W")
                or globVar.numPlayers == 2):
            choice = Canvas.pawn_to_new()
        else:
            choice = random.randint(1, 4)

        color = pc.color
        label = pc.label
        row = pc.row
        col = pc.col

        if choice == 1:
            pc = pieces.Rook(color, "rook")
        elif choice == 2:
            pc = pieces.Knight(color, "knight")
        elif choice == 3:
            pc = pieces.Bishop(color, "bishop")
        elif choice == 4:
            pc = pieces.Queen(color, "queen")

        pc.label = label
        pc.row = row
        pc.col = col

        updatePieces(pc)
        board.uGrid(pc)
Ejemplo n.º 34
0
class SonarScanner:
	def __init__(self, sonarPort, motorPort):
		self.motor = MotorScanner(motorPort)
		self.sonar = Sonar(sonarPort)
		self.canvas = Canvas()

	# 
	# Function to scan from 0 to 360. Each step takes SCAN_STEP Radian
	def scan(self):
		# initialize data
		data = []

		# Go to start angle
		self.motor.gotoAngle(SCANNER_START_ANGLE, 'cw')

		nStep = int((SCANNER_END_ANGLE - SCANNER_START_ANGLE)/SCANNER_SCAN_STEP)
		for i in range(0, nStep):
			# go to angle
			angle = SCANNER_START_ANGLE + SCANNER_SCAN_STEP*i
			self.motor.gotoAngle(angle, 'ccw')

			# read sonar data
			z = self.sonar.getSmoothSonarDistance(0.05)
			data.append(z)

		# Back to zero angle
		self.motor.gotoAngle(0, 'cw')

		return data

	def drawScanData(self, data):
		for i in range(0, len(data)):
			r = data[i]*SCANNER_DRAW_SCALE
			th = SCANNER_START_ANGLE + SCANNER_SCAN_STEP*i

			if(r > 200):
				continue

			x0 = int(SCANNER_DRAW_X0)
			y0 = int(SCANNER_DRAW_Y0)
			x1 = int(x0 + r*cos(th))
			y1 = int(y0 + r*sin(th))

			print radToDeg(th), r
			print (x0, y0, x1, y1)

			self.canvas.drawLine((x0, y0, x1, y1))
Ejemplo n.º 35
0
    def __init__(self, parent=None):
        super(Mozayik, self).__init__(parent)

        mainLayout = QHBoxLayout()
        
        #setup button icons
        assets = os.getcwd() + "/assets"
        if os.path.exists(assets):
            os.chdir(assets)
            trash = assets + "/trash.png"
            if os.path.isfile(trash):
                trashIcon = QIcon(QPixmap(trash))
            add = assets + "/plus.png"
            if os.path.isfile(add):
                addIcon = QIcon(QPixmap(add))
            folder = assets + "/folder.png"
            if os.path.isfile(folder):
                folderIcon = QIcon(QPixmap(folder))

        #setup buttons
        self.enterFolderButton = QPushButton(folderIcon, "")
        self.enterFolderButton.clicked.connect(self.enterFolderContact)
        self.addTilesButton = QPushButton(addIcon, "")
        self.addTilesButton.clicked.connect(self.addTilesContact)
        self.deleteButton = QPushButton(trashIcon, "")
        self.deleteButton.clicked.connect(self.deleteContact)

        #layout buttons
        buttonLayout1 = QHBoxLayout()
        buttonLayout1.addWidget(self.enterFolderButton)
        buttonLayout1.addWidget(self.addTilesButton)
        buttonLayout1.addWidget(self.deleteButton)

        #setup image viewer
        scrollView = QScrollArea()
        scrollView.setBackgroundRole(QPalette.Dark)
        self.viewer = Viewer()
        scrollView.setWidget(self.viewer)
        size = QSize(350,600)
        scrollView.setMaximumSize(size)
        #scrollView.setMinimumSize(size)

        #setup mozayik area
        #self.mozayik = QLabel("Area reserved")
        self.mozayik = Canvas()

        #layout main view
        viewLayout1 = QVBoxLayout()
        viewLayout1.addLayout(buttonLayout1)
        viewLayout1.setAlignment(buttonLayout1,Qt.AlignRight)
        viewLayout1.addWidget(scrollView)
        viewLayout1.setAlignment(scrollView,Qt.AlignLeft)
        
        mainLayout.addLayout(viewLayout1)
        mainLayout.addWidget(self.mozayik)

        self.setLayout(mainLayout)
        self.setWindowTitle("Mozayik")
Ejemplo n.º 36
0
 def __construct__(self):
   #extract, contain, and properly indent python content
   funcname = self.vbl_elem.getAttribute('name')
   args = self.vbl_elem.getAttribute('args')
   script = Canvas.normalize_python(node=self, definition="def %s(%s):"%(funcname, args))
   
   #run the code (which will define a function where we need it)
   try:  exec script in self.parent.__dict__
   except Exception, msg: Events.Error(self, msg, "bad syntax in python block")
Ejemplo n.º 37
0
class CanvasDemo:

    colors = ["pink", "grey", "yellow", "green", "red", "purple", "cyan",
            "pink", "grey", "yellow", "green", "red", "purple", "cyan",
            "pink", "grey", "yellow", "green", "red", "purple", "cyan"]
    layers = 5
    root = canvas = groups = None

    def __init__(self, root):
        self.root = root

        # make a frame and a canvas and some buttons
        frame = Frame(self.root)
        frame.pack(fill=X)
        label = Label(frame, text="Canvas test")
        label.pack()
        self.canvas = Canvas(frame, bg="grey", width=600, height=600)
        self.canvas.pack()
        cmd = Button(frame, text="Scale", command=self.scale)
        cmd.pack()
        self.groups = []
        for i in range(self.layers):
            self.groups.append(Group(self.canvas))

        # time the creation of the rectangles
        start = time()
        self.makeShapes()
        print "Took ", time() - start, " seconds to make", self.layers,"layers"

    def makeShapes(self):
        # make 100 rectangles
        for group in range(self.layers):
            actual = self.groups[group]
            MouseHandler(actual)
            for i1 in range(10):
                for i2 in range(10):
                    makeRectangle(self.canvas, actual, i1*40+10+group*20,
                            i2*40+10+group*5,
                            35, 35, self.colors[group], 2)

    def scale(self):
        for group in self.groups:
            group.scale(0, 0, 1.1, 1.1)
Ejemplo n.º 38
0
  def __construct__(self):
    #extract, contain, and properly indent python content
    funcname = self.vbl_elem.getAttribute('name')
    args = self.vbl_elem.getAttribute('args')
    prefix = "def %s(%s): import threading; t = threading.Thread(target=_thread_%s, args=[%s]); t.setDaemon(True); t.start();"%(funcname, args, funcname, args)
    definitionLine = "def _thread_%s(%s):"%(funcname, args)
    script = Canvas.normalize_python(node=self, prefix=prefix, definition=definitionLine)

    #run the code (which will define a function where we need it)
    try:  exec script in self.parent.__dict__
    except Exception, msg: Events.Error(self, msg, "bad syntax in python block\s%s"%script)
Ejemplo n.º 39
0
    def __init__(self, app):
        """
        Create a main window for the given application.
        """

        defaultOptions["palette"] = app.palette()
        Systray.__init__(self)

        self.expansions = 0
        self.client = None
        self.server = None
        self.running = False
        self.recovery = False
        mainWidgets["main"] = self
        mainWidgets["app"] = app

        self.canvas = Canvas(self)
        mainWidgets["canvas"] = self.canvas

        self.tabWidget = TabWidget(self)
        mainWidgets["tab"] = self.tabWidget

        self.setCentralWidget(self.tabWidget)
        # self.setCentralWidget(self.canvas)

        self.createActions()
        self.createMenus()
        self.createToolBars()
        self.createStatusBar()
        self.createDockWindows()
        self.createConfigWindows()
        self.createPopupWindows()
        self.createProgressBar()

        self.newScene()

        self.debugWindow.hide()
        self.tm.hide()
        self.routes.hide()

        self.setVisible(True)
        self.center()
        self.saveLayout(environ["config"] + "defaultLayout")

        self.defaultLayout = True
        if options["restore"]:
            self.loadLayout()
            self.defaultLayout = False

        self.loadProject()
        atexit.register(self.cleanup)
Ejemplo n.º 40
0
  def __construct__(self):    
    #extract, wrap, and properly indent python content
    self.funcname = self['name'] or "_%s_%s"%(self.on, self.canvas._uidcount)
    self.canvas.__dict__['_uidcount'] += 1
    args = self['args'] or "value"
    script = Canvas.normalize_python(node=self, definition="def %s(%s):"%(self.funcname, args))

    #run the code (which will define a function where we need it)
    try:  exec script in self.parent.__dict__
    except Exception, msg: Events.Error(self, msg, "bad syntax in python block")
    
    #if a reference is given adjust the target to that, otherwise use the parent per normal
    if self['reference']:
      self.parent.constrain(attr='early', func=self._reference)
    else:
      self.parent.constrain(attr=self.on, func=self.parent.__dict__[self.funcname])
Ejemplo n.º 41
0
    def closeTopology(self):
        """
        Close the current topology.
        """
        if self.running:
            self.log.append("You cannot close a topology when one is still running!")
            return False

        scene = self.canvas.scene()
        if scene and scene.items():
            reply = QtGui.QMessageBox.warning(
                self,
                self.tr(Core.globals.PROG_NAME),
                self.tr("Save before closing?"),
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel,
            )
            if reply == QtGui.QMessageBox.Yes:
                if not self.saveTopology():
                    return False
            elif reply == QtGui.QMessageBox.No:
                pass
            else:
                return False

        if isinstance(mainWidgets["canvas"], Tutorial):
            self.canvas = Canvas(self)
            mainWidgets["canvas"] = self.canvas
            self.tabWidget.removeTab(0)
            self.tabWidget.addTab(self.canvas, "Default Project")
            self.project = ""
            self.unlockDocks()

        self.filename = ""
        scene = Scene(self.canvas)
        scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
        self.canvas.setScene(scene)
        self.expansions = 0

        for nodeType in nodeTypes.keys():
            itemTypes = nodeTypes[nodeType]
            itemTypes[nodeType] = 0

        self.properties.clear()
        self.interfaces.clear()
        self.routes.clear()

        return True
Ejemplo n.º 42
0
Archivo: GUI.py Proyecto: More4me/AI
    def __initUI(self):
        self.parent.title("Sudoku")
        self.pack(fill=BOTH)
        self.canvas = Canvas(self,
                             width=WIDTH,
                             height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        clear_button = Button(self,
                              text="Clear answers",
                              command=self.__clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_puzzle()

        self.canvas.bind("<Button-1>", self.__cell_clicked)
        self.canvas.bind("<Key>", self.__key_pressed)
Ejemplo n.º 43
0
    def __init__(self, root):
        self.root = root

        # make a frame and a canvas and some buttons
        frame = Frame(self.root)
        frame.pack(fill=X)
        label = Label(frame, text="Canvas test")
        label.pack()
        self.canvas = Canvas(frame, bg="grey", width=600, height=600)
        self.canvas.pack()
        cmd = Button(frame, text="Scale", command=self.scale)
        cmd.pack()
        self.groups = []
        for i in range(self.layers):
            self.groups.append(Group(self.canvas))

        # time the creation of the rectangles
        start = time()
        self.makeShapes()
        print "Took ", time() - start, " seconds to make", self.layers,"layers"
Ejemplo n.º 44
0
    'end'       : C_end
}

Functions = {
}

Loop_Def = []
Loop_Time = 0

file = open('test3.txt', 'r')

for line in file:
    line = string.lower(trim(line))
    if line == 'end':
        print InCall
        if InCall == 'Loop':
            print Loop_Time
            for i in range(Loop_Time):
                Execute(Loop_Def)
        InCall = 'Main' 
    if InCall == 'Main':
        Execute([line])
    elif InCall == 'Loop':
        Loop_Def += [line]
    else:
        Functions[InCall] += [line]

file.close()

Canvas.complete()
Ejemplo n.º 45
0
def transformToWindowCoordinates(points):
    return [[(1 + t[0]) * WIDTH / 2 , (1 - t[1]) * HEIGHT / 2] for t in points]

if __name__ == "__main__":
    #check parameters
    if len(sys.argv) != 2:
        print "pointViewerTemplate.py"
        sys.exit(-1)

    # create main window
    mw = Tk()

    # create and position canvas and buttons
    cFr = Frame(mw, width=WIDTH, height=HEIGHT, relief="sunken", bd=1)
    cFr.pack(side="top")
    can = Canvas(cFr, width=WIDTH, height=HEIGHT)
    can.pack()
    bFr = Frame(mw)
    bFr.pack(side="left")
    bRotYn = Button(bFr, text="<-", command=rotYn)
    bRotYn.pack(side="left")
    bRotYp = Button(bFr, text="->", command=rotYp)
    bRotYp.pack(side="left")
    eFr = Frame(mw)
    eFr.pack(side="right")
    bExit = Button(eFr, text="Quit", command=(lambda root=mw: quit(root)))
    bExit.pack()

    modelObj = model.parse(sys.argv[1])
    cam.setupCameraForModel(modelObj)
Ejemplo n.º 46
0
    draw()


if __name__ == "__main__":
    #check parameters
    if len(sys.argv) != 1:
       print "LineClipping"
       sys.exit(-1)

    # create main window
    mw = Tk()
    mw._root().wm_title("Line clipping (Cohen-Sutherland Algorithm)")

    # create and position canvas and buttons
    cFr = Frame(mw, width=WIDTH, height=HEIGHT, relief="sunken", bd=1)
    cFr.pack(side="top")
    can = Canvas(cFr, width=WIDTH, height=HEIGHT)
    can.bind("<Button-1>",mouseEvent)
    can.pack()
    cFr = Frame(mw)
    cFr.pack(side="left")
    bClear = Button(cFr, text="Clear", command=clearAll)
    bClear.pack(side="left") 
    eFr = Frame(mw)
    eFr.pack(side="right")
    bExit = Button(eFr, text="Quit", command=(lambda root=mw: quit(root)))
    bExit.pack()

    # start
    mw.mainloop()
    
Ejemplo n.º 47
0
Archivo: play.py Proyecto: sswam/brace
def paper(width=400, height=300, colour="white"):
	global canvas, tk, paper_w, paper_h
	paper_w = width ; paper_h = height
	tk = Tk()
	canvas = Canvas(tk, width=width, height=height, background=colour)
	canvas.pack(fill=BOTH, expand=Y)
Ejemplo n.º 48
0
def sched_queerity():
    tk.after(min_queerity_sleep + int(random()*(max_queerity_sleep-min_queerity_sleep)), queerity)

intro()

if os_name == 'posix':
    def exiting():
	system("xset r on")
    atexit.register(exiting)
    system("xset r off")
    cursor="dot #111111"
else:
    cursor=None

tk = Tk()
canvas = Canvas(tk, width=w, height=h, background='black', cursor=cursor)
canvas.pack(fill=BOTH, expand=Y)

center = w/2+h/2*1j

tk.bind("h", help)
tk.bind("i", info)
tk.bind("<Escape>", do_exit)

start()

sched_queerity()

tk.mainloop()
Ejemplo n.º 49
0
def C_circle(args):
    Canvas.create_oval(cursor_pos[0]-int(args[0]), cursor_pos[1]-int(args[0]), cursor_pos[0]+int(args[0]), cursor_pos[1]+int(args[0]))
Ejemplo n.º 50
0
Archivo: GUI.py Proyecto: More4me/AI
class SudokuUI(Frame):
    """
    The Tkinter UI, responsible for drawing the board and accepting user input.
    """
    def __init__(self, parent, game):
        self.game = game
        Frame.__init__(self, parent)
        self.parent = parent

        self.row, self.col = -1, -1

        self.__initUI()

    def __initUI(self):
        self.parent.title("Sudoku")
        self.pack(fill=BOTH)
        self.canvas = Canvas(self,
                             width=WIDTH,
                             height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        clear_button = Button(self,
                              text="Clear answers",
                              command=self.__clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_puzzle()

        self.canvas.bind("<Button-1>", self.__cell_clicked)
        self.canvas.bind("<Key>", self.__key_pressed)

    def __draw_grid(self):
        """
        Draws grid divided with blue lines into 3x3 squares
        """
        for i in xrange(10):
            color = "blue" if i % 3 == 0 else "gray"

            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

    def __draw_puzzle(self):
        self.canvas.delete("numbers")
        for i in xrange(9):
            for j in xrange(9):
                answer = self.game.puzzle[i][j]
                if answer != 0:
                    x = MARGIN + j * SIDE + SIDE / 2
                    y = MARGIN + i * SIDE + SIDE / 2
                    original = self.game.start_puzzle[i][j]
                    color = "black" if answer == original else "sea green"
                    self.canvas.create_text(
                        x, y, text=answer, tags="numbers", fill=color
                    )

    def __draw_cursor(self):
        self.canvas.delete("cursor")
        if self.row >= 0 and self.col >= 0:
            x0 = MARGIN + self.col * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.col + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1
            self.canvas.create_rectangle(
                x0, y0, x1, y1,
                outline="red", tags="cursor"
            )

    def __draw_victory(self):
        # create a oval (which will be a circle)
        x0 = y0 = MARGIN + SIDE * 2
        x1 = y1 = MARGIN + SIDE * 7
        self.canvas.create_oval(
            x0, y0, x1, y1,
            tags="victory", fill="dark orange", outline="orange"
        )
        # create text
        x = y = MARGIN + 4 * SIDE + SIDE / 2
        self.canvas.create_text(
            x, y,
            text="You win!", tags="victory",
            fill="white", font=("Arial", 32)
        )

    def __cell_clicked(self, event):
        if self.game.game_over:
            return
        x, y = event.x, event.y
        if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN):
            self.canvas.focus_set()

            # get row and col numbers from x,y coordinates
            row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE

            # if cell was selected already - deselect it
            if (row, col) == (self.row, self.col):
                self.row, self.col = -1, -1
            elif self.game.puzzle[row][col] == 0:
                self.row, self.col = row, col
        else:
            self.row, self.col = -1, -1

        self.__draw_cursor()

    def __key_pressed(self, event):
        if self.game.game_over:
            return
        if self.row >= 0 and self.col >= 0 and event.char in "1234567890":
            self.game.puzzle[self.row][self.col] = int(event.char)
            self.col, self.row = -1, -1
            self.__draw_puzzle()
            self.__draw_cursor()
            if self.game.check_win():
                self.__draw_victory()

    def __clear_answers(self):
        self.game.start()
        self.canvas.delete("victory")
        self.__draw_puzzle()
Ejemplo n.º 51
0
	def __init__(self, sonarPort, motorPort):
		self.motor = MotorScanner(motorPort)
		self.sonar = Sonar(sonarPort)
		self.canvas = Canvas()
Ejemplo n.º 52
0
from Tkinter import *

sigma = 10.
r = 28.
b = 8/3.

def lorenz(v,t):
    x,y,z = v
    return [ sigma*(y-x) , r*x-y-x*z , x*y-b*z ]

t = linspace(0,50,10000)
v = [5,5,0]
res = odeint(lorenz,v,t)
plot(res[:,0],res[:,1])
show()

i = 0



screen = Tk()
wd,ht = screen.winfo_screenwidth(),screen.winfo_screenheight()
screen.geometry("%dx%d+0+0"%(wd,ht))
canv = Canvas(screen,height=ht,width=wd,background="black")
canv.pack()
update()
screen.mainloop()



Ejemplo n.º 53
0
class Plot(object):
    '''
    A canvas will be created where the selected values will be plotted as lines, with the best fitting scale.
    
    Initial version by:
        Michel Heiniger and Sandra Lang
    
    Latest source code can be found at:
        https://github.com/nebelriss/FluidX
    '''
    
    
    def __init__(self, master, frame, sw, sh):
        '''
        Constructor for the plot area.
        '''
        # initialization of 
        self.sw = sw
        self.sh = sh
        self.frame = frame
        
        # empty value list
        self.value_list = []
        
        # canvas area where the value lines and the coordinate system
        self.canvas = Canvas(self.frame, bg = "white")
        self.canvas.pack(expand = YES, fill = BOTH)
        
        #if the used os is a windows or a mac, they need a factor 1.5 for the y-axis
        if os.name == "nt":
            self.win_osx_factor = 1.5
        elif os.name == "mac":
            self.win_osx_factor = 1.5
            
        # if its a linux machine factor is 1           
        else:
            self.win_osx_factor = 1
        
        
        
    def createCoordSystem(self):
        '''
        This creates the coordinate system with a given max value for x,y axis.
        '''
        # Interval for the numbers 
        self.xInterval = 2
        self.yInterval = 0.2
        
        
        # delete all canvas with the tag "text"
        self.canvas.delete("text")                
        
        
        # draw axis lines
        self.canvas.create_line(self.sw-315, self.sh-150, 50, self.sh-150, fill = "black", width = 1)
        self.canvas.create_line(70, self.sh-130, 70, 70, fill = "black", width = 1)
        
        
        # text for Axis
        y = 'Y-Axis'
        x = 'X-Axis'
        # write the text at the right position
        self.canvas.create_text(70,40, text= y, tag = "text")
        self.canvas.create_text(self.sw-315,self.sh-120, text= x, tag = "text")
        
        
        # numbers for x and y axis
        maximumx = ((self.xMax) + 2) / self.xInterval
        maximumy = ((self.yMax) + 1) / self.yInterval
        
        
        # loop to write the numbers under the axis line and draw the separation lines for the x-axis
        for i in range(int(maximumx)):
            x = 70 + (i * self.dist_x * self.xInterval)
            self.canvas.create_line(x,self.sh-150,x,self.sh-155, width = 2)
            self.canvas.create_text(x,self.sh-140, text='%d'% (i * self.xInterval), anchor=N, tag = "text")   
        
        # loop to write the numbers under the axis line and draw the separation lines for the x-axis      
        for i in range (int(maximumy)):
            y = self.sh-150-(i * self.dist_y * self.yInterval) * self.win_osx_factor  
            self.canvas.create_line(70,y,75,y, width = 2)
            self.canvas.create_text(45,y, text=str((i * self.yInterval)), anchor=W, tag = "text")
        
        
            
    def createline (self, meta, values, idx, sel_idx, colors):
        '''
        Fist the given values are written in a list with the index number of the listbox and the selected items.
        '''
        # remove all lines with the tag "plot"
        self.canvas.delete("plot")
        
        
        # overwrite values with the given index with none
        try:
            self.value_list[idx][1] = None
        except IndexError:
            print "Index Error - List out of range"
  

        # write values in the list
        self.value_list[idx][1] = values
        self.value_list[idx][2] = sel_idx
        
        
        # The zero-point in the coordinate system
        xZeroTotal = 70
        yZeroTotal = self.sh-150
        
        # get the max value
        self.getMax(self.value_list)
        
           
        # draw lines with the selected values
        # read every row of the value_list
        for row in self.value_list:
            # write row to a different variable because I had to build a for loop like this (for row in row:)
            values = row[1]
            
            # get the value with the index 2 in each row
            for item in row[2]:

                for row in values:
                    endValue = row
                    
                    # setting zeroTotal to zero
                    xZero = xZeroTotal
                    yZero = yZeroTotal
                    # setting point to zero for the reason the line begins at the zero point
                    xPoint = xZero
                    yPoint = yZero                    

                    
                    # write xValue an yValue for the right selection
                    for row in endValue:
                        if item[0] == '1':
                            xValue = row[0]
                            yValue = row[6] 
                        elif item[0] == '2':
                            xValue = row[0]
                            yValue = row[7]
                        elif item[0] == '3':
                            xValue = row[1]
                            yValue = row[6]
                        elif item[0] == '4':
                            xValue = row[1]
                            yValue = row[7] 
                        elif item[0] == '5':
                            xValue = row[2]
                            yValue = row[6]
                        elif item[0] == '6':
                            xValue = row[2]
                            yValue = row[7]                                                                                                                                        
                        else:
                            pass
                        
                        # setting color for the line
                        color = colors[idx][int(item[0]) - 1]
                        
                        # calculating x,y points on the screen
                        xPoint = (xValue * self.dist_x) + 70
                        yPoint = self.sh - ((yValue * self.dist_y) + 150) * self.win_osx_factor
                        
                        # drawing line
                        self.canvas.create_line(xZero, yZero, xPoint, yPoint, fill=color, width = 3, tag = "plot")

                        self.canvas.create_oval(xPoint - 4, yPoint - 4, xPoint + 4, yPoint + 4, fill = color, outline = color, tag = "plot")
                        
                        # setting x,y points as new zero points
                        xZero = xPoint
                        yZero = yPoint
                        

        
    def createlist(self, idx):
        '''
        adding new index to the list with two empty fields
        '''
        self.value_list.append([idx])
        self.value_list[idx].append(None)
        self.value_list[idx].append(None)
        


        
        
        
    def getMax(self, value_list):
        '''
        This method is trying to find the max value for the scale grid.
        '''
        # setting max values to zero to find out the highest value
        self.xMax = 0
        self.yMax = 0

                        
        # get values
        for row in value_list:
            values = row[1]
            for row in values:
                endValue = row
                for row in endValue: 
                    
                    # check for max value in the x-axis                                                 
                    for i in range(1,3):
                        if self.xMax < row[i]:
                            self.xMax = row[i]
                    
                    # check for max value in the y-axis
                    for i in range(6,7):
                        if self.yMax < row[i]:
                            self.yMax = row[i]


        # calculating the distance between     
        self.dist_x = (self.sw - 400) / self.xMax
        self.dist_y = (self.sh - 500) / self.yMax       
        self.createCoordSystem()
        
Ejemplo n.º 54
0
class woyDraw:
    
    def __init__(self,ww,wh,root=NONE):

        self.xmin = 0
        self.xmax = ww
        self.ymin = wh
        self.ymax = 0
        
        if root==NONE:
            self.tk=Tk()
        else:
            self.tk = Toplevel(root)
        if ww <= 0.0:
            raise "<woyDraw - init> Fehler - Breite der Zeichenfläche muss > 0 sein!"
        else:
            self.ww = ww
        if wh <= 0.0:
            raise "<woyDraw - init> Fehler - Höhe der Zeichenfläche muss > 0 sein!"
        else:
            self.wh = wh       

    def close(self):
        self.tk.destroy()

    def settitle(self, title):
        self.title = title

    def font(self, setfont):
        self.font = setfont

    def transform(self, myDraw):
        for i in myDraw:
            i[0] = self.ww * (i[0] - self.xmin)/(self.xmax-self.xmin)
            i[1] = self.wh * (i[1] - self.ymax)/(self.ymin-self.ymax)           
        return myDraw
            
    def area(self, xmin,xmax,ymin,ymax):
        
        if xmin==xmax:
            raise "<woyDraw - area> Fehler - xmin darf nicht gleich xmax sein!"
        else:
            self.xmin = xmin
            self.xmax = xmax
        if ymin==ymax:
            raise "<woyDraw - area> Fehler - ymin darf nicht gleich ymax sein!"
        else:
            self.ymin = ymin
            self.ymax = ymax

    def show(self):
        self.tk.wm_title(self.title)
        self.board = Canvas(self.tk,relief=SUNKEN, bd=2, width=self.ww, height=self.wh)
        self.board.pack(fill=BOTH)
        Rectangle(self.board, (0,0), (self.ww,self.wh), fill="white", width=1)
        b = Button(self.tk, text="Close", font=self.font, command = self.close )
        b.pack()

    def draw(self,myDraw,myColor,myWidth):
        myDraw2 = self.transform(myDraw)
        Line(self.board,myDraw2,width=myWidth,fill=myColor)

    def rawdraw(self,myDraw,myColor,myWidth):
        Line(self.board,myDraw,width=myWidth,fill=myColor)
Ejemplo n.º 55
0
def C_line(args):
    global cursor_pos
    nextposition = (cursor_pos[0]+int(args[0]), cursor_pos[1]+int(args[1]))
    Canvas.create_line(cursor_pos[0], cursor_pos[1], nextposition[0], nextposition[1])
    cursor_pos = nextposition
Ejemplo n.º 56
0
class MainWindow(Systray):
    
    def __init__(self, app):
        """
        Create a main window for the given application.
        """
        defaultOptions["palette"] = app.palette()
        Systray.__init__(self)

        self.expansions = 0
        self.client = None
        self.server = None
        self.running = False
        self.recovery = False
        mainWidgets["main"] = self
        mainWidgets["app"] = app
        
        self.canvas = Canvas(self)
        mainWidgets["canvas"] = self.canvas

        self.tabWidget = TabWidget(self)
        mainWidgets["tab"] = self.tabWidget

        self.setCentralWidget(self.tabWidget)
        #self.setCentralWidget(self.canvas)
        
        self.createActions()
        self.createMenus()
        self.createToolBars()
        self.createStatusBar()
        self.createDockWindows()
        self.createConfigWindows()
        self.createPopupWindows()
        self.createProgressBar()
    
        self.newScene()
        
        self.debugWindow.hide()
        self.tm.hide()
        self.routes.hide()

        self.setVisible(True)
        self.center()
        self.saveLayout(environ["config"] + "defaultLayout")
        
        self.defaultLayout = True
        if options["restore"]:
            self.loadLayout()
            self.defaultLayout = False
            
        self.loadProject()        

    def center(self):
        """
        Center the window.
        """
        screen = QtGui.QDesktopWidget().screenGeometry()
        rect = self.geometry()
        self.move((screen.width()-rect.width())/2, (screen.height()-rect.height())/2)
        self.show()
    
    def getProject(self):
        """
        Return the project.
        """
        return self.project

    def startTutorial(self):
        """
        Start the interactive tutorial.
        """
        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append("You are already doing the tutorial!  If you would like to stop or restart, select 'Close' from the File menu now.")
            return

        if not self.closeTopology():
            return
        
        self.project = "Tutorial"
        self.filename = ""
        
        self.canvas = Tutorial(self)
        mainWidgets["canvas"] = self.canvas

        self.tabWidget.removeTab(0)
        self.tabWidget.addTab(self.canvas, "Tutorial")
        self.canvas.start()

        for nodeType in nodeTypes.keys():
            itemTypes = nodeTypes[nodeType]
            itemTypes[nodeType] = 0

        self.properties.clear()
        self.interfaces.clear()
        self.routes.clear()

        self.resetLayout(True)
        self.lockDocks()

    def lockDocks(self):
        """
        Lock the dock windows so they cannot be moved, closed or resized.
        """
        self.tm.hide()
        for dock in self.docks.values():
            dock.setFeatures(dock.NoDockWidgetFeatures)

    def unlockDocks(self):
        """
        Unlock the dock windows.
        """
        self.tm.show()
        for dock in self.docks.values():
            dock.setFeatures(dock.DockWidgetClosable | dock.DockWidgetMovable | dock.DockWidgetFloatable)
                             
    def faq(self):
        """
        Open the FAQ in the default browser.
        """
        olddir = os.getcwd()
        os.chdir(environ["doc"])
        loadpath = os.getcwd()
        os.chdir(olddir)

        if environ["os"] == "Windows":
            url = QtCore.QUrl("file:///" + loadpath + "/FAQ.html")
        else:
            url = QtCore.QUrl("file://" + loadpath + "/FAQ.html")
        QtGui.QDesktopServices.openUrl(url)

    def closeTopology(self):
        """
        Close the current topology.
        """
        if self.running:
            self.log.append("You cannot close a topology when one is still running!")
            return False

        scene = self.canvas.scene()
        if scene and scene.items():
            reply = QtGui.QMessageBox.warning(self, self.tr(Core.globals.PROG_NAME), self.tr("Save before closing?"), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel)
            if reply == QtGui.QMessageBox.Yes:
                if not self.saveTopology():
                    return False
            elif reply == QtGui.QMessageBox.No:
                pass
            else:
                return False
        
        if isinstance(mainWidgets["canvas"], Tutorial):
            self.canvas = Canvas(self)
            mainWidgets["canvas"] = self.canvas
            self.tabWidget.removeTab(0)
            self.tabWidget.addTab(self.canvas, "Default Project")
            self.project = ""
            self.unlockDocks()
                
        self.filename = ""
        scene = Scene(self.canvas)
        scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
        self.canvas.setScene(scene)
        self.expansions = 0
        
        for nodeType in nodeTypes.keys():
            itemTypes = nodeTypes[nodeType]
            itemTypes[nodeType] = 0

        self.properties.clear()
        self.interfaces.clear()
        self.routes.clear()
        
        return True

    def sendFile(self):
        """
        Start a process to select and send a file to the server.
        """
        if not self.server or self.server.poll() != None:
            self.log.append("Please start the server first!")
            return
        if not self.client or not self.client.isConnected():
            self.startClient()
            
        filename = self.loadFile("All Files (*.*)")
        if not filename:
            return
        
        self.sendWindow.setFilename(filename)
        self.sendWindow.show()
        
    def newScene(self):
        """
        Close the current topology and create a new one.
        """
        if self.running:
            self.log.append("You cannot create a new topology when one is still running!")
            return

        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append("You cannot create a new topology during the tutorial!")
            return

        if not self.closeTopology():
            return

        self.expandScene()

    def expandScene(self):
        """
        Expand the scene based on number of expansions.
        """
        x = 175 + self.expansions * 30
        y = 160 + self.expansions * 20
        scene = self.canvas.scene()
        item = QtGui.QGraphicsLineItem(-x, -y, x, y)
        scene.addItem(item)
        scene.removeItem(item)
        self.expansions += 1

    def newProject(self):
        """
        Create a new project for device sharing.
        """
        if self.running:
            self.log.append("You cannot create a new project when one is still running!")
            return

        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append("You cannot create a new project during the tutorial!")
            return
        
        filename = self.saveFile("gproj")
        if filename.isEmpty():
            return

        projectname = str(filename).split("/")[-1].strip(".gproj")
        from Core.Item import nodeTypes
        for nodeType in nodeTypes:
            if projectname.startswith(nodeType + "_"):
                self.popup.setWindowTitle("Invalid Project Name")
                self.popup.setText("You cannot name a project starting with the name of a device and underscore!")
                self.popup.show()
                return

        self.project = str(filename)
        file = QtCore.QFile(filename)
        if not file.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, self.tr("Save Error"),
                                      self.tr("Cannot write file %1:\n%2.")
                                      .arg(self.filename)
                                      .arg(file.errorString()))
            return
        
        out = QtCore.QTextStream(file)
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
        
        if options["username"]:
            out << "username="******"username"] + "\n"
        else:
            self.log.append("Warning, no username is specified!")
            
        if options["session"]:
            out << "session=" + options["session"] + "\n"
        elif options["server"]:
            out << "server=" + options["server"] + "\n"
        else:
            self.log.append("Warning, no server or session name is specified!")

        QtGui.QApplication.restoreOverrideCursor()

        self.tabWidget.addTab(self.canvas, projectname)

    def openProject(self):
        """
        Load an existing project for device sharing.
        """
        if self.running:
            self.log.append("You cannot open a project when one is still running!")
            return

        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append("You cannot open a project during the tutorial!")
            return
        
        filename = self.loadFile("GPROJ (*.gproj)")
        if filename.isEmpty():
            return

        self.project = str(filename)
        self.loadProject()

    def loadProject(self):
        """
        Load project file data into options.
        """

        if not self.project:
            self.tabWidget.addTab(self.canvas, "Default Project")
            return
        
        file = QtCore.QFile(self.project)
        if not file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, self.tr("Load Error"),
                                      self.tr("Cannot read file %1:\n%2.")
                                      .arg(self.project)
                                      .arg(file.errorString()))
            self.tabWidget.addTab(self.canvas, "Default Project")
            return
        
        _in = QtCore.QTextStream(file)
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

        while not _in.atEnd():
            line = str(_in.readLine())
            option, value = line.split("=", 1)
            options[option] = value
            
        self.configWindow.updateSettings()

        QtGui.QApplication.restoreOverrideCursor()
        projectname = self.project.split("/")[-1].strip(".gproj")
        self.tabWidget.addTab(self.canvas, projectname)

    def closeProject(self):
        """
        Close the current project.
        """
        if self.running:
            self.log.append("You cannot close a project when it is still running!")
            return

        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append("You cannot close a project during the tutorial!")
            return
        
        if self.tabWidget.count() == 1:
            self.tabWidget.addTab(self.canvas, "Default Project")
            self.project = ""
        else:
            self.tabWidget.removeTab(0)
        
    def export(self):
        """
        Open an export window to generate an image from the canvas.
        """
        self.exportWindow.show()
        
    def startBackend(self):
        """
        Start the backend server.
        """
        self.startServer()
        #self.startClient()

    def setRecovery(self, recovery):
        """
        Set the recovering state of the topology.
        """
        self.recovery = recovery
        
    def isRunning(self):
        """
        Returns whether a topology is running or not.
        """
        return self.running
    
    def startServer(self):
        """
        Start the server backend of gbuilder, which controls running topologies.
        """
        if self.server and self.server.poll() == None:
            self.log.append("A server is already running!")
            return
        
        base = "ssh -t " 
	if options["username"] :
		base += options['username'] + "@"
	base += options["server"]

        tunnel = " -L " + options["localPort"] + ":localhost:" + options["remotePort"]
        server = "bash -c -i 'gserver " + options["remotePort"] + "' || sleep 5"
        command = ""
        
        if environ["os"] == "Windows":
            startpath = environ["tmp"] + "gserver.start"
            try:
                startFile = open(startpath, "w")
                startFile.write("echo -ne \"\\033]0;gserver\\007\"\n")
                startFile.write(server)
                startFile.close()
            except:
                self.log.append("Failed to write to start file!")
                return
            
            command += "putty -"
            if options["session"]:
                command += "load " + options["session"] + " -l " + options["username"] + " -t"
            else:
                command += base
            command += tunnel + " -m \"" + startpath + "\""
        else:
            command += "xterm -T gserver -e " + base + tunnel + " \" " + server + "\""

        self.server = subprocess.Popen(str(command), shell=True)

    def startClient(self):
        """
        Start the client of gbuilder, which communicates with the server.
        """
        self.client = Client(self)
        self.client.connectTo("localhost", int(options["localPort"]), 10)
        #self.client.start()
        mainWidgets["client"] = self.client

    def compile(self):
        """
        Compile the current topology.
        """
        if self.running:
            self.log.append("You cannot compile a topology when one is still running!")
            return False

        if self.saveTopology() == False:
            return False
        
        scene = self.canvas.scene()
        compiler = Compiler(scene.items(), self.filename)
        xmlFile = compiler.compile()

        self.properties.display()
        self.interfaces.display()
        self.routes.display()
        
        if xmlFile:
            self.statusBar().showMessage(self.tr("Compiled '%1'").arg(xmlFile), 2000)
            return True
        else:
            self.statusBar().showMessage(self.tr("Compile failed"), 2000)
            return False

    def run(self):
        """
        Run the current topology.
        """
        if not self.server or self.server.poll() != None:
            self.log.append("Please start the server first!")
            return
        if not self.client or not self.client.isConnected():
            self.startClient()
            
        if self.isRunning() and not self.recovery:
            self.log.append("A topology is already running, please stop it first!")
            return

        scene = self.canvas.scene()
        items = scene.items()
        if items:
            if self.recovery:
                self.recovery = False
            elif options["autocompile"] and not self.compile():
                return
        else:
            self.log.append("Please create or load a topology first!")
            return

        options["elasticMode"] = False

        xmlFile = self.filename.replace(".gsav", ".xml")

        if not os.access(xmlFile, os.F_OK):
            self.log.append("Please compile the topology first!")
            return

        self.tm.show()
        
        #self.progressBar.setValue(0)
        self.client.process("file . " + xmlFile)
        self.client.send("init " + self.project.split("/")[-1].strip(".gproj"))
        self.client.send("canvas %d,%d" % (scene.width(), scene.height()))
        for item in items:
            if item.type == "Mobile" or item.type == "Wireless_access_point":
                x = item.pos().x()
                y = item.pos().y()
                self.client.send("mobile %s %d,%d" % (item.getName(), x, y))
        self.client.process("start " + xmlFile)

        self.running = True
        self.canvas.setAcceptDrops(False)
        scene = self.canvas.scene()
        scene.startRefresh()
        scene.clearSelection()
        
        self.properties.clear()
        self.interfaces.clear()
        self.routes.clear()
        
    def stop(self):
        """
        Stop the current running topology.
        """
        if not self.server or self.server.poll() != None:
            self.log.append("Please start the server first!")
            return
        if not self.client or not self.client.isConnected():
            self.startClient()

        if self.recovery:
            self.recovery = False
            
        scene = self.canvas.scene()
        activeDevices = False
        from Core.Device import Device
        for item in scene.items():
            if not isinstance(item, Device):
                continue
            if item.type == "Router":
                item.stop()
            if item.status:
                activeDevices = True

        if not activeDevices:
            self.stopped()
        elif not scene.isRefreshing():
            scene.startRefresh()
            
        self.client.process("stop")

    def stopped(self):
        """
        Handle a fully stopped topology.
        """
        self.running = False
        self.canvas.scene().stopRefresh()
        self.tm.hide()
        self.canvas.setAcceptDrops(True)
        
        olddir = os.getcwd()
        os.chdir(environ["tmp"])
        for tmpfile in os.listdir("."):
            if tmpfile.startswith("."):
                continue
            try:
                os.remove(tmpfile)
            except:
                continue
        os.chdir(olddir)

    def loadFile(self, filetype):
        """
        Load a file through a file dialog.
        """
        # Qt is very picky in the filename structure but python is not, so we use python
        # to form the correct path which will work for both Windows and Linux        
        olddir = os.getcwd()
        os.chdir(environ["sav"])
        loadpath = os.getcwd()
        os.chdir(olddir)
        
        filename = QtGui.QFileDialog.getOpenFileName(self,
                    self.tr("Choose a file name"), loadpath,
                    self.tr(filetype))

        return filename
        
    def loadTopology(self):
        """
        Load a topology.
        """
        if self.running:
            self.log.append("You cannot load a topology when one is still running!")
            return

        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append("You cannot load a topology during the tutorial!")
            return
        
        def loadIntoScene(line):
            scene = self.canvas.scene()
            itemType,arg = line.split(":")
            args = str(arg).strip("()").split(",")

            if itemType == "edge":
                source = scene.findItem(args[0])
                dest = scene.findItem(args[1])
                if source.type == "Mobile" or dest.type == "Mobile":
                    item = Wireless_Connection(source, dest)
                else:
                    item = Connection(source, dest)
                scene.addItem(item)
            else:
                devType, index = str(itemType).rsplit("_", 1)
                item = deviceTypes[devType]()
                item.setIndex(int(index))
                scene.addItem(item)
                item.setPos(float(args[0]), float(args[1]))
                item.nudge()

            return item

        def loadProperties(itemDict):
            currentInterfaceTarget = None
            currentRouteSubnet = None
            
            for item, properties in itemDict.iteritems():
                for line in properties:
                    count = 0
                    while line.find("\t") == 0:
                        line = line[1:]
                        count += 1

                    prop, value = line.split(":", 1)
                    if count == 1:
                        item.setProperty(prop, value)
                    elif count == 2:
                        currentInterfaceTarget = self.canvas.scene().findItem(value)
                    elif count == 3:
                        item.setInterfaceProperty(prop, value, currentInterfaceTarget)
                    elif count == 4:
                        currentRouteSubnet = value
                        item.addEntry("", "", value, currentInterfaceTarget)
                    elif count == 5:
                        item.setEntryProperty(prop, value, currentRouteSubnet, currentInterfaceTarget)

        filename = self.loadFile("GSAV (*.gsav)")
        if filename.isEmpty():
            return

        file = QtCore.QFile(filename)
        if not file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, self.tr("Load Error"),
                                      self.tr("Cannot read file %1:\n%2.")
                                      .arg(filename)
                                      .arg(file.errorString()))
            return

        self.newScene()
        self.filename = str(filename)

        _in = QtCore.QTextStream(file)
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

        itemDict = {}
        
        line = str(_in.readLine())
        lines = []
        while not _in.atEnd():
            item = loadIntoScene(line)
            line = str(_in.readLine())
            while line.find("\t") == 0:
                lines.append(line)
                line = str(_in.readLine())
            itemDict[item] = lines
            lines = []

        loadProperties(itemDict)
        
        QtGui.QApplication.restoreOverrideCursor()
        
        self.statusBar().showMessage(self.tr("Loaded '%1'").arg(filename), 2000)

    def saveFile(self, filetype):
        """
        Save a file through a file dialog.
        """
        olddir = os.getcwd()
        os.chdir(environ["sav"])
        savepath = os.getcwd()
        os.chdir(olddir)
        
        filename = QtGui.QFileDialog.getSaveFileName(self,
                    self.tr("Choose a file name"), savepath,
                    self.tr(filetype.upper() + " (*.%s)" % filetype))

        if filename.isEmpty():
            return filename
        
        if not filename.toLower().endsWith("." + filetype):
            filename += "." + filetype
        
        return filename
    
    def saveTopologyAs(self):
        """
        Save a topology under a given filename.
        """
        if not self.canvas.scene().items():
            self.log.append("There is nothing to save!")
            return False

        filename = self.saveFile("gsav")
        if filename.isEmpty():
            return False
            
        self.filename = str(filename)
        
        return self.saveTopology()
        
    def saveTopology(self):
        """
        Save a topology.
        """
        if not self.canvas.scene().items():
            self.log.append("There is nothing to save!")
            return False

        # for first time use
        if not self.filename:
            return self.saveTopologyAs()

        file = QtCore.QFile(self.filename)
        if not file.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, self.tr("Save Error"),
                                      self.tr("Cannot write file %1:\n%2.")
                                      .arg(self.filename)
                                      .arg(file.errorString()))
            return False
        
        out = QtCore.QTextStream(file)
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

        scene = self.canvas.scene()
        outstring = ""
        for item in scene.items():
            if isinstance(item, Node):
                outstring += item.toString()
        
        for item in scene.items():
            if isinstance(item, Edge):
                outstring += item.toString()

        out << outstring
        QtGui.QApplication.restoreOverrideCursor()
        
        self.statusBar().showMessage(self.tr("Saved '%1'").arg(self.filename), 2000)

        return True

    def copy(self):
        """
        Copy selected text from the log into the paste buffer.
        """
        self.log.copy()

    def config(self):
        """
        Open the options window.
        """
        self.configWindow.show()

    def arrange(self):
        """
        Rearrange the topology based on the distance between nodes.
        """
        if self.isRunning():
            self.log.append("Cannot arrange while running!")
            return

        if isinstance(mainWidgets["canvas"], Tutorial):
            mainWidgets["log"].append("Cannot arrange during the tutorial!")
            return
        
        options["elasticMode"] = not options["elasticMode"]
        
    def about(self):
        """
        Show the about window.
        """
        QtGui.QMessageBox.about(self, 
                                self.tr("About %s %s" 
                                    % (Core.globals.PROG_NAME,
                                       Core.globals.PROG_VERSION)),
                                self.tr("<b>%s %s</b><br>Written by Daniel Ng<br>under the supervision of Muthucumaru Maheswaran" 
                                    % (Core.globals.PROG_NAME, 
                                       Core.globals.PROG_VERSION)))
    
    def createActions(self):
        """
        Create the actions used in the menus and toolbars.
        """
        self.newSceneAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "new.png"), self.tr("&New"), self)
        self.newSceneAct.setShortcut(self.tr("Ctrl+N"))
        self.newSceneAct.setStatusTip(self.tr("Create a new topology"))
        self.connect(self.newSceneAct, QtCore.SIGNAL("triggered()"), self.newScene)

        self.closeAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "close.png"), self.tr("&Close"), self)
        self.closeAct.setShortcut(self.tr("Ctrl+W"))
        self.closeAct.setStatusTip(self.tr("Close the current topology"))
        self.connect(self.closeAct, QtCore.SIGNAL("triggered()"), self.closeTopology)
        
        self.loadAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "open.png"), self.tr("&Open..."), self)
        self.loadAct.setShortcut(self.tr("Ctrl+O"))
        self.loadAct.setStatusTip(self.tr("Load a topology"))
        self.connect(self.loadAct, QtCore.SIGNAL("triggered()"), self.loadTopology)
        
        self.saveAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "save.png"), self.tr("&Save..."), self)
        self.saveAct.setShortcut(self.tr("Ctrl+S"))
        self.saveAct.setStatusTip(self.tr("Save the current topology"))
        self.connect(self.saveAct, QtCore.SIGNAL("triggered()"), self.saveTopology)

        self.saveAsAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "save.png"), self.tr("&Save As..."), self)
        self.saveAsAct.setShortcut(self.tr("Ctrl+Shift+S"))
        self.saveAsAct.setStatusTip(self.tr("Save the current topology under a given filename"))
        self.connect(self.saveAsAct, QtCore.SIGNAL("triggered()"), self.saveTopologyAs)

        self.sendFileAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "send.png"), self.tr("&Send File..."), self)
        self.sendFileAct.setShortcut(self.tr("Ctrl+F"))
        self.sendFileAct.setStatusTip(self.tr("Choose a file to send to the server"))
        self.connect(self.sendFileAct, QtCore.SIGNAL("triggered()"), self.sendFile)
        
        self.exportAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "export.png"), self.tr("&Export..."), self)
        self.exportAct.setShortcut(self.tr("Ctrl+P"))
        self.exportAct.setStatusTip(self.tr("Export the current topology as an image"))
        self.connect(self.exportAct, QtCore.SIGNAL("triggered()"), self.export)

        self.copyAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "copy.png"), self.tr("&Copy"), self)
        self.copyAct.setShortcut(self.tr("Ctrl+C"))
        self.copyAct.setStatusTip(self.tr("Copy the selected text"))
        self.connect(self.copyAct, QtCore.SIGNAL("triggered()"), self.copy)

        self.compileAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "compile.png"), self.tr("&Compile"), self)
        self.compileAct.setShortcut(self.tr("Ctrl+E"))
        self.compileAct.setStatusTip(self.tr("Compile the current topology"))
        self.connect(self.compileAct, QtCore.SIGNAL("triggered()"), self.compile)
        
        self.runAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "run.png"), self.tr("&Run"), self)
        self.runAct.setShortcut(self.tr("Ctrl+R"))
        self.runAct.setStatusTip(self.tr("Run the current topology"))
        self.connect(self.runAct, QtCore.SIGNAL("triggered()"), self.run)

        self.stopAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "stop.png"), self.tr("&Stop"), self)
        self.stopAct.setShortcut(self.tr("Ctrl+D"))
        self.stopAct.setStatusTip(self.tr("Stop the current topology"))
        self.connect(self.stopAct, QtCore.SIGNAL("triggered()"), self.stop)

        self.startServerAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "startServer.png"), self.tr("&Start Server"), self)
        self.startServerAct.setShortcut(self.tr("Ctrl+T"))
        self.startServerAct.setStatusTip(self.tr("Start the server"))
        self.connect(self.startServerAct, QtCore.SIGNAL("triggered()"), self.startBackend)

        self.optionsAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "options.png"), self.tr("&Options"), self)
        self.optionsAct.setShortcut(self.tr("F2"))
        self.optionsAct.setStatusTip(self.tr("Show the options window"))
        self.connect(self.optionsAct, QtCore.SIGNAL("triggered()"), self.config)

        self.arrangeAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "arrange.png"), self.tr("&Arrange"), self)
        self.arrangeAct.setShortcut(self.tr("Ctrl+A"))
        self.arrangeAct.setStatusTip(self.tr("Arranges the current topology"))
        self.connect(self.arrangeAct, QtCore.SIGNAL("triggered()"), self.arrange)

        self.resetLayoutAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "layout.png"), self.tr("Reset Layout"), self)
        self.resetLayoutAct.setStatusTip(self.tr("Reset dock windows to the saved layout"))
        self.connect(self.resetLayoutAct, QtCore.SIGNAL("triggered()"), self.resetLayout)

        self.expandSceneAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "expand.png"), self.tr("Expand Scene"), self)
        self.expandSceneAct.setStatusTip(self.tr("Expand the scene for more space"))
        self.connect(self.expandSceneAct, QtCore.SIGNAL("triggered()"), self.expandScene)
        
        self.quitAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "exit.png"), self.tr("&Quit"), self)
        self.quitAct.setShortcut(self.tr("Ctrl+Q"))
        self.quitAct.setStatusTip(self.tr("Quit the application"))
        self.connect(self.quitAct, QtCore.SIGNAL("triggered()"), self.quit)

        self.newProjectAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "new.png"), self.tr("&New"), self)
        self.newProjectAct.setShortcut(self.tr("Ctrl+Shift+N"))
        self.newProjectAct.setStatusTip(self.tr("Create a new project"))
        self.connect(self.newProjectAct, QtCore.SIGNAL("triggered()"), self.newProject)

        self.openProjectAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "open.png"), self.tr("&Open"), self)
        self.openProjectAct.setShortcut(self.tr("Ctrl+Shift+O"))
        self.openProjectAct.setStatusTip(self.tr("Open an existing project"))
        self.connect(self.openProjectAct, QtCore.SIGNAL("triggered()"), self.openProject)

        self.closeProjectAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "close.png"), self.tr("&Close"), self)
        self.closeProjectAct.setShortcut(self.tr("Ctrl+Shift+W"))
        self.closeProjectAct.setStatusTip(self.tr("Close the current project"))
        self.connect(self.closeProjectAct, QtCore.SIGNAL("triggered()"), self.closeProject)
        
        self.tutorialAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "tutorial.png"), self.tr("&Tutorial"), self)
        self.connect(self.tutorialAct, QtCore.SIGNAL("triggered()"), self.startTutorial)

        self.faqAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "help.png"), self.tr("&FAQ"), self)
        self.connect(self.faqAct, QtCore.SIGNAL("triggered()"), self.faq)
        
        self.aboutAct = QtGui.QAction(QtGui.QIcon(environ["images"] + "giniLogo.png"), self.tr("&About"), self)
        self.aboutAct.setStatusTip(self.tr("Show the application's About box"))
        self.connect(self.aboutAct, QtCore.SIGNAL("triggered()"), self.about)

        self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self)
        self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box"))
        self.connect(self.aboutQtAct, QtCore.SIGNAL("triggered()"),
                     QtGui.qApp, QtCore.SLOT("aboutQt()"))

    def createMenus(self):
        """
        Create the menus with actions.
        """
        self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
        self.fileMenu.setPalette(defaultOptions["palette"])
        self.fileMenu.addAction(self.newSceneAct)
        self.fileMenu.addAction(self.loadAct)
        self.fileMenu.addAction(self.saveAct)
        self.fileMenu.addAction(self.saveAsAct)
        self.fileMenu.addAction(self.sendFileAct)
        self.fileMenu.addAction(self.exportAct)
        self.fileMenu.addAction(self.closeAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.quitAct)

        self.projectMenu = self.menuBar().addMenu(self.tr("&Project"))
        self.projectMenu.setPalette(defaultOptions["palette"])
        self.projectMenu.addAction(self.newProjectAct)
        self.projectMenu.addAction(self.openProjectAct)
        self.projectMenu.addAction(self.closeProjectAct)
        
        self.editMenu = self.menuBar().addMenu(self.tr("&Edit"))
        self.editMenu.setPalette(defaultOptions["palette"])
        self.editMenu.addAction(self.copyAct)
        self.editMenu.addAction(self.arrangeAct)
        self.editMenu.addAction(self.resetLayoutAct)
        self.editMenu.addAction(self.expandSceneAct)

        self.runMenu = self.menuBar().addMenu(self.tr("&Run"))
        self.runMenu.setPalette(defaultOptions["palette"])
        self.runMenu.addAction(self.compileAct)
        self.runMenu.addAction(self.runAct)
        self.runMenu.addAction(self.stopAct)
        self.runMenu.addAction(self.startServerAct)
        
        self.configMenu = self.menuBar().addMenu(self.tr("&Config"))
        self.configMenu.setPalette(defaultOptions["palette"])
        self.configMenu.addAction(self.optionsAct)
        
        self.menuBar().addSeparator()
        
        self.helpMenu = self.menuBar().addMenu(self.tr("&Help"))
        self.helpMenu.setPalette(defaultOptions["palette"])
        self.helpMenu.addAction(self.tutorialAct)
        self.helpMenu.addAction(self.faqAct)
        self.helpMenu.addAction(self.aboutAct)
        self.helpMenu.addAction(self.aboutQtAct)

    def createPopupMenu(self):
        """
        Customize the popup menu so that it is visible.
        """
        popupMenu = QtGui.QMainWindow.createPopupMenu(self)
        popupMenu.setPalette(defaultOptions["palette"])
        return popupMenu

    def createToolBars(self):
        """
        Create the toolbars with actions.
        """
        self.fileToolBar = self.addToolBar(self.tr("File"))
        self.fileToolBar.addAction(self.newSceneAct)
        self.fileToolBar.addAction(self.loadAct)
        self.fileToolBar.addAction(self.saveAct)
        self.fileToolBar.addAction(self.sendFileAct)
        self.fileToolBar.addAction(self.exportAct)
        self.fileToolBar.addAction(self.closeAct)
        
        self.editToolBar = self.addToolBar(self.tr("Edit"))
        self.editToolBar.addAction(self.copyAct)
        self.editToolBar.addAction(self.resetLayoutAct)
        self.editToolBar.addAction(self.expandSceneAct)

        self.runToolBar = self.addToolBar(self.tr("Run"))
        self.runToolBar.addAction(self.compileAct)
        self.runToolBar.addAction(self.runAct)
        self.runToolBar.addAction(self.stopAct)
        self.runToolBar.addAction(self.startServerAct)
        
    def createStatusBar(self):
        """
        Create the status bar.
        """
        self.statusBar().showMessage(self.tr("Ready"))

    def createProgressBar(self):
        """
        Create the progress bar.
        """
        self.progressBar = QtGui.QProgressBar()
        self.progressBar.setRange(0, 10000)
        self.progressBar.setValue(0)

        self.statusBar().addPermanentWidget(self.progressBar)
        self.progressBar.show()

    def getDeviceCount(self, alive=False):
        """
        Return the interfaceable device count, or the alive ones if alive=True.
        """
        from Core.Interfaceable import Interfaceable
        
        count = 0.0
        for item in self.canvas.scene().items():
            if isinstance(item, Interfaceable):
                if alive and item.status in ("", "dead"):
                    continue
                count += 1.0

        return count

    def updateProgressBar(self):
        """
        Update the progress bar.
        """
        maxVal = self.progressBar.maximum()
        finalVal = (self.getDeviceCount(True) / self.getDeviceCount()) * maxVal

        if finalVal < 0:
            finalVal = 0
            
        self.progressBar.setValue(finalVal)

        if finalVal == 0:
            return True

        return False
    
    def createConfigWindows(self):
        """
        Create the options window.
        """
        self.configWindow = ConfigDialog(self)

    def createDockWindows(self):
        """
        Create the dock windows: dropbar, log, properties, interfaces, routes.
        """
        self.log = LogWindow(self.tr("Log"), self)
        self.log.append("Welcome to %s %s!\n" 
                % (Core.globals.PROG_NAME, Core.globals.PROG_VERSION))
        self.log.setGeometry(QtCore.QRect(0, 0, 800, 114))
        mainWidgets["log"] = self.log

        self.dropbar = DropBar(self.tr("Components"), self)
        self.dropbar.setGeometry(QtCore.QRect(0, 0, 129, 390))
        mainWidgets["drop"] = self.dropbar
        
        self.properties = PropertiesWindow(self)
        self.properties.setWindowTitle("Properties")
        mainWidgets["properties"] = self.properties

        self.interfaces = InterfacesWindow(self)
        self.interfaces.setWindowTitle("Interfaces")
        mainWidgets["interfaces"] = self.interfaces
        
        self.routes = RoutesWindow(self.interfaces, self)
        self.routes.setWindowTitle("Routes")
        mainWidgets["routes"] = self.routes
        
        self.tm = TaskManagerWindow(self)
        self.tm.setWindowTitle("Task Manager")
        mainWidgets["tm"] = self.tm
        
        self.debugWindow = QtGui.QDockWidget(self.tr("Debug Window"))
        self.debugWindow.setWidget(DebugWindow(self))
        
        self.docks = {"Components":self.dropbar, "Log":self.log, "Properties":self.properties, "Interfaces":self.interfaces, "Routes":self.routes, "Task Manager":self.tm}
        
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dropbar)
        self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.log)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.properties)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.interfaces)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.routes)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.tm)

        self.tm.setFloating(True)
        self.routes.setFloating(True)
        self.debugWindow.setFloating(True)

    def createPopupWindows(self):
        """
        Create the different popup windows.
        """
        self.exportWindow = ExportWindow(self)
        self.sendWindow = SendDirectoryWindow(self)
        
        self.popup = QtGui.QMessageBox(self)
        self.popup.setIcon(QtGui.QMessageBox.Warning)
        self.popup.setWindowIcon(QtGui.QIcon(environ["images"]+"giniLogo.png"))
        mainWidgets["popup"] = self.popup

    def keyPressEvent(self, event):
        """
        Handle specific shortcut keys.
        """
        key = event.key()
        scene = self.canvas.scene()
        if key == QtCore.Qt.Key_Escape:
            scene.clearSelection()
        elif key == QtCore.Qt.Key_Delete:
            for item in scene.selectedItems():
                item.delete()
        elif key == QtCore.Qt.Key_C:
            items = scene.items()
            if not items:
                return
            selected = scene.selectedItems()
            scene.clearSelection()
            if selected:
                index = items.index(selected[0])
                items[index - 1].setSelected(True)
            else:
                items[0].setSelected(True)
        elif key == QtCore.Qt.Key_H:
            for dock in self.docks.values():
                dock.setFloating(not dock.isFloating())
        elif key == QtCore.Qt.Key_F10:
            self.debugWindow.show()
Ejemplo n.º 57
0
k = fft(x)

# definition to calculat the kinetic energie in the k-room
def B(k,t):
    return exp(t*complex(0.,1.)*k*k/2.)

 # definition to calculate the potential in the real room
def pot(x):
    return pow(abs(x*x-1),2)/2.
def A(x,t):
    return exp(t*complex(0.,1.)*(pot(x))/2.)

screen = Tk()
wd,ht = screen.winfo_screenwidth(),screen.winfo_screenheight()
screen.geometry("%dx%d+0+0"%(wd,ht))
canv = Canvas(screen,height=ht,width=wd,background="black")
canv.pack()

# some scale factor to enlarge the animation
scaley = 150
scalex = 140

# define the time
for t in linspace(0.1,0.5,2000):
#    calculate A and B
    expA = map(lambda x: A(x,t),x)
    expB = map(lambda k: B(k,t),k)

#    tranform back the k-room into the real room
    expB = ifft(expB)
#    calculate the time depended hamiltonien
Ejemplo n.º 58
0
    
    return (beta_gamma,alpha_gamma)


# in this definition is the repaint of the triangle and the decision if is a --
# green or red dot
def clicked_point(event):
    canv.delete(ALL)
    trian(a,b,c)
    x0 = event.x
    y0 = event.y
    p = complex(x0,y0)
    x = faktor(p)
    if (( 1>= x[0][0] >=0) and (x[0][1]>=0)):
        canv.create_oval(x0-4,y0-4,x0+4,y0+4,fill='green')
    else:
        if (( 1>= x[1][0] >=0) and (x[1][1]>=0)):
            canv.create_oval(x0-4,y0-4,x0+4,y0+4,fill='green')
        else:
            canv.create_oval(x0-4,y0-4,x0+4,y0+4,fill='red')
    

root = Tk()
canv = Canvas(root,width=size,height=size)
trian(a,b,c)
canv.bind("<Button-1>",clicked_point)
canv.bind("<B1-Motion>",clicked)
canv.pack()
root.mainloop()

Ejemplo n.º 59
0
 def __construct__(self):
   #extract and properly indent python content
   script = Canvas.normalize_python(node=self)
   #run th' junks
   try:  exec script in self.parent.__dict__
   except Exception, msg: Events.Error(self, msg, "bad syntax in python block")