예제 #1
0
class ModifyPanel(wx.Panel):
    """"""
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        main_Sizer = wx.BoxSizer(wx.VERTICAL)

        #strinfo=u" 对apk渠道各个资源的配置写在channelconfig.xlsx,并且放到程序目录下"
        #self.infosta= wx.StaticText(self, -1, strinfo)

        #select a apk ui
        self.apk_Box = wx.StaticBox(self, -1, u"Apk")
        apkBoxSizer = wx.StaticBoxSizer(self.apk_Box, wx.HORIZONTAL)
        self.apksta = wx.StaticText(self, -1, u"apk包:  ")
        self.apkdiredit = wx.TextCtrl(self, -1, "")
        self.apkdirbtn = wx.Button(self, label=u"...")
        apkBoxSizer.Add(self.apksta, 0, wx.ALL | wx.ALIGN_TOP, 5)
        apkBoxSizer.Add(self.apkdiredit, 1, wx.ALL | wx.ALIGN_TOP, 5)
        apkBoxSizer.Add(self.apkdirbtn, 0, wx.ALL | wx.ALIGN_TOP, 5)

        #select a resource ui
        """
        self.res_Box = wx.StaticBox(self, -1, u"Resource")
        resBoxSizer = wx.StaticBoxSizer(self.res_Box, wx.HORIZONTAL)
        self.ressta = wx.StaticText(self, -1, u"资源目录:")
        self.resdiredit = wx.TextCtrl(self, -1, "")
        self.resdirbtn = wx.Button(self, label=u"...")
        resBoxSizer.Add(self.ressta, 0, wx.ALL|wx.ALIGN_TOP, 5)
        resBoxSizer.Add(self.resdiredit, 1, wx.ALL|wx.ALIGN_TOP, 5)
        resBoxSizer.Add(self.resdirbtn, 0, wx.ALL|wx.ALIGN_TOP, 5)
        """
        #set out put directory
        self.outPut_Box = wx.StaticBox(self, -1, u"Output")
        outPutBoxSizer = wx.StaticBoxSizer(self.outPut_Box, wx.HORIZONTAL)
        self.outPutsta = wx.StaticText(self, -1, u"输出目录:")
        self.outPutdiredit = wx.TextCtrl(self, -1, "")
        self.outPutdirbtn = wx.Button(self, label=u"...")
        outPutBoxSizer.Add(self.outPutsta, 0, wx.ALL | wx.ALIGN_TOP, 5)
        outPutBoxSizer.Add(self.outPutdiredit, 1, wx.ALL | wx.ALIGN_TOP, 5)
        outPutBoxSizer.Add(self.outPutdirbtn, 0, wx.ALL | wx.ALIGN_TOP, 5)

        #layout operate button
        #The list static box
        self.choiceList_Box = wx.StaticBox(self, -1, u"列表")
        self.choiceSel = wx.Choice(self, -1, choices=[u"全不选", u"反选", u"全选"])
        self.choiceSel.SetSelection(0)
        self.keyStoreChoiceSel = wx.Choice(self, -1)
        choice_BoxSizer = wx.StaticBoxSizer(self.choiceList_Box, wx.HORIZONTAL)
        choice_BoxSizer.Add(self.choiceSel, 0, wx.ALL | wx.ALIGN_TOP, 5)
        choice_BoxSizer.Add(self.keyStoreChoiceSel, 0, wx.ALL | wx.ALIGN_TOP,
                            5)

        self.saveBtn = wx.Button(self, label=u"保存UI")
        self.GenBtn = wx.Button(self, label=u"生成")

        operate_Sizer = wx.BoxSizer(wx.HORIZONTAL)
        operate_Sizer.Add(choice_BoxSizer, 0,
                          wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 5)
        operate_Sizer.Add(self.saveBtn, 0, wx.ALIGN_LEFT | wx.EXPAND | wx.ALL,
                          5)
        operate_Sizer.Add(self.GenBtn, 0, wx.ALIGN_LEFT | wx.EXPAND | wx.ALL,
                          5)

        #add listctrl
        self.resultsOlv = ObjectListView(self,
                                         style=wx.LC_REPORT | wx.SUNKEN_BORDER)
        self.InitColumns()

        self.progress = wx.Gauge(self, -1)
        self.progress.SetRange(100)

        #main_Sizer.Add(self.infosta, 0, wx.EXPAND|wx.ALL, 5)
        main_Sizer.Add(apkBoxSizer, 0, wx.EXPAND | wx.ALL, 5)
        #main_Sizer.Add(resBoxSizer, 0, wx.EXPAND|wx.ALL, 5)
        main_Sizer.Add(outPutBoxSizer, 0, wx.EXPAND | wx.ALL, 5)
        main_Sizer.Add(self.resultsOlv, 1, wx.EXPAND | wx.ALL, 5)
        main_Sizer.Add(self.progress, 0, wx.EXPAND | wx.ALL, 5)
        main_Sizer.Add(operate_Sizer, 0, wx.EXPAND | wx.ALL, 5)
        self.SetSizer(main_Sizer)

        self.apkdirbtn.Bind(wx.EVT_BUTTON, self.onSelApkButton)
        #self.resdirbtn.Bind(wx.EVT_BUTTON, self.onSelResButton)
        self.outPutdirbtn.Bind(wx.EVT_BUTTON, self.onSelOutDirButton)
        self.choiceSel.Bind(wx.EVT_CHOICE, self.OnSelChoice)
        self.saveBtn.Bind(wx.EVT_BUTTON, self.onSaveUIButton)
        self.GenBtn.Bind(wx.EVT_BUTTON, self.onGenButton)

        #Set choice change event.
        self.choicesDict = {}
        self.choicesDict[u"全不选"] = self.ListCheckNotSel
        self.choicesDict[u"反选"] = self.ListCheckInverSel
        self.choicesDict[u"全选"] = self.ListCheckSelAll

        self.progress.SetValue(0)
        self.loadChannelCofigToList()

    #=======================Init End=====================================#

    def loadChannelCofigToList(self):
        """ Load Channel config then show to UI listCtrl"""

        UIConfigParser.getInstance().Read()
        ChannelResConfigParser.getInstance().Read()
        self.test_data = []
        configData = ChannelResConfigParser.getInstance().getConfigData()
        for (key, value) in configData.items():
            if key == "keystore":
                continue
            self.test_data.append(Results(str(key), "", ""))
        #Set value to list.
        self.resultsOlv.SetObjects(self.test_data)
        objects = self.resultsOlv.GetObjects()
        #Refresh UI.
        self.resultsOlv.RefreshObjects(objects)
        if configData.has_key("keystore"):
            for (key, value) in configData["keystore"].items():
                self.keyStoreChoiceSel.Append(key)

        self.keyStoreChoiceSel.SetSelection(0)
        self.apkdiredit.SetValue(UIConfigParser.getInstance().getApkPath())
        self.outPutdiredit.SetValue(
            UIConfigParser.getInstance().getOutPutPath())

    def InitColumns(self):
        """Init list colums."""

        self.resultsOlv.SetColumns([
            ColumnDefn(u"渠道", "left", 150, "channal_id"),
            #ColumnDefn(u"渠道信息", "left", 160, "channal_alias"),
            #ColumnDefn(u"渠道特制", "left", 320, "channal_custom")
        ])
        self.resultsOlv.CreateCheckStateColumn()

    def onSelApkButton(self, event):
        file_wildcard = "source file(*.apk)|*.apk"
        dialog = wx.FileDialog(
            self,
            "Get a apk file",
            #os.getcwd(),
            style=wx.FD_OPEN | wx.FD_CHANGE_DIR,
            wildcard=file_wildcard)
        if dialog.ShowModal() != wx.ID_OK:
            return
        self.apkdiredit.SetValue(dialog.GetPath())
        pass

    def onSelResButton(self, event):
        dialog = wx.DirDialog(None,
                              u"选择资源目录:",
                              style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        if dialog.ShowModal() == wx.ID_OK:
            self.resdiredit.SetValue(dialog.GetPath())

    def onSelOutDirButton(self, event):
        dialog = wx.DirDialog(None,
                              u"选择输出目录:",
                              style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        if dialog.ShowModal() == wx.ID_OK:
            self.outPutdiredit.SetValue(dialog.GetPath())
        pass

    def onSaveUIButton(self, event):
        self.saveUiInfo()

    def saveUiInfo(self):
        UIConfigParser.getInstance().setApkPath(self.apkdiredit.GetValue())
        UIConfigParser.getInstance().setOutPutPath(
            self.outPutdiredit.GetValue())
        UIConfigParser.getInstance().Write()

    def onGenButton(self, event):
        apkFile = self.apkdiredit.GetValue()
        if apkFile.strip() == "":
            self.messageBox(u"未选择APK")
            return
        if self.fileNoExist(apkFile):
            return
        """
        resdir = self.resdiredit.GetValue()
        if resdir.strip() == "":
            self.messageBox(u"未选择资源目录")
            return
        if self.fileNoExist(resdir):
            return
        """
        outPutdir = self.outPutdiredit.GetValue()
        if outPutdir.strip() == "":
            self.messageBox(u"未选择输出目录")
            return
        if self.fileNoExist(outPutdir):
            return

        iSel = self.keyStoreChoiceSel.GetSelection()
        keyStore = self.keyStoreChoiceSel.GetString(iSel)
        if keyStore.strip() == "":
            self.messageBox(u"keyStore为空")
            return
        if self.fileNoExist("%s/%s" % (sys.path[0], keyStore)):
            return

        #If the channel be selected,it's value is 1.
        #otherwise it's value is 0.
        selChanneldict = {}
        objects = self.resultsOlv.GetObjects()
        for obj in objects:
            if self.resultsOlv.GetCheckState(obj, 0):
                selChanneldict[self.resultsOlv.GetStringValueAt(obj, 1)] = 0

        #No select channel.
        if len(selChanneldict) <= 0:
            self.messageBox(u"未选择渠道")
            return

        self.saveUiInfo()
        #Call parse
        modify.callParse(selChanneldict, apkFile, outPutdir, keyStore,
                         self.progress)
        dlg = wx.MessageDialog(None, u"渠道处理完成", u"", wx.wx.OK)
        result = dlg.ShowModal()
        dlg.Destroy()
        self.progress.SetValue(0)

    def fileNoExist(self, filename):
        if os.path.exists(filename):
            return False
        dlg = wx.MessageDialog(None, u"%s 不存在" % (filename), u"错误",
                               wx.OK | wx.ICON_ERROR)
        result = dlg.ShowModal()
        dlg.Destroy()
        return True

    def messageBox(self, errorMsg):
        dlg = wx.MessageDialog(None, errorMsg, u"错误", wx.OK | wx.ICON_ERROR)
        result = dlg.ShowModal()
        dlg.Destroy()

    #========================choice event====================#
    def OnSelChoice(self, event):
        """Choice change event"""

        iSel = self.choiceSel.GetSelection()
        selString = self.choiceSel.GetString(iSel)
        self.choicesDict[selString]()

    def ListCheckSelAll(self):
        """Select all channals"""

        objects = self.resultsOlv.GetObjects()
        for obj in objects:
            self.resultsOlv.SetCheckState(obj, True)
        self.resultsOlv.RefreshObjects(objects)

    def ListCheckInverSel(self):
        """Inverse selection"""

        objects = self.resultsOlv.GetObjects()
        for obj in objects:
            self.resultsOlv.SetCheckState(
                obj, not self.resultsOlv.GetCheckState(obj))
        self.resultsOlv.RefreshObjects(objects)

    def ListCheckNotSel(self):
        """No select channals """

        objects = self.resultsOlv.GetObjects()
        for obj in objects:
            self.resultsOlv.SetCheckState(obj, False)
        self.resultsOlv.RefreshObjects(objects)
예제 #2
0
class LeftPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent)
        self.plots = []
        self.pickedColors = []
        self.colors = self.setupColors()
        self.plotsOlv = ObjectListView(self,
                                       wx.ID_ANY,
                                       style=wx.LC_REPORT | wx.SUNKEN_BORDER,
                                       useAlternateBackColors=False)
        self.plotsOlv.Bind(OLVEvent.EVT_ITEM_CHECKED, self.checkboxClicked)
        self.plotsOlv.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onDoubleClick)
        #self.plotsOlv.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.onRightClick)
        self.getPlots()
        self.setColumns()
        self.plotsOlv.CreateCheckStateColumn()
        self.plotsOlv.SetObjects(self.plots)
        bsizer = wx.BoxSizer()
        #bsizer.Add(lb, 1, wx.EXPAND)
        bsizer.Add(self.plotsOlv, 1, wx.EXPAND)
        self.SetSizer(bsizer)
        self.checkedPlots = {}
        pub.subscribe(self.refreshList, 'list.updated')
        pub.subscribe(self.checkboxClicked, 'checkbox.clicked')
        pub.subscribe(self.onSavePlot, 'file.savePlot')
        pub.subscribe(self.onDelete, 'edit.delete')

    def onDoubleClick(self, event):
        #print event.m_itemIndex
        dlg = wx.ColourDialog(self)
        # Ensure the full colour dialog is displayed,
        # not the abbreviated version.
        dlg.GetColourData().SetChooseFull(True)
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetColourData()
        color = data.GetColour().Get()
        htmlColor = "#%02x%02x%02x" % color
        dlg.Destroy()
        index = event.m_itemIndex
        stored.plots[index]['Color'] = htmlColor
        self.plots[index].icon = self.plots[index].createIcon(
            self.plotsOlv, htmlColor)
        self.plotsOlv.RefreshObject(self.plots[index])
        pub.sendMessage('item.checked', data=self.checkedPlots)

    def onDelete(self):
        if self.plotsOlv.GetSelectedObjects():
            objectList = self.plotsOlv.GetSelectedObjects()
            for object in objectList:
                index = object.index
                stored.plots.pop(index)
                self.plots.pop(index)
            self.refreshList()
            pub.sendMessage('update.statusBar', data="Plots deleted!")
        else:
            pub.sendMessage(
                'update.statusBar',
                data="Cannot delete plots! Please select one ore more plots!")

    def onSavePlot(self):
        if self.plotsOlv.GetSelectedObject():
            index = self.plotsOlv.GetSelectedObject().index
            data = stored.plots[index]
            outputString = "%s\n" % data['Title']
            outputString += "%s\n" % data['Type']
            outputString += "%s,%s\n" % (data['xTitle'], data['xTitle'])
            for idx, row in enumerate(data['xData'].tolist()):
                z = 0
                outputString += "%1.3f,%1.3f\n" % (data['xData'][idx],
                                                   data['yData'][idx])
            if stored.plots[index]['Type'] == "DifferenceMap" or stored.plots[
                    index]['Type'] == "DistanceMap":
                outputString += "z-Data:\n"
                numpy.set_printoptions(threshold=numpy.nan)
                zData = numpy.array_str(data['zData'])
                outputString += zData
            dialog = wx.FileDialog(None,
                                   message="Save plot data as ...",
                                   defaultDir=os.getcwd(),
                                   defaultFile=stored.plots[index]['Title'],
                                   wildcard="*.dat",
                                   style=wx.SAVE | wx.OVERWRITE_PROMPT)
            if dialog.ShowModal() == wx.ID_OK:
                path = dialog.GetPath()
                dataFile = open(path, 'w')
                print "\nSaving data...",
                dataFile.write(outputString)
                print "Done!\n"
                dataFile.close()
            dialog.Destroy()
            pub.sendMessage('update.statusBar', data="Plot data saved!")
        else:
            pub.sendMessage('update.statusBar',
                            data="Cannot save data! Please select one plot!")

    def setupColors(self):
        cnames = {
            'aliceblue': '#F0F8FF',
            'antiquewhite': '#FAEBD7',
            'aqua': '#00FFFF',
            'aquamarine': '#7FFFD4',
            'azure': '#F0FFFF',
            'beige': '#F5F5DC',
            'bisque': '#FFE4C4',
            'black': '#000000',
            'blanchedalmond': '#FFEBCD',
            'blue': '#0000FF',
            'blueviolet': '#8A2BE2',
            'brown': '#A52A2A',
            'burlywood': '#DEB887',
            'cadetblue': '#5F9EA0',
            'chartreuse': '#7FFF00',
            'chocolate': '#D2691E',
            'coral': '#FF7F50',
            'cornflowerblue': '#6495ED',
            'cornsilk': '#FFF8DC',
            'crimson': '#DC143C',
            'cyan': '#00FFFF',
            'darkblue': '#00008B',
            'darkcyan': '#008B8B',
            'darkgoldenrod': '#B8860B',
            'darkgray': '#A9A9A9',
            'darkgreen': '#006400',
            'darkkhaki': '#BDB76B',
            'darkmagenta': '#8B008B',
            'darkolivegreen': '#556B2F',
            'darkorange': '#FF8C00',
            'darkorchid': '#9932CC',
            'darkred': '#8B0000',
            'darksalmon': '#E9967A',
            'darkseagreen': '#8FBC8F',
            'darkslateblue': '#483D8B',
            'darkslategray': '#2F4F4F',
            'darkturquoise': '#00CED1',
            'darkviolet': '#9400D3',
            'deeppink': '#FF1493',
            'deepskyblue': '#00BFFF',
            'dimgray': '#696969',
            'dodgerblue': '#1E90FF',
            'firebrick': '#B22222',
            'floralwhite': '#FFFAF0',
            'forestgreen': '#228B22',
            'fuchsia': '#FF00FF',
            'gainsboro': '#DCDCDC',
            'ghostwhite': '#F8F8FF',
            'gold': '#FFD700',
            'goldenrod': '#DAA520',
            'gray': '#808080',
            'green': '#008000',
            'greenyellow': '#ADFF2F',
            'honeydew': '#F0FFF0',
            'hotpink': '#FF69B4',
            'indianred': '#CD5C5C',
            'indigo': '#4B0082',
            'ivory': '#FFFFF0',
            'khaki': '#F0E68C',
            'lavender': '#E6E6FA',
            'lavenderblush': '#FFF0F5',
            'lawngreen': '#7CFC00',
            'lemonchiffon': '#FFFACD',
            'lightblue': '#ADD8E6',
            'lightcoral': '#F08080',
            'lightcyan': '#E0FFFF',
            'lightgoldenrodyellow': '#FAFAD2',
            'lightgreen': '#90EE90',
            'lightgray': '#D3D3D3',
            'lightpink': '#FFB6C1',
            'lightsalmon': '#FFA07A',
            'lightseagreen': '#20B2AA',
            'lightskyblue': '#87CEFA',
            'lightslategray': '#778899',
            'lightsteelblue': '#B0C4DE',
            'lightyellow': '#FFFFE0',
            'lime': '#00FF00',
            'limegreen': '#32CD32',
            'linen': '#FAF0E6',
            'magenta': '#FF00FF',
            'maroon': '#800000',
            'mediumaquamarine': '#66CDAA',
            'mediumblue': '#0000CD',
            'mediumorchid': '#BA55D3',
            'mediumpurple': '#9370DB',
            'mediumseagreen': '#3CB371',
            'mediumslateblue': '#7B68EE',
            'mediumspringgreen': '#00FA9A',
            'mediumturquoise': '#48D1CC',
            'mediumvioletred': '#C71585',
            'midnightblue': '#191970',
            'mintcream': '#F5FFFA',
            'mistyrose': '#FFE4E1',
            'moccasin': '#FFE4B5',
            'navajowhite': '#FFDEAD',
            'navy': '#000080',
            'oldlace': '#FDF5E6',
            'olive': '#808000',
            'olivedrab': '#6B8E23',
            'orange': '#FFA500',
            'orangered': '#FF4500',
            'orchid': '#DA70D6',
            'palegoldenrod': '#EEE8AA',
            'palegreen': '#98FB98',
            'paleturquoise': '#AFEEEE',
            'palevioletred': '#DB7093',
            'papayawhip': '#FFEFD5',
            'peachpuff': '#FFDAB9',
            'peru': '#CD853F',
            'pink': '#FFC0CB',
            'plum': '#DDA0DD',
            'powderblue': '#B0E0E6',
            'purple': '#800080',
            'red': '#FF0000',
            'rosybrown': '#BC8F8F',
            'royalblue': '#4169E1',
            'saddlebrown': '#8B4513',
            'salmon': '#FA8072',
            'sandybrown': '#FAA460',
            'seagreen': '#2E8B57',
            'seashell': '#FFF5EE',
            'sienna': '#A0522D',
            'silver': '#C0C0C0',
            'skyblue': '#87CEEB',
            'slateblue': '#6A5ACD',
            'slategray': '#708090',
            'snow': '#FFFAFA',
            'springgreen': '#00FF7F',
            'steelblue': '#4682B4',
            'tan': '#D2B48C',
            'teal': '#008080',
            'thistle': '#D8BFD8',
            'tomato': '#FF6347',
            'turquoise': '#40E0D0',
            'violet': '#EE82EE',
            'wheat': '#F5DEB3',
            'white': '#FFFFFF',
            'whitesmoke': '#F5F5F5',
            'yellow': '#FFFF00',
            'yellowgreen': '#9ACD32'
        }
        return cnames

    def setColumns(self, data=None):
        self.plotsOlv.SetColumns([
            #imageGetter: "icon" is a property of plotListEntry objects
            ColumnDefn("Title", "left", 500, "title", imageGetter="icon")
        ])
        #print "hallo"

    def refreshList(self):
        self.plotsOlv.ClearAll()
        self.plots = []
        self.pickedColors = []
        self.colors = self.setupColors()
        self.getPlots()
        self.setColumns()
        self.plotsOlv.CreateCheckStateColumn()
        self.plotsOlv.SetObjects(self.plots)
        self.checkedPlots = {}

    def getPlots(self):
        for idx, plot in enumerate(stored.plots):
            #print self.colors
            if not "Color" in plot:
                allowedColor = False
                preferredCnames = {
                    'blue': '#0000FF',
                    'green': '#008000',
                    'red': '#FF00FF',
                    'orange': '#FFA500',
                    'violet': '#EE82EE',
                    'magenta': '#FF0000'
                }
                while not allowedColor:
                    if len(preferredCnames) > 0:
                        color = preferredCnames.popitem()[1]
                    else:
                        color = self.colors.popitem()[1]
                    if not color in self.pickedColors:
                        allowedColor = True
                    self.pickedColors.append(color)
                    #print color
                plot['Color'] = color
            else:
                pass
            olv = self.plotsOlv
            self.plots.append(
                PlotListEntry(olv, plot['Type'], plot['Title'], plot['Color'],
                              idx))
        #print self.plots

    def checkboxClicked(self, data):
        data.rowModel.toggleState()
        index = data.rowModel.index
        isChecked = data.rowModel.isChecked
        currentPlot = stored.plots[index]
        currentId = index
        currentType = currentPlot["Type"]
        allowed = True
        nonSuperposeableTypes = ["DifferenceMap", "DistanceMap"]
        if len(self.checkedPlots) == 0 and isChecked:
            #this is the first checked plot, just add it
            self.checkedPlots[currentId] = currentPlot
            #print "Added first plot"
        elif len(self.checkedPlots) > 0 and isChecked:
            #check if of same type as other checked plots
            for key, value in self.checkedPlots.iteritems():
                #value will be a graph dict from mtsslWizard
                if currentType != value[
                        "Type"] or currentType in nonSuperposeableTypes:
                    allowed = False
                    #print "False, cannot add plot"
            if allowed:
                self.checkedPlots[currentId] = currentPlot
                #print "True, plot added"
            else:
                #self.lb.Check(index, check=False)
                print "New:"
                print self.plotsOlv.GetCheckState(data.rowModel)
                self.plotsOlv.SetCheckState(data.rowModel, False)
                #data.rowModel.setCheckedState(False)
                pub.sendMessage(
                    'update.statusBar',
                    data="Plots are not of same type or not superposeable!")
                print self.plotsOlv.GetCheckState(data.rowModel)
                self.plotsOlv.RefreshObject(data.rowModel)
        elif len(self.checkedPlots) > 0 and not isChecked:
            self.checkedPlots.pop(currentId, None)
            #print "removed plot from plot list"
        pub.sendMessage('item.checked', data=self.checkedPlots)