def __init__(self,parent):
		super(MainWindow, self).__init__()
		self.graphics = Graphics()
		self.parent = parent
		self.setFixedSize(950,631)
		self.setWindowTitle("Balance of Power")
		self.setStyleSheet("QMainWindow::separator{ width: 0px; height: 0px, margin: -10px; }")
		self.world = World(4,False,0)
		self.policyWindow = PolicyWindow(self)
		self.mapView = MapView(self, self.world)
		self.statusBar = StatusBar(self)
		self.newGameWindow = NewGameWindow(self)
		self.newsWindow = NewsWindow(self)
		self.closeUpWindow = CloseUpWindow(self)
		self.scoresWindow = ScoresWindow(self)
		self.controlPanel = ControlPanel(self)
		self.lostGameWindow = LostGameWindow(self)
		for i in range(2,80,1):
			self.world.addNews(self.world.country[1], self.world.country[i], self.world.country[i], 2 + i%4, 1, 2, False)
		self.addDockWidget(Qt.BottomDockWidgetArea, self.controlPanel)
		self.addDockWidget(Qt.TopDockWidgetArea, self.statusBar)
		self.setCentralWidget(self.mapView)
		self.setWindowIcon(QIcon(self.graphics.progIcon))
		self.controlPanel.connectActions()
		self.menu = Menu(self)
		self.setMenuBar(self.menu)
		self.loadOptions()
		self.mapView.resetMapView()
		self.loadWorld()
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self)
        self.parent = parent
        self.setWindowTitle('imrenderin')

        ## Widgets
        self.menu_bar = MenuBar(self)
        self.menu_bar.setFixedHeight(25)
        self.status_bar = StatusBar(self)
        self.status_bar.setFixedHeight(35)

        ## Redirect stdout,stderr to dialog
        self.console = ConsoleDialog(sys.stdout)
        sys.stdout = self.console
        sys.stderr = self.console

        ## UI Elements
        self.display = Display(self)
        self.controls = DefaultUI(self, self.display)

        ## Layout
        vbox = QtGui.QVBoxLayout(self)
        vbox.addWidget(self.menu_bar)
        vbox.addWidget(self.controls)
        vbox.addWidget(self.status_bar)
        vbox.setSpacing(2)
        vbox.setContentsMargins(2, 2, 2, 2)

        self.setLayout(vbox)
        self.setMinimumWidth(200)
        self.setMinimumHeight(150)
        self.resize(_width, _height)
class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        LC_result = None

        old_age_choice = None
        old_gender_choices = None
        old_smk_years_choices = None
        old_qt_years_choices = None
        old_cpd_choices = None
        old_race_choices = None
        old_emp_choices = None
        old_flt_choices = None
        old_bmi_entry = None
        old_edu6_choices = None

        # init reading data table
        life_table = read_life_table_from_file(
            "input/Copy of Lung cancer_7-19-2019.xlsx")
        local_cancer = read_LC_table_from_file(
            "input/Copy of Lung cancer_7-19-2019.xlsx")
        regional_cancer = read_regional_cancer_table_from_file(
            "input/Copy of Lung cancer_7-19-2019.xlsx")
        distant_cancer = read_distant_cancer_table_from_file(
            "input/Copy of Lung cancer_7-19-2019.xlsx")

        # initiate the basehaz and the model_coef array to calculate the LCRAT_1mon_risk
        basehaz_G = get_basehaz_from_file("input/lcrisk_tool.xlsx", 6)
        basehaz_H = get_basehaz_from_file("input/lcrisk_tool.xlsx", 7)
        basehaz_J = get_basehaz_from_file("input/lcrisk_tool.xlsx", 9)
        model_coef_D = get_model_coef_from_file("input/lcrisk_tool.xlsx", 3)
        model_coef_F = get_model_coef_from_file("input/lcrisk_tool.xlsx", 5)

        self.memubar = MenuBar(parent)
        self.statusbar = StatusBar(self)
        self.toolbar = ToolBar(self)
        self.navbar = NavigationBar(self)
        self.main = Main(root)

        self.statusbar.pack(side="bottom", fill="x")
        self.toolbar.pack(side="top", fill="x")
        self.navbar.pack(side="left", fill="y")
        self.main.pack(side="right", fill="both", expand=True)

    def set_new_changing_state(p):
        global old_age_choice, old_gender_choices, old_smk_years_choices, old_qt_years_choices, old_cpd_choices, \
            old_race_choices, old_emp_choices, old_flt_choices, old_bmi_entry, old_edu6_choices

        old_age_choice = p.age
        old_gender_choices = p.gender
        old_smk_years_choices = p.smkyears
        old_qt_years_choices = p.qtyears
        old_cpd_choices = p.cpd
        old_race_choices = p.race
        old_emp_choices = p.emp
        old_flt_choices = p.fam_lung_trend
        old_bmi_entry = p.bmi
        old_edu6_choices = p.edu6
Example #4
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle("计算几何 测试")
        """
        菜单栏
        """
        newAct = QAction("&新建", self)
        newAct.setShortcuts(QKeySequence.New)
        newAct.setStatusTip("新建一个工程")
        newAct.triggered.connect(self.newProject)

        openAct = QAction("&打开", self)
        openAct.setShortcuts(QKeySequence.Open)
        openAct.setStatusTip("打开存在的工程")
        openAct.triggered.connect(self.openProject)

        fileMenu = self.menuBar().addMenu("&工程")
        fileMenu.addAction(newAct)
        fileMenu.addAction(openAct)
        """
        工具栏
        """
        fileToolBar = self.addToolBar("工程")
        fileToolBar.addAction(newAct)
        fileToolBar.addAction(openAct)

        fileToolBar.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea)
        self.addToolBar(Qt.TopToolBarArea, fileToolBar)
        """
        中心画布
        """
        self.mCanvas = MainCanvas()
        self.setCentralWidget(self.mCanvas)
        """
        状态栏
        """
        self.mStatusBar = StatusBar()
        self.setStatusBar(self.mStatusBar)
        """
        控制(dock)框
        """
        self.mCtrlWidget = CtrlWidget()
        ctrlDock = QDockWidget("控制")
        self.addDockWidget(Qt.RightDockWidgetArea, ctrlDock)
        ctrlDock.setWidget(self.mCtrlWidget)
        ctrlDock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        """
        绑定信号和槽
        """
        self.mCanvas.msCurrentChanged.connect(self.CurrentChanged)
        self.mCanvas.msMove.connect(self.mStatusBar.Move)
        self.mCtrlWidget.msRun.connect(self.Run)
Example #5
0
    def __init__(self):

        # settings
        self.buttonSize = 25
        self.defaultCanvasWidth = 500
        self.defaultCanvasHeight = 500
        self.padding = 20
        self.buttonImagePadding = 10
        self.adjBombTextSize = 25

        # window
        self.window = Tk()
        self.window.title("BOMBMOPPER")

        # frames
        self.statusFrame = Frame(self.window)
        self.statusFrame.pack(side=TOP)

        self.gameFrame = Frame(self.window)
        self.gameFrame.pack(side=BOTTOM)

        # canvas
        self.canvasWidth = self.defaultCanvasWidth
        self.canvasHeight = self.defaultCanvasHeight
        self.canvas = Canvas(self.gameFrame)
        self.canvas.config(width=self.canvasWidth,
                           height=self.canvasHeight,
                           background='gray',
                           highlightthickness=0)
        self.canvas.grid(column=0, row=0, sticky=(N, W, E, S))

        # play button
        self.playButton = PlayButton(self)

        # difficulty buttons
        self.easyButton = DifficultyButton(self, 'easy')
        self.intermediateButton = DifficultyButton(self, 'intermediate')
        self.hardButton = DifficultyButton(self, 'hard')

        # initialize board
        self.board = GameBoard(self)

        # initialize status bar
        self.statusBar = StatusBar(self)
        self.statusBar.packContents()
        self.window.update()
        self.statusBar.deactivate()

        # allow quitting without errors
        self.window.protocol('WM_DELETE_WINDOW', self.setInactive)
        self.isActive = True
Example #6
0
    def __init__(self, debugFlag, parent=None):
        QtGui.QWidget.__init__(self)

        self.debugFlag = debugFlag

        self.msgLog = MessageLog(debugFlag)
        self.statusBar = StatusBar(self.msgLog)
        self.buttonPanel = ButtonPanel(self.msgLog)
        self.buttonPanel.logPackageRequested.connect(self.packageLogs)

        self.statusBar.diskFillupDetected.connect(
            self.buttonPanel.handleDiskFillup)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.statusBar)
        mainLayout.addWidget(self.buttonPanel)
        mainLayout.addWidget(self.msgLog)
        self.setLayout(mainLayout)

        versionFile = open('../VERSION', 'r')
        versionNumber = versionFile.readline().rstrip('\n')
        if not Repo('..').head.is_detached:
            branchName = Repo('..').active_branch.name
        else:
            branchName = Repo('..').head.commit.hexsha
        versionText = versionNumber if (branchName == 'master') else branchName

        self.setWindowTitle('WillowGUI (%s)' % versionText)
        self.setWindowIcon(QtGui.QIcon('../img/round_logo_60x60.png'))
        #self.resize(400,200)
        self.center()

        ###
        try:
            self.startDaemon()
            self.msgLog.post('Daemon started.')
        except DaemonMissingError as e:
            self.msgLog.post('Path to daemon does not exist: %s' % e.path)

        try:
            hwif.init()
            self.msgLog.post('HWIF initialized.')
        except (ImportError, socket.error) as e:
            self.msgLog.post('Could not initialize HWIF.')

        self.statusBar.initializeWatchdog()
        def config_status(win):
            sdef = {
                    "timing":{
                        "justify":"center"
                        ,"minwidth":10
                    }

            }
            # check row number
            myStatusBar = StatusBar(win,1,sdef)
            return myStatusBar
Example #8
0
    def __init__(self, progPath, config, torrentHandler, persister, version):
        self.progPath = progPath
        self.config = config
        self.torrentHandler = torrentHandler
        self.persister = persister
        self.version = version
        
        self.log = logging.getLogger("Gui")
        self.stopFlag = False
        
        ##locale
        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
        
        
        ##Gui Stuff
        wx.Frame.__init__(self, None, -1, 'PyBit', size = wx.Size(800, 600), style = wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN)
        self.CentreOnScreen()
        
        #Layoutmanager
        vBox = wx.BoxSizer(wx.VERTICAL)
        
        #Menu
        menubar = wx.MenuBar()
        
        file = wx.Menu()
        file.Append(101, 'Add (by File)', 'Opens a torrent from your harddisk')
        file.Append(102, 'Add (by Url)', 'Fetches a torrent via http and adds it afterwards')
        file.AppendSeparator()
        file.Append(103, 'Create', 'Creates a new torrent')
        file.AppendSeparator()
        file.Append(104, 'Quit', 'Terminates the program, this could take a few seconds')
        menubar.Append(file, '&File')

        config = wx.Menu()
        config.Append(121, 'Configuration', 'Opens a configuration dialog')
        menubar.Append(config, '&Config')
        about = wx.Menu()
        about.Append(131, 'About', 'Information about the version and the authors of this software')
        about.Append(132, 'Show Changelog', 'Shows the changlog of PyBit')
        about.Append(133, 'Show Readme', 'Shows the readme')
        menubar.Append(about, '&About')
        
        self.SetMenuBar(menubar)
        
        #Windows
        self.splitter = wx.SplitterWindow(self, style=wx.CLIP_CHILDREN)
        self.splitter.SetMinimumPaneSize(50)
        
        #Child Windows
        self.childWindows = StatusPanel(self.splitter)        
        self.torrentStats = TorrentStats(self.torrentHandler.getStats, self.childWindows)
        self.torrentConnectionList = TorrentConnectionList(self.persister, self.version, self.torrentHandler.getStats, self.childWindows)
        self.torrentFileList = TorrentFileList(self.persister, self.version, self.torrentHandler.getStats, self.torrentHandler.setFilePriority, self.torrentHandler.setFileWantedFlag, self.childWindows)
        self.torrentRequestList = TorrentRequestList(self.persister, self.version, self.torrentHandler.getStats, self.childWindows)
        self.torrentTrackerList = TorrentTrackerList(self.persister, self.version, self.torrentHandler.getStats, self.torrentHandler.getTrackerInfo, self.torrentHandler.setTrackerInfo, self.childWindows)
        self.childWindows.addChild(self.torrentStats, 'General')
        self.childWindows.addChild(self.torrentConnectionList, 'Connections')
        self.childWindows.addChild(self.torrentFileList, 'Files')
        self.childWindows.addChild(self.torrentRequestList, 'Requests')
        self.childWindows.addChild(self.torrentTrackerList, 'Tracker')
        
        #Main Window
        self.torrentList = TorrentList(self.persister, self.version, self.torrentHandler, self.childWindows.changeTorrentId, self.torrentHandler.getStats, self.splitter)

        #startup the splitter
        self.splitter.SplitHorizontally(self.torrentList, self.childWindows)
        
        #Statusbar
        funcCaller = FunctionCallConverter(self.torrentHandler.getStats, funcKw={'wantedStats':{'transfer':True}},
                                           resultFilter=['inRawSpeed', 'outRawSpeed'], resultFilterFormat='list')
        self.sb = StatusBar(funcCaller.callForValue, self)
        self.SetStatusBar(self.sb)
        
        #Toolbar
        toolbar = self.CreateToolBar()
        toolbar.SetToolBitmapSize(wx.Size(22,22))
        toolbar.AddLabelTool(201, 'New', wx.BitmapFromImage(wx.Image('Icons/newFile.png', wx.BITMAP_TYPE_PNG)), shortHelp='Create Torrentfile', longHelp='Use to create a new torrent file')
        toolbar.AddLabelTool(202, 'Open File', wx.BitmapFromImage(wx.Image('Icons/openFile.png', wx.BITMAP_TYPE_PNG)), shortHelp='Open Torrentfile', longHelp='Use to open a torrent file')
        toolbar.AddLabelTool(203, 'Open Url', wx.BitmapFromImage(wx.Image('Icons/openUrl.png', wx.BITMAP_TYPE_PNG)), shortHelp='Fetch and open Torrentfile from url', longHelp='Use to fetch (and add) a torrent file via http')
        toolbar.AddSeparator()
        toolbar.AddLabelTool(211, 'Start',wx.BitmapFromImage(wx.Image('Icons/start.png', wx.BITMAP_TYPE_PNG)), shortHelp='Start', longHelp='Starts all selected torrents')
        toolbar.AddLabelTool(212, 'Stop',wx.BitmapFromImage(wx.Image('Icons/stop.png', wx.BITMAP_TYPE_PNG)), shortHelp='Stop', longHelp='Stops all selected torrents')
        toolbar.AddLabelTool(213, 'Remove',wx.BitmapFromImage(wx.Image('Icons/remove.png', wx.BITMAP_TYPE_PNG)), shortHelp='Remove', longHelp='Removes all selected torrents')
        toolbar.AddSeparator()
        toolbar.AddLabelTool(221, 'Up',wx.BitmapFromImage(wx.Image('Icons/up.png', wx.BITMAP_TYPE_PNG)), shortHelp='Up', longHelp='Moves all selected torrents one row up')
        toolbar.AddLabelTool(222, 'Down',wx.BitmapFromImage(wx.Image('Icons/down.png', wx.BITMAP_TYPE_PNG)), shortHelp='Down', longHelp='Moves all selected torrents one row down')
        toolbar.AddSeparator()
        toolbar.AddLabelTool(231, 'Quit', wx.BitmapFromImage(wx.Image('Icons/quit.png', wx.BITMAP_TYPE_PNG)), shortHelp='Quit', longHelp='Quits the application, this could take a moment.')
        toolbar.Realize()

        #menu events
        self.Bind(wx.EVT_MENU, self.OnAddFromFile, id=101)
        self.Bind(wx.EVT_MENU, self.OnAddFromUrl, id=102)
        self.Bind(wx.EVT_MENU, self.OnCreateTorrent, id=103)
        self.Bind(wx.EVT_MENU, self.OnClose, id=104)
        self.Bind(wx.EVT_MENU, self.OnConfig, id=121)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=131)
        self.Bind(wx.EVT_MENU, self.OnChangelog, id=132)
        self.Bind(wx.EVT_MENU, self.OnReadme, id=133)

        #toolbar events
        self.Bind(wx.EVT_TOOL, self.OnCreateTorrent, id=201)
        self.Bind(wx.EVT_TOOL, self.OnAddFromFile, id=202)
        self.Bind(wx.EVT_TOOL, self.OnAddFromUrl, id=203)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnStart, id=211)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnStop, id=212)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnRemove, id=213)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnUp, id=221)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnDown, id=222)
        self.Bind(wx.EVT_TOOL, self.OnClose, id=231)
        
        #other events
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.Show(True)
        
        #updater
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.timer.Start(1000)
Example #9
0
class Gui(wx.Frame):
    def __init__(self, progPath, config, torrentHandler, persister, version):
        self.progPath = progPath
        self.config = config
        self.torrentHandler = torrentHandler
        self.persister = persister
        self.version = version
        
        self.log = logging.getLogger("Gui")
        self.stopFlag = False
        
        ##locale
        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
        
        
        ##Gui Stuff
        wx.Frame.__init__(self, None, -1, 'PyBit', size = wx.Size(800, 600), style = wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN)
        self.CentreOnScreen()
        
        #Layoutmanager
        vBox = wx.BoxSizer(wx.VERTICAL)
        
        #Menu
        menubar = wx.MenuBar()
        
        file = wx.Menu()
        file.Append(101, 'Add (by File)', 'Opens a torrent from your harddisk')
        file.Append(102, 'Add (by Url)', 'Fetches a torrent via http and adds it afterwards')
        file.AppendSeparator()
        file.Append(103, 'Create', 'Creates a new torrent')
        file.AppendSeparator()
        file.Append(104, 'Quit', 'Terminates the program, this could take a few seconds')
        menubar.Append(file, '&File')

        config = wx.Menu()
        config.Append(121, 'Configuration', 'Opens a configuration dialog')
        menubar.Append(config, '&Config')
        about = wx.Menu()
        about.Append(131, 'About', 'Information about the version and the authors of this software')
        about.Append(132, 'Show Changelog', 'Shows the changlog of PyBit')
        about.Append(133, 'Show Readme', 'Shows the readme')
        menubar.Append(about, '&About')
        
        self.SetMenuBar(menubar)
        
        #Windows
        self.splitter = wx.SplitterWindow(self, style=wx.CLIP_CHILDREN)
        self.splitter.SetMinimumPaneSize(50)
        
        #Child Windows
        self.childWindows = StatusPanel(self.splitter)        
        self.torrentStats = TorrentStats(self.torrentHandler.getStats, self.childWindows)
        self.torrentConnectionList = TorrentConnectionList(self.persister, self.version, self.torrentHandler.getStats, self.childWindows)
        self.torrentFileList = TorrentFileList(self.persister, self.version, self.torrentHandler.getStats, self.torrentHandler.setFilePriority, self.torrentHandler.setFileWantedFlag, self.childWindows)
        self.torrentRequestList = TorrentRequestList(self.persister, self.version, self.torrentHandler.getStats, self.childWindows)
        self.torrentTrackerList = TorrentTrackerList(self.persister, self.version, self.torrentHandler.getStats, self.torrentHandler.getTrackerInfo, self.torrentHandler.setTrackerInfo, self.childWindows)
        self.childWindows.addChild(self.torrentStats, 'General')
        self.childWindows.addChild(self.torrentConnectionList, 'Connections')
        self.childWindows.addChild(self.torrentFileList, 'Files')
        self.childWindows.addChild(self.torrentRequestList, 'Requests')
        self.childWindows.addChild(self.torrentTrackerList, 'Tracker')
        
        #Main Window
        self.torrentList = TorrentList(self.persister, self.version, self.torrentHandler, self.childWindows.changeTorrentId, self.torrentHandler.getStats, self.splitter)

        #startup the splitter
        self.splitter.SplitHorizontally(self.torrentList, self.childWindows)
        
        #Statusbar
        funcCaller = FunctionCallConverter(self.torrentHandler.getStats, funcKw={'wantedStats':{'transfer':True}},
                                           resultFilter=['inRawSpeed', 'outRawSpeed'], resultFilterFormat='list')
        self.sb = StatusBar(funcCaller.callForValue, self)
        self.SetStatusBar(self.sb)
        
        #Toolbar
        toolbar = self.CreateToolBar()
        toolbar.SetToolBitmapSize(wx.Size(22,22))
        toolbar.AddLabelTool(201, 'New', wx.BitmapFromImage(wx.Image('Icons/newFile.png', wx.BITMAP_TYPE_PNG)), shortHelp='Create Torrentfile', longHelp='Use to create a new torrent file')
        toolbar.AddLabelTool(202, 'Open File', wx.BitmapFromImage(wx.Image('Icons/openFile.png', wx.BITMAP_TYPE_PNG)), shortHelp='Open Torrentfile', longHelp='Use to open a torrent file')
        toolbar.AddLabelTool(203, 'Open Url', wx.BitmapFromImage(wx.Image('Icons/openUrl.png', wx.BITMAP_TYPE_PNG)), shortHelp='Fetch and open Torrentfile from url', longHelp='Use to fetch (and add) a torrent file via http')
        toolbar.AddSeparator()
        toolbar.AddLabelTool(211, 'Start',wx.BitmapFromImage(wx.Image('Icons/start.png', wx.BITMAP_TYPE_PNG)), shortHelp='Start', longHelp='Starts all selected torrents')
        toolbar.AddLabelTool(212, 'Stop',wx.BitmapFromImage(wx.Image('Icons/stop.png', wx.BITMAP_TYPE_PNG)), shortHelp='Stop', longHelp='Stops all selected torrents')
        toolbar.AddLabelTool(213, 'Remove',wx.BitmapFromImage(wx.Image('Icons/remove.png', wx.BITMAP_TYPE_PNG)), shortHelp='Remove', longHelp='Removes all selected torrents')
        toolbar.AddSeparator()
        toolbar.AddLabelTool(221, 'Up',wx.BitmapFromImage(wx.Image('Icons/up.png', wx.BITMAP_TYPE_PNG)), shortHelp='Up', longHelp='Moves all selected torrents one row up')
        toolbar.AddLabelTool(222, 'Down',wx.BitmapFromImage(wx.Image('Icons/down.png', wx.BITMAP_TYPE_PNG)), shortHelp='Down', longHelp='Moves all selected torrents one row down')
        toolbar.AddSeparator()
        toolbar.AddLabelTool(231, 'Quit', wx.BitmapFromImage(wx.Image('Icons/quit.png', wx.BITMAP_TYPE_PNG)), shortHelp='Quit', longHelp='Quits the application, this could take a moment.')
        toolbar.Realize()

        #menu events
        self.Bind(wx.EVT_MENU, self.OnAddFromFile, id=101)
        self.Bind(wx.EVT_MENU, self.OnAddFromUrl, id=102)
        self.Bind(wx.EVT_MENU, self.OnCreateTorrent, id=103)
        self.Bind(wx.EVT_MENU, self.OnClose, id=104)
        self.Bind(wx.EVT_MENU, self.OnConfig, id=121)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=131)
        self.Bind(wx.EVT_MENU, self.OnChangelog, id=132)
        self.Bind(wx.EVT_MENU, self.OnReadme, id=133)

        #toolbar events
        self.Bind(wx.EVT_TOOL, self.OnCreateTorrent, id=201)
        self.Bind(wx.EVT_TOOL, self.OnAddFromFile, id=202)
        self.Bind(wx.EVT_TOOL, self.OnAddFromUrl, id=203)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnStart, id=211)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnStop, id=212)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnRemove, id=213)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnUp, id=221)
        self.Bind(wx.EVT_TOOL, self.torrentList.OnDown, id=222)
        self.Bind(wx.EVT_TOOL, self.OnClose, id=231)
        
        #other events
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.Show(True)
        
        #updater
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.timer.Start(1000)


    def OnTimer(self, event):
        try:
            if not self.stopFlag:
                #update Torrentlist
                self.torrentList.manualUpdate()
                self.childWindows.manualUpdate()

                #update Statusbar
                self.sb.manualUpdate()
        except:
            self.log.error("Failure in timer:\n%s", logTraceback())
            

    def OnAddFromFile(self, event):
        #torrentpath
        torrentDefaultDir = self.config.get('paths','torrentFolder')
        downloadDefaultDir = self.config.get('paths','downloadFolder')
        
        #let user select a torrent
        diag = wx.FileDialog(self, message='Select the torrent to open',defaultDir=torrentDefaultDir,\
                             wildcard='Torrent files (*.torrent)|*.torrent|All files (*.*)|*.*',\
                             style=wx.OPEN | wx.MULTIPLE)
        
        if diag.ShowModal() == wx.ID_OK:
            #user did select something
            torrentPaths = diag.GetPaths()
            
            #directory in which the download data should be stored
            saveDiag = wx.DirDialog(self, message='Select the directory in which the downloaded data should be stored',\
                                    defaultPath=downloadDefaultDir,style=wx.DD_NEW_DIR_BUTTON)
            if saveDiag.ShowModal() == wx.ID_OK:
                #user selected something
                savePath = saveDiag.GetPath()
                
                #load torrents one by one
                for torrentPath in torrentPaths:
                    self.log.info('Trying to read torrent file from "%s"', torrentPath)
                    try:
                        fl = open(torrentPath, 'rb')
                        with fl:
                            data = fl.read()
                    except (IOError, OSError):
                        data = None
                    
                    if data is None:
                        #failed to read file
                        self.log.error('Failed to read torrent file from "%s", torrent not added', torrentPath)
                        showErrorMessage(self, 'Failed to read torrent file from "%s".', torrentPath)
                    else:
                        #worked
                        self.log.info('Adding torrent with data path "%s"', savePath)
                        try:
                            self.torrentList.addTorrentByFile(data, savePath)
                        except MultiBtException, e:
                            self.log.error('Failed to add torrent, reason: %s', e.reason)
                            showErrorMessage(self, '%s.', e.reason)
                        except Exception, e:
                            self.log.critical('Internal error while adding torrent:\n%s', logTraceback())
                            showErrorMessage(self, 'Internal error, torrent not added.\n%s.', logTraceback())
            del saveDiag
Example #10
0
        indicatoron=False,
        width=12,
        defValue=True,
        callFunc=btnCallback,
        helpText="width=12, defValue=True, indicatoron=False",
    ).grid(row=row, column=col, sticky="w")
    row = 0
    col += 1
    Checkbutton(
        root,
        text="MmmmmNnnnn C",
        width=12,
        defValue=True,
        callFunc=btnCallback,
        helpText="defValue=True",
    ).grid(row=row, column=col, sticky="w")
    row += 1
    Checkbutton(
        root,
        text="MmmmmNnnnn D",
        indicatoron=False,
        width=12,
        defValue=True,
        callFunc=btnCallback,
        helpText="defValue=True, indicatoron=False",
    ).grid(row=row, column=col, sticky="w")
    row += 1
    StatusBar(root).grid(row=row, column=0, columnspan=3, sticky="ew")

    root.mainloop()
Example #11
0
 def create_statusbar(self):
     self.statusbar = StatusBar(master=self.master)
     self.statusbar.pack(fill=tk.X)
Example #12
0
class MainWindow(QtGui.QMainWindow):
	# custom signals
	errorString = QtCore.pyqtSignal(str)
	commonSet = QtCore.pyqtSignal(dict)
	uploadSignal = QtCore.pyqtSignal(QtCore.QString)
	contactMessage = QtCore.pyqtSignal(QtCore.QString, QtCore.QString)
	changeConnectState = QtCore.pyqtSignal()
	cacheDown = QtCore.pyqtSignal()
	serverDown = QtCore.pyqtSignal(str, str)
	serverDOWN = QtCore.pyqtSignal(str, str)
	initServeR = QtCore.pyqtSignal(TreeModel, str, str, bool)
	reinitServer = QtCore.pyqtSignal()
	setAccess = QtCore.pyqtSignal(str)
	netState = QtCore.pyqtSignal(str, str, int)
	def __init__(self, parent = None):
		QtGui.QMainWindow.__init__(self, parent)

		self.serverState = ''
		self.jobCount = 0
		self.commonSetOfSharedSource = {}
		self.USERS = {}
		self.SEP = os.sep

		#self.resize(450, 350)
		self.setWindowTitle('LightMight')
		self.setWindowIcon(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'tux_partizan.png'))

		self.Settings = QtCore.QSettings('LightMight','LightMight')
		self.Policy = Policy(self)
		self.avatarPath = InitConfigValue(self.Settings, 'AvatarPath', '')

		self.exit_ = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'exit.png'), '&Exit', self)
		self.exit_.setShortcut('Ctrl+Q')
		self.exit_.setStatusTip('Exit application')
		self.connect(self.exit_, QtCore.SIGNAL('triggered()'), self._close)

		listHelp = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'&About LightMight', self)
		listHelp.setStatusTip('Read help')
		self.connect(listHelp,QtCore.SIGNAL('triggered()'), self.showMSG)

		commonSettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'&Common Settings', self)
		commonSettings.setStatusTip('Set avatars, use cache, etc.')
		self.connect(commonSettings, QtCore.SIGNAL('triggered()'), self.showCommonSettingsShield)

		serverSettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'&Server Settings', self)
		serverSettings.setStatusTip('Set shared source, encrypt, etc.')
		self.connect(serverSettings, QtCore.SIGNAL('triggered()'), self.showServerSettingsShield)

		clientSettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'C&lient Settings', self)
		clientSettings.setStatusTip('Set the download path, etc.')
		self.connect(clientSettings, QtCore.SIGNAL('triggered()'), self.showClientSettingsShield)

		proxySettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'&Proxy Settings', self)
		proxySettings.setStatusTip('Set proxy...')
		self.connect(proxySettings, QtCore.SIGNAL('triggered()'), self.showProxySettingsShield)

		#colorSettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'Color&Font and Background', self)
		#colorSettings.setStatusTip('Set font color & background.')
		#self.connect(colorSettings, QtCore.SIGNAL('triggered()'), self.showColorSettingsShield)

		self.statusBar = StatusBar(self)
		self.setStatusBar(self.statusBar)

		menubar = self.menuBar()

		file_ = menubar.addMenu('&File')
		file_.addAction(self.exit_)

		set_ = menubar.addMenu('&Settings')
		set_.addAction(commonSettings)
		set_.addAction(serverSettings)
		set_.addAction(clientSettings)
		set_.addAction(proxySettings)
		#set_.addAction(colorSettings)

		help_ = menubar.addMenu('&Help')
		help_.addAction(listHelp)

		self.menuTab = Box(self)
		self.setCentralWidget(self.menuTab)

		self.trayIconMenu = QtGui.QMenu(self)
		show_hide = self.trayIconMenu.addAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'tux_partizan.png'), 'Hide / Show')
		self.connect(show_hide, QtCore.SIGNAL('triggered()'), self.show_n_hide)
		help_tray = self.trayIconMenu.addAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'), 'Help')
		self.connect(help_tray, QtCore.SIGNAL('triggered()'), self.showMSG)
		exit_tray = self.trayIconMenu.addAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'exit.png'), '&Exit')
		self.connect(exit_tray, QtCore.SIGNAL('triggered()'), self._close)
		self.trayIconPixmap = QtGui.QPixmap('..' + self.SEP + 'icons' + self.SEP + 'tux_partizan.png') # файл иконки
		self.trayIcon = QtGui.QSystemTrayIcon(self)
		self.trayIcon.setToolTip('LightMight')
		self.trayIcon.setContextMenu(self.trayIconMenu)
		self.trayIcon.setIcon(QtGui.QIcon(self.trayIconPixmap))
		self.connect(self.trayIcon, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), \
																			self.trayIconClicked)
		self.trayIcon.show()

		self.errorString.connect(self.showMSG)
		self.commonSet.connect(self.preProcessingComplete)
		self.uploadSignal.connect(self.uploadTask)
		self.contactMessage.connect(self.receiveBroadcastMessage)
		self.changeConnectState.connect(self.initAvahiBrowser)
		self.cacheDown.connect(self.cacheS)
		self.initServeR.connect(self.checkNetwork)
		self.reinitServer.connect(self.checkNetwork)
		self.serverDown.connect(self.menuTab.preStartServer)
		self.setAccess.connect(self.confirmAction)
		self.netState.connect(self.standByDown)
		self.StandBy = QtCore.QTimer()
		self.StandBy.timeout.connect(self.checkNetwork)
		self.StandBy.setInterval(20000)

		## 0 -- off; 1 -- on
		self.NetworkState = 1
		self.runServer4Proxy = 0

		self.restoredInitParameters = (None, None, '', False)
		self.searchCertificate()
		self.checkNetwork()

	def searchCertificate(self):
		pubKeyPath = Path.config('pubKey.pem')
		prvKeyPath = Path.config('prvKey.pem')
		if not os.path.isfile(pubKeyPath) or not os.path.isfile(prvKeyPath) :
			createCertificate()
		with open(pubKeyPath, 'rb') as f :
			_str = f.read()
			self.servPubKey = _str.encode('utf-8')
			self.servPubKeyHash = hashKey(self.servPubKey)
		with open(prvKeyPath, 'rb') as f :
			_str = f.read()
			self.servPrvKey = _str.encode('utf-8')

	'''
	data =  0/1/A/R(offline/online/answer/reinit)<separator>
			remoteServerName<separator>
			address<separator>
			port<separator>
			Encoding<separator>
			Status<separator>
			ShareInfo
	'''

	def receiveBroadcastMessage(self, data, addr):
		if data.count('<||>') != 6 : return None	## ignore non-standart packets
		mark, name, addr_in_data, port, encode, state, info = data.split('<||>', QtCore.QString.KeepEmptyParts)
		print 'New request :', mark, QtCore.QString().fromUtf8(name), addr_in_data, port, encode, state, info
		''' check correct IP for local network '''
		if addr == addr_in_data :
			if   mark == '1' : self.sentAnswer(addr); self.addNewContact(name, addr, port, encode, state, None, False)
			elif mark == '0' : self.delContact(name, addr_in_data, port, encode, state)
			elif mark == 'A' : self.addNewContact(name, addr, port, encode, state, None, False)
			elif mark == 'R' : self.reInitRequest(name, addr, port, encode, state)

	def sentAnswer(self, addr):
		name_ = InitConfigValue(self.Settings, 'ServerName', 'Own Avahi Server')
		if self.TLS :
			encode = 'Yes'
		else :
			encode = 'No'
		data = QtCore.QString('A' + '<||>' + \
							  name_ + '<||>' + \
							  self.server_addr + '<||>' + \
							  str(self.server_port) + '<||>' + \
							  encode + '<||>' + \
							  self.serverState + '<||>' + \
							  '*infoShare*')
		#Sender(data, addr)
		s = threading.Thread(target = Sender,  args = (data, addr,))
		s.start()

	def reInitRequest(self, name, addr, port, encode, state):
		 pass

	def delContact(self, name, addr, port, encode, state):
		#print [QtCore.QString().fromUtf8(name), addr, port, encode, state] , 'Must die!'
		if addr is not None and port is not None :
			key = str(addr + ':' + port)
			if key in self.USERS :
				for i in xrange(self.menuTab.userList.count()) :
					item_ = self.menuTab.userList.item(i)
					if item_ is not None and item_.data(QtCore.Qt.AccessibleTextRole).toList()[0] == key :
						self.menuTab.userList.takeItem(self.menuTab.userList.row(item_))
						if key in self.USERS :
							del self.USERS[key]
							#print key, 'deleted'
						_addr = str(addr)
						if self.serverThread is not None and _addr in self.serverThread.Obj.currentSessionID :
							del self.serverThread.Obj.currentSessionID[_addr]
							#print _addr, 'deletedDD'
						break
		else :
			item = self.menuTab.userList.findItems(name, \
					QtCore.Qt.MatchFlags(QtCore.Qt.MatchCaseSensitive))
			domain = str(state)
			#print item, ' find list'
			if len(item) > 0 :
				for item_ in item :
					data = item_.data(QtCore.Qt.AccessibleTextRole).toList()
					#for _item in data : print _item.toString()
					if str(data[1].toString()).lower()=='true' :
						# because avahi & broadcast reinit together
						if domain in data[2:] :
							self.menuTab.userList.takeItem(self.menuTab.userList.row(item_))
							key = str(data[0].toString())
							if key in self.USERS :
								del self.USERS[key]
								str_ = key.split(':')
								self.delContact(None, str_[0], str_[1], None, None)
								#print key, 'deleted in avahi_type'
		#print 'DEL down'

	def addNewContact(self, name, addr, port, encode, state, domain, avahi_method = True):
		#print [QtCore.QString().fromUtf8(name), addr, port, domain], 'new contact'
		key = str(addr + ':' + port)
		''' check uniqualled contact (uniqual IP:port) '''
		if not avahi_method :
			if key in self.USERS :
				'''
				print 'Not uniqual contact(B):', unicode(self.USERS[iter_][0]), \
												 self.USERS[iter_][1], \
												 self.USERS[iter_][2]
				'''
				return False
			addrExist = False
			for item in self.USERS.iterkeys() :
				if item.startswith(addr) :
					addrExist = True
					old_port = item.split(':')[1]
					break
			if addrExist : self.delContact(None, addr, old_port, None, None)
		else :
			''' check not uniqual name (avahi u. name > broadcast u. name) '''
			if key in self.USERS :
				'''
				print 'Not uniqual contact(A):', unicode(self.USERS[iter_][0]), \
												 self.USERS[iter_][1], \
												self.USERS[iter_][2]
				'''
				for i in xrange(self.menuTab.userList.count()) :
					item_ = self.menuTab.userList.item(i)
					data = item_.data(QtCore.Qt.AccessibleTextRole).toList()
					if domain not in data[2:] :
						data.append(domain)
						data[1] = avahi_method
						item_.setData(QtCore.Qt.AccessibleTextRole, QtCore.QVariant(data))
					return True
		new_item = QtGui.QListWidgetItem(name)
		_data = [key, 'true' if avahi_method else 'false', domain]
		new_item.setData(QtCore.Qt.AccessibleTextRole, QtCore.QVariant(_data))
		in_cashe, path_ = InCache(state)
		if in_cashe :
			head, tail = os.path.split(str(path_))
			path_ = os.path.join(head, 'avatars', tail)
		else :
			path_ = Path.tempAvatar(state)

		new_item.setIcon(QtGui.QIcon(path_))
		new_item.setToolTip(toolTipsHTMLWrap(path_, \
							'name : ' + name + '<br>'\
							'\naddress : ' + addr + '<br>'\
							'\nport : ' + port + '<br>'\
							'\nEncoding : ' + encode + '<br>'\
							'\nServerState : ' + state))
		self.menuTab.userList.addItem(new_item)
		""" Keys of USERS defined by "addr:port", because it uniqual property,
			but "state" may be not changed. In cache the important\exclusive role
			has the status of remote server.
		"""
		self.USERS[key] = (name, addr, port, encode, state, False)
		#print self.USERS
		return True

	def preinitAvahiBrowser(self):
		#if 'avahiBrowser' in dir(self) :	## multiply contact
		#	if '__del__' in dir(self.avahiBrowser) : self.avahiBrowser.__del__(); self.avahiBrowser = None
		# stopping caching
		if 'cachingThread' in dir(self) :
			self.cachingThread._shutdown()
			self.cachingThread.quit()
			del self.cachingThread
		if 'udpClient' in dir(self) :
			self.udpClient.stop()
		else : self.initAvahiBrowser()

	def cacheS(self):
		print 'Cache down signal received'

	def initAvahiBrowser(self):
		if str(self.Settings.value('AvahiDetect', 'True').toString())=='True' and 'avahiBrowser' not in dir(self):
			print 'Use Avahi'
			if ModuleExist.AvahiAvailable and 'avahiBrowser' not in dir(self) :
				self.avahiBrowser = AvahiBrowser(self.menuTab)
				self.avahiBrowser.start()
		if str(InitConfigValue(self.Settings, 'UseCache', 'False')) == 'True' :
			print 'Use Cache'
			self.cachingThread = DataCache(self.USERS, self)
			self.cachingThread.start()
		if str(self.Settings.value('BroadcastDetect', 'True').toString())=='True' :
			print 'Use Broadcast'
			self.udpClient = UdpClient(self)
			self.udpClient.start()
		else : self.initAvahiService()

	def initAvahiService(self):
		if 'avahiService' in dir(self) :
			if '__del__' in dir(self.avahiService) : self.avahiService.__del__()
			self.avahiService = None
		name_ = InitConfigValue(self.Settings, 'ServerName', 'Own Avahi Server')
		if self.TLS :
			encode = 'Yes'
		else :
			encode = 'No'
		if ModuleExist.AvahiAvailable and str(self.Settings.value('AvahiDetect', 'True').toString())=='True' :
			self.avahiService = AvahiService(self.menuTab, \
								name = name_, \
								port = self.server_port, \
								description = 'Encoding=' + encode + ';' + \
											  'State=' + str(self.serverState) + ';' + \
											  'Port=' + str(self.server_port) + ';' + \
											  'Address=' + self.server_addr + ';' + \
											  'Name=' + name_.toUtf8().data())
			self.avahiService.start()
		self.initBroadcast(name_, encode)

	def initBroadcast(self, name_ = None, encode = None):
		if name_ is None or encode is None : return None
		if str(self.Settings.value('BroadcastDetect', 'True').toString())=='True' :
			data = QtCore.QString('1' + '<||>' + \
								  name_ + '<||>' + \
								  self.server_addr + '<||>' + \
								  str(self.server_port) + '<||>' + \
								  encode + '<||>' + \
								  self.serverState + '<||>' + \
								  '*infoShare*')
			#Sender(data)
			s = threading.Thread(target = Sender, args = (data,))
			s.start()

	def checkNetwork(self, sharedSourceTree = None, \
						 loadFile = None, previousState = '', \
						 restart = False):
		self.StandBy.stop()
		if self.NetworkState == 1 : self.menuTab.enableRestartButton(False)
		if type(sharedSourceTree) == TreeModel :
			self.restoredInitParameters = (sharedSourceTree, loadFile, previousState, restart)
		checkNetwork = NetworkCheck(self)
		if not self.menuTab.progressBar.isVisible(): self.menuTab.progressBar.show()
		self.statusBar.clearMessage()
		self.statusBar.showMessage('Server offline')
		checkNetwork.start()

	def standByDown(self, address = '', msg = '', netState = 2):
		self.server_addr = str(address)
		self.server_port = getFreePort(int(InitConfigValue(self.Settings, 'MinPort', '34000')), \
										int(InitConfigValue(self.Settings, 'MaxPort', '34100')), \
										self.server_addr)[1]
		print [self.server_addr, ':', self.server_port], 'free'
		if netState > 1 :
			if self.NetworkState == 1 :
				self.NetworkState = 0
				st = str(msg + '\nStandBy?')
				question = QtGui.QMessageBox.question(self, 'Message', st, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
				if question == QtGui.QMessageBox.No : sys.exit(0)
				else :
					## standby mode run
					if 'cachingThread' in dir(self) :
						self.cachingThread._shutdown()
						self.cachingThread.quit()
						del self.cachingThread
					
					self.trayIconPixmap = QtGui.QPixmap('..' + self.SEP + 'icons' + self.SEP + 'LightMight_standBy.png')
					self.trayIcon.setToolTip('LightMight (StandBy)')
					self.trayIcon.setIcon(QtGui.QIcon(self.trayIconPixmap))
					self.menuTab.enableRestartButton(False)
			self.StandBy.start()
			return None
		self.NetworkState = 1
		self.runServer4Proxy = 1 if self.Settings.value('UseProxy', 'False')=='True' and not netState else 0
		self.trayIconPixmap = QtGui.QPixmap('..' + self.SEP + 'icons' + self.SEP + 'tux_partizan.png')
		self.trayIcon.setToolTip('LightMight')
		self.trayIcon.setIcon(QtGui.QIcon(self.trayIconPixmap))
		self.show()
		# init server
		self.initServer(self.restoredInitParameters[0], \
						self.restoredInitParameters[1], \
						self.restoredInitParameters[2], \
						self.restoredInitParameters[3])

	def initServer(self, sharedSourceTree = None, \
						 loadFile = None, previousState = '', \
						 restart = False):
		#print 'FN:%s\nPS:%s\nR:%s' % (loadFile, previousState, restart)
		self.previousState = previousState
		self.menuTab.progressBar.show()
		if 'serverThread' in dir(self) and restart :
			''' restart (old state) '''
			treeModel = sharedSourceTree
			firstRun = False
			del self.serverThread
			self.serverThread = None
			del self.serverPThread
			self.serverPThread = None
			self.serverState = self.previousState
		elif 'serverThread' in dir(self) :
			''' reinit (new state) '''
			treeModel = sharedSourceTree
			firstRun = False
			del self.serverThread
			self.serverThread = None
			del self.serverPThread
			self.serverPThread = None
			self.serverState = randomString(DIGITS_LENGTH)
		else :
			''' init (last state if it saved) '''
			treeModel = TreeModel('Name', 'Description')
			firstRun = True
			lastServerState = str(InitConfigValue(self.Settings, 'LastServerState', ''))
			#print [lastServerState]
			if lastServerState != '' : self.serverState = lastServerState
			else : self.serverState = randomString(DIGITS_LENGTH)

		""" create file of SharedResurces Structure """
		if firstRun :
			path_ = Path.config('lastSharedSource')
			if lastServerState != '' and os.path.exists(path_) :
				shutil.move(path_, Path.multiPath(Path.tempStruct, 'server', 'sharedSource_' + self.serverState))
			else :
				S = SharedSourceTree2XMLFile('sharedSource_' + self.serverState, treeModel.rootItem)
				S.__del__(); S = None
		elif loadFile is not None and loadFile != '' :
			if not moveFile(loadFile, Path.multiPath(Path.tempStruct, 'server', 'sharedSource_' + self.serverState), False) :
				S = SharedSourceTree2XMLFile('sharedSource_' + self.serverState, treeModel.rootItem)
				S.__del__(); S = None
		else :
			S = SharedSourceTree2XMLFile('sharedSource_' + self.serverState, treeModel.rootItem)
			S.__del__(); S = None
		self.serverReinited = firstRun

		""" creating match dictionary {number : fileName} """
		treeModel = TreeModel('Name', 'Description')		## cleaned treeModel.rootItem
		pathToLoadFile = Path.multiPath(Path.tempStruct, 'server', 'sharedSource_' + self.serverState)
		#with open(pathToLoadFile, 'rb') as f :
		#	print '%s consist :\n%s\n---END---' % (pathToLoadFile, f.read())
		self.threadSetupTree = SetupTree(TreeProcessing(), \
										[pathToLoadFile], \
										treeModel, \
										self, \
										True, \
										self)
		self.threadSetupTree.start()

	def preProcessingComplete(self, commonSet = {}):
		""" this for server commonSet """
		self.commonSetOfSharedSource = commonSet
		#print len(self.commonSetOfSharedSource), ' commonSet.count \n' #, self.commonSetOfSharedSource
		self.serverStart()
		self.serverPStart()

	def serverStart(self):
		if 'True' == str(InitConfigValue(self.Settings, 'UseTLS', 'False')) :
			self.TLS = True
		else :
			self.TLS = False
		#print self.TLS, '  <--- using TLS'
		self.serverThread = ToolsThread(\
										ServerDaemon( (self.server_addr, self.server_port), \
													self.commonSetOfSharedSource, \
													self, \
													TLS = self.TLS, \
													cert = None), \
										parent = self)
		self.serverThread.start()
		if self.serverReinited : self.preinitAvahiBrowser()
		else : self.initAvahiService()
		self.statusBar.clearMessage()
		self.statusBar.showMessage('Server online')
		self.menuTab.progressBar.hide()
		self.menuTab.enableRestartButton(True)

	def serverPStart(self):
		if not self.runServer4Proxy : return None
		self.serverP_addr = getExternalIP()
		if self.serverP_addr == '' : return None
		'''self.serverP_port = getFreePort(int(InitConfigValue(self.Settings, 'MinPort', '34000')), \
										int(InitConfigValue(self.Settings, 'MaxPort', '34100')), \
										'127.0.0.1')[1]
		'''
		self.serverP_port = self.server_port
		print [self.serverP_addr, ':', self.serverP_port], 'proxied server address'
		self.serverPThread = ToolsThread(\
										ServerDaemon( ('127.0.0.1', self.serverP_port), \
													self.commonSetOfSharedSource, \
													self, \
													TLS = self.TLS, \
													cert = None), \
										parent = self)
		self.serverPThread.start()

	def uploadTask(self, info):
			Info = unicode(info)
			job = QtCore.QProcess()
			self.jobCount += 1
			""" посчитать объём загрузок, создать файл с данными соответствия путей
				и ключей в self.commonSetOfSharedSource сервера
			"""
			nameMaskFile = randomString(DIGITS_LENGTH)
			with open(Path.multiPath(Path.tempStruct, 'client', nameMaskFile), 'a') as handler :
				downLoadSize = \
					TreeProcessing().getCommonSetOfSharedSource(self.menuTab.treeModel.rootItem, \
																None, \
																checkItem = True, \
																f = handler)[1]
			serverState = Info.partition('ServerState : ')[2].partition('</td>')[0].partition('\n')[0].replace('<br>', '')
			serverAddr = Info.partition('address : ')[2].partition('\n')[0].partition('<br>')[0]
			serverPort = Info.partition('port : ')[2].partition('\n')[0].partition('<br>')[0]
			description = Info.partition('Shared Source :')[0]
			encoding = Info.partition('Encoding : ')[2].partition('\n')[0].partition('<br>')[0]
			if encoding == 'Yes' :
				encode = 'True'
			else :
				encode = 'False'
			"""
			print   '\n\n!!!!', serverState, \
					'\n\n!!!!', serverAddr, \
					'\n\n!!!!', serverPort, \
					'\n\n!!!!', description, \
					'\n\n!!!!', encoding, '  info'
			"""
			""" task run """
			if serverAddr not in self.serverThread.Obj.currentSessionID :
				self.showMSG('Session not exist.\nMay be remote server reinit or close.')
				return None
			pid, start = job.startDetached('python', \
						 (QtCore.QStringList()	<< '.' + self.SEP + 'DownLoadClient.py' \
												<< nameMaskFile \
												<< str(downLoadSize) \
												<< str(self.jobCount) \
												<< serverState \
												<< serverAddr \
												<< serverPort \
												<< description \
												<< encode \
												<< self.serverThread.Obj.currentSessionID[serverAddr][0] \
												<< self.serverThread.Obj.currentSessionID[serverAddr][3]), \
						 os.getcwd())

	def show_n_hide(self):
		if self.isVisible():
			self.hide()
			self.menuTab.sharedTree.hide()
		else:
			self.show()
			#self.menuTab.sharedTree.show()

	def trayIconClicked(self, reason):
		if reason == QtGui.QSystemTrayIcon.DoubleClick :
			self.show_n_hide()

	def showMSG(self, str_ = "README"):
		if str_ == "README" :
			STR_ = '..' + self.SEP + '..' + self.SEP + 'README'
		else :
			STR_ = "MSG: " + str_
		showHelp = ListingText(STR_, self)
		showHelp.exec_()

	def showCommonSettingsShield(self):
		_CommonSettingsShield = CommonSettingsShield(self)
		_CommonSettingsShield.exec_()

	def showClientSettingsShield(self):
		_ClientSettingsShield = ClientSettingsShield(self)
		_ClientSettingsShield.exec_()

	def showServerSettingsShield(self):
		_ServerSettingsShield = ServerSettingsShield(self)
		self.serverDOWN.connect(_ServerSettingsShield.preInitServer)
		_ServerSettingsShield.exec_()
		self.serverDOWN.disconnect(_ServerSettingsShield.preInitServer)

	def showProxySettingsShield(self):
		_ProxySettingsShield = ProxySettingsShield(self)
		_ProxySettingsShield.exec_()

	'''def showColorSettingsShield(self):
		_ColorSettingsShield = ColorSettingsShield(self)
		_ColorSettingsShield.exec_()'''

	def confirmAction(self, address):
		_ConfirmRequest = ConfirmRequest(address, self)
		confirm = _ConfirmRequest.exec_()

	def disconnectSignals(self):
		if 'contactMessage' in dir(self) :
			self.contactMessage.disconnect(self.receiveBroadcastMessage)
		if 'changeConnectState' in dir(self) :
			self.changeConnectState.disconnect(self.initAvahiBrowser)
		if 'initServeR' in dir(self) :
			self.initServeR.disconnect(self.checkNetwork)
		if 'reinitServer' in dir(self) :
			self.reinitServer.disconnect(self.checkNetwork)
		if 'serverDown' in dir(self) :
			self.serverDown.disconnect(self.menuTab.preStartServer)

	def stopServices(self, restart = False, loadFile = '', mode = ''):
		if restart : self.statusBar.showMessage('Restart Services')
		else : self.statusBar.showMessage('Stop Services')
		# send offline packet
		self.menuTab.sentOfflinePost()
		# caching stop
		if not restart and 'cachingThread' in dir(self) :
			self.cachingThread._shutdown()
			self.cachingThread.quit()
			#del self.cachingThread
		# stop services
		if not restart and 'avahiBrowser' in dir(self) :
			if '__del__' in dir(self.avahiBrowser) : self.avahiBrowser.__del__()
			self.avahiBrowser = None
		if not restart and 'avahiService' in dir(self) :
			if '__del__' in dir(self.avahiService) : self.avahiService.__del__()
			self.avahiService = None
		if not restart and 'udpClient' in dir(self) :
			self.udpClient.stop()
		'''# send 'close session' request
		try :
			for item in self.USERS.iterkeys() :
				_addr, _port = item.split(':') if item in self.USERS else ('', '')
				addr = str(_addr); port = str(_port)
				if self.USERS[item][3] == 'Yes' :
					encode = True
				else :
					encode = False
				if addr in self.serverThread.Obj.currentSessionID and addr != self.server_addr :
					sessionID = self.serverThread.Obj.currentSessionID[addr][0]
					print addr, sessionID, ' send "close session" request'
					clnt = ToolsThread(\
										xr_client(\
												addr, \
												port, \
												self, \
												self, \
												encode), \
										parent = self)
					clnt.run()
					clnt.Obj.sessionClose(sessionID)
					clnt._terminate()
		except RuntimeError, err :
			print '[in stopServices() __init__] RuntimeError :', err
		finally : pass'''
		if 'serverThread' in dir(self) and self.serverThread is not None :
			self.serverThread._terminate(mode if restart and mode != '' else '', loadFile)
		if 'serverPThread' in dir(self) and self.serverPThread is not None :
			self.serverPThread._terminate(mode if restart and mode != '' else '', loadFile)
		if not restart : self.END = True

	def saveCache(self):
		Once = True
		limitCache = int(InitConfigValue(self.Settings, 'CacheSize', '100')) * 10000
		prefPath = Path.TempCache
		prefPathForAvatar = Path.TempAvatar
		prefPathInStationar = Path.Cache
		prefPathInStationarForAvatar = Path.Avatar
		if os.path.exists(Path.TempCache) :
			currentSize = getFolderSize(prefPathInStationar)
			#print currentSize, ':'
			listingCache = os.listdir(Path.TempCache)
			for name in listingCache :
				path = Path.tempCache(name)
				pathInStationarCache = Path.cache(name)
				if os.path.isfile(path) and not os.path.isfile(pathInStationarCache) :
					if moveFile(path, pathInStationarCache) :
						currentSize += os.path.getsize(pathInStationarCache)
					if moveFile(Path.tempAvatar(name), Path.avatar(name)) :
						currentSize += os.path.getsize(Path.avatar(name))
					#print currentSize
					if currentSize >= limitCache :
						print 'cache`s limit is reached'
						self.showMSG('cache`s limit is reached')
						break
					elif Once and currentSize >= limitCache*4/5 :
						Once = False
						self.showMSG('cache is reached more then 80% :\n' + \
									 str(currentSize) + \
									 ' from ' + \
									 str(limitCache))

	def saveTemporaryData(self):
		if InitConfigValue(self.Settings, 'UseCache', 'True') == 'True' : self.saveCache()
		if InitConfigValue(self.Settings, 'SaveLastStructure', 'True') == 'True' :
			if os.path.exists(Path.multiPath(Path.tempStruct, 'server', 'sharedSource_' + self.serverState)) :
				shutil.move(Path.multiPath(Path.tempStruct, 'server', 'sharedSource_' + self.serverState), \
							Path.config('lastSharedSource'))
				self.Settings.setValue('LastServerState', self.serverState)
			else :
				self.Settings.setValue('LastServerState', '')

	def _close(self):
		if hasattr(self, 'END') and self.END : return None
		self.disconnectSignals()
		self.stopServices()
		#print Path.multiPath(Path.tempStruct, 'server', 'sharedSource_' + self.serverState), ' close'
		self.saveTemporaryData()
		shutil.rmtree(Path.TempStruct, ignore_errors = True)
		self.close()

	def closeEvent(self, event):
		self._close()
Example #13
0
class BombMopper:

    # initialize game window
    def __init__(self):

        # settings
        self.buttonSize = 25
        self.defaultCanvasWidth = 500
        self.defaultCanvasHeight = 500
        self.padding = 20
        self.buttonImagePadding = 10
        self.adjBombTextSize = 25

        # window
        self.window = Tk()
        self.window.title("BOMBMOPPER")

        # frames
        self.statusFrame = Frame(self.window)
        self.statusFrame.pack(side=TOP)

        self.gameFrame = Frame(self.window)
        self.gameFrame.pack(side=BOTTOM)

        # canvas
        self.canvasWidth = self.defaultCanvasWidth
        self.canvasHeight = self.defaultCanvasHeight
        self.canvas = Canvas(self.gameFrame)
        self.canvas.config(width=self.canvasWidth,
                           height=self.canvasHeight,
                           background='gray',
                           highlightthickness=0)
        self.canvas.grid(column=0, row=0, sticky=(N, W, E, S))

        # play button
        self.playButton = PlayButton(self)

        # difficulty buttons
        self.easyButton = DifficultyButton(self, 'easy')
        self.intermediateButton = DifficultyButton(self, 'intermediate')
        self.hardButton = DifficultyButton(self, 'hard')

        # initialize board
        self.board = GameBoard(self)

        # initialize status bar
        self.statusBar = StatusBar(self)
        self.statusBar.packContents()
        self.window.update()
        self.statusBar.deactivate()

        # allow quitting without errors
        self.window.protocol('WM_DELETE_WINDOW', self.setInactive)
        self.isActive = True

    # for use by quit button; mainloop ends when self.isActive is False
    def setInactive(self):
        self.isActive = False

    # transition from opening screen (with play button) to difficulty selection
    def selectDifficulty(self):

        # turn off play button
        self.playButton.deactivate()

        # turn on difficulty selection buttons
        self.easyButton.activate()
        self.intermediateButton.activate()
        self.hardButton.activate()
        self.resizeCanvasToDefault()

    # transition from difficulty selection to playing game
    def playGame(self, gridSize, nBombs):

        # turn off difficulty selection buttons
        self.easyButton.deactivate()
        self.intermediateButton.deactivate()
        self.hardButton.deactivate()

        # start game board
        self.board.activate(gridSize, nBombs)

        # place status frame, turn on status bar
        self.statusFrame.pack(side=TOP)
        self.statusBar.activate()

    # reset size of canvas (for use after game a game ends)
    def resizeCanvasToDefault(self):
        self.resizeCanvas(self.defaultCanvasHeight, self.defaultCanvasWidth)

    # resize canvas; width and height are calculated in GameBoard based on selected difficulty
    def resizeCanvas(self, width, height):
        self.canvasWidth = width
        self.canvasHeight = height
        self.canvas.config(width=self.canvasWidth, height=self.canvasHeight)

    # run win/lose dialogue with win message
    def winGame(self):
        self.winLose("YOU WIN!")

    # run win/lose dialogue with lose message
    def loseGame(self):
        self.winLose("YOU LOSE!\nand you smell")

    # wait a short time (100ms), then open the win/lose dialogue with input message
    def winLose(self, message):
        self.window.after(100, lambda: self.winLosePopup(message))

    # open win/lose dialogue with input message
    # essentially says "<message>, Keep Playing?" and user selects yes or no
    def winLosePopup(self, message):
        result = tkMessageBox.askquestion(message, "Keep Playing?")
        if result == "yes":
            self.statusBar.deactivate()
            self.resizeCanvasToDefault()
            self.canvas.delete('all')
            self.board.reset()
            self.playButton.activate()
        else:
            self.isActive = False

    # keep displays up to date; run continuously
    # buttons run callbacks which update parameters of window / canvas
    # display is updated to match parameters when mainloop runs
    def mainloop(self):
        while self.isActive:
            self.window.update()
            self.canvas.update()
        self.window.destroy()
Example #14
0
def Create_Main():
    root = Tk()
    root.geometry("1280x700")
    root.resizable(0, 0)  # Code to ensure that the window did not resize.
    root.title("Main")  # Set Main Title.

    font = ("Forte", 12)

    bkg = PhotoImage(file="Imgs/background2.gif")
    bkg_lbl = Label(root, image=bkg)
    bkg_lbl.place(x=0, y=0, relwidth=1, relheight=1)

    lbl_1 = Label(root, text="Player 1", font=font, bg="White", fg="gray")
    lbl_1.place(x=180, y=130)

    lbl_1 = Label(root, text="Player 2", font=font, bg="White", fg="gray")
    lbl_1.place(x=950, y=130)



# --------------------------- Barras de Estado ------------------------

    Bar_Turno = StatusBar(root)

    Bar_Turno.set("Turno: %s", "Jugador 1")
    Bar_Turno.pack(padx=30, pady=65)

    Bar_Tiros_Player1 = StatusBar(root)
    Bar_Tiros_Player2 = StatusBar(root)
    Bar_Tiros_Player1.place(x=265, y=130)
    Bar_Tiros_Player2.place(x=1040, y=130)

    Bar_Tiros_Acert_Play1 = StatusBar(root)
    Bar_Tiros_Acert_Play2 = StatusBar(root)
    Bar_Tiros_Acert_Play1.place(x=365, y=130)
    Bar_Tiros_Acert_Play2.place(x=1145, y=130)


    Bar_Tiros_Player1.set("Tiros Totales: %s", "0")
    Bar_Tiros_Player2.set("Tiros Totales: %s", "0")

    Bar_Tiros_Acert_Play1.set("Tiros Acertados: %s", "0")
    Bar_Tiros_Acert_Play2.set("Tiros Acertados: %s", "0")


    frm_2 = Frame(root, width=520, height=520, bd=-2, bg="gray")
    frm_1 = Frame(root, width=520, height=520, bd=-2, bg="gray")

    frm_1.pack(side=LEFT)
    #frm_1.pack_propagate(0)

    frm_2.pack(side=RIGHT)

    def dialog_cons(n, msg):
        """

            :rtype : object
            """
        widg = Dialog(root, n)
        root.wait_window(widg.top)
        while widg.result == "":
            if msg != None:
                messagebox.showinfo("Warning!", msg)
            else:
                messagebox.showinfo("Warning!", "Please insert the name for the %s Player!" % n)
            widg = Dialog(root, n)
            root.wait_window(widg.top)
        return widg.result

    OneTwoPlayer = messagebox.askyesno("Player or PC", "Do you want to play with other human? (No = PC)")
    if OneTwoPlayer == 1:
        player1 = dialog_cons(1, None)
        player2 = dialog_cons(2, None)
        print(player1, player2)    # Testing Lines
    else:
        player1 = dialog_cons(1, None)
        player2 = "Computer"
        print(player1, player2)    # Testing Lines

    try:
        ships = int(dialog_cons("Ships", "Please Quantity of ships for the Game!"))
    except ValueError:
        messagebox.showinfo("Warning!", "La variable debe ser numero")
        ships = int(dialog_cons("Ships", "Please Quantity of ships for the Game!"))
    print(ships)    # Testing Lines

    try:
        xy = int(dialog_cons("Quantity of matrix: (Ej: nxn, insert n)", "Please insert the size for Game's matrix!"))
    except ValueError:
        messagebox.showinfo("Warning!", "La variable debe ser numero!")
        xy = int(dialog_cons("Ships", "Please Quantity of ships for the Game!"))
    print(xy)    # Testing Lines

    game = Main(player1, player2, xy, xy, ships)
    game.imprimir
    game.imprimir2
    game.images(frm_1, game.matrix_shoots_player_1, game.matrix_player_1)
    game.images(frm_2, game.matrix_shoots_comp_player_2, game.matrix_comp_player_2)




    frm_1.bind("<Button-1>", callback)
    frm_2.bind("<Button-1>", callback)

    root.bind("<Button-1>", callback)

    root.mainloop()
Example #15
0
class PooGUI(tk.Frame):
    """the main frame with the GUI, contains three sections and a menu bar
        - the main section is the plotting area using matplotlib
        - in the top right are sliders,
        - bottom right is a list of samples

        we have the following objects:
            -sList: a list of all samples
            -hList: a list of all hyperbolas
            -data: the raw SNP data (mbsData obj?)
            -coords: data structure with coordinates
            -psi: np.array[s1,s2] : psi
            -v: constant multiplier of hyperbolas
            -xlim, ylim: plotting limits
        """
#---------------------------------------------------------------------
#   drawing stuff for points, should eventually be moved to an 
#       appropriate plotting class,psi, data
#---------------------------------------------------------------------

    def dummyElements(self):
        #vars I need
        self.activeCanvas
        self.canvas['H'] #replace with self.canvas[]...
        self.canvas['Psi']
        self.sample_frame
        self.origin_frame
        self.slider_frame
        self.bgi
        self.matrixTL
        self.psimatrix
        #vars in config
        self.lwd #should be in either plot...
        self.threshold
        #vars in Data
        self.v
        self.clusters
        self.psi
        self.data
        self.psi_sum
        self.oList
        self.hList #??
        self.sList #???
        #vars I don't need

        #maybees

    def __init__(self, master=None):
        """the main constructor of the frame. As it is quite big,
        i split it up into subfunctions for the various ui parts.
        Might be worth to instead use children classes instead.

        The main app window will have a status bar at the bottom with
        progress messages and stuff. The main window will be
        the square matplotlib canvas on the right and a narrowish bar
        with samples, sliders, etc on the right
        """
        tk.Frame.__init__(self, master, relief=tk.SUNKEN)

        self.master = master
        self.d = Data(self)
        self.c = Config(O)
        
        self.canvas = dict()
        self.d.sList = []
        self.d.oList = []
        self.init_canvas_hyperbolas()
        self.init_canvas_pwp(active=True)
        self.init_sample_frame()
        #self.init_statusbar()
        self.init_slider_frame()
        self.init_menubar()

        #enable expansion
        tk.Grid.rowconfigure(self,1,weight=10)
        tk.Grid.rowconfigure(self,2,weight=1)
        tk.Grid.columnconfigure(self,1,weight=1)
        tk.Grid.columnconfigure(self,2,weight=1)
        tk.Grid.columnconfigure(self,0,weight=2)

    def initPsiMatrix(self,master):
        """initializes Matrix containing psi values
        should do the following:
            1. display matrix of Edits? MatrixWidget
            2. load data and display it
            3. colorcode
        """
        self.matrixTL = tk.Toplevel(master)
        self.psi_matrix = SimpleTable(self.matrixTL)
        self.psi_matrix.grid(sticky="nsew")
        self.psi_matrix.fill(self.d.sList,self.d.pairwise_stats['psi'])
        self.psi_matrix.fill_labels(self.d.sList)

    def init_menubar(self):
        """
        this function loads and populates the menubar, and will register its events
        """
        self.menubar = tk.Menu(self)

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="File", menu=menu)
        menu.add_command(label="Load SNP",command=self.loadSNP)
        menu.add_command(label="Load Coords", command=self.loadCoords)
        menu.add_command(label="Load Background Image", command=self.loadBGI)
        menu.add_command(label="Save plot", command=self.save_plot)
        menu.add_command(label="Quit", command=self.quit)

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Edit", menu=menu)
        menu.add_command(label="Set Reference Coordinates")

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="View", menu=menu)
        menu.add_command(label="Hyperbolas", 
                         command=self.showHyperbolaCanvas)
        menu.add_command(label="Pairwise Psi", 
                         command=self.showPsiCanvas)

        menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Run", menu=menu)
        menu.add_command(label="Find Origin All", command=self.optimizeAll)
        menu.add_command(label="Find Origin Visible")

        try:
            self.master.config(menu=self.menubar)
        except AttributeError:
            # master is a toplevel window (Python 1.4/Tkinter 1.63)
            self.master.tk.call(master, "config", "-menu", self.menubar)

    def init_canvas_hyperbolas(self, active=False):
        """
        this function creates the matplotlib canvas that will be used 
        to draw stuff
        master: parent frame
        active: is this displayed on startup?
        """
        self.canvas['H'] = HyperbolaCanvas(self, self.c,
                                           self.d.sList,
                                           self.d, width=300, height=300)
        self.canvas['H'].grid(column=0,row=0,rowspan=3,sticky="ewns")
        if not active:
            self.canvas['H'].hide()
        else:
            self.activeCanvas = self.canvas['H']

    def init_canvas_pwp(self, active=False):
        """
        this function creates the matplotlib canvas that will be used 
        to draw stuff
        master: parent frame
        active: is this displayed on startup?
        """
        self.canvas['Psi'] = PWPCanvas(self, self.c, self.d.sList,
                                       self.d, width=300, height=300)
        self.canvas['Psi'].grid(column=0,row=0,rowspan=3,sticky="ewns")
        if not active:
            self.canvas['Psi'].hide()
        else:
            self.activeCanvas = self.canvas['Psi']

    def init_statusbar(self):
        """function that creates a status bar at the bottom of the window"""
        self.sb = StatusBar(self)
        self.sb.grid(row=3,column=0,columnspan=2, sticky="ew")
    
    def init_slider_frame(self):
        self.slider_frame = SliderFrame(self,self, v=self.d.get_v())
        self.slider_frame.grid(column=1, row=0, sticky="")
    
    def init_sample_frame(self):
        self.sample_frame = SampleFrame(self, width=200, height=100)
        self.origin_frame = OriginFrame(self, width=200, height=100)
        for i in range(4):
            self.add_sample( SampleUI(master=self.sample_frame,
                                        data=self.d, config=self.c,
                                        cluster=None, text="SS%d"%i) )
            self.d.sList[i].grid(column=0,row=i)
        self.sample_frame.grid(column=1, row=1, sticky="ns")
        self.origin_frame.grid(column=1, row=2, sticky="ns")

#--------------------------------------------------

    def reset_sample_list(self):
        #reset everything:
        for sampleUI in self.d.sList:
            sampleUI.destroy()
        self.d.sList = []

        self.canvas['H'].samples = []
        self.canvas['Psi'].samples = []

    def add_sample(self, s):
        self.d.sList.append(s)
        self.canvas['H'].samples.append(s)
        self.canvas['Psi'].samples.append(s)

    def changeV(self,ele,val):
        """ 
        function that updates hyperbola when v is changed
        """

        #see if the value is actually a float, if not, return
        self.d.set_v( float( val.get() ))
        #update, whole thing, there might be a more efficient way to do this
        self.canvas['H'].update_()
        if self.activeCanvas == self.canvas['H']:
            self.activeCanvas.redraw()

    def changeLwd(self,val):
        """ 
        function that updates hyperbola when v is changed
        """

        print "Changing lwd" , val.get()
        #see if the value is actually a float, if not, return
        self.c.psi_lwd = float( val.get() )
        #redraw, whole thing, there might be a more efficient way to do this
        self.canvas['Psi'].update_()
        if self.activeCanvas ==self.canvas['Psi']:
            self.activeCanvas.redraw()
      
    def changeThreshold(self,val):
        """ 
        function that updates hyperbola when v is changed
        """

        print "Changing threshold" , val.get()
        #see if the value is actually a float, if not, return
        self.c.psi_threshold = float( val.get() )
        #update, whole thing, there might be a more efficient way to do this
        self.canvas['Psi'].update_()

        if self.activeCanvas ==self.canvas['Psi']:
            self.activeCanvas.redraw()
#---------------------------------------------------------------------
#   optimizing, should move to data
#---------------------------------------------------------------------
    def optimizeAll(self):
        ev,msev, pv,dv = [],[],[],[]
        activeStat = self.d.get_active_stat
        for cluster_id in self.d.clusters:
            cluster = self.d.clusters[cluster_id]
            n_pops = cluster.n_pops
            if n_pops <= 3:
                print "Warning, Cluster too small"
            data = np.empty((n_pops * (n_pops -1 ) /2, 5 ))
            row = 0
            for i, s1 in enumerate(cluster.pops):
                for j0, s2 in enumerate(cluster.pops[i+1:]):
                    j = i+j0 + 1
                    data[row] = s1.get_x(), s1.get_y(), \
                                s2.get_x(), s2.get_y(), \
                                self.d.get_active_stat(s1.pop, s2.pop)
                    row += 1
            e,mse,p,d = optimize.tdoa3(data,x0=O["opt_start"])
            print e[0]
            ev.append(e[0])
            msev.append(mse)
            pv.append(p)
            dv.append(d)
            self.d.set_v( e[0][0] )
            self.slider_frame.v_scale.set( e[0][0] )
            self.canvas['H'].update_()
            if self.activeCanvas == self.canvas['H']:
                self.activeCanvas.redraw()

            if cluster.origin is None:
                opt = \
                InferredOrigin(master=self.origin_frame,x=e[0][1],y=e[0][2],
                               text="Origin "+cluster.name)
                opt.set_color("red")
                cluster.origin = opt
            else:
                opt = cluster.origin
                opt.tX.set("%2.2f"%(e[0][1]))
                opt.tY.set("%2.2f"%(e[0][2]))
                opt.set_x(e[0][1])
                opt.set_y(e[0][2])
                opt.update_()
                print "UPDATED ORIGN"

            self.d.oList.append(opt)
            opt.grid(in_=self.origin_frame)
            self.canvas['H'].panel.add_artist( opt.circH )
            self.canvas['H'].update_()
            self.canvas['Psi'].panel.add_artist( opt.circP )
            #origins shouldn't be movable
            #opt.circH.connect()
            #opt.circP.connect()
            self.activeCanvas.redraw()
        return ev, msev, pv, dv


#------------------------------------Hyperbola---------------------------------
#   loading files and data
#---------------------------------------------------------------------
    def loadSNP(self,f=None):
        """loads SNP and saves them in data"""
        if f == None:
            f = tkFileDialog.askopenfile(mode='r')
        self.d.load_snp( np.loadtxt(f) )
        self.canvas['H'].draw_all_hyperbolas()
        self.canvas['Psi'].draw_all_pairwise_psi()
        self.initPsiMatrix(self.master)

#---------------------------- Sorting stuff ------------------------
#   this set of functions handles all the sorting of elements
#--------------------------------------------------


    def update_sample_order(self):
        """
            when the samples are sorted and have to be reordered, this function
            does it
        """
        self.d.sList = sorted(self.d.sList)
        self.sample_frame.update_sample_order(self.d.sList)
        self.psi_matrix.update_sample_order(self.d.sList)

#--------------------------------------------------
    def loadCoords(self,f=None):
        """loads Coords, creates the corresponding UI elements
            and the circles for plotting
        """

        default_cluster = self.d.default_cluster
        self.reset_sample_list()

        if f is None:
            f = tkFileDialog.askopenfile(mode='r',initialfile="coords.txt")
	    print f
	else:
	    f = open( f )

        for i,line in enumerate(f):
            p = Population()
            p.load_line(line)
            self.d.add_pop(p)

            sUI = SampleUIWPop(pop=p, master=self.sample_frame, 
                               config = self.c, data=self.d,
                               cluster=default_cluster)
            sUI.grid(column=0,row=i, sticky="ew")

            #create plotting circles and register events
            self.canvas['H'].panel.add_artist( sUI.circH )
            self.canvas['Psi'].panel.add_artist( sUI.circP )
            sUI.circH.connect()
            sUI.circP.connect()
            
            self.add_sample( sUI )

        self.nCoords = len( self.d.sList )
        self.activeCanvas.redraw()

    def loadPsi(self,f=None):
        """loads Psi directly. Assumes Coordinates are already loaded"""
        if f is None:
            f = tkFileDialog.askopenfile(mode='r',initialfile="psi.txt")

        self.d.add_pw_stat('psi', AntiCommutativePWStat(f=pw_psi))
        if self.d.pw_default_stat is None:
            self.d.set_pw_default_stat('psi')

        psiRaw = np.loadtxt(f, dtype="S100")
        for row in psiRaw:
            self.d.pairwise_stats['psi'][ row[0], row[1] ] =  float(row[2])

        psi_sum = psi_sum_cluster(self.d.pairwise_stats['psi'],
                                  self.d.sList)
        self.d.add_single_pop_stat('psi_sum',psi_sum)
        self.d.sort_stat="psi_sum"

        self.initPsiMatrix(self.master)
        self.d.update_all_colors()
        self.d.update_sample_order()
            
        #self.set_colors()
        self.canvas['H'].draw_all_hyperbolas()
        self.canvas['Psi'].draw_all_pairwise_psi()

        
    def loadBGI(self, f=None):
        """loads Background image"""
        if f is None:
            f = tkFileDialog.askopenfile(mode='r')

        try:
            self.bgi = mpimg.imread(f)
        except:
            raise ValueError("could not read image file, see"+ \
                             " matplotlib.image.imread for"+ \
                             " supported formats")
        self.canvas['H'].addBGI(self.bgi)
        self.canvas['Psi'].addBGI(self.bgi)

    def removeBGI(self):
        self.canvas['H'].removeBGI()
        self.canvas['Psi'].removeBGI()
        self.activeCanvas.redraw()

    def save_plot(self, f=None):
        if f == None:
            f = tkFileDialog.asksaveasfilename(initialfile="plot.pdf")
        self.activeCanvas.fig.savefig(f)

        


#---------------------------------------------------------------------
# various constructors
#---------------------------------------------------------------------

    def loadOptions(self):
        self.lwd = O['psi_lwd']
        self.threshold = O['psi_threshold']





#---------------------------------------------------------------------
#   other stuff
#---------------------------------------------------------------------
    def quit(self):
        """quits app"""
        print "bye"
        root.quit()
        root.destroy()

    def showPsiCanvas(self):
        self.canvas['H'].hide()
        self.canvas['Psi'].show()
        self.activeCanvas = self.canvas['Psi']
        for s in self.d.sList:
            s.updateCircles()
        self.activeCanvas.redraw()

    def showHyperbolaCanvas(self):
        self.canvas['H'].show()
        self.activeCanvas = self.canvas['H']
        self.canvas['Psi'].hide()
        for s in self.d.sList:
            s.updateCircles()
        self.activeCanvas.redraw()
Example #16
0
class MainWindow(QMainWindow):
    mCurrentStatus = "凸包"

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle("计算几何 测试")
        """
        菜单栏
        """
        newAct = QAction("&新建", self)
        newAct.setShortcuts(QKeySequence.New)
        newAct.setStatusTip("新建一个工程")
        newAct.triggered.connect(self.newProject)

        openAct = QAction("&打开", self)
        openAct.setShortcuts(QKeySequence.Open)
        openAct.setStatusTip("打开存在的工程")
        openAct.triggered.connect(self.openProject)

        fileMenu = self.menuBar().addMenu("&工程")
        fileMenu.addAction(newAct)
        fileMenu.addAction(openAct)
        """
        工具栏
        """
        fileToolBar = self.addToolBar("工程")
        fileToolBar.addAction(newAct)
        fileToolBar.addAction(openAct)

        fileToolBar.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea)
        self.addToolBar(Qt.TopToolBarArea, fileToolBar)
        """
        中心画布
        """
        self.mCanvas = MainCanvas()
        self.setCentralWidget(self.mCanvas)
        """
        状态栏
        """
        self.mStatusBar = StatusBar()
        self.setStatusBar(self.mStatusBar)
        """
        控制(dock)框
        """
        self.mCtrlWidget = CtrlWidget()
        ctrlDock = QDockWidget("控制")
        self.addDockWidget(Qt.RightDockWidgetArea, ctrlDock)
        ctrlDock.setWidget(self.mCtrlWidget)
        ctrlDock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        """
        绑定信号和槽
        """
        self.mCanvas.msCurrentChanged.connect(self.CurrentChanged)
        self.mCanvas.msMove.connect(self.mStatusBar.Move)
        self.mCtrlWidget.msRun.connect(self.Run)

    def newProject(self):
        pass

    def openProject(self):
        pass

    def CurrentChanged(self, status):
        self.mCurrentStatus = status
        self.mStatusBar.CurrentChanged(status)

    def Run(self):
        status = self.mCurrentStatus
        if "凸包" == status:
            self.mCanvas.DrawConvexhull()
        elif "线段求交" == status:
            self.mCanvas.DrawLineIntersection()
        else:
            print("未实现")
class Application(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self)
        self.parent = parent
        self.setWindowTitle('imrenderin')

        ## Widgets
        self.menu_bar = MenuBar(self)
        self.menu_bar.setFixedHeight(25)
        self.status_bar = StatusBar(self)
        self.status_bar.setFixedHeight(35)

        ## Redirect stdout,stderr to dialog
        self.console = ConsoleDialog(sys.stdout)
        sys.stdout = self.console
        sys.stderr = self.console

        ## UI Elements
        self.display = Display(self)
        self.controls = DefaultUI(self, self.display)

        ## Layout
        vbox = QtGui.QVBoxLayout(self)
        vbox.addWidget(self.menu_bar)
        vbox.addWidget(self.controls)
        vbox.addWidget(self.status_bar)
        vbox.setSpacing(2)
        vbox.setContentsMargins(2, 2, 2, 2)

        self.setLayout(vbox)
        self.setMinimumWidth(200)
        self.setMinimumHeight(150)
        self.resize(_width, _height)

    def about(self):
        msg = '''
About this thing
'''
        mb = QMessageBox(self)
        mb.setText(msg.strip())
        mb.setIcon(QtGui.QMessageBox.Information)
        mb.setWindowTitle('About')
        mb.show()

    def showConsole(self):
        self.console.show()

    def help(self):
        msg = '''
Don't Panic!
'''
        mb = QMessageBox(self)
        mb.setText(msg.strip())
        mb.setIcon(QtGui.QMessageBox.Information)
        mb.setWindowTitle('About')
        mb.show()

    def open(self):
        fd = QtGui.QFileDialog()
        path = fd.getOpenFileName(None, 'Open image file...', '')
        self.display.imshow(path)

    def toggleFullscreen(self):
        self.showNormal() if self.isFullScreen() else self.showFullScreen()
Example #18
0
 def create_status_bar(self, parent, notebook):
     """ Create the status bar on the bottom """
     self.status_bar = StatusBar(parent, notebook)
Example #19
0
	def __init__(self, parent = None):
		QtGui.QMainWindow.__init__(self, parent)

		self.serverState = ''
		self.jobCount = 0
		self.commonSetOfSharedSource = {}
		self.USERS = {}
		self.SEP = os.sep

		#self.resize(450, 350)
		self.setWindowTitle('LightMight')
		self.setWindowIcon(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'tux_partizan.png'))

		self.Settings = QtCore.QSettings('LightMight','LightMight')
		self.Policy = Policy(self)
		self.avatarPath = InitConfigValue(self.Settings, 'AvatarPath', '')

		self.exit_ = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'exit.png'), '&Exit', self)
		self.exit_.setShortcut('Ctrl+Q')
		self.exit_.setStatusTip('Exit application')
		self.connect(self.exit_, QtCore.SIGNAL('triggered()'), self._close)

		listHelp = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'&About LightMight', self)
		listHelp.setStatusTip('Read help')
		self.connect(listHelp,QtCore.SIGNAL('triggered()'), self.showMSG)

		commonSettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'&Common Settings', self)
		commonSettings.setStatusTip('Set avatars, use cache, etc.')
		self.connect(commonSettings, QtCore.SIGNAL('triggered()'), self.showCommonSettingsShield)

		serverSettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'&Server Settings', self)
		serverSettings.setStatusTip('Set shared source, encrypt, etc.')
		self.connect(serverSettings, QtCore.SIGNAL('triggered()'), self.showServerSettingsShield)

		clientSettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'C&lient Settings', self)
		clientSettings.setStatusTip('Set the download path, etc.')
		self.connect(clientSettings, QtCore.SIGNAL('triggered()'), self.showClientSettingsShield)

		proxySettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'&Proxy Settings', self)
		proxySettings.setStatusTip('Set proxy...')
		self.connect(proxySettings, QtCore.SIGNAL('triggered()'), self.showProxySettingsShield)

		#colorSettings = QtGui.QAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'),'Color&Font and Background', self)
		#colorSettings.setStatusTip('Set font color & background.')
		#self.connect(colorSettings, QtCore.SIGNAL('triggered()'), self.showColorSettingsShield)

		self.statusBar = StatusBar(self)
		self.setStatusBar(self.statusBar)

		menubar = self.menuBar()

		file_ = menubar.addMenu('&File')
		file_.addAction(self.exit_)

		set_ = menubar.addMenu('&Settings')
		set_.addAction(commonSettings)
		set_.addAction(serverSettings)
		set_.addAction(clientSettings)
		set_.addAction(proxySettings)
		#set_.addAction(colorSettings)

		help_ = menubar.addMenu('&Help')
		help_.addAction(listHelp)

		self.menuTab = Box(self)
		self.setCentralWidget(self.menuTab)

		self.trayIconMenu = QtGui.QMenu(self)
		show_hide = self.trayIconMenu.addAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'tux_partizan.png'), 'Hide / Show')
		self.connect(show_hide, QtCore.SIGNAL('triggered()'), self.show_n_hide)
		help_tray = self.trayIconMenu.addAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'help.png'), 'Help')
		self.connect(help_tray, QtCore.SIGNAL('triggered()'), self.showMSG)
		exit_tray = self.trayIconMenu.addAction(QtGui.QIcon('..' + self.SEP + 'icons' + self.SEP + 'exit.png'), '&Exit')
		self.connect(exit_tray, QtCore.SIGNAL('triggered()'), self._close)
		self.trayIconPixmap = QtGui.QPixmap('..' + self.SEP + 'icons' + self.SEP + 'tux_partizan.png') # файл иконки
		self.trayIcon = QtGui.QSystemTrayIcon(self)
		self.trayIcon.setToolTip('LightMight')
		self.trayIcon.setContextMenu(self.trayIconMenu)
		self.trayIcon.setIcon(QtGui.QIcon(self.trayIconPixmap))
		self.connect(self.trayIcon, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), \
																			self.trayIconClicked)
		self.trayIcon.show()

		self.errorString.connect(self.showMSG)
		self.commonSet.connect(self.preProcessingComplete)
		self.uploadSignal.connect(self.uploadTask)
		self.contactMessage.connect(self.receiveBroadcastMessage)
		self.changeConnectState.connect(self.initAvahiBrowser)
		self.cacheDown.connect(self.cacheS)
		self.initServeR.connect(self.checkNetwork)
		self.reinitServer.connect(self.checkNetwork)
		self.serverDown.connect(self.menuTab.preStartServer)
		self.setAccess.connect(self.confirmAction)
		self.netState.connect(self.standByDown)
		self.StandBy = QtCore.QTimer()
		self.StandBy.timeout.connect(self.checkNetwork)
		self.StandBy.setInterval(20000)

		## 0 -- off; 1 -- on
		self.NetworkState = 1
		self.runServer4Proxy = 0

		self.restoredInitParameters = (None, None, '', False)
		self.searchCertificate()
		self.checkNetwork()
Example #20
0
	def __init__(self, path = '', mode = 1, parent = None, task = None):
		QMainWindow.__init__(self, parent)
		self.tr = Translator('Thrifty')

		#self.resize(450, 350)
		self.setWindowTitle(self.tr._translate('Thrifty'))
		self.setWindowIcon(QIcon('/usr/share/thrifty/icons/sniper_soldier.png'))

		self.save_ = QAction(QIcon('/usr/share/thrifty/icons/save.png'), self.tr._translate('&Save'), self)
		self.save_.setShortcut('Ctrl+S')
		self.save_.setStatusTip(self.tr._translate('Save file'))
		self.connect(self.save_, SIGNAL('triggered()'), self._save)

		self.exit_ = QAction(QIcon('/usr/share/thrifty/icons/exit.png'), self.tr._translate('&Exit'), self)
		self.exit_.setShortcut('Ctrl+Q')
		self.exit_.setStatusTip(self.tr._translate('Exit application'))
		self.connect(self.exit_, SIGNAL('triggered()'), self._close)

		self.giveToYum = QAction(QIcon('/usr/share/thrifty/icons/exit.png'), self.tr._translate('to &Yum'), self)
		self.giveToYum.setShortcut('Ctrl+Y')
		self.giveToYum.setStatusTip(self.tr._translate('Give package list to Yum for reinstall'))
		self.connect(self.giveToYum, SIGNAL('triggered()'), self.runYum)
		self.giveToYum.setEnabled(False)

		menubar = self.menuBar()

		file_ = menubar.addMenu(self.tr._translate('&File'))
		file_.addAction(self.save_)
		file_.addAction(self.exit_)

		toYum = menubar.addMenu(self.tr._translate('&Action'))
		toYum.addAction(self.giveToYum)

		if task is not None :
			self.save_.setEnabled(False)
			if task : self.giveToYum.setEnabled(True)

		self.editor = QTextEdit(parent = self)
		self.setCentralWidget(self.editor)

		self.statusBar = StatusBar(self)
		self.setStatusBar(self.statusBar)

		self.Parent = parent
		self.mode = mode
		self.path = path
		self.editor.setUndoRedoEnabled(True)
		self.editor.setOverwriteMode(True)
		self.editor.createStandardContextMenu()
		if task is None :
			s = readFile(self.path)
		else : 
			s_ = readFile(self.path)
			if self.path == '' :
				s = s_
			else :
				l = []
				for item in s_.split('\n') :
					chunks = item.split(' ')
					if len(chunks) >= task + 1 :
						if chunks[task] != '' and chunks[task] not in l:
							l.append(chunks[task])
				_s = [s_ + '\n' for s_ in l]
				_s.sort()
				s = ''.join(_s)
		#print [s, QString().fromUtf8(s)]
		self.editor.setPlainText(QString().fromUtf8(s))
		self.statusBar.showMessage('Edit : ' + self.path)
class MainWindow(QMainWindow):
	def __init__(self,parent):
		super(MainWindow, self).__init__()
		self.graphics = Graphics()
		self.parent = parent
		self.setFixedSize(950,631)
		self.setWindowTitle("Balance of Power")
		self.setStyleSheet("QMainWindow::separator{ width: 0px; height: 0px, margin: -10px; }")
		self.world = World(4,False,0)
		self.policyWindow = PolicyWindow(self)
		self.mapView = MapView(self, self.world)
		self.statusBar = StatusBar(self)
		self.newGameWindow = NewGameWindow(self)
		self.newsWindow = NewsWindow(self)
		self.closeUpWindow = CloseUpWindow(self)
		self.scoresWindow = ScoresWindow(self)
		self.controlPanel = ControlPanel(self)
		self.lostGameWindow = LostGameWindow(self)
		for i in range(2,80,1):
			self.world.addNews(self.world.country[1], self.world.country[i], self.world.country[i], 2 + i%4, 1, 2, False)
		self.addDockWidget(Qt.BottomDockWidgetArea, self.controlPanel)
		self.addDockWidget(Qt.TopDockWidgetArea, self.statusBar)
		self.setCentralWidget(self.mapView)
		self.setWindowIcon(QIcon(self.graphics.progIcon))
		self.controlPanel.connectActions()
		self.menu = Menu(self)
		self.setMenuBar(self.menu)
		self.loadOptions()
		self.mapView.resetMapView()
		self.loadWorld()

	def loadOptions(self):
		try:
			with open("options.dat", "r") as f:
				options = json.load(f)
		except: options = DEFAULT_OPTS
		for i,j in zip(options[:3], self.menu.options[:3]):
			j.setChecked(i)
		self.newGameWindow.levelOpt[options[4]].setChecked(True)
		self.newGameWindow.modeOpt[options[5]].setChecked(True)
		self.newGameWindow.sideOpt[options[6]].setChecked(True)
		self.menu.languages[options[3]].setChecked(True)

	def saveOptions(self):
		options = [i.isChecked() for i in self.menu.options[:3]]
		for i in self.menu.languages.values():
			if i.isChecked():
				options += [i.text().lower() + ".json"]
				break
		options += [i.checkedId() for i in self.newGameWindow.buttonGroups]
		try:
			with open("options.dat", "w") as f:
				json.dump(options, f)
		except: pass

	def updateLevel(self):
		for i in INAVL_MAP_MODES[self.world.level - 1]:
			self.controlPanel.mapModeAction[i].setEnabled(False)
			self.controlPanel.mapModeButton[i].setEnabled(False)

	def setStatus(self, id):
		"""Set status label in the top part of the window"""
		# if -1, set currently moving player
		if id == -1:
			if self.world.twoPFlag:
				self.statusBar.setLabel(Local.strings[Local.MAIN_PANEL][15] \
				 	+ Local.strings[Local.DATA_COUNTRIES + self.world.human][Local.CTRY_NAME])
			else: self.statusBar.setLabel(Local.strings[Local.MAIN_PANEL][14])
		else: self.statusBar.setLabel(Local.strings[Local.MAIN_PANEL][id])
		time.sleep(.1)
		QApplication.processEvents()

	def endGame(self):
		"""Show effects of the game ending, depends on the active flag"""
		status = 0
		if self.world.winFlag:
			self.scoresWindow.setVisible(True)
			status = 27
		elif self.world.ANWFlag or self.world.NWFlag:
			self.lostGameWindow.showUp(self.world.ANWFlag)
			status = 28
		self.setStatus(status)

	def saveWorld(self, manual=False):
		"""Save the self.world property into the save.dat file using the pickle protocol"""
		try:
			pickle.dump(self.world, open("save.dat", "wb"))
			if manual:
				QMessageBox.information(self, Local.strings[Local.MENU][61], Local.strings[Local.MENU][70])
		except Exception as e:
			if manual:
				QMessageBox.critical(self, Local.strings[Local.MENU][61], Local.strings[Local.MENU][71])

	def loadWorld(self):
		"""Load the pickled save.dat file into the self.world property"""
		try:
			self.setWorld(pickle.load(open("save.dat", "rb")))
			w = self.world
			self.setStatus(-1)
			self.controlPanel.drawScores()
			self.controlPanel.yearLabel.setText(str(w.year))
			self.controlPanel.switchPlayerButton.setEnabled(w.twoPFlag)
			self.controlPanel.nextTurnButton.setEnabled(not any((w.winFlag, w.ANWFlag, w.NWFlag, w.beingQuestioned)))
			if w.winFlag: self.setStatus(27)
			elif w.ANWFlag or w.NWFlag: self.setStatus(28)
			else: self.setStatus(-1)
			self.mapView.scene().mapPainter.recalculateMapBuffer()
			self.mapView.resetMapView()
		except: pass

	def setWorld(self, newWorld):
		"""Set the self.world property"""
		# Backup old graphics polygons items
		polys = [c.mapPolyObject for c in self.world.country]
		# Make sure all the data are cleared
		try: del self.world
		except: pass
		# Create the new world
		self.world = newWorld
		self.mapView.scene().mapPainter.setWorld(self.world)
		self.updateLevel()
		# Move old graphics polygons onto the new world
		for poly,cntry in zip(polys, self.world.country):
			cntry.mapPolyObject = poly
		# Reset the news window
		self.newsWindow.setLocked(any((newWorld.winFlag, newWorld.ANWFlag, newWorld.NWFlag)))
		self.newsWindow.question.setEnabled(False)
		self.newsWindow.backDown.setEnabled(False)
		self.newsWindow.filters[2 * newWorld.cmptr].setChecked(True)

	def closeEvent(self, event):
		if self.menu.options[0].isChecked():
			self.saveWorld()
		event.accept()
Example #22
0
class Editor(QMainWindow):
	def __init__(self, path = '', mode = 1, parent = None, task = None):
		QMainWindow.__init__(self, parent)
		self.tr = Translator('Thrifty')

		#self.resize(450, 350)
		self.setWindowTitle(self.tr._translate('Thrifty'))
		self.setWindowIcon(QIcon('/usr/share/thrifty/icons/sniper_soldier.png'))

		self.save_ = QAction(QIcon('/usr/share/thrifty/icons/save.png'), self.tr._translate('&Save'), self)
		self.save_.setShortcut('Ctrl+S')
		self.save_.setStatusTip(self.tr._translate('Save file'))
		self.connect(self.save_, SIGNAL('triggered()'), self._save)

		self.exit_ = QAction(QIcon('/usr/share/thrifty/icons/exit.png'), self.tr._translate('&Exit'), self)
		self.exit_.setShortcut('Ctrl+Q')
		self.exit_.setStatusTip(self.tr._translate('Exit application'))
		self.connect(self.exit_, SIGNAL('triggered()'), self._close)

		self.giveToYum = QAction(QIcon('/usr/share/thrifty/icons/exit.png'), self.tr._translate('to &Yum'), self)
		self.giveToYum.setShortcut('Ctrl+Y')
		self.giveToYum.setStatusTip(self.tr._translate('Give package list to Yum for reinstall'))
		self.connect(self.giveToYum, SIGNAL('triggered()'), self.runYum)
		self.giveToYum.setEnabled(False)

		menubar = self.menuBar()

		file_ = menubar.addMenu(self.tr._translate('&File'))
		file_.addAction(self.save_)
		file_.addAction(self.exit_)

		toYum = menubar.addMenu(self.tr._translate('&Action'))
		toYum.addAction(self.giveToYum)

		if task is not None :
			self.save_.setEnabled(False)
			if task : self.giveToYum.setEnabled(True)

		self.editor = QTextEdit(parent = self)
		self.setCentralWidget(self.editor)

		self.statusBar = StatusBar(self)
		self.setStatusBar(self.statusBar)

		self.Parent = parent
		self.mode = mode
		self.path = path
		self.editor.setUndoRedoEnabled(True)
		self.editor.setOverwriteMode(True)
		self.editor.createStandardContextMenu()
		if task is None :
			s = readFile(self.path)
		else : 
			s_ = readFile(self.path)
			if self.path == '' :
				s = s_
			else :
				l = []
				for item in s_.split('\n') :
					chunks = item.split(' ')
					if len(chunks) >= task + 1 :
						if chunks[task] != '' and chunks[task] not in l:
							l.append(chunks[task])
				_s = [s_ + '\n' for s_ in l]
				_s.sort()
				s = ''.join(_s)
		#print [s, QString().fromUtf8(s)]
		self.editor.setPlainText(QString().fromUtf8(s))
		self.statusBar.showMessage('Edit : ' + self.path)

	def runYum(self):
		self.save_.setEnabled(False)
		self.exit_.setEnabled(False)
		self.giveToYum.setEnabled(False)
		packageList = self.editor.toPlainText()
		self.editor.clear()
		self.editor.setReadOnly(True)
		Data = QStringList()
		Data.append('yum')
		Data.append('-y')
		Data.append('reinstall')
		for item in packageList.split('\n') :
			if item != '' :
				#print [item]
				Data.append(item)
		## run yum in dispatched process
		self.y = QProcess()
		self.y.readyReadStandardOutput.connect(self.appendOutputString)
		self.y.readyReadStandardError.connect(self.appendErrorString)
		self.y.finished.connect(self.showResult)
		self.y.start('pkexec', Data)
		if self.y.waitForStarted() :
			#print self.y.state()
			self.statusBar.showMessage(self.tr._translate('Yum runned...'))
		else :
			self.showResult()

	def appendOutputString(self):
		output = self.y.readAllStandardOutput()
		self.editor.append(QString().fromUtf8(output))

	def appendErrorString(self):
		error = self.y.readAllStandardError()
		self.editor.append(QString().fromUtf8(error))

	def showResult(self):
		self.exit_.setEnabled(True)
		self.statusBar.showMessage(self.tr._translate('Ready to exit.'))

	def _save(self):
		text = self.editor.toPlainText()
		if self.mode :
			with open(self.path, 'wb') as f :
				f.write(text.toUtf8().data())
		else :
			fileName = os.path.join('/tmp', randomString(12))
			with open(fileName, 'wb') as f :
				f.write(text.toUtf8().data())
			self.s = QProcess()
			Data = QStringList()
			Data.append('/usr/bin/python')
			Data.append('/usr/share/thrifty/saveHelper.py')
			Data.append(self.path)
			Data.append(fileName)
			self.s.finished.connect(self.showExitCode)
			#for i in xrange(Data.count()) :
			#	print Data[i],
			#print
			self.s.start('pkexec', Data)
			if self.s.waitForStarted() :
				print 'status %s' % self.s.state()
			else :
				print '%s not saved' % self.path
				self.showExitCode()

	def showExitCode(self):
		self.statusBar.showMessage(self.tr._translate('Exit code: ') + str(self.s.exitCode()))

	def _close(self):
		self.Parent.enableEditorButton()
		self.close()

	def closeEvent(self, e):
		self.Parent.enableEditorButton()
		e.accept()
Example #23
0
class PyDrawCanvas(tk.Canvas):

    def __init__(self, master=None, **kwargs):
        super().__init__(master=master, **kwargs)
        self.elements = []
        self.init_events()
        self.init_menubar()
        self.init_context()
        self.set_appicon()
        self.set_title()
        self.statusbar = None
        self.drp_Operation = None
        self.selectedObject = None

    # region Inits

    def set_appicon(self):
        self.master.tk.call('wm', 'iconphoto', self.master._w, PhotoImage(file='appicon.png'))

    def set_title(self):
        self.master.title("PyDraw by Festina Lente Software ")

    def init_events(self):
        self.focus_set()
        self.bind("<Key>", self.on_keypress)
        self.bind("<Configure>", self.on_resize)
        self.bind("<ButtonPress-1>", self.on_left_click)
        self.bind("<B1-Motion>", self.on_drag)
        self.bind("<ButtonRelease-1>", self.on_drop)
        self.master.protocol('WM_DELETE_WINDOW', self.on_closing)

    def init_menubar(self):
        self.menubar = MainMenu(self.master, self)

    def init_after_pack(self):
        self.create_statusbar()

    # endregion

    # region DrawingContext

    def init_context(self):
        self.drawing_area = Rectangle((0, 0, 1000, 1000))
        self.canvas_area = Rectangle((0, 0, self.winfo_width(), self.winfo_height()))
        self.drawing_context = DrawingContext(orig=self.drawing_area, target=self.canvas_area, border=0.05)

    def transposeBack(self, pos):
        return self.drawing_context.transposeBack(pos)

    def transpose(self, pos):
        return self.drawing_context.transpose(pos)

    # endregion

    # region Events

    def on_keypress(self, event):
        ec = event.char
        ek = event.keysym

        if ek == 'Escape':
            self.selectedObject = None


    def on_resize(self, event):
        self.canvas_area = Rectangle((0, 0, self.winfo_width(), self.winfo_height()))
        self.drawing_context.target_rect = self.canvas_area
        self.redraw()

    def on_left_click(self, event):
        x, y = event.x, event.y
        d_point = self.drawing_context.transposeBack(Point(x, y))
        if not self.drawing_area.contains_point(d_point):
            # ignore outside border
            return

        if self.selectedObject:
            self.drp_Operation = Drp_MoveObject(self, Point(x, y), self.selectedObject)
        else:
            newLine = LineElement(start=d_point, end=d_point + (1, 1))
            self.add_element(newLine)
            self.redraw()
            self.drp_Operation = Drp_DrawLine(self, Point(x, y), newLine)
            self.selectedObject = newLine

    def on_object_click(self, object, event):
        self.selectedObject = object
        # print(f"on_object_click: event={event},object={object}")

    def on_closing(self):
        if not messagebox.askokcancel(
                'Exit Tool',
                'Do you really want to exit this tool?'):
            return
        self.master.destroy()

    def on_drag(self, event):
        if self.drp_Operation:
            self.drp_Operation.on_drag((event.x, event.y))

    def on_drop(self, event):
        if self.drp_Operation:
            self.drp_Operation.on_drop((event.x, event.y))
            self.drp_Operation = None

    # endregion

    # region Elements

    def add_element(self, drawing_element):
        self.elements.append(drawing_element)
        self.redraw()

    def new_drawing(self):
        self.setStatusMessage(text='Creating new drawing')
        self.elements = []
        self.redraw()
        self.setStatusMessage(text='Created new drawing', resetInSecs=5)

    # endregion

    # region Drawing

    def redraw(self):
        self.delete("all")
        self.draw_border()
        for element in self.elements:
            element.draw_on_canvas(self, self.drawing_context)

    def draw_border(self):
        ctx = self.drawing_context
        p1 = ctx.transpose(self.drawing_area.start)
        p3 = ctx.transpose(self.drawing_area.end)
        p2, p4 = Point(p1.x, p3.y), Point(p3.x, p1.y)
        points = [p1, p2, p3, p4, p1]
        flat_points = [item for p in points for item in p.xy]
        self.create_line(*flat_points)

    # endregion

    # region Statusbar

    def create_statusbar(self):
        self.statusbar = StatusBar(master=self.master)
        self.statusbar.pack(fill=tk.X)

    def setStatusMessage(self, **kwargs):
        if self.statusbar:
            self.statusbar.setMessage(**kwargs)
        else:
            txt = kwargs.get("text", "")
            print(f'{datetime.now()} Status:  {txt}')

    def setProgress(self, **kwargs):
        if self.statusbar:
            self.statusbar.setProgress(**kwargs)
        else:
            ptext = kwargs.get('text', '')
            value = kwargs.get('value', 0)
            range = kwargs.get('maximum', 0)
            progr = "" if not value \
                else f'[{value}]' if not range \
                else f'[{value}/{range}]'

            print(f'{datetime.now()} Progress: {progr} - {ptext}')
Example #24
0
class MainWindow(QtGui.QWidget):
    def __init__(self, debugFlag, parent=None):
        QtGui.QWidget.__init__(self)

        self.debugFlag = debugFlag

        self.msgLog = MessageLog(debugFlag)
        self.statusBar = StatusBar(self.msgLog)
        self.buttonPanel = ButtonPanel(self.msgLog)
        self.buttonPanel.logPackageRequested.connect(self.packageLogs)

        self.statusBar.diskFillupDetected.connect(
            self.buttonPanel.handleDiskFillup)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.statusBar)
        mainLayout.addWidget(self.buttonPanel)
        mainLayout.addWidget(self.msgLog)
        self.setLayout(mainLayout)

        versionFile = open('../VERSION', 'r')
        versionNumber = versionFile.readline().rstrip('\n')
        if not Repo('..').head.is_detached:
            branchName = Repo('..').active_branch.name
        else:
            branchName = Repo('..').head.commit.hexsha
        versionText = versionNumber if (branchName == 'master') else branchName

        self.setWindowTitle('WillowGUI (%s)' % versionText)
        self.setWindowIcon(QtGui.QIcon('../img/round_logo_60x60.png'))
        #self.resize(400,200)
        self.center()

        ###
        try:
            self.startDaemon()
            self.msgLog.post('Daemon started.')
        except DaemonMissingError as e:
            self.msgLog.post('Path to daemon does not exist: %s' % e.path)

        try:
            hwif.init()
            self.msgLog.post('HWIF initialized.')
        except (ImportError, socket.error) as e:
            self.msgLog.post('Could not initialize HWIF.')

        self.statusBar.initializeWatchdog()

    def startDaemon(self):
        daemonPath = os.path.join(config.daemonDir, 'build/leafysd')
        if os.path.exists(daemonPath):
            self.daemonProcess = subprocess.Popen([
                daemonPath, '-N', '-A', '192.168.1.2', '-I',
                config.networkInterface
            ],
                                                  stdout=oFile,
                                                  stderr=eFile)
        else:
            raise DaemonMissingError(daemonPath)

    def exit(self):
        print 'Cleaning up, then exiting..'
        if self.debugFlag:
            self.packageLogs()
        self.statusBar.watchdogThread.terminate()

    def center(self):
        windowCenter = self.frameGeometry().center()
        screenCenter = QtGui.QDesktopWidget().availableGeometry().center()
        self.move(screenCenter - windowCenter)

    def packageLogs(self):
        log_dir = '../log/'
        for log in self.msgLog.backlogs:
            self.msgLog.logWrite(log, log_dir + log.objectName.lower())
        vitalsLogFilename = log_dir + '/vitals'
        self.statusBar.writeVitalsLog(vitalsLogFilename)
        dt = datetime.datetime.fromtimestamp(time.time())
        zipFilename = str(
            QtGui.QFileDialog.getSaveFileName(
                self, 'Save Zipped logs',
                '../log/logs_from_%02d-%02d-%04d_%02d:%02d:%02d.zip' %
                (dt.month, dt.day, dt.year, dt.hour, dt.minute, dt.second)))
        if zipFilename:
            with zipfile.ZipFile(zipFilename, 'w') as f:
                for log in self.msgLog.backlogs:
                    f.write(log_dir + log.objectName.lower())
                f.write('../log/oFile')
                f.write('../log/eFile')
        self.msgLog.post('Saved debugging logs to {0}'.format(zipFilename))
Example #25
0
 def init_statusbar(self):
     """function that creates a status bar at the bottom of the window"""
     self.sb = StatusBar(self)
     self.sb.grid(row=3,column=0,columnspan=2, sticky="ew")