Example #1
0
    def __init__(self, buf):
        self.edit_only = buf.worksheet.edit_only

        if not self.edit_only:
            buf.worksheet.sig_chunk_inserted.connect( self.on_chunk_inserted )
            buf.worksheet.sig_chunk_changed.connect( self.on_chunk_changed )
            buf.worksheet.sig_chunk_status_changed.connect( self.on_chunk_status_changed )
            buf.worksheet.sig_chunk_deleted.connect( self.on_chunk_deleted )
            buf.worksheet.sig_state.connect( self.on_notify_state )

            # Track changes to update completion
            buf.connect_after('insert-text', self.on_after_insert_text)
            buf.connect_after('delete-range', self.on_after_delete_range)
            buf.connect_after('end-user-action', self.on_after_end_user_action)

            self.__inserted_in_user_action = False
            self.__deleted_in_user_action = False

        if not self.edit_only:
            self.sidebar = Sidebar()
        else:
            self.sidebar = None

        buf.connect('add-custom-result', self.on_add_custom_result)
        buf.connect('add-sidebar-results', self.on_add_sidebar_results)
        buf.connect('remove-sidebar-results', self.on_remove_sidebar_results)
        buf.connect('pair-location-changed', self.on_pair_location_changed)
            
        gtk.TextView.__init__(self, buf)
        if not self.edit_only:
            self.set_border_window_size(gtk.TEXT_WINDOW_LEFT, LEFT_MARGIN_WIDTH)
        self.set_left_margin(2)

        # Attach a "behavior object" to the view which, by ugly hacks, makes it
        # do simply and reasonable things for cut-and-paste and DND
        sanitize_textview_ipc.sanitize_view(self)

        self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK)

        self.__completion_popup = CompletionPopup(self)
        self.__doc_popup = DocPopup()
        self.__mouse_over_object = None
        self.__mouse_over_timeout = None

        self.__mouse_over_start = buf.create_mark(None, buf.get_start_iter(), True)

        self.__arg_highlight_start = None
        self.__arg_highlight_end = None
        buf.connect('mark-set', self.on_mark_set)

        self.__cursor_chunk = None
        self.__scroll_to_result = False
        self.__scroll_to = buf.create_mark(None, buf.get_start_iter(), True)
        self.__scroll_idle = None

        self.__update_sidebar_positions_idle = 0
        self.__pixels_below_buffer = 0
        self.__last_chunk = None

        self.connect('destroy', self.on_destroy)
Example #2
0
    def __init__(self):
        Gtk.Window.__init__(self)
        self.connect("destroy", self.on_quit)
        self.set_default_size(1000, 600)
        self.load_css()

        header_bar = Gtk.HeaderBar()
        header_bar.set_show_close_button(True)
        header_bar.props.title = "TVTracker"

        search_button = Gtk.ToggleButton()
        search_icon = Gtk.Image.new_from_icon_name("edit-find-symbolic", 4)

        search_button.add(search_icon)
        header_bar.pack_start(search_button)
        self.set_titlebar(header_bar)

        self.store = Store()

        box = Gtk.Box(Gtk.Orientation.HORIZONTAL)

        self.sidebar = Sidebar(self.store, search_button)
        self.sidebar.connect("notify::selected-show",
                             self.on_navigation_change)

        separator = Gtk.Separator()
        self.show_info = ShowInfo(self.store)
        self.show_info.connect("subscription_changed",
                               self.on_subscription_change)

        box.pack_start(self.sidebar, False, False, 0)
        box.pack_start(separator, False, False, 0)
        box.pack_start(self.show_info, True, True, 0)
        self.add(box)
Example #3
0
def build():
    ########sizes
    mergins = 20
    win_size = (800, 700)
    top_size = (win_size[0] - 2 * mergins, 30)
    side_size = (100, win_size[1] - top_size[1] - 2 * mergins)
    word_size = (win_size[0] - mergins * 2 - side_size[0], 80)

    #####coordinates
    top_cord = (mergins, mergins)
    side_cord = (mergins, mergins + top_size[1])
    word_cord = (side_size[0] + mergins, mergins + top_size[1])
    #####initializing
    pygame.init()
    screen = pygame.display.set_mode(win_size)
    #####
    buttons = [
        Button(text="Quit"),
        Button(text="Setup"),
        Button(text="Depth")
    ]
    side_bar = Sidebar(side_cord,
                       w=side_size[0],
                       h=side_size[1],
                       buttons=buttons)
    #####
    top_bar = topbar.topBar(top_size, pos=top_cord)
    #####
    word_bar = topbar.word(word_size, "word", pos=word_cord)
    clock = pygame.time.Clock()

    #####
    exit = False
    while not exit:
        e = pygame.event.wait()
        if e.type == pygame.QUIT:
            exit = True

        cntnr = pygame.Surface(
            (win_size[0] - 2 * mergins + 4, win_size[1] - 2 * mergins + 4))
        ####
        import random
        r = random.randint(23, 150)
        g = random.randint(23, 150)
        b = random.randint(23, 150)
        ####
        cntnr.fill((r, g, b))
        side_surf = side_bar.draw_buttons()
        screen.blit(cntnr, (mergins - 2, mergins - 2))
        screen.blit(top_bar, top_cord)
        screen.blit(side_surf, side_cord)
        screen.blit(word_bar, word_cord)
        pygame.display.update()
        clock.tick(40)

    pygame.quit()
Example #4
0
  def testLinks(self):
    """Make sure all the links are pointed to the correct paths."""
    sidebar = Sidebar(self.driver)

    home_link = sidebar.GetLink(sidebar.HOME_LINK)
    self.assertEquals(PATHS['landing_page_path'],
                      home_link.get_attribute('data-href'))

    users_link = sidebar.GetLink(sidebar.USERS_LINK)
    self.assertEquals(PATHS['user_page_path'],
                      users_link.get_attribute('data-href'))

    proxy_servers_link = sidebar.GetLink(sidebar.PROXY_SERVERS_LINK)
    self.assertEquals(PATHS['proxy_server_list'],
                      proxy_servers_link.get_attribute('data-href'))

    setup_link = sidebar.GetLink(sidebar.SETUP_LINK)
    self.assertEquals(PATHS['setup_oauth_path'],
                      setup_link.get_attribute('data-href'))

    sync_notifications_link = sidebar.GetLink(sidebar.SYNC_NOTIFICATIONS_LINK)
    self.assertEquals(PATHS['sync_top_level_path'],
                      sync_notifications_link.get_attribute('data-href'))

    logout_link = sidebar.GetLink(sidebar.LOGOUT_LINK)
    self.assertEquals(PATHS['logout'], logout_link.get_attribute('data-href'))
Example #5
0
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.heading = tk.Label(self,
                                text="Products",
                                background="lightgrey",
                                pady="5")
        self.heading.pack(side="top", fill="x")
        self.sidebar = Sidebar(self, "Products")
        self.sidebar.pack(side="left", fill="y")
        self.main = tk.Frame(master=self)
        self.productsList = createListFrame(self.main, "Products",
                                            productModule.getAllProducts(),
                                            "No Products", "Change Product",
                                            self.changeProduct, [])

        self.productAdd = tk.Frame(master=self.main, padx=30, pady=100)
        self.productAddInit()
        self.switchMain("Product List")
Example #6
0
    def __init__(self):
        QPlainTextEdit.__init__(self)
        self.position_margin = QFontMetricsF(
            self.document().defaultFont()).width("#") * 80
        # Margin line
        self._margin = False
        # Sidebar
        self.sidebar = Sidebar(self)
        # Highlight current line
        self._color_current_line = QColor('lightblue')
        self._alpha_current_line = self._color_current_line.setAlpha(50)
        # Connection
        self.connect(self, SIGNAL("blockCountChanged(int)"),
                     self.sidebar.update_area_width)
        self.connect(self, SIGNAL("updateRequest(const QRect&, int)"),
                     self.sidebar.update_area)
        self.connect(self, SIGNAL("cursorPositionChanged()"),
                     self._highlight_current_line)

        self._highlight_current_line()
Example #7
0
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.heading = tk.Label(self,
                                text="Invoices",
                                background="lightgrey",
                                pady="5")
        self.heading.pack(side="top", fill="x")
        self.sidebar = Sidebar(self, "Invoices")
        self.sidebar.pack(side="left", fill="y")
        self.main = tk.Frame(master=self)
        self.invoicesList = tk.Frame()
        self.updateList("unpaid")

        self.invoiceAdd = tk.Frame(master=self.main, padx=30, pady=30)
        self.invoiceAddInit()
        self.products = {}
        self.productList = tk.Frame(master=self.main, padx=30, pady=30)
        self.invoiceProductList()
        self.switchMain("Current Invoices")
Example #8
0
  async def create_html(resource: str) -> str:
    template_uri = HTML_PATH_MAPPINGS[resource]
    main_template_task = asyncio.create_task(fetch_file_txt(file=template_uri, metric=MAIN_SITE_METRIC, from_disk=True))
    sidebar_task = asyncio.create_task(Sidebar(template_uri=os.environ['SIDEBAR_URI']).get())
    main_injections = ASSET_REPLACEMENTS
    main_template = await main_template_task
    main_html = inject(main_template, main_injections)
    sidebar_html = await sidebar_task

    html = main_html.replace('{SIDEBAR_ITEMS}', sidebar_html)

    return html
Example #9
0
    def __init__(self, s):
        self.board_ = Board(s.boardsize_)

        self.robots_ = []
        for i in range(s.robots_):
            self.robots_.append(
                Robot(COLORS[i], rd(s.boardsize_), rd(s.boardsize_)))
        Robot.validate_positions(self.board_, self.robots_)

        self.target_ = Target(s.boardsize_, self.board_, self.robots_)

        if (s.test_rounds_ > 0):
            self.test_rounds_ = s.test_rounds_
        else:
            self.test_rounds_ = 0

        self.players_ = s.assign_players()

        self.graphics_ = GraphicalBoard(s.boardsize_)
        self.sidebar_ = Sidebar(self.graphics_, self.players_)
        self.games_to_win_ = 7
Example #10
0
	def __init__(self, image, master=None ):
		super().__init__(master)

		self.master = master	
		self.imagePath = image
		self.resize = True

		self.canvas_config()
		self.master.width = self.width
		self.master.height = self.height

		sidebar = Sidebar(self.master, self.canvas)
		self.keybinds()
Example #11
0
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.heading = tk.Label(self,
                                text="Clients",
                                background="lightgrey",
                                pady="5")
        self.heading.pack(side="top", fill="x")
        self.sidebar = Sidebar(self, "Clients")
        self.sidebar.pack(side="left", fill="y")
        self.main = tk.Frame(master=self)

        self.clientList = createListFrame(self.main, "Clients",
                                          clientModule.get_all_clients(),
                                          "No Clients", "See Invoices",
                                          self.clientInvoiceView, [])

        self.clientAdd = tk.Frame(master=self.main, padx=30, pady=100)
        self.clientAddInit()

        self.clientView = tk.Frame(master=self.main)

        self.switchMain("Client List")
Example #12
0
 def draw_initial_board(self,board):
     #clear any previous game state
     self.screen.fill(self.background)  
     
     #sidebar - check if already exists in case of board reset
     if hasattr(self, 'sidebar'):
         self.sidebar.__init__(self,board)
     else:
         self.sidebar=Sidebar(self,board)        
     
     #draw
     for i in range(board.gridsize):
         for j in range(board.gridsize):
             self.screen.blit(self.floor,
                         (self.wallsize+i*(self.tilesize+self.wallsize),
                          self.wallsize+j*(self.tilesize+self.wallsize)))
     
     #set walls
     for i in range(board.boardsize):
         for j in range(board.boardsize):
             if board.boardstate[i,j]==1:
                 #horizontal, vertical or gap?
                 if i%2==0:
                     if j%2==0:
                         #gap
                         self.screen.blit(self.wall_c,
                                          (getXYOffset(i,j,self)))
                     else:
                         self.screen.blit(self.wall_h,
                                          (getXYOffset(i,j,self)))
                 else:
                     self.screen.blit(self.wall_v,
                                      (getXYOffset(i,j,self)))
                     
     #draw flag
     self.redraw_flag(board)
             
     #draw robot(s) at their turn start positions, which should be same as current in all cases
     self.robot_rects={}
     for colour in board.robot_colours:
         self.screen.blit(self.robots[colour],getXYGridOffset(board.robots[colour].position[0],board.robots[colour].position[1],self))
         self.robot_rects[colour]=self.robots[colour].get_rect()
         self.robot_rects[colour]=self.robot_rects[colour].move(getXYGridOffset(board.robots[colour].position[0],board.robots[colour].position[1],self))
     
     pygame.display.flip()
Example #13
0
    def initUI(self):
        self.setWindowTitle('Chess')
        self.resize(700, 500)

        layout = QHBoxLayout()

        playingFiled = Board()
        playingFiled.setObjectName("boardPlayer")
        playingFiled.createBord()
        sidebar = Sidebar()

        layout.addWidget(playingFiled,
                         3)  # Takes 3 times more space than sidebar
        layout.addWidget(sidebar, 1)

        self.setCentralWidget(QWidget())
        self.centralWidget().setLayout(layout)

        playingFiled.playerChanged.connect(sidebar.TimePanel.boardSays)
        self.show()
Example #14
0
    def __init__(self):
        QPlainTextEdit.__init__(self)
        self.position_margin = QFontMetricsF(
            self.document().defaultFont()).width("#") * 80
        # Margin line
        self._margin = False
        # Sidebar
        self.sidebar = Sidebar(self)
        # Highlight current line
        self._color_current_line = QColor('lightblue')
        self._alpha_current_line = self._color_current_line.setAlpha(50)
        # Connection
        self.connect(self, SIGNAL("blockCountChanged(int)"),
                    self.sidebar.update_area_width)
        self.connect(self, SIGNAL("updateRequest(const QRect&, int)"),
                    self.sidebar.update_area)
        self.connect(self, SIGNAL("cursorPositionChanged()"),
                    self._highlight_current_line)

        self._highlight_current_line()
Example #15
0
class ClientsView(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.heading = tk.Label(self,
                                text="Clients",
                                background="lightgrey",
                                pady="5")
        self.heading.pack(side="top", fill="x")
        self.sidebar = Sidebar(self, "Clients")
        self.sidebar.pack(side="left", fill="y")
        self.main = tk.Frame(master=self)

        self.clientList = createListFrame(self.main, "Clients",
                                          clientModule.get_all_clients(),
                                          "No Clients", "See Invoices",
                                          self.clientInvoiceView, [])

        self.clientAdd = tk.Frame(master=self.main, padx=30, pady=100)
        self.clientAddInit()

        self.clientView = tk.Frame(master=self.main)

        self.switchMain("Client List")

    #Creating a view of the invoices of clients
    def clientInvoiceView(self, client_id):
        client = clientModule.getClient(client_id)
        self.clientView = createListFrame(
            self.main, client["CustomerName"],
            invoiceModule.getInvoices(client_id), "No Invoices", "Pay Invoice",
            lambda: invoiceModule.payInvoice(client_id), ["ClientID"])
        self.switchMain("Client View")

    #creating a view of the form for adding clients
    def clientAddInit(self):
        lbl_name = tk.Label(master=self.clientAdd, text="Name")
        ent_name = tk.Entry(master=self.clientAdd)
        lbl_email = tk.Label(master=self.clientAdd, text="Email")
        ent_email = tk.Entry(master=self.clientAdd)
        lbl_address = tk.Label(master=self.clientAdd, text="Address")
        ent_address = tk.Entry(master=self.clientAdd)
        btn_submit = tk.Button(master=self.clientAdd,
                               text="Add Client",
                               height=3,
                               width=10,
                               command=lambda: buttonAction())
        lbl_name.pack()
        ent_name.pack()
        lbl_email.pack()
        ent_email.pack()
        lbl_address.pack()
        ent_address.pack()
        btn_submit.pack()

        def buttonAction():
            self.createClient(ent_name.get(), ent_email.get(),
                              ent_address.get())

            ent_name.delete(0, 100)
            ent_email.delete(0, 100)
            ent_address.delete(0, 100)

    def createClient(self, name, email, address):
        clientModule.createClient(name, email, address)
        self.switchMain("Client List")

    #Changing between the views.
    def switchMain(self, name):
        self.clientList.pack_forget()
        self.clientAdd.pack_forget()
        self.clientView.pack_forget()
        if name == "Client List":
            self.clientList = createListFrame(self.main, "Clients",
                                              clientModule.get_all_clients(),
                                              "No Clients", "See Invoices",
                                              self.clientInvoiceView, [])
            self.clientList.pack()
        elif name == "Add Client":
            self.clientAdd.pack()
        elif name == "Client View":
            self.clientView.pack()

        self.main.pack()
Example #16
0
  def __init__(self,screen,backend = {}):
    self.screen = screen;
    self.screen_lock = thread.allocate()
    self.draw_skeleton = True
    self.video_display = False
    self.dispInfo = pygame.display.Info()
    self.skeleton_to_depth_image = nui.SkeletonEngine.skeleton_to_depth_image
    self.control_words = ['pause','run','quit','repeat',"train",'test']
    self.paused = False;
    self.skeletons = None
    self.DEPTH_WINSIZE = 320,240
    self.VIDEO_WINSIZE = 640,480
    self.skeletal_map = []
    self.state = self.SETUP;
    self.mode = self.TRAINING;
    self.backend = backend;
    self.wordlist = CircularArray(backend['words'])
    self.word = "None"
    self.test_word = self.wordlist.roll()
    self.backend_wait = True;
    self.show_depth = False;
    ####
    if self.video_display:
      size = self.dispInfo.current_w-self.VIDEO_WINSIZE[0];
    else:
      size = self.dispInfo.current_w-self.DEPTH_WINSIZE[0];
    size = size + 100
    #self.clock_image = resize((size,size), ou_img="ui/images/_clock.gif");
    self.sent_data = False;
    self.use_speech = True;
    self.repeat = False
    self.camera_surf = pygame.Surface(self.DEPTH_WINSIZE)
    
    
    ##########
    self.counter = self.READY_COUNTER;
    self.action = Text(self.screen,w=100, h=50,pos=(485,0),text=self.test_word[0],color=THECOLORS['white']);
    self.count = Text(self.screen,w=100, h=100,pos=(485,55),text=str(self.counter),color=THECOLORS['white']);

    ####general state display paramters
    self.mergin_side = 20;
    self.mergin_top = 20;
    ###top bar
    self.top_bar_size = (self.dispInfo.current_w-2*self.mergin_side,70);
    self.topbar_pos = (self.mergin_side,self.mergin_side)
    self.topbar = bars.topBar(self.top_bar_size,pos=self.topbar_pos);
    ###side bar
    self.side_bar_w = 100;
    self.side_bar_h = self.dispInfo.current_h-self.mergin_top*2-self.top_bar_size[1];
    self.side_bar_pos = (self.mergin_side,self.top_bar_size[1]+self.mergin_top);
    ###word bar
    w = self.dispInfo.current_w-self.side_bar_w-2*self.mergin_side
    self.word_bar_size = (w,70);
    self.word_bar_pos = (self.mergin_side+self.side_bar_w,self.mergin_side+self.top_bar_size[1])
    
    ###camera feedback pos
    self.camera_feed_pos = (self.mergin_side+self.side_bar_w,self.word_bar_pos[1]+self.word_bar_size[1]);
    ####SETUP display parameters
    self.train_button_pos = (100,100);
    self.train_button = Button(pos=self.train_button_pos,text="TRAINING");
    #++++++++++
    self.user_button_pos = (100,210);
    #++++++++
    self.depth_button = Button(text="DEPTH")
    #++++++
    self.user_button = Button(pos=self.user_button_pos,text="USER");
    self.setup_sidebar = Sidebar(self.side_bar_pos,w=self.side_bar_w,h=self.side_bar_h,buttons=[self.train_button,self.user_button,self.depth_button])
    self.setup_sidebar_surf = self.setup_sidebar.draw_buttons()

    ###Text input
    self.text_in_h = 40;
    self.text_in_w = 100;
    self.text_in_pos = (self.camera_feed_pos[0]+self.DEPTH_WINSIZE[0]+10,self.camera_feed_pos[1])
    self.text_input = InputBox(self.text_in_pos[0], self.text_in_pos[1], self.text_in_w, self.text_in_h)
    ####READY display parameters
    self.quit_button = Button(text="QUIT");
    #++++++++++
    self.setup_button = Button(text="SETUP");
    #++++++
    self.puase_button = Button(text="PAUSE");
    #++++++

    self.sidar_bar = Sidebar(self.side_bar_pos,w=self.side_bar_w,h=self.side_bar_h,buttons=[self.quit_button,self.puase_button,self.setup_button,self.depth_button])
    self.sidebar_surf = self.sidar_bar.draw_buttons()
    #++++++
    #self.clock_pos = (self.camera_feed_pos[0]+self.DEPTH_WINSIZE[0]+10,self.camera_feed_pos[1]+self.text_in_h)
    self.clock_pos = (self.camera_feed_pos[0]+self.DEPTH_WINSIZE[0]+70,self.camera_feed_pos[1])
    self.clock = Clock(size=self.DEPTH_WINSIZE[1] + 30);
    ####RECODRING display parameters 
    

    ####FEEDBACK parameters
    self.feedback_bar_pos=(self.word_bar_pos[0], self.camera_feed_pos[1]+self.DEPTH_WINSIZE[1]+10);
    self.feedback_bar_size = self.word_bar_size;


    
   
    self.speech_thread = SpeechTrigger(self);
    self.listen = False;
    ###
    self.ctl_word_size = 40;
    self.ctl_pose = self.camera_feed_pos[0],self.camera_feed_pos[1]+self.DEPTH_WINSIZE[1]+30
    self.ctl_size = self.word_bar_size[0],300
    self.clt_words=ControlWords(self.WORDS,font_size=self.ctl_word_size,pose=self.ctl_pose,size=self.ctl_size)
    self.setup_clt_words=ControlWords(self.SETUP_WORDS,font_size=self.ctl_word_size,pose=self.ctl_pose,size=self.ctl_size)
    self.ctl_surf = self.clt_words.show()
    self.setup_ctl_surf=self.setup_clt_words.show()

    ### Feedback bars
    self.congrats_bar = bars.congrats(self.feedback_bar_size,pos = self.feedback_bar_pos);
    self.no_data_bar = bars.noData(self.feedback_bar_size,pos = self.feedback_bar_pos);
    self.processing_bar = bars.processing(self.feedback_bar_size,pos = self.feedback_bar_pos)
    self.gogo_bar = bars.gogo(size=(self.clock.size, self.clock.size),pos=self.clock_pos);
    self.correct_word_pos = (self.feedback_bar_pos[0],(self.feedback_bar_pos[1]+self.feedback_bar_size[1]))
    ####Test words
    self.train_bars = mappers.trainer_vocab_display_mapper(self);
    self.test_bars = mappers.test__vocab_display_mapper(self);
    self.sorry_bar_mapper = mappers.sorry_bar_mapper(self);
    self.correct_word_bar = mappers.correct__word_display_mapper(self);
Example #17
0
class PykinectInt:
  DEPTH_WINSIZE = 320,240
  VIDEO_WINSIZE = 640,480
  ###STATES
  SETUP = 0;
  RECORDING = 1;
  FEEDBACK = 2;
  READY = 3;
  WAIT = 4;
  ###modes
  USER = 0;
  TRAINING = 1;
  #### Limits
  READY_COUNTER=3;
  RECORDING_COUNTER=2;
  FEEDBACK_COUNTER = 4;
  WAIT_COUNTER=4;
  WORDS = {"pause: ":"to pause","run: ": "to unpause","quit: ":"to quit","repeat: ": "to repeat the last word"}
  SETUP_WORDS = {"train":"to start practice mode", "test": "To start test mode"}

  def __init__(self,screen,backend = {}):
    self.screen = screen;
    self.screen_lock = thread.allocate()
    self.draw_skeleton = True
    self.video_display = False
    self.dispInfo = pygame.display.Info()
    self.skeleton_to_depth_image = nui.SkeletonEngine.skeleton_to_depth_image
    self.control_words = ['pause','run','quit','repeat',"train",'test']
    self.paused = False;
    self.skeletons = None
    self.DEPTH_WINSIZE = 320,240
    self.VIDEO_WINSIZE = 640,480
    self.skeletal_map = []
    self.state = self.SETUP;
    self.mode = self.TRAINING;
    self.backend = backend;
    self.wordlist = CircularArray(backend['words'])
    self.word = "None"
    self.test_word = self.wordlist.roll()
    self.backend_wait = True;
    self.show_depth = False;
    ####
    if self.video_display:
      size = self.dispInfo.current_w-self.VIDEO_WINSIZE[0];
    else:
      size = self.dispInfo.current_w-self.DEPTH_WINSIZE[0];
    size = size + 100
    #self.clock_image = resize((size,size), ou_img="ui/images/_clock.gif");
    self.sent_data = False;
    self.use_speech = True;
    self.repeat = False
    self.camera_surf = pygame.Surface(self.DEPTH_WINSIZE)
    
    
    ##########
    self.counter = self.READY_COUNTER;
    self.action = Text(self.screen,w=100, h=50,pos=(485,0),text=self.test_word[0],color=THECOLORS['white']);
    self.count = Text(self.screen,w=100, h=100,pos=(485,55),text=str(self.counter),color=THECOLORS['white']);

    ####general state display paramters
    self.mergin_side = 20;
    self.mergin_top = 20;
    ###top bar
    self.top_bar_size = (self.dispInfo.current_w-2*self.mergin_side,70);
    self.topbar_pos = (self.mergin_side,self.mergin_side)
    self.topbar = bars.topBar(self.top_bar_size,pos=self.topbar_pos);
    ###side bar
    self.side_bar_w = 100;
    self.side_bar_h = self.dispInfo.current_h-self.mergin_top*2-self.top_bar_size[1];
    self.side_bar_pos = (self.mergin_side,self.top_bar_size[1]+self.mergin_top);
    ###word bar
    w = self.dispInfo.current_w-self.side_bar_w-2*self.mergin_side
    self.word_bar_size = (w,70);
    self.word_bar_pos = (self.mergin_side+self.side_bar_w,self.mergin_side+self.top_bar_size[1])
    
    ###camera feedback pos
    self.camera_feed_pos = (self.mergin_side+self.side_bar_w,self.word_bar_pos[1]+self.word_bar_size[1]);
    ####SETUP display parameters
    self.train_button_pos = (100,100);
    self.train_button = Button(pos=self.train_button_pos,text="TRAINING");
    #++++++++++
    self.user_button_pos = (100,210);
    #++++++++
    self.depth_button = Button(text="DEPTH")
    #++++++
    self.user_button = Button(pos=self.user_button_pos,text="USER");
    self.setup_sidebar = Sidebar(self.side_bar_pos,w=self.side_bar_w,h=self.side_bar_h,buttons=[self.train_button,self.user_button,self.depth_button])
    self.setup_sidebar_surf = self.setup_sidebar.draw_buttons()

    ###Text input
    self.text_in_h = 40;
    self.text_in_w = 100;
    self.text_in_pos = (self.camera_feed_pos[0]+self.DEPTH_WINSIZE[0]+10,self.camera_feed_pos[1])
    self.text_input = InputBox(self.text_in_pos[0], self.text_in_pos[1], self.text_in_w, self.text_in_h)
    ####READY display parameters
    self.quit_button = Button(text="QUIT");
    #++++++++++
    self.setup_button = Button(text="SETUP");
    #++++++
    self.puase_button = Button(text="PAUSE");
    #++++++

    self.sidar_bar = Sidebar(self.side_bar_pos,w=self.side_bar_w,h=self.side_bar_h,buttons=[self.quit_button,self.puase_button,self.setup_button,self.depth_button])
    self.sidebar_surf = self.sidar_bar.draw_buttons()
    #++++++
    #self.clock_pos = (self.camera_feed_pos[0]+self.DEPTH_WINSIZE[0]+10,self.camera_feed_pos[1]+self.text_in_h)
    self.clock_pos = (self.camera_feed_pos[0]+self.DEPTH_WINSIZE[0]+70,self.camera_feed_pos[1])
    self.clock = Clock(size=self.DEPTH_WINSIZE[1] + 30);
    ####RECODRING display parameters 
    

    ####FEEDBACK parameters
    self.feedback_bar_pos=(self.word_bar_pos[0], self.camera_feed_pos[1]+self.DEPTH_WINSIZE[1]+10);
    self.feedback_bar_size = self.word_bar_size;


    
   
    self.speech_thread = SpeechTrigger(self);
    self.listen = False;
    ###
    self.ctl_word_size = 40;
    self.ctl_pose = self.camera_feed_pos[0],self.camera_feed_pos[1]+self.DEPTH_WINSIZE[1]+30
    self.ctl_size = self.word_bar_size[0],300
    self.clt_words=ControlWords(self.WORDS,font_size=self.ctl_word_size,pose=self.ctl_pose,size=self.ctl_size)
    self.setup_clt_words=ControlWords(self.SETUP_WORDS,font_size=self.ctl_word_size,pose=self.ctl_pose,size=self.ctl_size)
    self.ctl_surf = self.clt_words.show()
    self.setup_ctl_surf=self.setup_clt_words.show()

    ### Feedback bars
    self.congrats_bar = bars.congrats(self.feedback_bar_size,pos = self.feedback_bar_pos);
    self.no_data_bar = bars.noData(self.feedback_bar_size,pos = self.feedback_bar_pos);
    self.processing_bar = bars.processing(self.feedback_bar_size,pos = self.feedback_bar_pos)
    self.gogo_bar = bars.gogo(size=(self.clock.size, self.clock.size),pos=self.clock_pos);
    self.correct_word_pos = (self.feedback_bar_pos[0],(self.feedback_bar_pos[1]+self.feedback_bar_size[1]))
    ####Test words
    self.train_bars = mappers.trainer_vocab_display_mapper(self);
    self.test_bars = mappers.test__vocab_display_mapper(self);
    self.sorry_bar_mapper = mappers.sorry_bar_mapper(self);
    self.correct_word_bar = mappers.correct__word_display_mapper(self);

  def surface_to_array(self,surface):
    buffer_interface = surface.get_buffer()
    address = ctypes.c_void_p()
    size = Py_ssize_t()
    _PyObject_AsWriteBuffer(buffer_interface,
                          ctypes.byref(address), ctypes.byref(size))
    bytes = (ctypes.c_byte * size.value).from_address(address.value)
    bytes.object = buffer_interface
    return bytes
  def pos_to_array(self,joint):
    #print "joint", joint
    return [joint.x,joint.y,joint.z]
  


  def map_skeleton(self,skeleton):
    skltl = Skeletal();
    skltl.head = self.pos_to_array(skeleton.SkeletonPositions[JointId.Head]);
      
    skltl.should_center = self.pos_to_array(skeleton.SkeletonPositions[JointId.ShoulderCenter]);
    skltl.shoulder_left = self.pos_to_array(skeleton.SkeletonPositions[JointId.ShoulderLeft]);
    skltl.shoulder_right = self.pos_to_array(skeleton.SkeletonPositions[JointId.ShoulderRight]);

    skltl.elbow_left = self.pos_to_array(skeleton.SkeletonPositions[JointId.ElbowLeft]);
    skltl.elbow_right = self.pos_to_array(skeleton.SkeletonPositions[JointId.ElbowRight]);

    skltl.wrist_left = self.pos_to_array(skeleton.SkeletonPositions[JointId.WristLeft]);
    skltl.wrist_right = self.pos_to_array(skeleton.SkeletonPositions[JointId.WristRight]);

    skltl.hand_left =self.pos_to_array(skeleton.SkeletonPositions[JointId.HandLeft]);
    skltl.hand_right =self.pos_to_array(skeleton.SkeletonPositions[JointId.HandRight]);

    skltl.hip_center =self.pos_to_array(skeleton.SkeletonPositions[JointId.HipCenter]);
    skltl.hip_left =self.pos_to_array(skeleton.SkeletonPositions[JointId.HipLeft]);
    skltl.hip_right =self.pos_to_array(skeleton.SkeletonPositions[JointId.HandRight]);

    skltl.ankle_left =self.pos_to_array(skeleton.SkeletonPositions[JointId.AnkleLeft]);
    skltl.ankle_right =self.pos_to_array(skeleton.SkeletonPositions[JointId.AnkleRight]);

    skltl.foot_left =self.pos_to_array(skeleton.SkeletonPositions[JointId.FootLeft]);
    skltl.foot_right =self.pos_to_array(skeleton.SkeletonPositions[JointId.FootRight]);

    skltl.knee_left =self.pos_to_array(skeleton.SkeletonPositions[JointId.KneeLeft]);
    skltl.knee_right =self.pos_to_array(skeleton.SkeletonPositions[JointId.KneeRight]);
    skltl.spine =self.pos_to_array(skeleton.SkeletonPositions[JointId.spine]);
    return skltl;
  def collect(self,skltns):
    sf = [];
    for index, sklton in enumerate(skltns):
      sk = self.map_skeleton(sklton)
      if sk.is_not_empty():
        sf.append(sk);
    if not sf==[]:
      self.skeletal_map.append(ScanFrame(sf));

  def draw_skeleton_data(self,pSkelton, index, positions, width = 4):
    start = pSkelton.SkeletonPositions[positions[0]]
       
    for position in itertools.islice(positions, 1, None):
      next = pSkelton.SkeletonPositions[position.value]
      if self.video_display:
        curstart = self.skeleton_to_depth_image(start, self.VIDEO_WINSIZE[0], self.VIDEO_WINSIZE[1]) 
        curend = self.skeleton_to_depth_image(next, self.VIDEO_WINSIZE[0], self.VIDEO_WINSIZE[1])
        if curstart[0]<self.VIDEO_WINSIZE[0] and curstart[1]<self.VIDEO_WINSIZE[1]:
          if curend[0]<self.VIDEO_WINSIZE[0] and curend[1]<self.VIDEO_WINSIZE[1]:
            # curstart = curstart[0]+self.camera_feed_pos[0],curstart[1]+self.camera_feed_pos[1];
            # curend = curend[0]+self.camera_feed_pos[0],curend[1]+self.camera_feed_pos[1]
            pygame.draw.line(self.camera_surf, SKELETON_COLORS[index], curstart, curend, width);
      else:
        curstart = self.skeleton_to_depth_image(start, self.DEPTH_WINSIZE[0], self.DEPTH_WINSIZE[1]) 
        curend = self.skeleton_to_depth_image(next, self.DEPTH_WINSIZE[0], self.DEPTH_WINSIZE[1])
        if curstart[0]<self.DEPTH_WINSIZE[0] and curstart[1]<self.DEPTH_WINSIZE[1]:
          if curend[0]<self.DEPTH_WINSIZE[0] and curend[1]<self.DEPTH_WINSIZE[1]:
            # curstart = curstart[0]+self.camera_feed_pos[0],curstart[1]+self.camera_feed_pos[1];
            # curend = curend[0]+self.camera_feed_pos[0],curend[1]+self.camera_feed_pos[1]
            pygame.draw.line(self.camera_surf, SKELETON_COLORS[index], curstart, curend, width);
      start = next
  def draw_skeletons(self,skeletons):
    if not self.show_depth:
      self.camera_surf.fill((0,0,0))
    for index, data in enumerate(skeletons):
      # draw the Head
      if self.video_display:
        HeadPos = self.skeleton_to_depth_image(data.SkeletonPositions[JointId.Head], self.VIDEO_WINSIZE[0], self.VIDEO_WINSIZE[1])
      else:
        HeadPos = self.skeleton_to_depth_image(data.SkeletonPositions[JointId.Head], self.DEPTH_WINSIZE[0], self.DEPTH_WINSIZE[1])
      self.draw_skeleton_data(data, index, SPINE, 10)
      pygame.draw.circle(self.camera_surf, SKELETON_COLORS[index], (int(HeadPos[0]), int(HeadPos[1])), 20, 0)
  
      # drawing the limbs
      self.draw_skeleton_data(data, index, LEFT_ARM)
      self.draw_skeleton_data(data, index, RIGHT_ARM)
      self.draw_skeleton_data(data, index, LEFT_LEG)
      self.draw_skeleton_data(data, index, RIGHT_LEG)
    self.screen.blit(self.camera_surf,self.camera_feed_pos)
    pygame.display.update()
  def word_trigger(self,_words):
    pygame.event.post(pygame.event.Event(SPEECHEVENT,words = _words));
  def depth_frame_ready(self,frame):
    if self.video_display:
      return
    #print "Adding depth........"
    depth_surface = pygame.Surface(self.DEPTH_WINSIZE);

    with self.screen_lock:
      if self.show_depth:
        address = self.surface_to_array(self.camera_surf)
        frame.image.copy_bits(address)
        del address
        self.screen.blit(self.camera_surf,self.camera_feed_pos)
      if self.skeletons is not None and self.draw_skeleton:
        self.draw_skeletons(self.skeletons)
        if self.state==self.RECORDING:
          self.collect(self.skeletons);

      
      disp(self)
      pygame.display.update()
      #print "deleted!"


  def video_frame_ready(self,frame):
    #print "video_display: ",self.video_display
    if not self.video_display:
      return
    #print "Adding......."
    vid_surface = pygame.Surface(self.VIDEO_WINSIZE);

    with self.screen_lock:
      if self.show_depth:
        address = self.surface_to_array(self.camera_surf)
        frame.image.copy_bits(address)
        del address
        self.screen.blit(self.camera_surf,self.camera_feed_pos);
      if self.skeletons is not None and self.draw_skeleton:
        self.draw_skeletons(self.skeletons)
        if self.state==self.RECORDING:
          self.collect(self.skeletons);
      disp(self)
      pygame.display.update()
  def loop(self):
    pygame.display.set_caption('Louder than words')
    self.screen.fill(THECOLORS["black"])
    if self.use_speech:
      self.listen = True;
      self.speech_thread.start()


    kinect = nui.Runtime()
    kinect.skeleton_engine.enabled = True
    def post_frame(frame):
        try:
          pygame.event.post(pygame.event.Event(KINECTEVENT, skeletons = frame.SkeletonData))
        except:
          pass
    kinect.skeleton_frame_ready += post_frame
    
    kinect.depth_frame_ready += self.depth_frame_ready    
    kinect.video_frame_ready += self.video_frame_ready    
    
    kinect.video_stream.open(nui.ImageStreamType.Video, 2, nui.ImageResolution.Resolution640x480, nui.ImageType.Color)
    kinect.depth_stream.open(nui.ImageStreamType.Depth, 2, nui.ImageResolution.Resolution320x240, nui.ImageType.Depth)

    print('Controls: ')
    print('     d - Switch to depth view')
    print('     v - Switch to video view')
    print('     s - Toggle displaing of the skeleton')
    print('     u - Increase elevation angle')
    print('     j - Decrease elevation angle')

    pygame.time.set_timer(RECORDEVENT, 1000);
    done = False
    skeleton_counter = 0
    clock  = pygame.time.Clock()
    while not done:
      #r = random.randint(0,34);
      #g = random.randint(0,34);
      #b = random.randint(0,34);
      #background_color = (r,g,b);
      background_color = (1, 0, 79)
      e = pygame.event.wait()
      self.dispInfo = pygame.display.Info()
      if e.type == pygame.QUIT:
        self.listen = False
        done = True
        break
      elif e.type == RECORDEVENT:
        transition_handle(self,background_color,skeleton_counter)
      elif e.type == KINECTEVENT:
          skeletons = e.skeletons
          #print "recieving skeletons"
          ###COLLECTING DATA
          if self.state==self.RECORDING:
            if not self.paused:
              skeleton_counter+=1;
              self.collect(skeletons);
          if self.draw_skeleton:
            #print "sending skeletons"
            
            self.draw_skeletons(skeletons)
            pygame.display.update()
      elif e.type == KEYDOWN:
        if e.key == K_ESCAPE:
          done = True
          break
        elif e.key == K_d:
          with self.screen_lock:
            self.video_display = False
        elif e.key == K_v:
          with self.screen_lock:
            self.screen = pygame.display.set_mode(self.VIDEO_WINSIZE,0,16)
            self.video_display = True
        elif e.key == K_s:
          self.draw_skeleton = not self.draw_skeleton
        elif e.key == K_u:
          kinect.camera.elevation_angle = kinect.camera.elevation_angle + 2
        elif e.key == K_j:
          kinect.camera.elevation_angle = kinect.camera.elevation_angle - 2
        elif e.key == K_x:
          kinect.camera.elevation_angle = 2

      ######
      ##Click response
      ###
      if e.type ==MOUSEBUTTONDOWN:
        done=mouse_handle(self,done);
      if e.type==SPEECHEVENT:
        while len(e.words)!=0:
          speech_word = e.words.pop(0)
          done = word_handle(self,speech_word,done)
        
      disp(self);
      pygame.display.update();
      clock.tick();
    
    self.backend['save_data']()
    pygame.quit()
Example #18
0
class InvoicesView(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.heading = tk.Label(self,
                                text="Invoices",
                                background="lightgrey",
                                pady="5")
        self.heading.pack(side="top", fill="x")
        self.sidebar = Sidebar(self, "Invoices")
        self.sidebar.pack(side="left", fill="y")
        self.main = tk.Frame(master=self)
        self.invoicesList = tk.Frame()
        self.updateList("unpaid")

        self.invoiceAdd = tk.Frame(master=self.main, padx=30, pady=30)
        self.invoiceAddInit()
        self.products = {}
        self.productList = tk.Frame(master=self.main, padx=30, pady=30)
        self.invoiceProductList()
        self.switchMain("Current Invoices")

    #Creating a view of the list of invoices
    def updateList(self, type):
        if (type == "paid"):
            self.invoicesList = createListFrame(
                self.main, "Invoice History", invoiceModule.getPaidInvoices(),
                "Currently no paid invoices.", "Delete Invoice",
                self.payInvoice, ["ClientID"])
        elif (type == "unpaid"):
            self.invoicesList = createListFrame(
                self.main, "Unpaid Invoices",
                invoiceModule.getUnpaidInvoices(),
                "Currently no unpaid invoices.", "Pay Invoice",
                self.payInvoice, ["ClientID"])

    #creating a view of the form for creating invoices
    def invoiceAddInit(self):
        dropdownClients = {}
        dropdownClients[""] = ""  # Blank space for dropdownmenu
        for client in clientModule.get_all_clients():
            dropdownClients[client["_id"]] = client["CustomerName"]

        tkvar_client = tk.StringVar(master=self.invoiceAdd)
        lbl_client = tk.Label(master=self.invoiceAdd, text="Client")
        opt_client = ttk.OptionMenu(self.invoiceAdd, tkvar_client,
                                    *dropdownClients.values())
        opt_client["width"] = 18

        lbl_title = tk.Label(master=self.invoiceAdd, text="Title")
        ent_title = tk.Entry(master=self.invoiceAdd)
        lbl_description = tk.Label(master=self.invoiceAdd, text="Description")
        ent_description = tk.Entry(master=self.invoiceAdd)
        lbl_dueDate = tk.Label(master=self.invoiceAdd, text="Due Date")
        ent_dueDate = tk.Entry(master=self.invoiceAdd)
        btn_submit = tk.Button(
            master=self.invoiceAdd,
            text="Create Invoice",
            height=3,
            width=10,
            command=lambda: self.createInvoice(
                get_id(tkvar_client.get()), ent_title.get(),
                ent_description.get(), ent_dueDate.get(), self.products))

        lbl_client.pack(padx=5, pady=5, fill="x")
        opt_client.pack(padx=5, pady=5, fill="x")
        lbl_title.pack(padx=5, pady=5, fill="x")
        ent_title.pack(padx=5, pady=5, fill="x")
        lbl_description.pack(padx=5, pady=5, fill="x")
        ent_description.pack(padx=5, pady=5, fill="x")
        lbl_dueDate.pack(padx=5, pady=5, fill="x")
        ent_dueDate.pack(padx=5, pady=5, fill="x")
        btn_submit.pack(padx=5, pady=5, fill="x")

        def get_id(*args):  # on select function
            for i, j in dropdownClients.items():
                if j == tkvar_client.get():
                    return i

    #Creating view for adding products to the invoice
    def invoiceProductList(self):
        dropdownProducts = {}
        dropdownProducts[""] = ""  # Blank space for dropdownmenu
        for product in productModule.getAllProducts():
            dropdownProducts[product["_id"]] = product["ProductName"]

        lbl_products = tk.Label(master=self.productList, text="Products")
        tkvar_product = tk.StringVar(master=self.productList)
        opt_products = ttk.OptionMenu(self.productList, tkvar_product,
                                      *dropdownProducts.values())
        opt_products["width"] = 18

        btn_addProduct = tk.Button(
            master=self.productList,
            text="Add Product",
            padx=5,
            pady=3,
            command=lambda: self.addProduct(get_id(tkvar_product.get()),
                                            tkvar_product.get()))

        lbl_products.pack(padx=5, pady=5, fill="x")
        opt_products.pack(padx=5, pady=5, fill="x")
        btn_addProduct.pack(padx=5, pady=5, fill="x")

        def get_id(*args):  # on select function
            for i, j in dropdownProducts.items():
                if j == tkvar_product.get():
                    return i

    def addProduct(self, productID, product):
        if productID in self.products:
            self.products[productID] += 1
        else:
            self.products[productID] = 1
        self.label = tk.Label(master=self.productList, text=product)
        self.label.pack(padx=5, pady=5, fill="x")

        self.switchMain("Create Invoice")

    def payInvoice(self, id):
        invoiceModule.payInvoice(id)

    def createInvoice(self, client, title, description, dueDate, list):
        cost = 0
        for product in self.products:
            cost += int(productModule.getProduct(product)["Cost"])
        invoiceModule.createInvoice(client, title, description, dueDate, cost,
                                    list)

        self.switchMain("Invoice List")

    def switchMain(self, name):
        self.invoicesList.pack_forget()
        self.invoiceAdd.pack_forget()
        self.productList.pack_forget()
        if (name == "Current Invoices"):
            self.updateList("unpaid")
            self.invoicesList.pack()
        elif (name == "Invoice History"):
            self.updateList("paid")
            self.invoicesList.pack()
        elif (name == "Create Invoice"):
            self.invoiceAdd.pack(fill="both", side="left", expand=True)
            self.productList.pack(fill="both", side="right", expand=True)

        self.main.pack(fill="both")
Example #19
0
    def __init__(self, params, **kw):

        super(ViewForm, self).__init__(**kw)

        # save reference of params dictionary in requeste
        cherrypy.request.terp_params = params
        cherrypy.request.terp_fields = []

        editable = params.editable
        readonly = params.readonly

        if editable is None:
            editable = True

        if readonly is None:
            readonly = False

        self.screen = Screen(prefix='',
                             hastoolbar=True,
                             editable=editable,
                             readonly=readonly,
                             selectable=params.selectable or 2)

        self.sidebar = Sidebar(self.screen.model,
                               self.screen.toolbar,
                               self.screen.id,
                               self.screen.view_type,
                               context=self.screen.context)

        self.is_dashboard = getattr(cherrypy.request, '_terp_dashboard', False)

        self.search = None

        if params.view_type in ('tree', 'graph'):
            self.search = Search(model=params.model,
                                 domain=params.domain,
                                 context=params.context,
                                 values=params.search_data or {})

        if params.view_type == 'tree':
            self.screen.id = False

        if 'form' not in self.screen.view_mode:
            self.screen.widget.show_links = 0
            self.screen.widget.link = 0
            self.screen.editable = False
            self.screen.widget.editable = False

        # get the correct view title
        if params.context:
            self.screen.string = params.context.get('_terp_view_name',
                                                    self.screen.string)
        self.screen.string = self.screen.string

        # get the actual pager data
        self.limit = self.screen.limit
        self.offset = self.screen.offset
        self.count = self.screen.count

        self.search_domain = params.search_domain
        self.search_data = params.search_data

        if params.hidden_fields:
            self.hidden_fields = params.hidden_fields
Example #20
0
class Edistor(QPlainTextEdit):
    """ QPlainTextEdit implementation

        This class is the base of editor

        Highlight current line method:
            @color: string color
            @alpha: int
    """
    def __init__(self):
        QPlainTextEdit.__init__(self)
        self.position_margin = QFontMetricsF(
            self.document().defaultFont()).width("#") * 80
        # Margin line
        self._margin = False
        # Sidebar
        self.sidebar = Sidebar(self)
        # Highlight current line
        self._color_current_line = QColor('lightblue')
        self._alpha_current_line = self._color_current_line.setAlpha(50)
        # Connection
        self.connect(self, SIGNAL("blockCountChanged(int)"),
                     self.sidebar.update_area_width)
        self.connect(self, SIGNAL("updateRequest(const QRect&, int)"),
                     self.sidebar.update_area)
        self.connect(self, SIGNAL("cursorPositionChanged()"),
                     self._highlight_current_line)

        self._highlight_current_line()

    def margin(self, show=False):
        """ Set the margin line """
        if show:
            self._margin = Margin()

    def paintEvent(self, e):
        QPlainTextEdit.paintEvent(self, e)
        if self._margin:
            qp = QPainter()
            qp.begin(self.viewport())
            qp.setPen(self._margin.color)
            offset = self.contentOffset()
            qp.drawLine(self.position_margin + offset.x(), 0,
                        self.position_margin + offset.x(),
                        self.viewport().height())
            qp.end()

    def highlightCurrentLine(self, color, alpha):
        self._color_current_line = QColor(color)
        self._alpha_current_line = self._color_current_line.setAlpha(alpha)
        self._highlight_current_line()

    def _highlight_current_line(self):
        self.extra_selections = []
        selection = QTextEdit.ExtraSelection()
        selection.format.setBackground(self._color_current_line)
        selection.format.setProperty(QTextFormat.FullWidthSelection,
                                     QVariant(True))
        selection.cursor = self.textCursor()
        selection.cursor.clearSelection()
        self.extra_selections.append(selection)
        self.setExtraSelections(self.extra_selections)

    def resizeEvent(self, e):
        QPlainTextEdit.resizeEvent(self, e)
        cr = self.contentsRect()
        self.sidebar.setGeometry(
            QRect(cr.left(), cr.top(), self.sidebar.width(), cr.height()))
Example #21
0
class ProductsView(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.heading = tk.Label(self,
                                text="Products",
                                background="lightgrey",
                                pady="5")
        self.heading.pack(side="top", fill="x")
        self.sidebar = Sidebar(self, "Products")
        self.sidebar.pack(side="left", fill="y")
        self.main = tk.Frame(master=self)
        self.productsList = createListFrame(self.main, "Products",
                                            productModule.getAllProducts(),
                                            "No Products", "Change Product",
                                            self.changeProduct, [])

        self.productAdd = tk.Frame(master=self.main, padx=30, pady=100)
        self.productAddInit()
        self.switchMain("Product List")

    def productAddInit(self):
        lbl_name = tk.Label(master=self.productAdd, text="Name")
        ent_name = tk.Entry(master=self.productAdd)
        lbl_description = tk.Label(master=self.productAdd, text="Description")
        ent_description = tk.Entry(master=self.productAdd)
        lbl_category = tk.Label(master=self.productAdd, text="Category")
        ent_category = tk.Entry(master=self.productAdd)
        lbl_cost = tk.Label(master=self.productAdd, text="Cost")
        ent_cost = tk.Entry(master=self.productAdd)
        lbl_inventory = tk.Label(master=self.productAdd, text="Inventory")
        ent_inventory = tk.Entry(master=self.productAdd)

        btn_submit = tk.Button(
            master=self.productAdd,
            text="Add Product",
            height=3,
            width=10,
            command=lambda: self.createProduct(ent_name.get(
            ), ent_description.get(), ent_category.get(), ent_cost.get(),
                                               ent_inventory.get()))
        lbl_name.pack()
        ent_name.pack()
        lbl_description.pack()
        ent_description.pack()
        lbl_category.pack()
        ent_category.pack()
        lbl_cost.pack()
        ent_cost.pack()
        lbl_inventory.pack()
        ent_inventory.pack()
        btn_submit.pack()

    def changeProduct(self, id):
        print("product Changed: " + str(id))

    def createProduct(self, name, description, category, cost, qty):
        productModule.createProduct(name, description, category, cost, qty)
        self.switchMain("Product List")

    def switchMain(self, name):
        self.productsList.pack_forget()
        self.productAdd.pack_forget()
        if (name == "Product List"):
            self.productsList = createListFrame(self.main, "Products",
                                                productModule.getAllProducts(),
                                                "No Products",
                                                "Change Product",
                                                self.changeProduct, [])
            self.productsList.pack()
        elif (name == "Add Product"):
            self.productAdd.pack()

        self.main.pack()
Example #22
0
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html

from navbar import Navbar
from sidebar import Sidebar
from dashboard import Dashboard

nav = Navbar()
side = Sidebar()
dashboard = Dashboard()

body = dbc.Container(
    [
        dbc.Row([
                    dbc.Col(html.Div(side), lg=2),
                    dbc.Col(html.Div(dashboard)),
        ])
    ],
    fluid=True
)


def Homepage():
    layout = html.Div([
    nav,
    body
    ])
    return layout
Example #23
0
class Application(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.connect("destroy", self.on_quit)
        self.set_default_size(1000, 600)
        self.load_css()

        header_bar = Gtk.HeaderBar()
        header_bar.set_show_close_button(True)
        header_bar.props.title = "TVTracker"

        search_button = Gtk.ToggleButton()
        search_icon = Gtk.Image.new_from_icon_name("edit-find-symbolic", 4)

        search_button.add(search_icon)
        header_bar.pack_start(search_button)
        self.set_titlebar(header_bar)

        self.store = Store()

        box = Gtk.Box(Gtk.Orientation.HORIZONTAL)

        self.sidebar = Sidebar(self.store, search_button)
        self.sidebar.connect("notify::selected-show",
                             self.on_navigation_change)

        separator = Gtk.Separator()
        self.show_info = ShowInfo(self.store)
        self.show_info.connect("subscription_changed",
                               self.on_subscription_change)

        box.pack_start(self.sidebar, False, False, 0)
        box.pack_start(separator, False, False, 0)
        box.pack_start(self.show_info, True, True, 0)
        self.add(box)

    def on_quit(self, window=None):
        self.store.save_store()

        for filename in glob.glob("cache/temp_*.jpg"):
            os.remove(filename)

        Gtk.main_quit()

    def on_subscription_change(self, show_info_component, show_id,
                               is_subscribed):
        show = self.store.get_show_by_id(show_id)

        if is_subscribed == True:
            self.sidebar.add_item(show)
        else:
            self.sidebar.remove_item(show)

    def on_navigation_change(self, sidebar, selected_show_prop):

        selected_show_id = sidebar.get_property("selected_show")
        selected_show = self.store.get_show_by_id(selected_show_id)
        is_subscribed = self.store.is_show_subscribed(selected_show_id)

        self.show_info.set_id(selected_show["id"])
        self.show_info.set_name(selected_show["name"])
        self.show_info.set_status(selected_show["status"])
        self.show_info.set_rating(selected_show["rating"]["average"])
        self.show_info.set_summary(selected_show["summary"])
        self.show_info.set_genre(selected_show["genres"])
        self.show_info.set_episodes(selected_show["episodes"])
        self.show_info.set_subscribed(is_subscribed)

    def load_css(self):
        style_provider = Gtk.CssProvider()

        css = open('style.css', 'rb')
        data = css.read()
        css.close()

        style_provider.load_from_data(data)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
Example #24
0
    def __init__(self, name, mem, email, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9'  # X11 color: 'gray85'
        _ana1color = '#d9d9d9'  # X11 color: 'gray85'
        _ana2color = '#ececec'  # Closest X11 color: 'gray92'
        self.style = ttk.Style()
        if sys.platform == "win32":
            self.style.theme_use('winnative')
        self.style.configure('.', background=_bgcolor)
        self.style.configure('.', foreground=_fgcolor)
        self.style.configure('.', font="TkDefaultFont")
        self.style.map('.',
                       background=[('selected', _compcolor),
                                   ('active', _ana2color)])

        top.geometry("1280x686+297+168")
        top.minsize(120, 1)
        top.maxsize(3004, 1913)
        top.resizable(1, 1)
        top.title("New Toplevel")
        top.configure(background="#000040")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="#000000")

        top.resizable(False, False)
        img = ImageTk.PhotoImage(file="bg.png")
        self.Background = tk.Label(top, image=img)
        self.Background.place(relx=0, rely=0, height=1000, width=1500)
        self.Background = img

        self.menubar = tk.Menu(top,
                               font="TkMenuFont",
                               bg=_bgcolor,
                               fg=_fgcolor)
        top.configure(menu=self.menubar)

        ####################################################################Movies Slider###################################################################
        global d
        global to
        to = top
        img = ImageTk.PhotoImage(
            Image.open(d[0][0]).resize((560, 277), Image.ANTIALIAS))
        self.Movie_image = tk.Label(top, image=img)
        self.Movie_image.place(relx=0.202, rely=0.286, height=277, width=560)
        self.Movie_image = img

        self.Previous_b = tk.Button(top, command=lambda: self.bac(top))
        self.Previous_b.place(relx=0.172, rely=0.277, height=284, width=27)
        self.Previous_b.configure(activebackground="#000040")
        self.Previous_b.configure(activeforeground="white")
        self.Previous_b.configure(activeforeground="#ffffff")
        self.Previous_b.configure(background="#b3eaff")
        self.Previous_b.configure(disabledforeground="#a3a3a3")
        self.Previous_b.configure(
            font="-family {Segoe UI} -size 20 -weight bold")
        self.Previous_b.configure(foreground="#000000")
        self.Previous_b.configure(highlightbackground="#d9d9d9")
        self.Previous_b.configure(highlightcolor="black")
        self.Previous_b.configure(pady="0")
        self.Previous_b.configure(text='''<''')

        self.Next_b = tk.Button(top, command=lambda: self.ahead(top))
        self.Next_b.place(relx=0.648, rely=0.277, height=284, width=27)
        self.Next_b.configure(activebackground="#000040")
        self.Next_b.configure(activeforeground="white")
        self.Next_b.configure(activeforeground="#ffffff")
        self.Next_b.configure(background="#b3eaff")
        self.Next_b.configure(disabledforeground="#a3a3a3")
        self.Next_b.configure(font="-family {Segoe UI} -size 20 -weight bold")
        self.Next_b.configure(foreground="#000000")
        self.Next_b.configure(highlightbackground="#d9d9d9")
        self.Next_b.configure(highlightcolor="black")
        self.Next_b.configure(pady="0")
        self.Next_b.configure(text='''>''')

        #########################################################################################################################################

        ##########################################################Main##########################################################
        self.Label3 = tk.Label(top)
        self.Label3.place(relx=0.172, rely=0.131, height=48, width=193)
        self.Label3.configure(activebackground="#f9f9f9")
        self.Label3.configure(activeforeground="black")
        self.Label3.configure(background="#000040")
        self.Label3.configure(borderwidth="5")
        self.Label3.configure(disabledforeground="#a3a3a3")
        self.Label3.configure(font="-family {Segoe UI} -size 22")
        self.Label3.configure(foreground="#ffffff")
        self.Label3.configure(highlightbackground="#d9d9d9")
        self.Label3.configure(highlightcolor="black")
        self.Label3.configure(text='''Recommended!''')

        self.Movie_image = tk.Label(top)
        self.Movie_image.place(relx=0.202, rely=0.286, height=277, width=560)
        self.Movie_image.configure(activebackground="#f9f9f9")
        self.Movie_image.configure(activeforeground="black")
        self.Movie_image.configure(background="#d9d9d9")
        self.Movie_image.configure(disabledforeground="#a3a3a3")
        self.Movie_image.configure(foreground="#000000")
        self.Movie_image.configure(highlightbackground="#d9d9d9")
        self.Movie_image.configure(highlightcolor="black")

        self.Book_b = tk.Button(top)
        self.Book_b.place(relx=0.215, rely=0.752, height=54, width=177)
        self.Book_b.configure(activebackground="#000040")
        self.Book_b.configure(activeforeground="white")
        self.Book_b.configure(activeforeground="#ffffff")
        self.Book_b.configure(background="#b3eaff")
        self.Book_b.configure(disabledforeground="#a3a3a3")
        self.Book_b.configure(cursor="hand2")
        self.Book_b.configure(font="-family {Segoe UI} -size 14")
        self.Book_b.configure(foreground="#000000")
        self.Book_b.configure(highlightbackground="#d9d9d9")
        self.Book_b.configure(highlightcolor="black")
        self.Book_b.configure(pady="0")
        self.Book_b.configure(text='''Book Ticket!''')

        self.Description_f = tk.LabelFrame(top)
        self.Description_f.place(relx=0.357,
                                 rely=0.729,
                                 relheight=0.108,
                                 relwidth=0.287)
        self.Description_f.configure(relief='groove')
        self.Description_f.configure(foreground="black")
        self.Description_f.configure(background="#d9d9d9")
        #self.Description_f.configure(cursor="fleur")
        self.Description_f.configure(highlightbackground="#d9d9d9")
        self.Description_f.configure(highlightcolor="black")

        self.Description_l = tk.Label(self.Description_f)
        self.Description_l.place(relx=0.008,
                                 rely=0.041,
                                 height=72,
                                 width=360,
                                 bordermode='ignore')
        self.Description_l.configure(activebackground="#f9f9f9")
        self.Description_l.configure(activeforeground="black")
        self.Description_l.configure(anchor='nw')
        self.Description_l.configure(background="#000040")
        self.Description_l.configure(disabledforeground="#a3a3a3")
        self.Description_l.configure(font="-family {Segoe UI} -size 12")
        self.Description_l.configure(foreground="#ffffff")
        self.Description_l.configure(highlightbackground="#d9d9d9")
        self.Description_l.configure(highlightcolor="black")
        self.Description_l.configure(text='''Description''')

        self.Info_f = tk.LabelFrame(top)
        self.Info_f.place(relx=0.685,
                          rely=0.294,
                          relheight=0.389,
                          relwidth=0.122)
        self.Info_f.configure(relief='groove')
        self.Info_f.configure(foreground="black")
        self.Info_f.configure(background="#000040")
        self.Info_f.configure(highlightbackground="#d9d9d9")
        self.Info_f.configure(highlightcolor="black")

        self.Rating_l = tk.Label(self.Info_f)
        self.Rating_l.place(relx=0.045,
                            rely=0.026,
                            height=27,
                            width=146,
                            bordermode='ignore')
        self.Rating_l.configure(activebackground="#f9f9f9")
        self.Rating_l.configure(activeforeground="black")
        self.Rating_l.configure(background="#000040")
        self.Rating_l.configure(disabledforeground="#a3a3a3")
        self.Rating_l.configure(font="-family {Segoe UI} -size 14")
        self.Rating_l.configure(foreground="#ffffff")
        self.Rating_l.configure(highlightbackground="#d9d9d9")
        self.Rating_l.configure(highlightcolor="black")
        self.Rating_l.configure(text='''Rating''')

        self.TSeparator1 = ttk.Separator(self.Info_f)
        self.TSeparator1.place(relx=0.032,
                               rely=0.236,
                               relwidth=1.269,
                               bordermode='ignore')
        #####################################################Stars###########################################################

        self.Star1 = tk.Label(self.Info_f)
        self.Star1.place(relx=0.173,
                         rely=0.154,
                         height=14,
                         width=16,
                         bordermode='ignore')
        self.Star1.configure(activebackground="#f9f9f9")
        self.Star1.configure(activeforeground="black")
        self.Star1.configure(background="#000040")
        self.Star1.configure(disabledforeground="#a3a3a3")
        self.Star1.configure(foreground="#000000")
        self.Star1.configure(highlightbackground="#d9d9d9")
        self.Star1.configure(highlightcolor="black")

        self.Star2 = tk.Label(self.Info_f)
        self.Star2.place(relx=0.301,
                         rely=0.154,
                         height=14,
                         width=17,
                         bordermode='ignore')
        self.Star2.configure(activebackground="#f9f9f9")
        self.Star2.configure(activeforeground="black")
        self.Star2.configure(background="#000040")
        self.Star2.configure(disabledforeground="#a3a3a3")
        self.Star2.configure(foreground="#000000")
        self.Star2.configure(highlightbackground="#d9d9d9")
        self.Star2.configure(highlightcolor="black")

        self.Star3 = tk.Label(self.Info_f)
        self.Star3.place(relx=0.436,
                         rely=0.154,
                         height=14,
                         width=16,
                         bordermode='ignore')
        self.Star3.configure(activebackground="#f9f9f9")
        self.Star3.configure(activeforeground="black")
        self.Star3.configure(background="#000040")
        self.Star3.configure(disabledforeground="#a3a3a3")
        self.Star3.configure(foreground="#000000")
        self.Star3.configure(highlightbackground="#d9d9d9")
        self.Star3.configure(highlightcolor="black")

        self.Star4 = tk.Label(self.Info_f)
        self.Star4.place(relx=0.564,
                         rely=0.154,
                         height=14,
                         width=16,
                         bordermode='ignore')
        self.Star4.configure(activebackground="#f9f9f9")
        self.Star4.configure(activeforeground="black")
        self.Star4.configure(background="#000040")
        self.Star4.configure(disabledforeground="#a3a3a3")
        self.Star4.configure(foreground="#000000")
        self.Star4.configure(highlightbackground="#d9d9d9")
        self.Star4.configure(highlightcolor="black")

        self.Star5 = tk.Label(self.Info_f)
        self.Star5.place(relx=0.699,
                         rely=0.154,
                         height=14,
                         width=16,
                         bordermode='ignore')
        self.Star5.configure(activebackground="#f9f9f9")
        self.Star5.configure(activeforeground="black")
        self.Star5.configure(background="#000040")
        self.Star5.configure(disabledforeground="#a3a3a3")
        self.Star5.configure(foreground="#000000")
        self.Star5.configure(highlightbackground="#d9d9d9")
        self.Star5.configure(highlightcolor="black")

        #######################################################################################################################################

        self.Cast_l = tk.Label(self.Info_f)
        self.Cast_l.place(relx=0.045,
                          rely=0.558,
                          height=109,
                          width=145,
                          bordermode='ignore')
        self.Cast_l.configure(activebackground="#f9f9f9")
        self.Cast_l.configure(activeforeground="black")
        self.Cast_l.configure(anchor='nw')
        self.Cast_l.configure(background="#000040")
        self.Cast_l.configure(disabledforeground="#a3a3a3")
        self.Cast_l.configure(font="-family {Segoe UI} -size 12")
        self.Cast_l.configure(foreground="#ffffff")
        self.Cast_l.configure(highlightbackground="#d9d9d9")
        self.Cast_l.configure(highlightcolor="black")
        self.Cast_l.configure(text='''Cast''')

        self.Genre_l = tk.Label(self.Info_f)
        self.Genre_l.place(relx=0.045,
                           rely=0.277,
                           height=48,
                           width=145,
                           bordermode='ignore')
        self.Genre_l.configure(activebackground="#f9f9f9")
        self.Genre_l.configure(activeforeground="black")
        self.Genre_l.configure(background="#000040")
        self.Genre_l.configure(disabledforeground="#a3a3a3")
        self.Genre_l.configure(font="-family {Segoe UI} -size 13")
        self.Genre_l.configure(foreground="#ffffff")
        self.Genre_l.configure(highlightbackground="#d9d9d9")
        self.Genre_l.configure(highlightcolor="black")
        self.Genre_l.configure(text='''Genre''')

        self.TSeparator3 = ttk.Separator(top)
        self.TSeparator3.place(relx=0.165, rely=0.168, relheight=0.845)
        self.TSeparator3.configure(orient="vertical")

        self.Label8 = tk.Label(top)
        self.Label8.place(relx=0.172, rely=0.204, height=42, width=547)
        self.Label8.configure(activebackground="#f9f9f9")
        self.Label8.configure(activeforeground="black")
        self.Label8.configure(anchor='w')
        self.Label8.configure(background="#000040")
        self.Label8.configure(disabledforeground="#a3a3a3")
        self.Label8.configure(font="-family {Segoe UI} -size 20")
        self.Label8.configure(foreground="#ffffff")
        self.Label8.configure(highlightbackground="#d9d9d9")
        self.Label8.configure(highlightcolor="black")
        self.Label8.configure(text='''Title''')

        self.Label9 = tk.Label(top)
        self.Label9.place(relx=0.60, rely=0.204, height=42, width=547)
        self.Label9.configure(activebackground="#f9f9f9")
        self.Label9.configure(activeforeground="black")
        self.Label9.configure(anchor='w')
        self.Label9.configure(background="#000040")
        self.Label9.configure(disabledforeground="#a3a3a3")
        self.Label9.configure(font="-family {Segoe UI} -size 20")
        self.Label9.configure(foreground="#ffffff")
        self.Label9.configure(highlightbackground="#d9d9d9")
        self.Label9.configure(highlightcolor="black")
        self.Label9.configure(text='''UA/A''')

        Searchbar.__init__(self, top=None)
        Memberbar.__init__(self, mem, top=None)
        Homebar.__init__(self, name, mem, top=None)
        Sidebar.__init__(self, top=None)
Example #25
0
class App:
    def __init__(self, s):
        self.board_ = Board(s.boardsize_)

        self.robots_ = []
        for i in range(s.robots_):
            self.robots_.append(
                Robot(COLORS[i], rd(s.boardsize_), rd(s.boardsize_)))
        Robot.validate_positions(self.board_, self.robots_)

        self.target_ = Target(s.boardsize_, self.board_, self.robots_)

        if (s.test_rounds_ > 0):
            self.test_rounds_ = s.test_rounds_
        else:
            self.test_rounds_ = 0

        self.players_ = s.assign_players()

        self.graphics_ = GraphicalBoard(s.boardsize_)
        self.sidebar_ = Sidebar(self.graphics_, self.players_)
        self.games_to_win_ = 7

    def KeyToDir(self, key):
        if key == pygame.K_UP:
            return "NORTH"
        elif key == pygame.K_DOWN:
            return "SOUTH"
        elif key == pygame.K_RIGHT:
            return "EAST"
        elif key == pygame.K_LEFT:
            return "WEST"
        else:
            return "NOT SUPPORTED"

    def Run(self):
        self.graphics_.drawBoardState(self.board_, self.robots_, self.target_)
        self.sidebar_.drawScoreboard(self.players_)
        self.sidebar_.displayMessage(["Click a player name to select."])
        game_over = False

        while True:
            pygame.time.delay(100)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.display.quit()
                    pygame.quit()
                    exit()
                if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
                    # get mouse input to determine player
                    current_player, other_player = self.sidebar_.DeterminePlayer(
                        event.pos)
                    if current_player == None:
                        break

                    # copy robot position for second player to try to find a better solution
                    robot_start_position = copy.deepcopy(self.robots_)

                    self.sidebar_.displayMessage(
                        ["Click a robot and move", " with arrow keys."])

                    # execute the moves of the current player
                    cp_move_count = current_player.execute_moves(
                        self, 10, "Manhattan Distance")
                    if cp_move_count == FAILURE or cp_move_count == TIME_CUTOFF or cp_move_count == DEPTH_CUTOFF:
                        print('{cp} was not able to reach the target. If {op} can find a solution, they win the round.'\
                            .format(cp=current_player.name_, op=other_player.name_))
                        cp_move_count = float("inf")
                    else:
                        print('{cp} was able to reach the target in {count} moves. {op} gets 1 minute to find a better solution.'\
                            .format(cp=current_player.name_, count=cp_move_count, op=other_player.name_))
                    pygame.time.delay(1000)

                    # reset board to the original, before any moves in the round
                    self.sidebar_.switchPlayer()
                    first_player_robots = self.robots_
                    self.robots_ = robot_start_position
                    self.graphics_.drawBoardState(self.board_, self.robots_,
                                                  self.target_)

                    # execute moves of the other player
                    op_move_count = other_player.execute_moves(
                        self, 10, "Manhattan Distance")
                    if op_move_count == FAILURE or op_move_count == TIME_CUTOFF or op_move_count == DEPTH_CUTOFF:
                        print('{op} was not able to reach the target.'\
                            .format(count=op_move_count, op=other_player.name_))
                        op_move_count = float("inf")
                    else:
                        print('{op} was able to reach the target in {count} moves.'\
                            .format(count=op_move_count, op=other_player.name_))
                    pygame.time.delay(1000)

                    # deselect all players, and calculate the score of the round
                    self.sidebar_.noPlayer()
                    if op_move_count < cp_move_count:
                        other_player.score_ += 1
                        print('{op} won the round.'.format(
                            op=other_player.name_))
                    elif cp_move_count == float(
                            "inf") and op_move_count == float("inf"):
                        self.robots = robot_start_position
                        self.sidebar_.displayMessage([
                            "Neither player found a",
                            "solution, no points awarded"
                        ])
                        pygame.time.delay(3000)
                    else:
                        current_player.score_ += 1
                        print('{cp} won the round.'.format(
                            cp=current_player.name_))
                        self.robots_ = first_player_robots

                    # reset move counters
                    for p in self.players_:
                        p.move_count_ = 0

                    # final messages of the round
                    self.sidebar_.displayMessage(
                        ["Round complete.", "Click a player name to select."])
                    self.sidebar_.drawScoreboard(self.players_)

                    # check if a player won
                    for p in self.players_:
                        if p.score_ == self.games_to_win_:
                            self.sidebar_.displayMessage(
                                ["{p} wins!".format(p=p.name_)])
                            game_over = True

                    # reset the target location
                    self.target_.set_target(self.board_, self.robots_)
                    self.graphics_.drawBoardState(self.board_, self.robots_,
                                                  self.target_)

    def Run_Test(self, limit=None, heuristic=None):
        self.graphics_.drawBoardState(self.board_, self.robots_, self.target_)

        test_csv_file = open('test_csvs/test.csv', mode='a+')
        csv_writer = csv.writer(test_csv_file, delimiter=';')

        csv_writer.writerow([])
        csv_writer.writerow([
            'AI', 'Board Size', 'Robots', 'Iteration', 'Outcome', 'Moves',
            'Nodes Expanded'
        ])

        successes = 0
        total_moves = 0
        total_nodes_expanded = 0

        for i in range(self.test_rounds_):
            pygame.time.delay(100)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.display.quit()
                    pygame.quit()
                    exit()

            current_player = self.players_[0]

            AI_name = current_player.name_
            if (heuristic != None):
                AI_name = current_player.name_ + " - " + str(heuristic)
            if (limit != 0 and limit != None):
                AI_name = current_player.name_ + " - " + str(limit)

            print("\n\nRunning test " + str(i + 1))

            cp_move_count = current_player.execute_moves(
                self, limit, heuristic)
            if (cp_move_count == FAILURE or cp_move_count == TIME_CUTOFF
                    or cp_move_count == DEPTH_CUTOFF):
                print('{cp} expanded {nodes} nodes.'.format(
                    cp=AI_name, nodes=current_player.nodes_expanded_))
                csv_writer.writerow([
                    AI_name, self.board_.boardsize_,
                    len(self.robots_), i + 1, cp_move_count
                ])
            else:
                successes += 1
                total_moves += cp_move_count
                total_nodes_expanded += current_player.nodes_expanded_
                print('{cp} was able to reach the target in {count} moves.'.
                      format(cp=AI_name, count=cp_move_count))
                print(
                    '{cp} expanded {nodes} nodes to find the solution.'.format(
                        cp=AI_name, nodes=current_player.nodes_expanded_))
                csv_writer.writerow([
                    AI_name, self.board_.boardsize_,
                    len(self.robots_), i + 1, 'SUCCESS', cp_move_count,
                    current_player.nodes_expanded_
                ])
            pygame.time.delay(1000)

            self.target_.set_target(self.board_, self.robots_)
            self.graphics_.drawBoardState(self.board_, self.robots_,
                                          self.target_)
        test_csv_file.close()
        print("Finished test")
        if (successes == 0):
            results = [
                AI_name,
                str(self.board_.boardsize_),
                str(len(self.robots_)),
                str(0)
            ]
        else:
            results = [
                AI_name,
                str(self.board_.boardsize_),
                str(len(self.robots_)),
                str(successes / self.test_rounds_),
                str(total_moves / successes),
                str(total_nodes_expanded / successes)
            ]
        return results
Example #26
0
class Graphics(object):
    def load_graphics(self):
        #default floor tile
        self.floor = pygame.image.load("graphics/floor_small.png").convert()
        
        #vertical, horizontal and fill walls
        self.wall_v = pygame.image.load("graphics/wall_v_small.png").convert()
        self.wall_h = pygame.image.load("graphics/wall_h_small.png").convert()
        self.wall_c = pygame.image.load("graphics/wall_c.png").convert()
        
        #robots and flags
        self.robots={"yellow":pygame.image.load("graphics/robot_yellow_small.png").convert(),
                         "red":pygame.image.load("graphics/robot_red_small.png").convert(),
                         "green":pygame.image.load("graphics/robot_green_small.png").convert(),
                         "blue":pygame.image.load("graphics/robot_blue_small.png").convert(),
                         "silver":pygame.image.load("graphics/robot_silver_small.png").convert()}
                         
        self.flags={"yellow":pygame.image.load("graphics/flag_yellow_small.png").convert(),
                        "red":pygame.image.load("graphics/flag_red_small.png").convert(),
                        "green":pygame.image.load("graphics/flag_green_small.png").convert(),
                        "blue":pygame.image.load("graphics/flag_blue_small.png").convert(),
                        "rainbow":pygame.image.load("graphics/flag_rainbow_small.png").convert()}
            
        #sidebar
        #title
        self.title = pygame.image.load("graphics/title.png").convert()      
        
        #dimensions for drawing
        self.tilesize = self.floor.get_width()
        self.wallsize = self.wall_c.get_width()
        self.sidebar_width = self.title.get_width()
    
    def __init__(self, gridsize, boardsize):
        #initialise display for converting pixel format of images
        self.screen=pygame.display.set_mode()
        
        #load images and set dimensions
        self.load_graphics()
        
        self.screensize = width, height = gridsize*self.tilesize + (gridsize+1)*self.wallsize + self.sidebar_width,gridsize*self.tilesize+(gridsize+1)*self.wallsize
        self.sidebar_rect = pygame.Rect(width-self.sidebar_width,0,self.sidebar_width,height)
        self.speed = 2 #pixels per frame
        self.black=0,0,0
        self.background=200,200,200
        self.screen=pygame.display.set_mode(self.screensize)
        pygame.display.set_caption("Ricochet Robots")
    
    def redraw_flag(self,board):
        self.screen.blit(self.flags[board.flag_colour],getXYGridOffset(board.flagloc[0],board.flagloc[1],self))
        pygame.display.flip()
    
    def redraw_robots(self,board):    
        for colour in board.robot_colours:
            self.screen.blit(self.robots[colour],getXYGridOffset(board.robots[colour].position[0],board.robots[colour].position[1],self))        
        pygame.display.flip()
        
    
    def draw_initial_board(self,board):
        #clear any previous game state
        self.screen.fill(self.background)  
        
        #sidebar - check if already exists in case of board reset
        if hasattr(self, 'sidebar'):
            self.sidebar.__init__(self,board)
        else:
            self.sidebar=Sidebar(self,board)        
        
        #draw
        for i in range(board.gridsize):
            for j in range(board.gridsize):
                self.screen.blit(self.floor,
                            (self.wallsize+i*(self.tilesize+self.wallsize),
                             self.wallsize+j*(self.tilesize+self.wallsize)))
        
        #set walls
        for i in range(board.boardsize):
            for j in range(board.boardsize):
                if board.boardstate[i,j]==1:
                    #horizontal, vertical or gap?
                    if i%2==0:
                        if j%2==0:
                            #gap
                            self.screen.blit(self.wall_c,
                                             (getXYOffset(i,j,self)))
                        else:
                            self.screen.blit(self.wall_h,
                                             (getXYOffset(i,j,self)))
                    else:
                        self.screen.blit(self.wall_v,
                                         (getXYOffset(i,j,self)))
                        
        #draw flag
        self.redraw_flag(board)
                
        #draw robot(s) at their turn start positions, which should be same as current in all cases
        self.robot_rects={}
        for colour in board.robot_colours:
            self.screen.blit(self.robots[colour],getXYGridOffset(board.robots[colour].position[0],board.robots[colour].position[1],self))
            self.robot_rects[colour]=self.robots[colour].get_rect()
            self.robot_rects[colour]=self.robot_rects[colour].move(getXYGridOffset(board.robots[colour].position[0],board.robots[colour].position[1],self))
        
        pygame.display.flip()
        
    def animate(self,board,key):                
        #check for reset (pressed r)
        if key in (pygame.K_r,pygame.K_n,pygame.K_f,pygame.K_u):
            self.draw_initial_board(board)
            return
               
        #check for show flags (pressed s)
        if key==pygame.K_s:
            self.redraw_flag(board)
            return
            
        #check for victory state - only allows reset options unless still needs to do the final animation to reach that state
        if board.victory and ((self.robot_rects[board.active_robot].left,self.robot_rects[board.active_robot].top)==getXYGridOffset(board.flagloc[0],board.flagloc[1],self)):
            if key not in (pygame.K_r,pygame.K_n,pygame.K_f,pygame.K_u,pygame.K_s):
                return        
        
        #find active robot
        robot=board.robots[board.active_robot]
        #image
        robot_image=self.robots[board.active_robot]
        #copy of active rectangle - must update before returning
        robotrect=self.robot_rects[board.active_robot]
        #ensure info pane has correct info
        if key in (pygame.K_1,pygame.K_2,pygame.K_3,pygame.K_4,pygame.K_5,pygame.K_KP1,pygame.K_KP2,pygame.K_KP3,pygame.K_KP4,pygame.K_KP5):
            self.sidebar.update_active_text(board.active_robot) 
            
        #determine number of frames from speed and difference between new robot position and old
        xnew,ynew=getXYGridOffset(robot.position[0],
                                    robot.position[1],
                                    self)
                                    
        xold,yold=getXYGridOffset(robot.last_position[0],
                                    robot.last_position[1],
                                    self)
            
        nframes=get_n_frames(xold,yold,xnew,ynew,self.speed)
                
        #case when no movement - do nothing
        if nframes==0:
            return
        
        #check whether flag needs including in animation
        draw_flag=check_flag_between_grid_locations(board.flagloc,tuple(robot.position),tuple(robot.last_position))
        flagloc=getXYGridOffset(board.flagloc[0],board.flagloc[1],self)
        
        #set lag to slow movement
        frame_delay=4
        
        if key == pygame.K_LEFT:
            #print 'left pressed'
            velocity=(-self.speed,0)
            #animate
            for frame in range(nframes):
                #fill rectangle with background - rectangle skips edge walls
                animation_rect = (xnew,ynew,xold-xnew+self.tilesize,self.tilesize)
                self.screen.fill(self.background,animation_rect)
                #draw floor (and flag when necessary) then robot in new location
                for i in range(1+robot.last_position[1]-robot.position[1]):
                    #print robot.position, robot.last_position, i
                    self.screen.blit(self.floor,
                                (self.wallsize+(robot.position[1]+i-1)*(self.tilesize+self.wallsize),
                                 self.wallsize+(robot.position[0]-1)*(self.tilesize+self.wallsize)))
                if draw_flag:
                    self.screen.blit(self.flags[board.flag_colour],flagloc)
                robotrect=robotrect.move(velocity)
                self.screen.blit(robot_image,robotrect)
                #pygame.display.flip()
                pygame.display.update(animation_rect)
                #slow animation down
                pygame.time.wait(frame_delay)
                       
        elif key == pygame.K_RIGHT:
            velocity=(self.speed,0)
            #animate
            for frame in range(nframes):
                #fill rectangle with background - rectangle skips edge walls
                animation_rect = (xold,ynew,xnew-xold+self.tilesize,self.tilesize)
                self.screen.fill(self.background,animation_rect)
                #draw floor (and flag when necessary) then robot in new location
                for i in range(1+robot.position[1]-robot.last_position[1]):
                    #print robot.position, robot.last_position, i
                    self.screen.blit(self.floor,
                                (self.wallsize+(robot.last_position[1]+i-1)*(self.tilesize+self.wallsize),
                                 self.wallsize+(robot.last_position[0]-1)*(self.tilesize+self.wallsize)))
                if draw_flag:
                    self.screen.blit(self.flags[board.flag_colour],flagloc)
                robotrect=robotrect.move(velocity)
                self.screen.blit(robot_image,robotrect)
                #pygame.display.flip()
                pygame.display.update(animation_rect)
                #slow animation down
                pygame.time.wait(frame_delay)            
        elif key == pygame.K_UP:
            velocity=(0,-self.speed)
            #animate
            for frame in range(nframes):
                #fill rectangle with background - rectangle skips edge walls
                animation_rect = (xnew,ynew,self.tilesize,yold-ynew+self.tilesize)
                self.screen.fill(self.background,animation_rect)
                #draw floor (and flag when necessary) then robot in new location
                for i in range(1+robot.last_position[0]-robot.position[0]):
                    #print robot.position, robot.last_position, i
                    self.screen.blit(self.floor,
                                (self.wallsize+(robot.position[1]-1)*(self.tilesize+self.wallsize),
                                 self.wallsize+(robot.position[0]+i-1)*(self.tilesize+self.wallsize)))
                if draw_flag:
                    self.screen.blit(self.flags[board.flag_colour],flagloc)
                robotrect=robotrect.move(velocity)
                self.screen.blit(robot_image,robotrect)
                #pygame.display.flip()
                pygame.display.update(animation_rect)
                #slow animation down
                pygame.time.wait(frame_delay)            
        elif key == pygame.K_DOWN:
            velocity=(0,self.speed)
            #animate
            for frame in range(nframes):
                #fill rectangle with background - rectangle skips edge walls
                animation_rect = (xnew,yold,self.tilesize,ynew-yold+self.tilesize)
                self.screen.fill(self.background,animation_rect)
                #draw floor (and flag when necessary) then robot in new location
                for i in range(1+robot.position[0]-robot.last_position[0]):
                    #print robot.position, robot.last_position, i
                    self.screen.blit(self.floor,
                                (self.wallsize+(robot.last_position[1]-1)*(self.tilesize+self.wallsize),
                                 self.wallsize+(robot.last_position[0]+i-1)*(self.tilesize+self.wallsize)))
                if draw_flag:
                    self.screen.blit(self.flags[board.flag_colour],flagloc)
                robotrect=robotrect.move(velocity)
                self.screen.blit(robot_image,robotrect)
                #pygame.display.flip()
                pygame.display.update(animation_rect)
                #slow animation down
                pygame.time.wait(frame_delay)              
        else:
            return
        
        #update moves taken and final robot rectangle
        self.sidebar.update_moves_text(board.moves_taken)
        self.robot_rects[board.active_robot]=robotrect
                
        return
            

            
            
Example #27
0
    def __init__(self, view, model, res_id=False, domain=[], context={}, action=None, fields=None):
        super(ViewTree, self).__init__(name='view_tree', action=action)

        self.model = view['model']
        self.domain2 = domain or []
        self.context = context or {}
        self.domain = []
        
        fields_info = dict(fields)

        self.field_parent = view.get("field_parent") or None

        if self.field_parent:
            self.domain = domain

        self.view = view
        self.view_id = view['view_id']

        proxy = rpc.RPCProxy(self.model)

        ctx = dict(self.context,
                   **rpc.session.context)
                
        dom = xml.dom.minidom.parseString(view['arch'].encode('utf-8'))

        root = dom.childNodes[0]
        attrs = node_attributes(root)
        self.string = attrs.get('string', 'Unknown')
        self.toolbar = attrs.get('toolbar', False)

        ids = []
        id = res_id
        
        colors = {}
        for color_spec in attrs.get('colors', '').split(';'):
            if color_spec:
                colour, test = color_spec.split(':')
                colors[colour] = test
                
        if self.toolbar:
            ids = proxy.search(self.domain2, 0, 0, 0, ctx)
            self.toolbar = proxy.read(ids, ['name', 'icon'], ctx)

            if not id and ids:
                id = ids[0]

            if id:
                ids = proxy.read([id], [self.field_parent], ctx)[0][self.field_parent]
        elif not ids:
            ids = proxy.search(domain, 0, 0, 0, ctx)

        self.headers = []
        self.parse(root, fields)

        self.tree = treegrid.TreeGrid(name="tree_%d" % (id),
                                      model=self.model,
                                      headers=self.headers,
                                      url=url("/openerp/tree/data"),
                                      ids=ids,
                                      domain=self.domain,
                                      context=self.context,
                                      field_parent=self.field_parent,
                                      onselection="onSelection",
                                      fields_info=fields_info,
                                      colors=colors)
        self.id = id
        self.ids = ids

        toolbar = {}
        for item, value in view.get('toolbar', {}).items():
            if value: toolbar[item] = value
        if toolbar:
            self.sidebar = Sidebar(self.model, None, toolbar, context=self.context)

        # get the correct view title
        self.string = self.context.get('_terp_view_name', self.string) or self.string
    def __init__(self):
        wx.Frame.__init__(self, None, title='OpenVPN Connector')

        self.CreateStatusBar()
        #Create multi-panel UI
        self.mainpanel = wx.Panel(self)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        splitter = wx.SplitterWindow(self.mainpanel)  #horizontal
        subsplitter = wx.SplitterWindow(splitter)  #vertical
        self.subsplitter = subsplitter
        # top_sizer = wx.BoxSizer(wx.HORIZONTAL)
        # top_panel = wx.Panel(subsplitter)

        self.sidebar = Sidebar(subsplitter)
        sidebarMenu = [("Configs", Configs), ("Command Flags", Flags),
                       ("Preferences", Preferences)]

        self.subpanels = {}
        for name, pnl in sidebarMenu:
            panel = pnl(self.subsplitter)
            panel.Hide()
            # top_sizer.Add(panel, 2, wx.ALL|wx.EXPAND, 2)
            self.subpanels[name] = panel
        self.subpanels["Configs"].Show()
        # self.currentpanel = self.subpanels["Configs"]
        # top_panelthe.SetSizer(top_sizer)

        #the bottom_sizer contains buttons and controls
        bottom_sizer = wx.BoxSizer(wx.HORIZONTAL)
        bottom_panel = wx.Panel(splitter)

        txt = Output(bottom_panel)

        control_grid = wx.GridSizer(cols=3)
        for label in [
                "Clear", "Export", "Reconnect", "Disconnect", "Force Reconnect"
        ]:
            btn = wx.Button(bottom_panel, label=label)
            btn.Bind(wx.EVT_BUTTON, self.OnButton)
            control_grid.Add(btn, 0, wx.ALL | wx.EXPAND, 2)
        # self.text = wx.StaticText(bottom_panel,label="Connection: None")
        # bottom_sizer.Add(self.text, 5, wx.ALL|wx.EXPAND, 2)

        bottom_sizer.Add(txt, 2, wx.ALL | wx.EXPAND, 2)
        bottom_sizer.Add(control_grid, 1, wx.ALL | wx.EXPAND, 2)
        bottom_panel.SetSizer(bottom_sizer)

        # mainsizer.Add(top_panel, 3, wx.ALL|wx.EXPAND, 0)
        # mainsizer.Add(bottom_panel, 1, wx.ALL|wx.EXPAND, 0)

        subsplitter.SplitVertically(self.sidebar, self.subpanels["Configs"])
        subsplitter.SetSashGravity(0.3)
        splitter.SplitHorizontally(subsplitter, bottom_panel)
        splitter.SetSashGravity(0.7)

        # mainsizer.Add(subsplitter, 1, wx.ALL|wx.EXPAND, 0)
        mainsizer.Add(splitter, 1, wx.ALL | wx.EXPAND, 5)
        self.mainsizer = mainsizer
        self.mainpanel.SetSizer(mainsizer)
        self.mainsizer.Fit(self)
        self.SetMinSize(self.GetBestSize())
        self.Show()

        # if reconnect == "1":
        # self.on.Disable()
        # if lastconnection != "0":
        # print("connecting to last used connection")
        # SubCall(lastconnection)
        # else:
        # self.off.Disable()

        #pub-sub
        pub.subscribe(self.DoConnect, "DoConnect")
        pub.subscribe(self.PubSubChangeMainPanel, "PubSubChangeMainPanel")

        #Timers
        self.log_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnLogTimer, self.log_timer)
        self.log_read = 0
Example #29
0
class Edistor(QPlainTextEdit):
    """ QPlainTextEdit implementation

        This class is the base of editor

        Highlight current line method:
            @color: string color
            @alpha: int
    """

    def __init__(self):
        QPlainTextEdit.__init__(self)
        self.position_margin = QFontMetricsF(
            self.document().defaultFont()).width("#") * 80
        # Margin line
        self._margin = False
        # Sidebar
        self.sidebar = Sidebar(self)
        # Highlight current line
        self._color_current_line = QColor('lightblue')
        self._alpha_current_line = self._color_current_line.setAlpha(50)
        # Connection
        self.connect(self, SIGNAL("blockCountChanged(int)"),
                    self.sidebar.update_area_width)
        self.connect(self, SIGNAL("updateRequest(const QRect&, int)"),
                    self.sidebar.update_area)
        self.connect(self, SIGNAL("cursorPositionChanged()"),
                    self._highlight_current_line)

        self._highlight_current_line()

    def margin(self, show=False):
        """ Set the margin line """
        if show:
            self._margin = Margin()

    def paintEvent(self, e):
        QPlainTextEdit.paintEvent(self, e)
        if self._margin:
            qp = QPainter()
            qp.begin(self.viewport())
            qp.setPen(self._margin.color)
            offset = self.contentOffset()
            qp.drawLine(self.position_margin + offset.x(), 0,
                        self.position_margin + offset.x(),
                        self.viewport().height())
            qp.end()

    def highlightCurrentLine(self, color, alpha):
        self._color_current_line = QColor(color)
        self._alpha_current_line = self._color_current_line.setAlpha(alpha)
        self._highlight_current_line()

    def _highlight_current_line(self):
        self.extra_selections = []
        selection = QTextEdit.ExtraSelection()
        selection.format.setBackground(self._color_current_line)
        selection.format.setProperty(
            QTextFormat.FullWidthSelection, QVariant(True))
        selection.cursor = self.textCursor()
        selection.cursor.clearSelection()
        self.extra_selections.append(selection)
        self.setExtraSelections(self.extra_selections)

    def resizeEvent(self, e):
        QPlainTextEdit.resizeEvent(self, e)
        cr = self.contentsRect()
        self.sidebar.setGeometry(QRect(cr.left(), cr.top(),
                                self.sidebar.width(), cr.height()))
    def __init__(self, params, **kw):

        super(ViewForm, self).__init__(**kw)

        # save reference of params dictionary in requeste
        cherrypy.request.terp_params = params
        cherrypy.request.terp_fields = []
        self.notebook_tab = params.notebook_tab or 0
        self.context_menu = params.get('context_menu')
        editable = params.editable
        readonly = params.readonly

        if editable is None:
            editable = True

        if readonly is None:
            readonly = False

        self.is_dashboard = getattr(cherrypy.request, '_terp_dashboard', False)

        self.search = None
        search_param = params.search_domain or []
        params_domain = params.domain or []
        for element in params_domain:
            if element not in search_param:
                if not isinstance(element, tuple):
                    search_param.append(element)
                else:
                    key, op, value = element
                    search_param.append((key, op, value))

        cherrypy.request.custom_search_domain = []
        cherrypy.request.custom_filter_domain = []

        if params.view_type in ('tree', 'graph'):
            search_view_id = False
            if params and '_terp_search_view' in params:
                if not params.search_view and params.context:
                    search_view_id = params.context.get('search_view')

            self.search = Search(source=params.source,
                                 model=params.model,
                                 domain=search_param,
                                 context=params.context,
                                 values=params.search_data or {},
                                 filter_domain=params.filter_domain or [],
                                 search_view=params.search_view,
                                 group_by_ctx=params.group_by_ctx or [],
                                 **{
                                     'clear': params.get('_terp_clear'),
                                     'search_view_id': search_view_id
                                 })

            cherrypy.request.custom_search_domain = self.search.listof_domain or []
            cherrypy.request.custom_filter_domain = self.search.custom_filter_domain or []
            params.search_domain = self.search.listof_domain
            params.filter_domain = self.search.custom_filter_domain
            params.group_by_ctx = self.search.groupby

        self.screen = Screen(prefix='',
                             hastoolbar=True,
                             hassubmenu=True,
                             editable=editable,
                             readonly=readonly,
                             selectable=params.selectable or 2)

        if self.screen.widget and self.screen.view_type in ['form', 'tree']:
            self.logs = Logs()

        if self.screen.widget and hasattr(self.screen.widget, 'sidebar'):
            self.sidebar = self.screen.widget.sidebar
        else:
            if params.target != 'new' and not self.screen.is_dashboard and not self.screen.is_wizard and (
                    len(params.view_mode) > 1 or 'tree' in params.view_mode):
                self.sidebar = Sidebar(self.screen.model,
                                       self.screen.submenu,
                                       self.screen.toolbar,
                                       self.screen.id,
                                       self.screen.view_type,
                                       context=self.screen.context)

        if params.view_type == 'tree':
            self.screen.id = False

        if 'form' not in self.screen.view_mode and not isinstance(
                self.screen.widget, ListGroup):
            self.screen.widget.link = 0
            self.screen.editable = False
            self.screen.widget.editable = False

        # get the correct view title
        if params.context:
            self.screen.string = params.context.get('_terp_view_name',
                                                    self.screen.string)
        self.screen.string = self.screen.string

        # get the actual pager data
        self.limit = self.screen.limit
        self.offset = self.screen.offset
        self.count = self.screen.count

        self.search_domain = params.search_domain
        self.search_data = params.search_data
        self.filter_domain = params.filter_domain or []

        if params.hidden_fields:
            self.hidden_fields = params.hidden_fields
Example #31
0
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9'  # X11 color: 'gray85'
        _ana1color = '#d9d9d9'  # X11 color: 'gray85'
        _ana2color = '#ececec'  # Closest X11 color: 'gray92'
        self.style = ttk.Style()
        if sys.platform == "win32":
            self.style.theme_use('winnative')
        self.style.configure('.', background=_bgcolor)
        self.style.configure('.', foreground=_fgcolor)
        self.style.configure('.', font="TkDefaultFont")
        self.style.map('.',
                       background=[('selected', _compcolor),
                                   ('active', _ana2color)])

        top.geometry("1280x686+212+135")
        top.minsize(120, 1)
        top.maxsize(3004, 1913)
        top.resizable(1, 1)
        top.title("New Toplevel")
        top.configure(background="#000040")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="#000000")

        top.resizable(False, False)
        global img
        img = ImageTk.PhotoImage(file="bg.png")
        self.Background = tk.Label(top, image=img)
        self.Background.place(relx=0, rely=0, height=900, width=1200)
        self.Background = img

        self.menubar = tk.Menu(top,
                               font="TkMenuFont",
                               bg=_bgcolor,
                               fg=_fgcolor)
        top.configure(menu=self.menubar)

        ################################################################Result instance############################################################
        self.Movie1 = tk.Frame(top)
        self.Movie1.place(relx=0.18,
                          rely=0.233,
                          relheight=0.138,
                          relwidth=0.621)

        self.Movie1.configure(relief='groove')
        self.Movie1.configure(borderwidth="2")
        self.Movie1.configure(relief="groove")
        self.Movie1.configure(background="#00002b")

        self.Image1 = tk.Label(self.Movie1)
        self.Image1.place(relx=0.025, rely=0.095, height=73, width=135)
        self.Image1.configure(background="#d9d9d9")
        self.Image1.configure(disabledforeground="#a3a3a3")
        self.Image1.configure(foreground="#000000")
        self.Image1.configure(text='''image''')

        self.Description1 = tk.Label(self.Movie1)
        self.Description1.place(relx=0.239, rely=0.095, height=73, width=573)
        self.Description1.configure(anchor='nw')
        self.Description1.configure(background="#00002b")
        self.Description1.configure(cursor="fleur")
        self.Description1.configure(disabledforeground="#a3a3a3")
        self.Description1.configure(font="-family {Segoe UI} -size 12")
        self.Description1.configure(foreground="#bcfbfe")
        self.Description1.configure(text='''description''')

        ##############################################################################################################################################

        ##################################################################scroller########################################################
        self.Previous = tk.Button(top)
        self.Previous.place(relx=0.383, rely=0.933, height=24, width=47)
        self.Previous.configure(activebackground="#ececec")
        self.Previous.configure(activeforeground="#000000")
        self.Previous.configure(background="#b4eafe")
        self.Previous.configure(disabledforeground="#a3a3a3")
        self.Previous.configure(font="-family {Segoe UI} -size 15")
        self.Previous.configure(foreground="#000000")
        self.Previous.configure(highlightbackground="#d9d9d9")
        self.Previous.configure(highlightcolor="black")
        self.Previous.configure(pady="0")
        self.Previous.configure(text='''<''')

        self.Next = tk.Button(top)
        self.Next.place(relx=0.57, rely=0.933, height=24, width=47)
        self.Next.configure(activebackground="#ececec")
        self.Next.configure(activeforeground="#000000")
        self.Next.configure(background="#b4eafe")
        self.Next.configure(disabledforeground="#a3a3a3")
        self.Next.configure(font="-family {Segoe UI} -size 15")
        self.Next.configure(foreground="#000000")
        self.Next.configure(highlightbackground="#d9d9d9")
        self.Next.configure(highlightcolor="black")
        self.Next.configure(pady="0")
        self.Next.configure(text='''>''')

        self.Page_list = tk.Label(top)
        self.Page_list.place(relx=0.43, rely=0.933, height=21, width=164)
        self.Page_list.configure(activebackground="#f0f0f0f0f0f0")
        self.Page_list.configure(background="#000040")
        self.Page_list.configure(disabledforeground="#a3a3a3")
        self.Page_list.configure(font="-family {Segoe UI} -size 12")
        self.Page_list.configure(foreground="#b4eafe")
        self.Page_list.configure(text='''1 of 4''')

        Searchbar.__init__(self, top=None)
        Memberbar.__init__(self, top=None)
        Homebar.__init__(self, top=None)
        Sidebar.__init__(self, top=None)
Example #32
0
class ShellView(gtk.TextView):
    __gsignals__ = {}

    sidebar_open = gobject.property(type=bool, default=False)

    def __init__(self, buf):
        self.edit_only = buf.worksheet.edit_only

        if not self.edit_only:
            buf.worksheet.sig_chunk_inserted.connect( self.on_chunk_inserted )
            buf.worksheet.sig_chunk_changed.connect( self.on_chunk_changed )
            buf.worksheet.sig_chunk_status_changed.connect( self.on_chunk_status_changed )
            buf.worksheet.sig_chunk_deleted.connect( self.on_chunk_deleted )
            buf.worksheet.sig_state.connect( self.on_notify_state )

            # Track changes to update completion
            buf.connect_after('insert-text', self.on_after_insert_text)
            buf.connect_after('delete-range', self.on_after_delete_range)
            buf.connect_after('end-user-action', self.on_after_end_user_action)

            self.__inserted_in_user_action = False
            self.__deleted_in_user_action = False

        if not self.edit_only:
            self.sidebar = Sidebar()
        else:
            self.sidebar = None

        buf.connect('add-custom-result', self.on_add_custom_result)
        buf.connect('add-sidebar-results', self.on_add_sidebar_results)
        buf.connect('remove-sidebar-results', self.on_remove_sidebar_results)
        buf.connect('pair-location-changed', self.on_pair_location_changed)
            
        gtk.TextView.__init__(self, buf)
        if not self.edit_only:
            self.set_border_window_size(gtk.TEXT_WINDOW_LEFT, LEFT_MARGIN_WIDTH)
        self.set_left_margin(2)

        # Attach a "behavior object" to the view which, by ugly hacks, makes it
        # do simply and reasonable things for cut-and-paste and DND
        sanitize_textview_ipc.sanitize_view(self)

        self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK)

        self.__completion_popup = CompletionPopup(self)
        self.__doc_popup = DocPopup()
        self.__mouse_over_object = None
        self.__mouse_over_timeout = None

        self.__mouse_over_start = buf.create_mark(None, buf.get_start_iter(), True)

        self.__arg_highlight_start = None
        self.__arg_highlight_end = None
        buf.connect('mark-set', self.on_mark_set)

        self.__cursor_chunk = None
        self.__scroll_to_result = False
        self.__scroll_to = buf.create_mark(None, buf.get_start_iter(), True)
        self.__scroll_idle = None

        self.__update_sidebar_positions_idle = 0
        self.__pixels_below_buffer = 0
        self.__last_chunk = None

        self.connect('destroy', self.on_destroy)

    def __get_worksheet_line_yrange(self, line):
        buffer_line = self.get_buffer().pos_to_iter(line)
        return self.get_line_yrange(buffer_line)

    def __get_chunk_yrange(self, chunk, include_padding=False, include_results=False):
        # include_padding: whether to include pixels_above/pixels_below
        # include_results: whether to include the results of the chunk

        y, _ = self.__get_worksheet_line_yrange(chunk.start)
        end_y, end_height = self.__get_worksheet_line_yrange(chunk.end - 1)
        height = end_y + end_height - y

        if isinstance(chunk, StatementChunk) and chunk.results_end_mark is not None:
            if include_results:
                buf = self.get_buffer()
                end_iter = buf.get_iter_at_mark(chunk.results_end_mark)
                end_line_y, end_line_height = self.get_line_yrange(end_iter)
                height = end_line_y + end_line_height - y

                if not include_padding:
                    y += chunk.pixels_above
                    height -= chunk.pixels_above + chunk.pixels_below
            else:
                # In this case, pixels_below is part of the results, which we don't include
                if not include_padding:
                    y += chunk.pixels_above
                    height -= chunk.pixels_above
        elif not include_padding:
            y += chunk.pixels_above
            height -= chunk.pixels_above + chunk.pixels_below

        return y, height

    def __get_worksheet_line_at_y(self, y, adjust):
        buf = self.get_buffer()
        (buffer_line, _) = self.get_line_at_y(y)
        return buf.iter_to_pos(buffer_line, adjust)[0]

    def paint_chunk(self, cr, area, chunk, fill_color, outline_color):
        buf = self.get_buffer()

        chunk_y, chunk_height = self.__get_chunk_yrange(chunk)

        _, window_y = self.buffer_to_window_coords(gtk.TEXT_WINDOW_LEFT, 0, chunk_y)
        cr.rectangle(area.x, window_y, area.width, chunk_height)
        cr.set_source_rgb(*fill_color)
        cr.fill()

        cr.rectangle(0.5, window_y + 0.5, LEFT_MARGIN_WIDTH - 1, chunk_height - 1)
        cr.set_source_rgb(*outline_color)
        cr.set_line_width(1)
        cr.stroke()

    def do_realize(self):
        gtk.TextView.do_realize(self)

        if not self.edit_only:
            self.get_window(gtk.TEXT_WINDOW_LEFT).set_background(self.style.white)

        # While the the worksheet is executing, we want to display a watch cursor
        # Trying to override the cursor setting of GtkTextView is really hard because
        # of things like hiding the cursor when typing, so we take the simple approach
        # of using an input-only "cover window" that we set the cursor on and
        # show on top of the GtkTextView's normal window.

        self.__watch_window = gtk.gdk.Window(self.window,
                                             self.allocation.width, self.allocation.height,
                                             gtk.gdk.WINDOW_CHILD,
                                             (gtk.gdk.SCROLL_MASK |
                                              gtk.gdk.BUTTON_PRESS_MASK |
                                              gtk.gdk.BUTTON_RELEASE_MASK |
                                              gtk.gdk.POINTER_MOTION_MASK |
                                              gtk.gdk.POINTER_MOTION_HINT_MASK),
                                             gtk.gdk.INPUT_ONLY,
                                             x=0, y=0)
        self.__watch_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
        self.__watch_window.set_user_data(self)

        if self.get_buffer().worksheet.state == NotebookFile.EXECUTING:
            self.__watch_window.show()
            self.__watch_window.raise_()

    def on_destroy(self, obj):
        self.__completion_popup.destroy()
        self.__completion_popup = None
        self.__doc_popup.destroy()
        self.__doc_popup = None

        if self.__scroll_idle is not None:
            glib.source_remove(self.__scroll_idle)

    def do_unrealize(self):
        self.__watch_window.set_user_data(None)
        self.__watch_window.destroy()
        self.__watch_window = None

        gtk.TextView.do_unrealize(self)

    def do_size_allocate(self, allocation):
        gtk.TextView.do_size_allocate(self, allocation)
        if (self.flags() & gtk.REALIZED) != 0:
            self.__watch_window.resize(allocation.width, allocation.height)

    def __iterate_expose_chunks(self, event):
        _, start_y = self.window_to_buffer_coords(gtk.TEXT_WINDOW_LEFT, 0, event.area.y)
        start_line = self.__get_worksheet_line_at_y(start_y, adjust=ADJUST_AFTER)

        _, end_y = self.window_to_buffer_coords(gtk.TEXT_WINDOW_LEFT, 0, event.area.y + event.area.height - 1)
        end_line = self.__get_worksheet_line_at_y(end_y, adjust=ADJUST_BEFORE)

        return self.get_buffer().worksheet.iterate_chunks(start_line, end_line + 1)

    def __expose_window_left(self, event):
        cr = event.window.cairo_create()

        for chunk in self.__iterate_expose_chunks(event):
            if isinstance(chunk, StatementChunk):
                if chunk.executing:
                    self.paint_chunk(cr, event.area, chunk, (0, 1, 0), (0, 0.5, 0))
                elif chunk.error_message is not None:
                    self.paint_chunk(cr, event.area, chunk, (1, 0, 0), (0.5, 0, 0))
                elif chunk.needs_compile:
                    self.paint_chunk(cr, event.area, chunk, (1, 1, 0), (0.5, 0.5, 0))
                elif chunk.needs_execute:
                    self.paint_chunk(cr, event.area, chunk, (1, 0, 1), (0.5, 0, 0.5))
                else:
                    self.paint_chunk(cr, event.area, chunk, (0, 0, 1), (0, 0, 0.5))

    def __draw_rect_outline(self, event, rect):
        if (rect.y + rect.height <= event.area.y or rect.y >= event.area.y + event.area.height):
            return

        cr = event.window.cairo_create()
        cr.set_line_width(1.)
        cr.rectangle(rect.x + 0.5, rect.y + 0.5, rect.width - 1, rect.height - 1)
        cr.set_source_rgb(0.6, 0.6, 0.6)
        cr.stroke()

    def __expose_arg_highlight(self, event):
        buf = self.get_buffer()

        # We want a rectangle enclosing the range between arg_highlight_start and
        # arg_highlight_end; the method here isn't correct in the presence of
        # RTL text, but the necessary Pango functionality isn't exposed to
        # a GtkTextView user. RTL code is rare. We also don't handle multiple-line
        # highlight regions right. (Return ends the highlight, so you'd need to paste)
        rect = self.get_iter_location(buf.get_iter_at_mark (self.__arg_highlight_start))
        rect.x, rect.y = self.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT,
                                                      rect.x, rect.y)
        rect.width = 0
        end_rect = self.get_iter_location(buf.get_iter_at_mark (self.__arg_highlight_end))
        end_rect.x, end_rect.y = self.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT,
                                                              end_rect.x, end_rect.y)
        end_rect.width = 0

        rect = rect.union(end_rect)

        self.__draw_rect_outline(event, rect)

    def __expose_pair_location(self, event):
        pair_location = self.get_buffer().get_pair_location()
        if pair_location is None:
            return
        
        rect = self.get_iter_location(pair_location)

        rect.x, rect.y = self.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT, rect.x, rect.y)

        self.__draw_rect_outline(event, rect)

    def __line_boundary_in_selection(self, line):
        buf = self.get_buffer()

        try:
            line_iter = buf.pos_to_iter(line)
        except IndexError:
            return

        sel_start, sel_end = buf.get_selection_bounds()
        return sel_start.compare(line_iter) < 0 and sel_end.compare(line_iter) >= 0

    def __expose_padding_areas(self, event):
        buf = self.get_buffer()

        # This is a fixup for the padding areas we add to chunks when leaving
        # space for sidebar widgets - gtk.TextView draws these areas as part
        # of the chunk that is being padded (so partially selected when the
        # line is partially selected.) This just looks wrong, so we paint over
        # that so that padding areas are _between_ lines.

        cr = event.window.cairo_create()

        left_margin = self.get_property('left-margin')
        right_margin = self.get_property('right-margin')
        selection_left, _ = self.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT,
                                                         left_margin, 0)
        window_width, _ = event.window.get_size()
        # 1 here is gtktextview.c:SPACE_FOR_CURSOR - padding on the right for the cursor
        selection_width = window_width - left_margin - right_margin - 1

        for chunk in self.__iterate_expose_chunks(event):
            if chunk.pixels_above != 0 or chunk.pixels_below != 0:
                total_y, total_height = self.__get_chunk_yrange(chunk, include_padding=True, include_results=True)
                no_pad_y, no_pad_height = self.__get_chunk_yrange(chunk, include_padding=False, include_results=True)
                _, total_y = self.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT, 0, total_y)
                _, no_pad_y = self.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT, 0, no_pad_y)

                if chunk.pixels_above != 0:
                    cr.rectangle(selection_left, total_y,
                                 selection_width, no_pad_y - total_y)
                    if self.__line_boundary_in_selection(chunk.start):
                        cr.set_source_color(self.style.base[gtk.STATE_SELECTED])
                    else:
                        cr.set_source_color(self.style.base[self.state])
                    cr.fill()

                if chunk.pixels_below != 0:
                    cr.rectangle(selection_left, no_pad_y + no_pad_height,
                                 selection_width, total_y + total_height - (no_pad_y + no_pad_height))
                    if self.__line_boundary_in_selection(chunk.end):
                        cr.set_source_color(self.style.base[gtk.STATE_SELECTED])
                    else:
                        cr.set_source_color(self.style.base[self.state])
                    cr.fill()

    def __update_last_chunk(self, new_last_chunk):
        buf = self.get_buffer()

        if self.__last_chunk and self.__pixels_below_buffer != 0:
            buf.set_pixels_below(self.__last_chunk, 0)

        self.__last_chunk = new_last_chunk
        if self.__pixels_below_buffer != 0:
            buf.set_pixels_below(self.__last_chunk, self.__pixels_below_buffer)

    def __set_pixels_below_buffer(self, pixels_below):
        self.set_pixels_below_lines(pixels_below)
        self.get_buffer().set_pixels_below(self.__last_chunk, pixels_below)
        self.__pixels_below_buffer = pixels_below

    def __update_sidebar_positions(self):
        # Each StatementChunk with sidebar widgets has already been added as a "slot"
        # to the sidebar. For each of these slots we determine a vertical
        # range which includes the StatementChunk, and any preceding CommentChunk.
        #
        # We also handle adding space before slots with sidebar widgets and at the end
        # of the buffer so that previous sidebar widgets have enough room.
        #
        # Rather than trying to update things incrementally, we just run
        # through the chunks in the buffer twice and compute the positions from
        # scratch.

        self.__update_sidebar_positions_idle = 0
        buf = self.get_buffer()

        set_chunks = set()
        widget_end_y = None

        slots = self.sidebar.slots
        if len(slots) > 0:
            self.sidebar.freeze_positions()

            # Main position loop where we determine the slot positions
            #
            # The "slot_extra" here is the number of pixels inside the slot which were
            # added as chunk_above/chunk_below in previous runs of this code and will
            # be removed unless we add them again in this run.

            slot_index = 0
            for chunk in buf.worksheet.iterate_chunks(0, slots[-1].chunk.end):
                if chunk == slots[slot_index].chunk:
                    if slot_start_chunk is None:
                        slot_start_chunk = chunk
                        slot_extra = chunk.pixels_above + chunk.pixels_below
                    else:
                        slot_extra += chunk.pixels_above + chunk.pixels_below

                    slot_start_y, _ = self.__get_chunk_yrange(slot_start_chunk,
                                                              include_results=True, include_padding=True)

                    chunk_start_y, chunk_height =  self.__get_chunk_yrange(chunk,
                                                                           include_results=True, include_padding=True)
                    slot_height = chunk_start_y + chunk_height - slot_start_y - slot_extra

                    if widget_end_y is not None and widget_end_y > slot_start_y:
                        buf.set_pixels_above(slot_start_chunk, widget_end_y - slot_start_y)
                        set_chunks.add(slot_start_chunk)
                        slot_start_y = widget_end_y

                    slots[slot_index].set_position(slot_start_y, slot_height)

                    widget_end_y = slot_start_y + slots[slot_index].get_results_height()
                    slot_index += 1
                    slot_start_chunk = None
                else:
                    if isinstance(chunk, CommentChunk):
                        slot_start_chunk = chunk
                        slot_extra = chunk.pixels_above + chunk.pixels_below
                    elif isinstance(chunk, StatementChunk):
                        slot_start_chunk = None
                    elif slot_start_chunk is not None:
                        slot_extra += chunk.pixels_above + chunk.pixels_below

            self.sidebar.thaw_positions()

        # Any chunk we where didn't assign pixels_above needs to have pixels_above
        # set back to zero - it might have been set for some previous pass
        for chunk in buf.worksheet.iterate_chunks():
            if chunk.pixels_above != 0 and not chunk in set_chunks:
                buf.set_pixels_above(chunk, 0)

        # Finally, add space at the end of the buffer, if necessary

        pixels_below = 0
        if widget_end_y is not None:
            end_line_y, end_line_height = self.get_line_yrange(buf.get_end_iter())
            end_y = end_line_y + end_line_height - self.__pixels_below_buffer
            if widget_end_y > end_y:
                pixels_below = widget_end_y - end_y

        self.__set_pixels_below_buffer(pixels_below)

        return False

    def __queue_update_sidebar_positions(self, before_resize=False):

        # We want to position the sidebar results with respect to the buffer
        # contents, so position has to be done after validation finishes, but there
        # is no hook to figure that out for gtk.TextView(). So, what we do is
        # that we figure that if anything _interesting_ gets repositioned there
        # will be an expose event, and in the expose event, add an idle that
        # is low enough priority to run after validation finishes.
        #
        # Now, in the positioning process, we actually _modify_ the buffer
        # contents by adding space above chunks to give previoous sidebar
        # results enough room. This produces a quasi-circular dependency
        # and a loop - but since the addition of space modifies the layout
        # in a predictable way, we can just subtract that back out. What we
        # expect to happen is:
        #
        #  - Buffer modification
        #  - Expose event
        #  - Our idle runs, we compute positions, and add space
        #  - Expose event
        #  - Our idle runs, we compute positions, compensating for the added
        #    space; the new computation is the same, and nothing further happens.
        #
        # (If there is a bug in the compensation code, an infinite loop will
        # be triggered.)

        if len(self.sidebar.slots) == 0 and self.__pixels_below_buffer == 0:
            return

        if before_resize and self.__update_sidebar_positions_idle != 0:
            glib.source_remove(self.__update_sidebar_positions_idle)
            self.__update_sidebar_positions_idle = 0

        if self.__update_sidebar_positions_idle == 0:
            if before_resize:
                priority = PRIORITY_SIDEBAR_BEFORE_RESIZE
            else:
                priority = PRIORITY_SIDEBAR_AFTER_VALIDATE

            self.__update_sidebar_positions_idle = glib.idle_add(self.__update_sidebar_positions,
                                                                 priority=priority)

    def do_expose_event(self, event):
        buf = self.get_buffer()

        if not self.edit_only and event.window == self.get_window(gtk.TEXT_WINDOW_LEFT):
            self.__queue_update_sidebar_positions()
            self.__expose_window_left(event)
            return False

        gtk.TextView.do_expose_event(self, event)

        if event.window == self.get_window(gtk.TEXT_WINDOW_TEXT):
            if self.__arg_highlight_start:
                self.__expose_arg_highlight(event)
            else:
                self.__expose_pair_location(event)
            if buf.get_has_selection():
                self.__expose_padding_areas(event)

        return False

    # This is likely overengineered, since we're going to try as hard as possible not to
    # have tabs in our worksheets. We don't do the funky handling of \f.
    def __count_indent(self, text):
        indent = 0
        for c in text:
            if c == ' ':
                indent += 1
            elif c == '\t':
                indent += 8 - (indent % 8)
            else:
                break

        return indent

    def __find_outdent(self, iter):
        buf = self.get_buffer()
        line, _ = buf.iter_to_pos(iter)

        current_indent = self.__count_indent(buf.worksheet.get_line(line))

        while line > 0:
            line -= 1
            line_text = buf.worksheet.get_line(line)
            # Empty lines don't establish indentation
            if ALL_WHITESPACE_RE.match(line_text):
                continue

            indent = self.__count_indent(line_text)
            if indent < current_indent:
                return re.match(r"^[\t ]*", line_text).group(0)

        return ""

    def __find_default_indent(self, iter):
        buf = self.get_buffer()
        line, offset = buf.iter_to_pos(iter)

        while line > 0:
            line -= 1
            chunk = buf.worksheet.get_chunk(line)
            if isinstance(chunk, StatementChunk):
                return chunk.tokenized.get_next_line_indent(line - chunk.start)
            elif isinstance(chunk, CommentChunk) or isinstance(chunk, BlankChunk):
                return " " * self.__count_indent(buf.worksheet.get_line(line))

        return ""

    def __reindent_line(self, iter, indent_text):
        buf = self.get_buffer()
        insert_mark = buf.get_insert()

        line, pos = buf.iter_to_pos(iter, adjust=ADJUST_NONE)
        if line == None:
            return

        line_text = buf.worksheet.get_line(line)
        prefix = re.match(r"^[\t ]*", line_text).group(0)

        diff = self.__count_indent(indent_text) - self.__count_indent(prefix)
        if diff == 0:
            return 0

        common_len = 0
        for a, b in zip(prefix, indent_text):
            if a != b:
                break
            common_len += 1
    
        start = iter.copy()
        start.set_line_offset(common_len)
        end = iter.copy()
        end.set_line_offset(len(prefix))

        # Nitpicky-detail. If the selection starts at the start of the line, and we are
        # inserting white-space there, then the whitespace should be *inside* the selection
        mark_to_start = None
        if common_len == 0 and buf.get_has_selection():
            if buf.get_iter_at_mark(insert_mark).compare(start) == 0:
                mark_to_start = mark
                
            mark = buf.get_selection_bound()
            if buf.get_iter_at_mark(mark).compare(start) == 0:
                mark_to_start = mark
        
        buf.delete(start, end)
        buf.insert(end, indent_text[common_len:])

        if mark_to_start is not None:
            end.set_line_offset(0)
            buf.move_mark(mark_to_start, end)

        insert_iter = buf.get_iter_at_mark(insert_mark)
        insert_line, _ = buf.iter_to_pos(insert_iter, adjust=ADJUST_NONE)
        if insert_line == line:
            # We shifted the insertion cursor around behind gtk.TextView's back,
            # by inserting text on the same line; this will result in a wrong
            # virtual cursor position. Calling buf.place_cursor() will cause
            # the virtual cursor position to be reset to the proper value.
            buf.place_cursor(insert_iter)

        return diff

    def __reindent_selection(self, outdent):
        buf = self.get_buffer()

        bounds = buf.get_selection_bounds()
        if bounds == ():
            insert_mark = buf.get_insert()
            bounds = buf.get_iter_at_mark(insert_mark), buf.get_iter_at_mark(insert_mark)
        start, end = bounds

        line, _ = buf.iter_to_pos(start, adjust=ADJUST_AFTER)
        end_line, end_offset = buf.iter_to_pos(end, adjust=ADJUST_BEFORE)
        if end_offset == 0 and end_line > line:
            end_line -= 1

        iter = buf.pos_to_iter(line)

        if outdent:
            indent_text = self.__find_outdent(iter)
        else:
            indent_text = self.__find_default_indent(iter)

        diff = self.__reindent_line(iter, indent_text)

        if not buf.get_has_selection():
            iter = buf.get_iter_at_mark(buf.get_insert())
            if iter.get_line_offset() < len(indent_text):
                iter.set_line_offset(len(indent_text))
                buf.place_cursor(iter)

        while True:
            line += 1
            if line > end_line:
                return

            iter = buf.pos_to_iter(line)
            current_indent = self.__count_indent(buf.worksheet.get_line(line))
            self.__reindent_line(iter, max(0, " " * (current_indent + diff)))

    def __hide_completion(self):
        if self.__completion_popup.showing:
            self.__completion_popup.popdown()
            
    def do_focus_out_event(self, event):
        self.__hide_completion()
        self.__doc_popup.popdown()
        return gtk.TextView.do_focus_out_event(self, event)

    def __rewrite_window(self, event):
        # Mouse events on the "watch window" that covers the text view
        # during calculation need to be forwarded to the real text window
        # since it looks bad if keynav works, but you can't click on the
        # window to set the cursor, select text, and so forth

        if event.window == self.__watch_window:
            event.window = self.get_window(gtk.TEXT_WINDOW_TEXT)

        # Events on the left-margin window also get written so the user can
        # click there when starting a drag selection. We need to adjust the
        # X coordinate in that case
        if not self.edit_only and event.window == self.get_window(gtk.TEXT_WINDOW_LEFT):
            event.window = self.get_window(gtk.TEXT_WINDOW_TEXT)
            if event.type == gtk.gdk._3BUTTON_PRESS:
                # Workaround for http://bugzilla.gnome.org/show_bug.cgi?id=573664
                event.x = 50.
            else:
                event.x -= LEFT_MARGIN_WIDTH

    def do_button_press_event(self, event):
        self.__rewrite_window(event)

        self.__doc_popup.popdown()

        return gtk.TextView.do_button_press_event(self, event)

    def do_button_release_event(self, event):
        self.__rewrite_window(event)

        return gtk.TextView.do_button_release_event(self, event)

    def do_motion_notify_event(self, event):
        self.__rewrite_window(event)

        return gtk.TextView.do_motion_notify_event(self, event)

    def __remove_arg_highlight(self, cursor_to_end=True):
        buf = self.get_buffer()

        end = buf.get_iter_at_mark (self.__arg_highlight_end)

        buf.delete_mark(self.__arg_highlight_start)
        self.__arg_highlight_start = None
        buf.delete_mark(self.__arg_highlight_end)
        self.__arg_highlight_end = None

        if cursor_to_end:
            # If the arg_highlight ends at closing punctuation, skip over it
            tmp = end.copy()
            tmp.forward_char()
            text = buf.get_slice(end, tmp)

            if text in (")", "]", "}"):
                buf.place_cursor(tmp)
            else:
                buf.place_cursor(end)

    def do_key_press_event(self, event):
        buf = self.get_buffer()

        if self.__completion_popup.focused and self.__completion_popup.on_key_press_event(event):
            return True
        
        if self.__doc_popup.focused:
            self.__doc_popup.on_key_press_event(event)
            return True

        if not self.edit_only and event.keyval in (gtk.keysyms.F2, gtk.keysyms.KP_F2):
            self.__hide_completion()

            if self.__doc_popup.showing:
                self.__doc_popup.focus()
            else:
                self.show_doc_popup(focus_popup=True)

            return True

        if not self.__arg_highlight_start:
            self.__doc_popup.popdown()
        
        if event.keyval in (gtk.keysyms.KP_Enter, gtk.keysyms.Return):
            self.__hide_completion()

            if self.__arg_highlight_start:
                self.__remove_arg_highlight()
                self.__doc_popup.popdown()
                return True
            
            increase_indent = False
            insert = buf.get_iter_at_mark(buf.get_insert())
            line, pos = buf.iter_to_pos(insert, adjust=ADJUST_NONE)

            # Inserting return inside a ResultChunk would normally do nothing
            # but we want to make it insert a line after the chunk
            if line is None and not buf.get_has_selection():
                line, pos = buf.iter_to_pos(insert, adjust=ADJUST_BEFORE)
                iter = buf.pos_to_iter(line, -1)
                buf.place_cursor(iter)
                buf.insert_interactive(iter, "\n", True)
                
                return True

            buf.begin_user_action()
            
            gtk.TextView.do_key_press_event(self, event)
            # We need the chunks to be updated when computing the line indents
            buf.worksheet.rescan()

            insert = buf.get_iter_at_mark(buf.get_insert())
            
            self.__reindent_line(insert, self.__find_default_indent(insert))

            # If we have two comment lines in a row, assume a block comment
            if (line > 0 and
                isinstance(buf.worksheet.get_chunk(line), CommentChunk) and
                isinstance(buf.worksheet.get_chunk(line - 1), CommentChunk)):
                self.get_buffer().insert_interactive_at_cursor("# ", True)

            buf.end_user_action()
                
            return True
        elif event.keyval in (gtk.keysyms.Tab, gtk.keysyms.KP_Tab) and event.state & gtk.gdk.CONTROL_MASK == 0:
            buf.begin_user_action()
            self.__reindent_selection(outdent=False)
            buf.end_user_action()

            return True
        elif event.keyval == gtk.keysyms.ISO_Left_Tab and event.state & gtk.gdk.CONTROL_MASK == 0:
            buf.begin_user_action()
            self.__reindent_selection(outdent=True)
            buf.end_user_action()

            return True
        elif event.keyval == gtk.keysyms.space and event.state & gtk.gdk.CONTROL_MASK != 0:
            if self.__completion_popup.showing:
                if self.__completion_popup.spontaneous:
                    self.__completion_popup.popup(spontaneous=False)
                else:
                    self.__completion_popup.popdown()
            else:
                if self.__doc_popup.showing:
                    self.__doc_popup.popdown()
                self.__completion_popup.popup(spontaneous=False)
            return True
        elif event.keyval in (gtk.keysyms.z, gtk.keysyms.Z) and \
                (event.state & gtk.gdk.CONTROL_MASK) != 0 and \
                (event.state & gtk.gdk.SHIFT_MASK) == 0:
            buf.worksheet.undo()
            
            return True
        # This is the gedit/gtksourceview binding to cause your hands to fall off
        elif event.keyval in (gtk.keysyms.z, gtk.keysyms.Z) and \
                (event.state & gtk.gdk.CONTROL_MASK) != 0 and \
                (event.state & gtk.gdk.SHIFT_MASK) != 0:
            buf.worksheet.redo()
            
            return True
        # This is the familiar binding (Eclipse, etc). Firefox supports both
        elif event.keyval in (gtk.keysyms.y, gtk.keysyms.Y) and event.state & gtk.gdk.CONTROL_MASK != 0:
            buf.worksheet.redo()

            return True
        
        return gtk.TextView.do_key_press_event(self, event)

    def __show_mouse_over(self):
        self.__mouse_over_timeout = None
        
        if self.__completion_popup.showing:
            return
        
        self.__doc_popup.set_target(self.__mouse_over_object)
        location = self.get_buffer().get_iter_at_mark(self.__mouse_over_start)
        self.__doc_popup.position_at_location(self, location)
        self.__doc_popup.popup()

        return False
        
    def __stop_mouse_over(self):
        if self.__mouse_over_timeout:
            glib.source_remove(self.__mouse_over_timeout)
            self.__mouse_over_timeout = None
            
        self.__mouse_over_object = None
        
    def do_motion_notify_event(self, event):
        # Successful mousing-over depends on knowing the types of symbols so doing the
        # checks are pointless in edit-only mode
        if not self.edit_only and event.window == self.get_window(gtk.TEXT_WINDOW_TEXT) and not self.__doc_popup.focused:
            buf = self.get_buffer()
            
            x, y = self.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, int(event.x), int(event.y))
            iter, _ = self.get_iter_at_position(x, y)
            line, offset = buf.iter_to_pos(iter, adjust=ADJUST_NONE)
            if line is not None:
                obj, start_line, start_offset, _,_ = buf.worksheet.get_object_at_location(line, offset)
            else:
                obj = None

            if not obj is self.__mouse_over_object:
                self.__stop_mouse_over()
                self.__doc_popup.popdown()
                if obj is not None:
                    start = buf.pos_to_iter(start_line, start_offset)
                    buf.move_mark(self.__mouse_over_start, start)

                    self.__mouse_over_object = obj
                    try:
                        timeout = self.get_settings().get_property('gtk-tooltip-timeout')
                    except TypeError: # GTK+ < 2.12
                        timeout = 500
                    self.__mouse_over_timeout = glib.timeout_add(timeout, self.__show_mouse_over)
                
        return gtk.TextView.do_motion_notify_event(self, event)

    def do_leave_notify_event(self, event):
        self.__stop_mouse_over()
        if not self.__doc_popup.focused:
            self.__doc_popup.popdown()
        return False

    def do_backspace(self):
        buf = self.get_buffer()
        
        if buf.get_has_selection():
            return gtk.TextView.do_backspace(self)

        insert = buf.get_iter_at_mark(buf.get_insert())
        line, offset = buf.iter_to_pos(insert)
        
        current_chunk = buf.worksheet.get_chunk(line)
        if isinstance(current_chunk, StatementChunk) or isinstance(current_chunk, BlankChunk):
            line_text = buf.worksheet.get_line(line)[0:offset]

            if re.match(r"^[\t ]+$", line_text) and not (line > 0 and self.is_continued(line - 1)):
                self.__reindent_selection(outdent=True)
                return
                       
        return gtk.TextView.do_backspace(self)

    def is_continued(self, line):
        """Determine if line causes a continuation."""
        buf = self.get_buffer()
        chunk = buf.worksheet.get_chunk(line)
        while not isinstance(chunk, StatementChunk) and line > 0:
            line -= 1
            chunk = buf.worksheet.get_chunk(line)
        return isinstance(chunk, StatementChunk) and chunk.tokenized.is_continued(line - chunk.start)

    def __invalidate_status(self, chunk):
        buf = self.get_buffer()
        
        chunk_y, chunk_height = self.__get_chunk_yrange(chunk, include_padding=True)

        _, window_y = self.buffer_to_window_coords(gtk.TEXT_WINDOW_LEFT, 0, chunk_y)

        if self.window:
            left_margin_window = self.get_window(gtk.TEXT_WINDOW_LEFT)
            left_margin_window.invalidate_rect((0, window_y, LEFT_MARGIN_WIDTH, chunk_height),
                                               False)

    def on_chunk_inserted(self, worksheet, chunk):
        buf = self.get_buffer()

        self.__invalidate_status(chunk)
        if chunk.end == buf.worksheet.get_line_count():
            self.__update_last_chunk(chunk)

    def on_chunk_changed(self, worksheet, chunk, changed_lines):
        self.__invalidate_status(chunk)

    def on_chunk_status_changed(self, worksheet, chunk):
        self.__invalidate_status(chunk)
        
        if self.__cursor_chunk == chunk and not chunk.executing:
            # This is the chunk with the cursor and it's done executing
            self.__scroll_idle = glib.idle_add(self.scroll_result_onscreen,
                                               priority=PRIORITY_SCROLL_RESULT_ONSCREEN)

    def scroll_result_onscreen(self):
        """Scroll so that both the insertion cursor and the following result
        are onscreen.  If we cannot get both, get as much of the result while
        still getting the insertion cursor."""

        buf = self.get_buffer()
        if self.__scroll_to_result:
            if self.__cursor_chunk.sidebar_results:
                # We assume that we don't have both sidebar and normal results
                for slot in self.sidebar.slots:
                    if slot.chunk == self.__cursor_chunk:
                        self.sidebar.scroll_to_slot_results(slot)
                        break
            else:
                try:
                    iter = buf.pos_to_iter(self.__cursor_chunk.end) # Start of next chunk
                except IndexError:
                    iter = buf.get_end_iter()
                else:
                    iter.backward_line() # Move to line before start of next chunk

                buf.move_mark(self.__scroll_to, iter)
                self.scroll_mark_onscreen(self.__scroll_to)

        self.scroll_mark_onscreen(buf.get_insert())

        self.__cursor_chunk = None
        self.__scroll_idle = None
        return False

    def on_chunk_deleted(self, worksheet, chunk):
        buf = self.get_buffer()

        if self.__cursor_chunk == chunk:
            self.__cursor_chunk = None
            if self.__scroll_idle is not None:
                glib.source_remove(self.__scroll_idle)
            self.__scroll_idle = None

        if self.__last_chunk == chunk:
            self.__last_chunk = None

            new_last_chunk = buf.worksheet.get_chunk(buf.worksheet.get_line_count() - 1)
            # We might find a newly created chunk that hasn't been "inserted" yet -
            # in that case, we wait until we get 'chunk_inserted'
            if hasattr(new_last_chunk, 'pixels_above'):
                self.__update_last_chunk(new_last_chunk)

    def on_notify_state(self, worksheet, param_spec):
        if (self.flags() & gtk.REALIZED) != 0:
            if worksheet.state == NotebookFile.EXECUTING:
                self.__watch_window.show()
                self.__watch_window.raise_()
            else:
                self.__watch_window.hide()

        self.set_cursor_visible(worksheet.state != NotebookFile.EXECUTING)

    def on_after_insert_text(self, buf, location, text, len):
        if buf.worksheet.in_user_action() and not buf.in_modification():
            self.__inserted_in_user_action = True

    def on_after_delete_range(self, buf, start, end):
        if buf.worksheet.in_user_action() and not buf.in_modification():
            self.__deleted_in_user_action = True

    def on_after_end_user_action(self, buf):
        if not buf.worksheet.in_user_action():
            if self.__completion_popup.showing:
                if self.__inserted_in_user_action or self.__deleted_in_user_action:
                    self.__completion_popup.update()
            else:
                if self.__inserted_in_user_action and global_settings.autocomplete:
                    self.__completion_popup.popup(spontaneous=True)
            self.__inserted_in_user_action = False
            self.__deleted_in_user_action = False

    def on_add_custom_result(self, buf, result, anchor):
        widget = result.create_widget()
        widget.show()
        self.add_child_at_anchor(widget, anchor)

    def on_add_sidebar_results(self, buf, chunk):
        if len(self.sidebar.slots) == 0:
            self.sidebar_open = True

        widgets = []
        for result in chunk.sidebar_results:
            widget = result.create_widget()
            widget.show()
            widgets.append(widget)

        self.sidebar.add_slot(chunk, widgets)

        # The final sidebar position calculation aren't be done until
        # we've finished revalidating the text view, but we need
        # to get some approproximate guess done before we allocate
        # the sidebar, or we'll get flashing
        self.__queue_update_sidebar_positions(before_resize=True)

    def on_remove_sidebar_results(self, buf, chunk):
        if len(self.sidebar.slots) == 1:
            self.__queue_update_sidebar_positions()
            self.sidebar_open = False

        self.sidebar.remove_slot(chunk)

    def on_mark_set(self, buffer, iter, mark):
        if self.__arg_highlight_start:
            # See if the user moved the cursor out of the highlight regionb
            buf = self.get_buffer()
            if mark != buf.get_insert():
                return

            if (iter.compare(buf.get_iter_at_mark(self.__arg_highlight_start)) < 0 or
                iter.compare(buf.get_iter_at_mark(self.__arg_highlight_end)) > 0):
                self.__remove_arg_highlight(cursor_to_end=False)

    def __invalidate_char_position(self, iter):
        y, height = self.get_line_yrange(iter)
        if self.window:
            text_window = self.get_window(gtk.TEXT_WINDOW_TEXT)
            width, _ = text_window.get_size()
            text_window.invalidate_rect((0, y, width, height), False)
        
    def on_pair_location_changed(self, buf, old_position, new_position):
        if old_position:
            self.__invalidate_char_position(old_position)
        if new_position:
            self.__invalidate_char_position(new_position)

    #######################################################
    # Public API
    #######################################################

    def calculate(self, end_at_insert=False):
        buf = self.get_buffer()
        line, _ = buf.iter_to_pos(buf.get_iter_at_mark(buf.get_insert()), ADJUST_BEFORE)

        if end_at_insert:
            end_line = line + 1 # +1 to include line with cursor
        else:
            end_line = None

        buf.worksheet.calculate(end_line=end_line)

        # If the cursor is in a StatementChunk or we are executing up to
        # the cursor, we will scroll the result into view.  Otherwise,
        # we will just scroll the cursor into view.  If there is no
        # StatementChunk between the cursor and the beginning of the
        # worksheet, or if the StatementChunk has already been executed,
        # there is no need to scroll at all.
        statement_line = line
        in_statement = True
        while line >= 0:
            chunk = buf.worksheet.get_chunk(statement_line)
            if isinstance(chunk, StatementChunk):
                if chunk.needs_compile or chunk.needs_execute:
                    self.__cursor_chunk = chunk
                    self.__scroll_to_result = end_at_insert or in_statement
                return
            statement_line -= 1
            in_statement = False

    def copy_as_doctests(self):
        buf = self.get_buffer()

        bounds = buf.get_selection_bounds()
        if bounds == ():
            start, end = buf.get_iter_at_mark(buf.get_insert())
        else:
            start, end = bounds

        start_line, start_offset = buf.iter_to_pos(start, adjust=ADJUST_BEFORE)
        end_line, end_offset = buf.iter_to_pos(end, adjust=ADJUST_BEFORE)

        doctests = buf.worksheet.get_doctests(start_line, end_line + 1)
        self.get_clipboard(gtk.gdk.SELECTION_CLIPBOARD).set_text(doctests)

    def show_doc_popup(self, focus_popup=False):
        """Pop up the doc popup for the symbol at the insertion point, if any

        @param focus_popup: if True, the popup will be given keyboard focus

        """

        buf = self.get_buffer()

        insert = buf.get_iter_at_mark(buf.get_insert())
        line, offset = buf.iter_to_pos(insert, adjust=ADJUST_NONE)
        if line is not None:
            obj, start_line, start_offset, _, _ = buf.worksheet.get_object_at_location(line, offset, include_adjacent=True)
        else:
            obj = None

        if obj is not None:
            start = buf.pos_to_iter(start_line, start_offset)
            self.__stop_mouse_over()
            self.__doc_popup.set_target(obj)
            self.__doc_popup.position_at_location(self, start)
            if focus_popup:
                self.__doc_popup.popup_focused()
            else:
                self.__doc_popup.popup()

    def highlight_arg_region(self, start, end):
        """Highlight the region between start and end for argument insertion.
        A box will be drawn around the region as long as the cursor is inside
        the region. If the user hits return, the cursor will be moved to the
        end (and past a single closing punctuation at the end, if any.)

        @param start iter at the start of the highlight region
        @param end iter at the end of the highlight region

        """

        buf = self.get_buffer()

        self.__arg_highlight_start = buf.create_mark(None, start, left_gravity=True)
        self.__arg_highlight_end = buf.create_mark(None, end, left_gravity=False)