예제 #1
0
    def AnalysePhoto(self, nom_fichier=None):
        if nom_fichier == None:
            self.ctrl_listview.MAJ()
            if 'phoenix' in wx.PlatformInfo:
                img = wx.Image(TAILLE_IMAGE_ORIGINALE[0],
                               TAILLE_IMAGE_ORIGINALE[1])
                img.SetRGB((0, 0, TAILLE_IMAGE_ORIGINALE[0],
                            TAILLE_IMAGE_ORIGINALE[1]), 0, 0, 0)
            else:
                img = wx.EmptyImage(TAILLE_IMAGE_ORIGINALE[0],
                                    TAILLE_IMAGE_ORIGINALE[1])
                img.SetRGBRect((0, 0, TAILLE_IMAGE_ORIGINALE[0],
                                TAILLE_IMAGE_ORIGINALE[1]), 0, 0, 0)

            self.AfficheImageOriginale(img.ConvertToBitmap())
            return False

        self.label_infos.SetLabel(_(u"Analyse de l'image en cours..."))
        self.Layout()

        dlgAttente = wx.BusyInfo(_(u"Analyse de l'image en cours..."), None)
        wx.Yield()

        cascade = cv2.CascadeClassifier(
            Chemins.GetStaticPath("Divers/haarcascade_frontalface_alt2.xml"))
        img = cv2.imread(nom_fichier.encode("iso-8859-15"))
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        height, width = frame.shape[:2]
        if 'phoenix' in wx.PlatformInfo:
            bmp = wx.Bitmap.FromBuffer(width, height, frame)
        else:
            bmp = wx.BitmapFromBuffer(width, height, frame)

        listePhotos = []
        faces = cascade.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in faces:
            bmpVisage = bmp.GetSubBitmap((x, y, w, h))

            # Ajuste taille de l'image
            if 'phoenix' in wx.PlatformInfo:
                imgVisage = bmpVisage.ConvertToImage()
            else:
                imgVisage = wx.ImageFromBitmap(bmpVisage)
            imgVisage.Rescale(width=TAILLE_IMAGE[0],
                              height=TAILLE_IMAGE[1],
                              quality=wx.IMAGE_QUALITY_HIGH)
            bmpVisage = imgVisage.ConvertToBitmap()

            # Ajoute la photo à la liste
            listePhotos.append(bmpVisage)

            # Tracé du cadre rouge
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

        # Envoie les visages au ListView
        self.ctrl_listview.MAJ(listePhotos)

        # Envoie l'image originale vers le staticbitmap
        if 'phoenix' in wx.PlatformInfo:
            bmp = wx.Bitmap.FromBuffer(width, height, frame)
        else:
            bmp = wx.BitmapFromBuffer(width, height, frame)
        self.AfficheImageOriginale(bmp)

        # MAJ Label_infos
        texte = _(
            u"Noethys a détecté %d visages.\n\nDouble-cliquez sur les lignes\nde la liste pour les associer\nà des individus."
        ) % len(listePhotos)
        self.label_infos.SetLabel(texte)
        self.Layout()

        del dlgAttente
예제 #2
0
    def GetListeFichiersReseau(self):
        """ Récupère la liste des fichiers réseau à afficher """
        listeFichiers = []

        # Connexion au réseau MySQL
        hote = self.codesReseau["hote"]
        utilisateur = self.codesReseau["utilisateur"]
        motdepasse = self.codesReseau["motdepasse"]
        port = self.codesReseau["port"]

        if hote == "" or utilisateur == "":
            return listeFichiers

        DB = GestionDB.DB(nomFichier=u"%s;%s;%s;%s[RESEAU]" %
                          (port, hote, utilisateur, motdepasse))
        if DB.echec == 1:
            DB.Close()
            return listeFichiers

        # Test de connexion à une base de données
        listeDatabases = []
        DB.ExecuterReq("SHOW DATABASES;")
        listeValeurs = DB.ResultatReq()
        for valeurs in listeValeurs:
            listeDatabases.append(valeurs[0])

        # Récupération des infos
        for nomFichier in listeDatabases:
            if (self.prefixe == None and nomFichier.endswith("_tdata")) or (
                    self.prefixe != None and nomFichier.endswith("_tdata")
                    and nomFichier.startswith(self.prefixe)):

                titre = nomFichier[:-6]

                # Taille des 3 bases de données
                taille = 0
                taille = FormatFileSize(float(taille))

                # Date de dernière modification
                dateModif = None

                # Ouverture de la base de données pour récupérer les infos sur le fichier
                nom = u""
                description = u""
                img = wx.Image(
                    Chemins.GetStaticPath("Images/80x80/Logo_tw.png"),
                    wx.BITMAP_TYPE_PNG)
                img = RecadreImg(img)
                image = img.ConvertToBitmap()

                # Mémorisation
                listeFichiers.append({
                    "titre": titre,
                    "image": image,
                    "description": description,
                    "taille": taille,
                    "dateModif": dateModif
                })

        # Fermeture connexion
        DB.Close()

        return listeFichiers
예제 #3
0
    def onInit(self, showSplash=True, testMode=False):
        """
        :Parameters:

          testMode: bool
            If set to True then startup wizard won't appear and stdout/stderr
            won't be redirected to the Coder
        """
        self.version = psychopy.__version__
        self.SetAppName('PsychoPy2')

        # import localization after wx:
        from psychopy.app import localization  # needed by splash screen
        self.localization = localization
        self.locale = localization.wxlocale
        self.locale.AddCatalog(self.GetAppName())

        # set default paths and prefs
        self.prefs = psychopy.prefs
        if self.prefs.app['debugMode']:
            logging.console.setLevel(logging.DEBUG)
        # indicates whether we're running for testing purposes
        self.testMode = testMode
        self.osf_session = None

        if showSplash:
            # show splash screen
            splashFile = os.path.join(self.prefs.paths['resources'],
                                      'psychopySplash.png')
            splashBitmap = wx.Image(name=splashFile).ConvertToBitmap()
            splash = AS.AdvancedSplash(None,
                                       bitmap=splashBitmap,
                                       timeout=3000,
                                       style=AS.AS_TIMEOUT | wx.FRAME_SHAPED,
                                       shadowcolour=wx.RED)  # transparency?
            splash.SetTextPosition((10, 240))
            splash.SetText(_translate("  Loading libraries..."))
        else:
            splash = None

        # SLOW IMPORTS - these need to be imported after splash screen starts
        # but then that they end up being local so keep track in self
        if splash:
            splash.SetText(_translate("  Loading PsychoPy2..."))
        from psychopy.compatibility import checkCompatibility
        # import coder and builder here but only use them later
        from psychopy.app import coder, builder, dialogs, urls
        self.keys = self.prefs.keys
        self.prefs.pageCurrent = 0  # track last-viewed page, can return there
        self.IDs = IDStore()
        self.urls = urls.urls
        self.quitting = False
        # check compatibility with last run version (before opening windows)
        self.firstRun = False

        if '--firstrun' in sys.argv:
            del sys.argv[sys.argv.index('--firstrun')]
            self.firstRun = True
        if 'lastVersion' not in self.prefs.appData:
            # must be before 1.74.00
            last = self.prefs.appData['lastVersion'] = '1.73.04'
            self.firstRun = True
        else:
            last = self.prefs.appData['lastVersion']

        if self.firstRun and not self.testMode:
            self.firstrunWizard()

        # setup links for URLs
        # on a mac, don't exit when the last frame is deleted, just show menu
        if sys.platform == 'darwin':
            self.menuFrame = MenuFrame(parent=None, app=self)
        # get preferred view(s) from prefs and previous view
        if self.prefs.app['defaultView'] == 'last':
            mainFrame = self.prefs.appData['lastFrame']
        else:
            # configobjValidate should take care of this situation
            allowed = ['last', 'coder', 'builder', 'both']
            if self.prefs.app['defaultView'] in allowed:
                mainFrame = self.prefs.app['defaultView']
            else:
                self.prefs.app['defaultView'] = 'both'
                mainFrame = 'both'
        # fetch prev files if that's the preference
        if self.prefs.coder['reloadPrevFiles']:
            scripts = self.prefs.appData['coder']['prevFiles']
        else:
            scripts = []
        appKeys = list(self.prefs.appData['builder'].keys())
        if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys):
            exps = self.prefs.appData['builder']['prevFiles']
        else:
            exps = []
        # then override the prev files by command options and passed files
        if len(sys.argv) > 1:
            if sys.argv[1] == __name__:
                # program was executed as "python.exe PsychoPyIDE.py %1'
                args = sys.argv[2:]
            else:
                # program was executed as "PsychoPyIDE.py %1'
                args = sys.argv[1:]
            # choose which frame to start with
            if args[0] in ['builder', '--builder', '-b']:
                mainFrame = 'builder'
                args = args[1:]  # can remove that argument
            elif args[0] in ['coder', '--coder', '-c']:
                mainFrame = 'coder'
                args = args[1:]  # can remove that argument
            # did we get .py or .psyexp files?
            elif args[0][-7:] == '.psyexp':
                mainFrame = 'builder'
                exps = [args[0]]
            elif args[0][-3:] == '.py':
                mainFrame = 'coder'
                scripts = [args[0]]
        else:
            args = []

        self.dpi = int(wx.GetDisplaySize()[0] /
                       float(wx.GetDisplaySizeMM()[0]) * 25.4)
        if not (50 < self.dpi < 120):
            self.dpi = 80  # dpi was unreasonable, make one up

        if sys.platform == 'win32':
            # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32
            self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        else:
            self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
        self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
        self._codeFont.SetFaceName(self.prefs.coder['codeFont'])

        # removed Aug 2017: on newer versions of wx (at least on mac)
        # this looks too big
        # if hasattr(self._mainFont, 'Larger'):
        #     # Font.Larger is available since wyPython version 2.9.1
        #     # PsychoPy still supports 2.8 (see ensureMinimal above)
        #     self._mainFont = self._mainFont.Larger()
        #     self._codeFont.SetPointSize(
        #         self._mainFont.GetPointSize())  # unify font size

        # create both frame for coder/builder as necess
        if splash:
            splash.SetText(_translate("  Creating frames..."))
        self.coder = None
        self.copiedRoutine = None
        self.copiedCompon = None
        self._allFrames = []  # ordered; order updated with self.onNewTopWindow
        if mainFrame in ['both', 'coder']:
            self.showCoder(fileList=scripts)
        if mainFrame in ['both', 'builder']:
            self.showBuilder(fileList=exps)

        # send anonymous info to www.psychopy.org/usage.php
        # please don't disable this, it's important for PsychoPy's development
        self._latestAvailableVersion = None
        self.updater = None
        prefsConn = self.prefs.connections
        if prefsConn['checkForUpdates'] or prefsConn['allowUsageStats']:
            connectThread = threading.Thread(
                target=connections.makeConnections, args=(self, ))
            connectThread.start()
        # query github in the background to populate a local cache about
        # what versions are available for download:
        from psychopy.tools import versionchooser as vc
        versionsThread = threading.Thread(target=vc._remoteVersions,
                                          args=(True, ))
        versionsThread.start()

        ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True)
        # tell the user what has changed
        if not ok and not self.firstRun and not self.testMode:
            title = _translate("Compatibility information")
            dlg = dialogs.MessageDialog(parent=None,
                                        message=msg,
                                        type='Info',
                                        title=title)
            dlg.ShowModal()

        if self.prefs.app['showStartupTips'] and not self.testMode:
            tipFile = os.path.join(self.prefs.paths['resources'],
                                   _translate("tips.txt"))
            tipIndex = self.prefs.appData['tipIndex']
            tp = wx.CreateFileTipProvider(tipFile, tipIndex)
            showTip = wx.ShowTip(None, tp)
            self.prefs.appData['tipIndex'] = tp.GetCurrentTip()
            self.prefs.saveAppData()
            self.prefs.app['showStartupTips'] = showTip
            self.prefs.saveUserPrefs()

        if self.prefs.connections['checkForUpdates']:
            self.Bind(wx.EVT_IDLE, self.checkUpdates)
        else:
            self.Bind(wx.EVT_IDLE, self.onIdle)

        # doing this once subsequently enables the app to open & switch among
        # wx-windows on some platforms (Mac 10.9.4) with wx-3.0:
        if wx.version() >= '3.0' and sys.platform == 'darwin':
            _Showgui_Hack()  # returns ~immediately, no display
            # focus stays in never-land, so bring back to the app:
            if mainFrame in ['both', 'builder']:
                self.showBuilder()
            else:
                self.showCoder()

        return True
예제 #4
0
파일: canvas.py 프로젝트: xtuyaowu/imagepy
 def set_ips(self, ips):
     self.ips = ips
     self.imgbox = [0,0,ips.size[1],ips.size[0]]
     self.bmp = wx.Image(ips.size[1], ips.size[0])
     self.self_fit()
예제 #5
0
    def __init__(self,
                 parent,
                 ID,
                 title,
                 size,
                 pathSrc="./",
                 style=wx.DEFAULT_FRAME_STYLE):
        self.sessionLog = SessionLog(pathSrc)
        wx.Frame.__init__(self,
                          parent,
                          ID,
                          title,
                          size=self.sessionLog.getSize(),
                          style=style)

        # --- Détection du système d'exploitation
        self.win32 = (wx.Platform == '__WXMSW__')
        self.OS = os.sep
        # --- Définition des paths des différents dossiers ---
        self.pathSrc = pathSrc
        self.pathIcone = self.pathSrc + "icones" + self.OS
        self.pathLibrary = "/home/cfournier/Documents/Perso/BiblioSyl/data/Example_library.lsc"
        self.pathCouv = "/home/cfournier/Documents/Perso/BiblioSyl/data/Example_library_book_cover/"

        # --- Vérification de la présence des dossiers ---
        #		for myDir in [self.pathData, self.pathCouv, self.pathLivre]:
        #			if not os.path.isdir(myDir):
        #				os.makedirs(myDir)

        # --- Changement de couleur de l'arrière plan
        self.myBackgroundColour = wx.Colour(255, 255, 255, 255)
        self.SetBackgroundColour(self.myBackgroundColour)

        # --- Si True, fenêtre d'ajout de livre ouverte
        self.ajoutLivreFrame = False

        # --- Création de la barre de log
        self.CreateStatusBar(1)

        # --- Dimension de la fenêtre et de ses différents éléments
        self.menuSize = 0  # Hauteur en pixel du menu
        if self.win32: self.menuSize = 61
        self.searchBanner = 70  # Hauteur en pixel de la bannière du champs de recherche
        self.w = size[0]  # Largeur totale de la fenêtre
        self.h = size[
            1] - 20 - self.searchBanner - self.menuSize  # Hauteur de la fenêtre sans le log ni la bannière de recherche ni le menu
        self.vboxWidth = 280  # Largeur de la vbox avec couverture et commentaire
        self.couvRatio = 1.45  # Ratio Largeur/Hauteur de la couverture
        self.bordGWidth = 85  # Largeur de l'arabesque bordure gauche

        self.SetMinSize((size[0] / 2.0, size[1]))

        # --- Création de la liste
        self.list = VirtualList(self)

        # --- Initialisation de la barre de menu
        self.initMenuBar()

        # --- Initialisation des box
        self.vboxAll = wx.BoxSizer(wx.VERTICAL)  # Contient tous les BoxSizer
        self.hbox = wx.BoxSizer(wx.HORIZONTAL)  # Bordure | list | vbox
        self.vbox = wx.BoxSizer(wx.VERTICAL)  # Couverture | Commentaire

        # --- Initialisation du champs de recherche et de statistiques
        fontStBox = createMyFont({
            'pointSize': 12,
            'weight': wx.BOLD,
            'faceName': 'Comic Sans MS'
        })
        fontStText = createMyFont()

        # 1er champs: TextCtrl
        self.vboxAll.Add((-1, self.searchBanner), flag=wx.LEFT)
        x, y = 5, 0
        StBox = wx.StaticBox(self,
                             label="Recherche par mots-clés".decode('utf-8'),
                             pos=(x, y),
                             size=(275, self.searchBanner - 5))
        StBox.SetFont(fontStBox)
        x += 5
        self.keyWords = wx.TextCtrl(self,
                                    value="",
                                    pos=(x, 25),
                                    size=(265, 25),
                                    style=wx.TE_PROCESS_ENTER)
        x += 275
        # 2ème champs: Mots-clés actuels
        StBox = wx.StaticBox(self,
                             label="Mots-clés actuels".decode('utf-8'),
                             pos=(x, y),
                             size=(280, self.searchBanner - 5))
        StBox.SetFont(fontStBox)
        x += 5
        self.currKeyWords = wx.StaticText(self,
                                          label="",
                                          pos=(x, 20),
                                          size=(270, self.searchBanner - 30),
                                          style=wx.ST_NO_AUTORESIZE
                                          | wx.TE_MULTILINE)
        self.currKeyWords.SetFont(fontStText)
        x += 280
        # 3ème champs: Statistiques
        self.StBoxStat = wx.StaticBox(self,
                                      label="Quelques chiffres",
                                      pos=(x, y),
                                      size=(700, self.searchBanner - 5))
        self.StBoxStat.SetFont(fontStBox)
        x += 5
        self.statistiques = wx.StaticText(self,
                                          label="",
                                          pos=(x, 20),
                                          size=(690, self.searchBanner - 30),
                                          style=wx.TE_MULTILINE)
        #		self.statistiques = wx.TextCtrl(self, pos=(x,20), size = (690, self.searchBanner-30), style=wx.TE_MULTILINE|wx.TE_READONLY|wx.NO_BORDER)
        self.statistiques.SetFont(fontStText)
        self.statistiques.SetBackgroundColour(self.myBackgroundColour)

        # --- Initialisation bordure gauche
        self.hbox.Add((self.bordGWidth, -1), 0, flag=wx.EXPAND)
        img = wx.Image(self.pathIcone + "bordureDouble.png",
                       wx.BITMAP_TYPE_ANY)
        img = img.Scale(self.bordGWidth, self.bordGWidth * 10.7,
                        wx.IMAGE_QUALITY_HIGH)
        self.bitmapBordG = img.ConvertToBitmap()
        img = self.bitmapBordG.GetSubBitmap(
            wx.Rect(0, 0, self.bitmapBordG.GetWidth(), self.h))
        self.bordG = wx.StaticBitmap(self,
                                     -1,
                                     img,
                                     pos=(0, self.searchBanner),
                                     size=(img.GetWidth(), img.GetHeight()))

        # --- Ajout de la liste des livres à la hbox
        self.hbox.Add(self.list, proportion=1, flag=wx.EXPAND)

        # --- Initialisation de la liste de couverture des livres
        self.lCouvBitmap = self.initCouvertures(self.pathCouv)
        # Initialisation de la couverture du livre
        tmp = self.lCouvBitmap[DEFAULTCOVER]
        self.couv = wx.StaticBitmap(self,
                                    -1,
                                    tmp,
                                    size=(tmp.GetWidth(), tmp.GetHeight()))
        # self.vbox.Add(self.couv, flag=wx.SizerFlags().Align(wx.ALIGN_TOP))
        self.vbox.Add(self.couv, flag=wx.ALIGN_TOP)

        # --- Ajout des commentaires
        comSTtitle = wx.StaticText(self,
                                   label="Commentaire sur ce livre:",
                                   style=wx.DEFAULT)
        font = createMyFont({
            'pointSize': 14,
            'family': wx.ROMAN,
            'style': wx.SLANT,
            'weight': wx.BOLD,
            'underline': True
        })
        comSTtitle.SetFont(font)
        comSTtitle.SetForegroundColour((255, 0, 0))

        self.comTC = wx.TextCtrl(
            self,
            value="Les commentaires associés à vos livres seront affichés ici."
            .decode('utf-8'),
            size=(self.vboxWidth, self.h),
            style=wx.TE_MULTILINE | wx.TE_READONLY)
        font = createMyFont({
            'pointSize': 10,
            'family': wx.SWISS,
            'faceName': "Comic Sans MS"
        })
        self.comTC.SetFont(font)
        self.vbox.AddMany([(comSTtitle), (self.comTC, 1, wx.RIGHT)])

        # --- "Empillage" final des box
        self.hbox.Add(self.vbox, proportion=0, flag=wx.RIGHT)
        self.vboxAll.Add(self.hbox, proportion=1, flag=wx.EXPAND)
        self.SetSizer(self.vboxAll)

        # --- Définition des events
        # self.Bind(wx.EVT_SIZE, self.OnResize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
        self.Bind(wx.EVT_TEXT, self.OnKeyWords)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnKeyWords)
        self.Bind(wx.EVT_TIMER, self.OnTimer)
        self.Bind(wx.EVT_CLOSE, self.OnQuit)

        # --- Initialisation du Timer
        self.timer = wx.Timer(self, 1)
        self.pointeur = 0  # Position du pointeur dans le message
        self.rawStatMess = ""  # Message brut des statistiques
        self.list.calcStatistiques()  # Mise à jour du message
        self.timer.Start(200)  # X millisecondes d'intervalle

        # --- Affichage et centrage de la fenêtre
        self.Centre()
        self.Show(True)
예제 #6
0
 def __init__(self, *args, **kw):
     wx.combo.ComboCtrl.__init__(self, *args, **kw)
     bmp = wx.BitmapFromImage(wx.Image(p.resource_filename('CPAC', \
                                  'GUI/resources/images/folder7.gif')))
     self.SetButtonBitmaps(bmp, False)
예제 #7
0
    def onInit(self, showSplash=True, testMode=False):
        """This is launched immediately *after* the app initialises with wx
        :Parameters:

          testMode: bool
        """
        self.SetAppName('PsychoPy3')

        if showSplash:  #showSplash:
            # show splash screen
            splashFile = os.path.join(self.prefs.paths['resources'],
                                      'psychopySplash.png')
            splashImage = wx.Image(name=splashFile)
            splashImage.ConvertAlphaToMask()
            splash = AS.AdvancedSplash(
                None,
                bitmap=splashImage.ConvertToBitmap(),
                timeout=3000,
                agwStyle=AS.AS_TIMEOUT | AS.AS_CENTER_ON_SCREEN,
            )  # transparency?
            w, h = splashImage.GetSize()
            splash.SetTextPosition((int(340), h - 30))
            splash.SetText(
                _translate("Copyright (C) 2020 OpenScienceTools.org"))
        else:
            splash = None

        # SLOW IMPORTS - these need to be imported after splash screen starts
        # but then that they end up being local so keep track in self

        from psychopy.compatibility import checkCompatibility
        # import coder and builder here but only use them later
        from psychopy.app import coder, builder, runner, dialogs

        if '--firstrun' in sys.argv:
            del sys.argv[sys.argv.index('--firstrun')]
            self.firstRun = True
        if 'lastVersion' not in self.prefs.appData:
            # must be before 1.74.00
            last = self.prefs.appData['lastVersion'] = '1.73.04'
            self.firstRun = True
        else:
            last = self.prefs.appData['lastVersion']

        if self.firstRun and not self.testMode:
            pass

        # setup links for URLs
        # on a mac, don't exit when the last frame is deleted, just show menu
        if sys.platform == 'darwin':
            self.menuFrame = MenuFrame(parent=None, app=self)
        # fetch prev files if that's the preference
        if self.prefs.coder['reloadPrevFiles']:
            scripts = self.prefs.appData['coder']['prevFiles']
        else:
            scripts = []
        appKeys = list(self.prefs.appData['builder'].keys())
        if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys):
            exps = self.prefs.appData['builder']['prevFiles']
        else:
            exps = []
        runlist = []

        self.dpi = int(wx.GetDisplaySize()[0] /
                       float(wx.GetDisplaySizeMM()[0]) * 25.4)
        if not (50 < self.dpi < 120):
            self.dpi = 80  # dpi was unreasonable, make one up

        if sys.platform == 'win32':
            # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32
            self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        else:
            self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)

        try:
            self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
        except wx._core.wxAssertionError:
            # if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN
            self._codeFont = wx.Font(self._mainFont.GetPointSize(),
                                     wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL,
                                     wx.FONTWEIGHT_NORMAL)
        # that gets most of the properties of _codeFont but the FaceName
        # FaceName is set in the setting of the theme:
        self.theme = self.prefs.app['theme']

        # removed Aug 2017: on newer versions of wx (at least on mac)
        # this looks too big
        # if hasattr(self._mainFont, 'Larger'):
        #     # Font.Larger is available since wyPython version 2.9.1
        #     # PsychoPy still supports 2.8 (see ensureMinimal above)
        #     self._mainFont = self._mainFont.Larger()
        #     self._codeFont.SetPointSize(
        #         self._mainFont.GetPointSize())  # unify font size

        # create both frame for coder/builder as necess
        if splash:
            splash.SetText(_translate("  Creating frames..."))

        # Parse incoming call
        parser = argparse.ArgumentParser(prog=self)
        parser.add_argument('--builder', dest='builder', action="store_true")
        parser.add_argument('-b', dest='builder', action="store_true")
        parser.add_argument('--coder', dest='coder', action="store_true")
        parser.add_argument('-c', dest='coder', action="store_true")
        parser.add_argument('--runner', dest='runner', action="store_true")
        parser.add_argument('-r', dest='runner', action="store_true")
        view, args = parser.parse_known_args(sys.argv)
        print(args)
        # Check from filetype if any windows need to be open
        if any(arg.endswith('.psyexp') for arg in args):
            view.builder = True
            exps = [file for file in args if file.endswith('.psyexp')]
        if any(arg.endswith('.psyrun') for arg in args):
            view.runner = True
            runlist = [file for file in args if file.endswith('.psyrun')]
        # If still no window specified, use default from prefs
        if not any(
                getattr(view, key) for key in ['builder', 'coder', 'runner']):
            if self.prefs.app['defaultView'] in view:
                setattr(view, self.prefs.app['defaultView'], True)
            elif self.prefs.app['defaultView'] == 'all':
                view.builder = True
                view.coder = True
                view.runner = True

        # Create windows
        if view.runner:
            self.showRunner(fileList=runlist)
        if view.coder:
            self.showCoder(fileList=scripts)
        if view.builder:
            self.showBuilder(fileList=exps)

        # send anonymous info to www.psychopy.org/usage.php
        # please don't disable this, it's important for PsychoPy's development
        self._latestAvailableVersion = None
        self.updater = None
        self.news = None
        self.tasks = None

        prefsConn = self.prefs.connections

        ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True)
        # tell the user what has changed
        if not ok and not self.firstRun and not self.testMode:
            title = _translate("Compatibility information")
            dlg = dialogs.MessageDialog(parent=None,
                                        message=msg,
                                        type='Info',
                                        title=title)
            dlg.ShowModal()

        if (self.prefs.app['showStartupTips'] and not self.testMode
                and not blockTips):
            tipFile = os.path.join(self.prefs.paths['resources'],
                                   _translate("tips.txt"))
            tipIndex = self.prefs.appData['tipIndex']
            if parse_version(wx.__version__) >= parse_version('4.0.0a1'):
                tp = wx.adv.CreateFileTipProvider(tipFile, tipIndex)
                showTip = wx.adv.ShowTip(None, tp)
            else:
                tp = wx.CreateFileTipProvider(tipFile, tipIndex)
                showTip = wx.ShowTip(None, tp)

            self.prefs.appData['tipIndex'] = tp.GetCurrentTip()
            self.prefs.saveAppData()
            self.prefs.app['showStartupTips'] = showTip
            self.prefs.saveUserPrefs()

        self.Bind(wx.EVT_IDLE, self.onIdle)

        # doing this once subsequently enables the app to open & switch among
        # wx-windows on some platforms (Mac 10.9.4) with wx-3.0:
        v = parse_version
        if sys.platform == 'darwin':
            if v('3.0') <= v(wx.version()) < v('4.0'):
                _Showgui_Hack()  # returns ~immediately, no display
                # focus stays in never-land, so bring back to the app:
                if prefs.app['defaultView'] in [
                        'all', 'builder', 'coder', 'runner'
                ]:
                    self.showBuilder()
                else:
                    self.showCoder()
        # after all windows are created (so errors flushed) create output
        self._appLoaded = True
        if self.coder:
            self.coder.setOutputWindow()  # takes control of sys.stdout

        # flush any errors to the last run log file
        logging.flush()
        sys.stdout.flush()
        # we wanted debug mode while loading but safe to go back to info mode
        if not self.prefs.app['debugMode']:
            logging.console.setLevel(logging.INFO)

        return True
예제 #8
0
# -*- coding: utf-8 -*-

__author__ = 'Mehmet Öztürk'

import wx

IMG_PATH = 'wxsqlm/images/'
IMG_PATH_TREE = IMG_PATH + 'tree/'
IMG_PATH_BUTTONS = IMG_PATH + 'buttons/'

LOGO_ICON = IMG_PATH + 'logo.png'

TREE_ICONS = dict(
    target=wx.Image(IMG_PATH_TREE + 'target.png', wx.BITMAP_TYPE_PNG),
    # http://openiconlibrary.sourceforge.net/gallery2/?./Icons/devices/computer-4.png
    db=wx.Image(IMG_PATH_TREE + 'db.png', wx.BITMAP_TYPE_PNG),
    # http://www.iconarchive.com/show/colobrush-icons-by-eponas-deeway/system-database-icon.html
    tbl=wx.Image(IMG_PATH_TREE + 'tbl.png', wx.BITMAP_TYPE_PNG),
    # http://icones.pro/en/table-4-png-image.html
    col=wx.Image(IMG_PATH_TREE + 'col.png', wx.BITMAP_TYPE_PNG))
# http://www.iconarchive.com/show/farm-fresh-icons-by-fatcow/column-one-icon.html

BUTTON_ICONS = dict(
    target=IMG_PATH_BUTTONS + 'target.png',
    # http://openiconlibrary.sourceforge.net/gallery2/?./Icons/devices/computer-4.png
    db=IMG_PATH_BUTTONS + 'db.png',
    tbl=IMG_PATH_BUTTONS + 'tbl.png',
    # http://icones.pro/en/multiple-table-png-image.html
    tblDump=IMG_PATH_BUTTONS + 'tblDump.png',
    # http://www.iconarchive.com/show/farm-fresh-icons-by-fatcow/table-go-icon.html
    col=IMG_PATH_BUTTONS + 'col.png',
예제 #9
0
    def __init__(self):

        # Initialize the main frame (aka window).
        # Title the window 'DicoMetrics'.
        # Set the initial size to 1024x768.
        wx.Frame.__init__(self, None, -1, 'DICOM Metrics', size=(1024,768))   # Need to make it actually start of with the 1024x768 size.
        
        # Set the dicom listener to be paused on startup of the application.
        self.paused = True

        #
        # Collection of GUI element IDs.
        #
        self.ID_FILE_OPEN_PATIENT_PLAN     = 201
        self.ID_FILE_OPEN_PATIENT_RESULTS  = 202
        self.ID_FILE_SAVE_PATIENT_RESULTS  = 203
        self.ID_FILE_QUIT      = 204
        self.ID_CONFIG_LOAD    = 301
        self.ID_CONFIG_SAVE    = 302
        self.ID_TOOLBAR_TOGGLE = 303
        self.ID_HELP_CONTENTS  = 401
        self.ID_HELP_ABOUT     = 402

        self.ID_TOOL_OPEN_PATIENT_PLAN     = 10
        self.ID_TOOL_OPEN_PATIENT_RESULTS  = 20
        self.ID_TOOL_SAVE_PATIENT_RESULTS  = 30
        self.ID_TOOL_START = 40
        self.ID_TOOL_STOP  = 50
        self.ID_TOOL_QUIT  = 60

        self.ID_SPLITTER       = 70
        self.ID_SAVE_MESSAGES  = 80

        #
        # Collection of GUI BMPs.
        #
        # Make image objects for each of the icons on the toolbar:
        # save, start, stop, exit.
        #save_bmp = wx.Image('SaveTool.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        #start_bmp = wx.Image('StartTool.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        #stop_bmp  = wx.Image('StopTool.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        #exit_bmp  = wx.Image('QuitTool.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.OpenPatientPlanMenuBMP    = wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN, wx.ART_OTHER, (16,16))
        self.OpenPatientResultsMenuBMP = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, (16,16))
        self.SavePatientResultsMenuBMP = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, (16,16))
        self.QuitMenuBMP           = wx.ArtProvider.GetBitmap(wx.ART_QUIT, wx.ART_OTHER, (16,16))
        self.LoadConfigsMenuBMP    = wx.ArtProvider.GetBitmap(wx.ART_REDO, wx.ART_OTHER, (16,16))
        self.SaveConfigsMenuBMP    = wx.ArtProvider.GetBitmap(wx.ART_UNDO, wx.ART_OTHER, (16,16))
        self.HelpContentsMenuBMP   = wx.ArtProvider.GetBitmap(wx.ART_HELP, wx.ART_OTHER, (16,16))
        self.HelpAboutMenuBMP      = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_OTHER, (16,16))
        
        self.OpenPatientPlanToolBMP    = wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN, wx.ART_OTHER, (32,32))
        self.OpenPatientResultsToolBMP = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, (32,32))
        self.SavePatientResultsToolBMP = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, (32,32))
        #self.StartToolBMP  = wx.ArtProvider.GetBitmap(wx.ART_PLUS, wx.ART_OTHER, (32,32))
        #self.StopToolBMP   = wx.ArtProvider.GetBitmap(wx.ART_MINUS, wx.ART_OTHER, (32,32))
        self.StartToolBMP  = wx.Image('StartTool.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.StopToolBMP   = wx.Image('StopTool.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.QuitToolBMP   = wx.ArtProvider.GetBitmap(wx.ART_QUIT, wx.ART_OTHER, (32,32))

        # Run the method to create the main panel.
        self.create_main_panel()
        
        # Run the method to create the menu.
        self.create_menu()

        # Run the method to create the toolbar.
        self.create_toolbar()
예제 #10
0
    def InstallControls(self,
                        frame,
                        menuBar=None,
                        toolBar=None,
                        statusBar=None,
                        document=None):
        toolsMenuIndex = menuBar.FindMenu(_("&Tools"))
        if toolsMenuIndex > -1:
            toolsMenu = menuBar.GetMenu(toolsMenuIndex)
        else:
            toolsMenu = wx.Menu()

        app_image_path = appdirs.GetAppImageDirLocation()

        if toolsMenuIndex == -1:
            index = menuBar.FindMenu(_("&Run"))
            if index == -1:
                index = menuBar.FindMenu(_("&Project"))
            if index == -1:
                index = menuBar.FindMenu(_("&Format"))
            if index == -1:
                index = menuBar.FindMenu(_("&View"))
            menuBar.Insert(index + 1, toolsMenu, _("&Tools"))
            id = wx.NewId()
            item = wx.MenuItem(toolsMenu, id, _("&Terminator"))
            item.SetBitmap(
                wx.BitmapFromImage(
                    wx.Image(os.path.join(app_image_path, "cmd.png"),
                             wx.BITMAP_TYPE_ANY)))
            toolsMenu.AppendItem(item)
            wx.EVT_MENU(frame, id, self.OpenTerminator)

            id = wx.NewId()
            toolsMenu.Append(id, _("&UnitTest"))
            wx.EVT_MENU(frame, id, self.RunUnitTest)

            id = wx.NewId()
            item = wx.MenuItem(toolsMenu, id, _("&Interpreter"))
            item.SetBitmap(
                wx.BitmapFromImage(
                    wx.Image(os.path.join(app_image_path, "interpreter.png"),
                             wx.BITMAP_TYPE_ANY)))
            toolsMenu.AppendItem(item)
            wx.EVT_MENU(frame, id, self.OpenInterpreter)

            if sysutilslib.isWindows():
                id = wx.NewId()
                toolsMenu.Append(id, _("&Web Browser"))
                wx.EVT_MENU(frame, id, self.GotoDefaultWebView)

        helpMenuIndex = menuBar.FindMenu(_("&Help"))
        helpMenu = menuBar.GetMenu(helpMenuIndex)
        start_index = 0
        if sysutilslib.isWindows():
            id = wx.NewId()
            item = wx.MenuItem(toolsMenu, id, _("&Python Help Document"),
                               _("Open the help document of Python"))
            item.SetBitmap(
                wx.BitmapFromImage(
                    wx.Image(os.path.join(app_image_path, "pydoc.png"),
                             wx.BITMAP_TYPE_ANY)))
            helpMenu.InsertItem(0, item)
            wx.EVT_MENU(frame, id, self.OpenPythonHelpDocument)
            start_index += 1

        id = wx.NewId()
        helpMenu.Insert(start_index, id, _("&Tips of Day"),
                        _("Display tips of day"))
        wx.EVT_MENU(frame, id, self.ShowTipsOfDay)
        start_index += 1

        id = wx.NewId()
        helpMenu.Insert(start_index, id, _("&Check for Updates"),
                        _("Check program update information"))
        wx.EVT_MENU(frame, id, self.CheckforUpdate)
        start_index += 1

        id = wx.NewId()
        helpMenu.Insert(start_index, id, _("&Visit NovalIDE Website"),
                        _("Goto official website of NovalIDE"))
        wx.EVT_MENU(frame, id, self.GotoWebsite)
        start_index += 1

        id = wx.NewId()
        helpMenu.Insert(start_index, id, _("&Python Website"),
                        _("Goto official website of Python"))
        wx.EVT_MENU(frame, id, self.GotoPythonWebsite)
        start_index += 1

        if self._extensions:
            if toolsMenu.GetMenuItems():
                toolsMenu.AppendSeparator()
            for ext in self._extensions:
                # Append a tool menu item for each extension
                ext.id = wx.NewId()
                toolsMenu.Append(ext.id, ext.menuItemName)
                wx.EVT_MENU(frame, ext.id, frame.ProcessEvent)
                wx.EVT_UPDATE_UI(frame, ext.id, frame.ProcessUpdateUIEvent)
예제 #11
0
 def show_picture(self, path, pos):
     pic = wx.Image(path, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
     bmp = wx.StaticBitmap(self, 0, pic, pos=pos)
     bmp.Show()
예제 #12
0
    def Action(self):

        # Set a background for the UI
        ui_bitmap = wx.Image("PROGRAM_INSTALL_FULLPATH\\background.jpg",
                             wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.under = wx.StaticBitmap(self, -1, ui_bitmap, (0, 0))

        # Image Banner
        banner_bitmap1 = wx.Bitmap("PROGRAM_INSTALL_FULLPATH\\DenseNet.png")
        banner_image1 = banner_bitmap1.ConvertToImage()
        banner_image1 = banner_image1.Scale(285, 200, wx.IMAGE_QUALITY_HIGH)
        banner_bitmap2 = banner_image1.ConvertToBitmap()
        ui_banner_bitmap = wx.StaticBitmap(self, -1, banner_bitmap2, (0, 2))

        # The Left menu below the banner, which contains the File dialog button, report text box and about button
        left_menu = wx.StaticBox(self.under, -1, "")
        left_menu.SetSize((285, 370))
        left_menu.SetPosition((0, 200))
        left_menu.SetBackgroundColour(wx.WHITE)

        # The right region to display the picture selected from the dialog.
        right_region = wx.StaticBox(self, -1, "Picture")
        right_region.SetSize((650, 510))
        right_region.SetBackgroundColour(wx.WHITE)
        right_region.SetPosition((300, 10))
        self.magic_collection.append(
            right_region
        )  # Adding the right region object to the UI object array

        # The report text box, to report prediction results
        report_box = wx.TextCtrl(
            left_menu,
            -1, "1. Click the Button Above \n \n"
            "2.Select your picture. \n \n"
            "3. Wait till the Program studies the picture and display the result here",
            size=(285, 200),
            style=wx.TE_MULTILINE | wx.TE_PROCESS_ENTER,
            pos=(5, 80))
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        report_box.SetFont(font)

        self.magic_collection.append(
            report_box)  # Adding the report text box to the UI objects array

        # A Sample picture in the right region
        modification_bitmap1 = wx.Bitmap(
            "PROGRAM_INSTALL_FULLPATH\\sample.jpg")
        modification_image1 = modification_bitmap1.ConvertToImage()
        modification_image1 = modification_image1.Scale(
            650, 490, wx.IMAGE_QUALITY_HIGH)
        modification_bitmap2 = modification_image1.ConvertToBitmap()
        report_bitmap = wx.StaticBitmap(right_region, -1, modification_bitmap2,
                                        (0, 20))
        self.magic_collection.append(report_bitmap)

        # Text label
        image_dialog_label = wx.StaticText(left_menu, -1, "Select Picture")
        image_dialog_label.SetPosition((20, 20))
        image_dialog_label.SetForegroundColour(wx.BLUE)
        image_dialog_label.SetBackgroundColour(wx.WHITE)

        # The button to call the file dialog function
        dialog_button = wx.Button(left_menu, -1, "Click to Select")
        dialog_button.SetPosition((20, 40))
        dialog_button.SetSize((120, 30))
        dialog_button_bitmap = wx.Bitmap(
            "PROGRAM_INSTALL_FULLPATH\\select-file.png")
        dialog_button_bitmap_pressed = wx.Bitmap(
            "PROGRAM_INSTALL_FULLPATH\\select-file-hover.png")
        dialog_button.SetBitmap(dialog_button_bitmap, wx.LEFT)
        dialog_button.SetBitmapPressed(dialog_button_bitmap_pressed)
        self.Bind(wx.EVT_BUTTON, self.launchFileDialog, dialog_button)

        # The button to call the About DenseNet dialog
        about_densenet = wx.Button(left_menu, -1, "About DenseNet")
        about_densenet.SetPosition((20, 285))
        about_densenet.SetSize((200, 30))
        about_densenet_bitmap = wx.Bitmap("PROGRAM_INSTALL_FULLPATH\\info.png")
        about_densenet.SetBitmap(about_densenet_bitmap, wx.LEFT)
        self.Bind(wx.EVT_BUTTON, self.aboutDensenet, about_densenet)

        # The button to call the About dialog
        about_button = wx.Button(left_menu, -1, "About DenseNet Playground")
        about_button.SetPosition((20, 320))
        about_button.SetSize((200, 30))
        about_button_bitmap = wx.Bitmap("PROGRAM_INSTALL_FULLPATH\\info.png")
        about_button.SetBitmap(about_button_bitmap, wx.LEFT)
        self.Bind(wx.EVT_BUTTON, self.aboutApplication, about_button)
예제 #13
0
    def __init__(self, parent):
        wx.ListCtrl.__init__(self,
                             parent,
                             -1,
                             style=wx.LC_REPORT | wx.LC_VIRTUAL | wx.LC_HRULES
                             | wx.LC_VRULES)

        self.principalFrame = parent

        self.defaultFont = self.GetFont()
        self.styledFont = createMyFont()
        self.SetFont(self.styledFont)

        self.selectedItem = 0
        self.selectedID = ''

        self.visuLivreFrame = False
        self.modifLivreFrame = False

        # --- Initialisation de la classe Etagere, avec chargement de la liste de livre
        self.maBiblio = Library(self.principalFrame.pathLibrary)

        # --- Ajout des icônes
        self.il = wx.ImageList(32, 16)
        # Icônes de triages et de notes données aux livres
        triage = {
            'sm_up': 'GO_UP_B.png',
            'sm_dn': 'GO_DOWN_B.png',
            'note_a': 'note_a.jpg',
            'note_b': 'note_b.jpg',
            'note_c': 'note_c.jpg',
            'note_d': 'note_d.jpg',
            'note_f': 'note_f.jpg'
        }
        for k, v in triage.items():
            img = wx.Image(self.principalFrame.pathIcone + v,
                           wx.BITMAP_TYPE_ANY)
            img = img.Scale(32, 16, wx.IMAGE_QUALITY_HIGH)
            img = img.ConvertToBitmap()
            s = "self.%s= self.il.Add(img)" % k
            exec(s)
#		a={"sm_up":"GO_UP","sm_dn":"GO_DOWN"}
#		for k,v in a.items():
#			s="self.%s= self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(32,16)))" % (k,v)
#			exec(s)
        self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)

        # --- Ajout de couleurs de fond pour différencier les lignes
        self.listColor = []
        self.listColor.append(wx.ListItemAttr())
        self.listColor[-1].SetBackgroundColour("#B3FFFA")  # Bleu pâle
        self.listColor.append(wx.ListItemAttr())
        self.listColor[-1].SetBackgroundColour("#FAB3FF")  # Rose pâle
        self.listColor.append(wx.ListItemAttr())
        self.listColor[-1].SetBackgroundColour("#FFFAB3")  # Jaune pâle
        self.listColor.append(wx.ListItemAttr())
        self.listColor[-1].SetBackgroundColour("#FFFFFF")  # Blanc
        self.listColor.append(wx.ListItemAttr())
        self.listColor[-1].SetBackgroundColour("#DDDDDD")  # Gris claire

        self.currentColor = 0  # Iterateur de couleur

        # --- Initialisation des colonnes
        self.columnList = {
            0: ['Auteur', 140],
            1: ['Titre', 320],
            2: ['Editeur', 130],
            3: ['Parution', 95],
            4: ['Genre', 140],
            5: ['Pages', 70],
            6: ['Lieu', 140],
            7: ['Note', 0]
        }
        for k, v in self.columnList.items():
            if k in [3, 5]:
                s = "self.InsertColumn(%i, '%s', wx.LIST_FORMAT_CENTER, width=%i)" % (
                    k, v[0], v[1])
            else:
                s = "self.InsertColumn(%i, '%s', width=%i)" % (k, v[0], v[1])
            exec(s)

        # --- Initialisation des premiers items (nombre d'items = nombre d'éléments dans le dictionnaire)
        self.itemDataMap = self.convertToDataMap()
        self.itemIndexMap = range(1, len(self.itemDataMap) + 1)
        self.SetItemCount(len(self.itemDataMap))
        #		self.itemsColor = [-1]*len(self.itempDataMap)		# Couleur pour chaque item

        # --- Initialisation des modules mixins
        listmix.ListCtrlAutoWidthMixin.__init__(self)
        listmix.ColumnSorterMixin.__init__(self, len(self.columnList))

        # --- On définit le trie par défaut sur 'Genre' (colonne 4) A->Z ordre alphabétique (1)
        self.currentSorter = 4  # Numéro courant de la colonne triante
        self.SortListItems(self.currentSorter, 1)

        # --- Initialisation du menu popup
        self.initPopupMenu()

        # --- Définition des events
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
        self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnItemRightClick)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
예제 #14
0
    def __init__(self, parent, username=""):
        '''
        Constructor
        '''
        wx.Dialog.__init__(self,
                           None,
                           -1,
                           yi_name,
                           size=(510, 434),
                           style=wx.NO_BORDER)

        self.frame = parent
        imgPath = os.path.join(UtilFunc.module_path(), 'res/background.png')
        bgpng = wx.Image(imgPath, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        size = bgpng.GetSize()
        self.SetClientSize(size)
        bgParent = BGPanel(self, size=size, bmp=bgpng)

        bgParent.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown)
        bgParent.Bind(wx.EVT_MOTION, self.OnPanelMotion)
        bgParent.Bind(wx.EVT_LEFT_UP, self.OnPanelLeftUp)

        self.user = wx.TextCtrl(bgParent,
                                -1,
                                use_name, (149, 254),
                                size=(250, 28),
                                style=wx.NO_BORDER)
        font = wx.Font(14, wx.SWISS, wx.NORMAL, wx.NORMAL, faceName=u"微软雅黑")
        self.user.SetFont(font)
        self.user.Bind(wx.EVT_LEFT_DOWN, self.OnUserTextDown)

        self.password = wx.TextCtrl(bgParent,
                                    -1,
                                    u"", (149, 289),
                                    size=(250, 28),
                                    style=wx.TE_PASSWORD | wx.NO_BORDER)
        self.password.SetMaxLength(16)
        self.password.SetFont(font)

        imgPath = os.path.join(UtilFunc.module_path(), 'res/sign_in.png')
        login_png = wx.Image(imgPath, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        btn = wx.BitmapButton(bgParent,
                              -1,
                              login_png, (104, 359),
                              style=wx.NO_BORDER)

        self.Bind(wx.EVT_BUTTON, self.OnLogin, btn)
        imgPath = os.path.join(UtilFunc.module_path(), 'res/sign_in_hover.png')
        login_png = wx.Image(imgPath, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        btn.SetBitmapSelected(login_png)
        imgPath = os.path.join(UtilFunc.module_path(), 'res/sign_in_down.png')
        login_png = wx.Image(imgPath, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        btn.SetBitmapHover(login_png)

        btn_z = TPButton(bgParent,
                         -1,
                         register_account,
                         pos=(412, 293),
                         style=0)
        btn_z.SetTextForeground((0x00, 0x00, 0x00))
        btn_z.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)
        self.Bind(wx.EVT_BUTTON, self.OnRegister, btn_z)

        btn = TPButton(bgParent, -1, forget_sec, pos=(412, 255), style=0)
        btn.SetTextForeground((0x00, 0x00, 0x00))
        btn.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)
        self.Bind(wx.EVT_BUTTON, self.OnGetPassword, btn)
        self.Bind(wx.EVT_CLOSE, parent.OnClose)

        imgPath = os.path.join(UtilFunc.module_path(), 'res/closebutton.png')
        close_button = wx.Image(imgPath, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        btn3 = wx.BitmapButton(bgParent,
                               -1,
                               close_button,
                               pos=(470, 7),
                               style=wx.NO_BORDER)
        self.Bind(wx.EVT_BUTTON, self.Closebutton, btn3)

        imgPath = os.path.join(UtilFunc.module_path(), 'res/minibutton.png')
        mini_button = wx.Image(imgPath, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        btn4 = wx.BitmapButton(bgParent,
                               -1,
                               mini_button,
                               pos=(434, 7),
                               style=wx.NO_BORDER)
        self.Bind(wx.EVT_BUTTON, self.Minibutton, btn4)
예제 #15
0
    if havewx:
        import re
        from threading import Thread, currentThread
        from types import *

        if wx.VERSION >= (3, 0, 0):
            app = wx.App(redirect=False)
        else:
            app = wx.PySimpleApp(redirect=False)
        app.SetTopWindow(wx.Frame(None, -1))

        default_locale = None
        SetupI18n()

        defaulticon = wx.Image(Bpath("images", "brz.png"))
        starticon = wx.Image(Bpath("images", "icoplay24.png"))
        stopicon = wx.Image(Bpath("images", "icostop24.png"))

        class ParamsEntryDialog(wx.TextEntryDialog):
            if wx.VERSION < (2, 6, 0):

                def Bind(self, event, function, id=None):
                    if id is not None:
                        event(self, id, function)
                    else:
                        event(self, function)

            def __init__(self,
                         parent,
                         message,
예제 #16
0
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        self.board = []
        self.game_count = 0

        self.blank_tile = self.scale_bitmap(
            wx.Image('./assets/blank_tile.png', wx.BITMAP_TYPE_ANY), BTN_SIZE,
            BTN_SIZE)
        self.flag_tile = self.scale_bitmap(
            wx.Image('./assets/flag_tile.png', wx.BITMAP_TYPE_ANY), BTN_SIZE,
            BTN_SIZE)
        self.clicked_tile = self.scale_bitmap(
            wx.Image('./assets/clicked_tile.png', wx.BITMAP_TYPE_ANY),
            BTN_SIZE, BTN_SIZE)
        self.one = self.scale_bitmap(
            wx.Image('./assets/1.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.two = self.scale_bitmap(
            wx.Image('./assets/2.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.three = self.scale_bitmap(
            wx.Image('./assets/3.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.four = self.scale_bitmap(
            wx.Image('./assets/4.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.five = self.scale_bitmap(
            wx.Image('./assets/5.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.six = self.scale_bitmap(
            wx.Image('./assets/6.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.seven = self.scale_bitmap(
            wx.Image('./assets/7.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.eight = self.scale_bitmap(
            wx.Image('./assets/8.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.nine = self.scale_bitmap(
            wx.Image('./assets/9.png', wx.BITMAP_TYPE_ANY), BTN_SIZE, BTN_SIZE)
        self.mine_tile = self.scale_bitmap(
            wx.Image('./assets/mine_tile.png', wx.BITMAP_TYPE_ANY), BTN_SIZE,
            BTN_SIZE)
        self.red_mine_tile = self.scale_bitmap(
            wx.Image('./assets/red_mine_tile.png', wx.BITMAP_TYPE_ANY),
            BTN_SIZE, BTN_SIZE)

        reset_bmp = self.scale_bitmap(
            wx.Image('./assets/reset.png', wx.BITMAP_TYPE_ANY), 80, 40)
        reset_btn = wx.StaticBitmap(self, -1, reset_bmp, pos=(10, 10))
        reset_btn.Bind(wx.EVT_LEFT_DOWN, lambda e: self.start_game(e))

        self.start_game()

        for m in range(LEN):
            for n in range(LEN):
                btn = wx.StaticBitmap(self,
                                      -1,
                                      self.blank_tile,
                                      pos=(10 + m * BTN_SIZE,
                                           50 + n * BTN_SIZE))
                btn.SetLabel('blank')
                btn.Bind(wx.EVT_LEFT_DOWN,
                         lambda e, m=m, n=n: self.handle_click(e, m, n))
                btn.Bind(wx.EVT_RIGHT_DOWN,
                         lambda e, m=m, n=n: self.handle_right_click(e, m, n))
                self.board[m][n].extend([btn, self.get_bmp(m, n)])
예제 #17
0
    def draw_layer(self, image):
        try:
            dc = wx.MemoryDC()
            dc.SelectObject(self.bitmap)
            dc.SetBackground(wx.Brush("black"))
            dc.Clear()

            if self.slicer == 'Slic3r' or self.slicer == 'Skeinforge':

                if self.scale != 1.0:
                    layercopy = copy.deepcopy(image)
                    height = float(layercopy.get('height').replace('m', ''))
                    width = float(layercopy.get('width').replace('m', ''))

                    layercopy.set('height', str(height * self.scale) + 'mm')
                    layercopy.set('width', str(width * self.scale) + 'mm')
                    layercopy.set(
                        'viewBox', '0 0 ' + str(width * self.scale) + ' ' +
                        str(height * self.scale))

                    g = layercopy.find("{http://www.w3.org/2000/svg}g")
                    g.set('transform', 'scale(' + str(self.scale) + ')')
                    stream = io.StringIO(
                        PNGSurface.convert(
                            dpi=self.dpi,
                            bytestring=xml.etree.ElementTree.tostring(
                                layercopy)))
                else:
                    stream = io.StringIO(
                        PNGSurface.convert(
                            dpi=self.dpi,
                            bytestring=xml.etree.ElementTree.tostring(image)))

                pngImage = wx.ImageFromStream(stream)

                # print "w:", pngImage.Width, ", dpi:", self.dpi, ", w (mm): ",(pngImage.Width / self.dpi) * 25.4

                if self.layer_red:
                    pngImage = pngImage.AdjustChannels(1, 0, 0, 1)

                dc.DrawBitmap(wx.BitmapFromImage(pngImage), self.offset[0],
                              self.offset[1], True)

            elif self.slicer == 'bitmap':
                if isinstance(image, str):
                    image = wx.Image(image)
                if self.layer_red:
                    image = image.AdjustChannels(1, 0, 0, 1)
                dc.DrawBitmap(
                    wx.BitmapFromImage(
                        image.Scale(image.Width * self.scale,
                                    image.Height * self.scale)),
                    self.offset[0], -self.offset[1], True)
            else:
                raise Exception(self.slicer + " is an unknown method.")

            self.pic.SetBitmap(self.bitmap)
            self.pic.Show()
            self.Refresh()

        except:
            raise
            pass
예제 #18
0
    def _initMenu(self, width, height):
        panel = wx.Panel(self, style=wx.NO_BORDER, size=(width, height))
        panel.SetBackgroundColour(colors.GREY_VERY_LIGHT)

        font = wx.Font(wx.FontInfo(10).Bold())

        # Config tab
        self.configTab = wx.Panel(panel,
                                  id=Tab.CONFIG.value,
                                  style=wx.NO_BORDER,
                                  size=(width, 60))

        pngConfig = wx.Image(str(icons.ONE),
                             wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.bmpConfig = wx.StaticBitmap(self.configTab,
                                         Tab.CONFIG.value,
                                         pngConfig,
                                         size=(pngConfig.GetWidth(),
                                               pngConfig.GetHeight()))

        self.txtConfig = wx.StaticText(self.configTab, Tab.CONFIG.value,
                                       'Configurações')
        self.txtConfig.SetFont(font)

        vConfigTabSizer = wx.BoxSizer(wx.VERTICAL)
        hConfigTabSizer = wx.BoxSizer(wx.HORIZONTAL)
        hConfigTabSizer.Add(self.bmpConfig, 0, wx.CENTER)
        hConfigTabSizer.Add(self.txtConfig,
                            wx.SizerFlags(0).Center().Border(wx.LEFT, 10))
        vConfigTabSizer.Add(hConfigTabSizer,
                            wx.SizerFlags(1).Left().Border(wx.LEFT, 25))

        self.configTab.SetSizer(vConfigTabSizer)

        # Account tab
        self.accountTab = wx.Panel(panel,
                                   id=Tab.ACCOUNT.value,
                                   style=wx.NO_BORDER,
                                   size=(width, 60))

        pngAccount = wx.Image(str(icons.TWO),
                              wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.bmpAccount = wx.StaticBitmap(self.accountTab,
                                          Tab.ACCOUNT.value,
                                          pngAccount,
                                          size=(pngAccount.GetWidth(),
                                                pngAccount.GetHeight()))

        self.txtAccount = wx.StaticText(self.accountTab, Tab.ACCOUNT.value,
                                        'Minha conta')
        self.txtAccount.SetFont(font)

        vAccountTabSizer = wx.BoxSizer(wx.VERTICAL)
        hAccountTabSizer = wx.BoxSizer(wx.HORIZONTAL)
        hAccountTabSizer.Add(self.bmpAccount, 1, wx.CENTER)
        hAccountTabSizer.Add(self.txtAccount,
                             wx.SizerFlags(0).Center().Border(wx.LEFT, 10))

        vAccountTabSizer.Add(hAccountTabSizer,
                             wx.SizerFlags(1).Left().Border(wx.LEFT, 25))
        self.accountTab.SetSizer(vAccountTabSizer)

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(self.configTab, wx.SizerFlags(0).Border(wx.TOP, 30))
        mainSizer.Add(self.accountTab, wx.SizerFlags(0).Expand())
        panel.SetSizer(mainSizer)

        return panel
예제 #19
0
 def play(self, item, history = True, play = True):
  """
  Plays the track given in item.
  
  If history is True, add any current track to the history.
  If play is True, play the track immediately.
  """
  logger.debug('Playing item: %s.', item)
  id = functions.get_id(item)
  track = None # The object to store the track in until it's ready for playing.
  error = None # Any error that occured.
  if id in library.downloaded: # The file has already been downloaded.
   try:
    track = FileStream(file = library.get_path(item))
    if self.current_library and item in self.current_library:
     new_item = copy(item)
     if 'playCount' in new_item:
      new_item['playCount'] += 1
     self.current_library[self.current_library.index(item)] = new_item # Save it with the modified play count so the poll thread doesn't screw anything up.
   except BassError as e:
    del library.downloaded[id]
    return self.play(item, history = history, play = play) # Try again... File's probably not there or something...
  else:
   if id in library.downloading:
    if time() - library.downloading[id] <= config.config.get('library', 'download_timeout'):
     return wx.MessageBox('This song is still downloading, please wait.', 'Download In Progress')
    else:
     del library.downloading[id]
   try:
    url = application.mobile_api.get_stream_url(id)
   except gmusicapi.exceptions.CallFailure as e:
    application.device_id = None
    return wx.MessageBox('Cannot play with that device: %s.' % e, 'Invalid Device')
   except functions.RE as e:
    if self.current_track:
     self.current_track.set_position(self.current_track.get_length() - 1)
     self.play_pause.SetLabel(config.config.get('windows', 'play_label'))
    return wx.MessageBox(*functions.format_requests_error(e))
   try:
    track = URLStream(url = url)
   except BassError as e:
    error = e # Just store it for later alerting.
   if config.config.get('library', 'cache'): # The user wants their tracks downloaded.
    Thread(target = functions.download_file, args = [url, id, item]).start()
  if error:
   return wx.MessageBox(str(e), 'Error')
  if self.current_track:
   self.current_track.stop()
   if history:
    self.add_history(self.get_current_track())
  self._current_track = item
  if application.lyrics_frame:
   Thread(target = application.lyrics_frame.populate_lyrics, args = [item.get('artist'), item.get('title')]).start()
  self.current_track = track
  self.SetTitle()
  self.duration = columns.parse_durationMillis(self.get_current_track().get('durationMillis'))
  self.update_hotkey_area()
  self.set_volume()
  self.set_pan()
  self.set_frequency()
  if play:
   self.current_track.play()
   self.play_pause.SetLabel(config.config.get('windows', 'pause_label'))
  else:
   self.play_pause.SetLabel(config.config.get('windows', 'play_label'))
  filename = os.path.join(application.artwork_directory, item['albumId'] + '.jpg')
  if filename != self.album_art_filename:
   if filename in os.listdir(application.artwork_directory):
    logger.debug('Loading album art from cache.')
   else:
    url = item['albumArtRef'][0]['url']
    logger.debug('Downloading album art from %s.', url)
    art = requests.get(url)
    with open(filename, 'wb') as f:
     f.write(art.content)
   self.album_art_filename = filename
   i = wx.Image(filename)
   self.album_art.SetBitmap(i.ConvertToBitmap())
   i.Destroy()
   logger.info('Loaded album art from %s.', filename)
  try:
   Thread(target = application.mobile_api.increment_song_playcount, args = [id]).start()
   self.artist_info = application.mobile_api.get_artist_info(item['artistId'][0])
   try:
    self.set_artist_bio(self.artist_info.get('artistBio', 'No information available.'))
   except wx.PyDeadObjectError:
    pass # The frame has been deleted.
  except functions.RE:
   pass # We are not connected to the internet, but we can still play stuff.
예제 #20
0
    def __init__(self, parent, path, name, thumb=None, is_gf=False):
        super(Item, self).__init__(parent)

        self.path = path
        self.thumb = thumb
        self.is_gf = is_gf
        self.selected = False

        self.UpdateBackground()

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)

        # controls

        # image = wx.Image(image)
        image = wx.Image(thumbnail.DEFAULT_ICON)
        image.Resize(THUMBNAIL_SIZE, (
            (THUMBNAIL_SIZE[0] - image.GetWidth()) / 2,
            (THUMBNAIL_SIZE[1] - image.GetHeight()) / 2,
        ))
        self.bitmap = wx.StaticBitmap(
            self,
            bitmap=image.ConvertToBitmap()
        )

        self.Bind(EVT_THUMBNAIL_LOAD, self.OnThumbnailLoad)
        self.LoadThumbnail()

        self.sizer.Add(
            self.bitmap,
            flag=wx.ALL,
            border=2
        )

        self.text = wx.StaticText(
            self,
            label=name,
            style=(
                wx.ALIGN_CENTRE_HORIZONTAL |
                wx.ST_NO_AUTORESIZE |
                wx.ST_ELLIPSIZE_END
            )
        )
        self.text.SetMaxSize((THUMBNAIL_SIZE[0], -1))

        if self.GetParent().dark_theme:
            self.text.SetForegroundColour("#FFFFFF")

        self.sizer.Add(
            self.text,
            flag=wx.ALL | wx.EXPAND | wx.ALIGN_CENTER,
            border=5
        )

        self.Layout()

        # ToolTip
        tooltip = wx.ToolTip(name)
        tooltip.SetDelay(1000)
        self.SetToolTip(tooltip)

        # events

        self.Bind(wx.EVT_LEFT_UP, self.PropagateEvent)
        self.Bind(wx.EVT_RIGHT_UP, self.OnMouseRight)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDouble)

        self.bitmap.Bind(wx.EVT_LEFT_UP, self.PropagateEvent)
        self.bitmap.Bind(wx.EVT_RIGHT_UP, self.PropagateEvent)
        self.bitmap.Bind(wx.EVT_RIGHT_UP, self.OnMouseRight)
        self.bitmap.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDouble)

        self.text.Bind(wx.EVT_LEFT_UP, self.PropagateEvent)
        self.text.Bind(wx.EVT_RIGHT_UP, self.OnMouseRight)
        self.text.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDouble)
예제 #21
0
 def get_image_size(self):
     dimx = dimy = 0
     if self.image_loc:
         image = wx.Image(self.image_loc)
         dimx, dimy = image.GetSize()
     return dimx, dimy
    def __init__(self, parent):
        super(PicturePointsPanel, self).__init__(parent=parent)

        self.password = ""

        SEGOE_12 = wx.Font(12, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Segoe UI')
        SEGOE_13 = wx.Font(13, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Segoe UI')
        SEGOE_18 = wx.Font(18, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Segoe UI')

        headerText = wx.StaticText(self, label="Set eye-gazing picture points password", pos=(20, 20), size=wx.Size(150, 40))
        headerText.SetFont(SEGOE_18)

        infoText = wx.StaticText(self, label="Select a picture to use or choose your own:", pos=(20, 65), size=wx.Size(150, 40))
        infoText.SetFont(SEGOE_12)

        #current file directory
        curdir = os.path.dirname(os.path.realpath(__file__))

        sample1Img = wx.Image(curdir + "/images/sample1.jpg", wx.BITMAP_TYPE_ANY)
        sample1ImgIcon = sample1Img.Scale(192, 108, wx.IMAGE_QUALITY_HIGH)
        sample1ImgIcon = sample1ImgIcon.ConvertToBitmap()
        sample1Button = wx.BitmapButton(self, -1, sample1ImgIcon, pos=(25, 98), size=(192, 108))
        sample1Button.Bind(wx.EVT_BUTTON, self.selectSampleImage)
        sample1Button.SetLabel("1")

        sample2Img = wx.Image(curdir + "/images/sample2.jpg", wx.BITMAP_TYPE_ANY)
        sample2ImgIcon = sample2Img.Scale(192, 108, wx.IMAGE_QUALITY_HIGH)
        sample2ImgIcon = sample2ImgIcon.ConvertToBitmap()
        sample2Button = wx.BitmapButton(self, -1, sample2ImgIcon, pos=(225, 98), size=(192, 108))
        sample2Button.Bind(wx.EVT_BUTTON, self.selectSampleImage)
        sample2Button.SetLabel("2")

        sample3Img = wx.Image(curdir + "/images/sample3.jpg", wx.BITMAP_TYPE_ANY)
        sample3ImgIcon = sample3Img.Scale(192, 108, wx.IMAGE_QUALITY_HIGH)
        sample3ImgIcon = sample3ImgIcon.ConvertToBitmap()
        sample3Button = wx.BitmapButton(self, -1, sample3ImgIcon, pos=(425, 98), size=(192, 108))
        sample3Button.Bind(wx.EVT_BUTTON, self.selectSampleImage)
        sample3Button.SetLabel("3")

        sample4Img = wx.Image(curdir + "/images/sample4.jpg", wx.BITMAP_TYPE_ANY)
        sample4ImgIcon = sample4Img.Scale(192, 108, wx.IMAGE_QUALITY_HIGH)
        sample4ImgIcon = sample4ImgIcon.ConvertToBitmap()
        sample4Button = wx.BitmapButton(self, -1, sample4ImgIcon, pos=(25, 214), size=(192, 108))
        sample4Button.Bind(wx.EVT_BUTTON, self.selectSampleImage)
        sample4Button.SetLabel("4")

        sample5Img = wx.Image(curdir + "/images/sample5.jpg", wx.BITMAP_TYPE_ANY)
        sample5ImgIcon = sample5Img.Scale(192, 108, wx.IMAGE_QUALITY_HIGH)
        sample5ImgIcon = sample5ImgIcon.ConvertToBitmap()
        sample5Button = wx.BitmapButton(self, -1, sample5ImgIcon, pos=(225, 214), size=(192, 108))
        sample5Button.Bind(wx.EVT_BUTTON, self.selectSampleImage)
        sample5Button.SetLabel("5")

        sample6Img = wx.Image(curdir + "/images/sample6.jpg", wx.BITMAP_TYPE_ANY)
        sample6ImgIcon = sample6Img.Scale(192, 108, wx.IMAGE_QUALITY_HIGH)
        sample6ImgIcon = sample6ImgIcon.ConvertToBitmap()
        sample6Button = wx.BitmapButton(self, -1, sample6ImgIcon, pos=(425, 214), size=(192, 108))
        sample6Button.Bind(wx.EVT_BUTTON, self.selectSampleImage)
        sample6Button.SetLabel("6")

        #sample7Img = wx.Image(curdir + "/images/SaveButton.png", wx.BITMAP_TYPE_ANY)
        #sample7ImgIcon = sample7Img.Scale(59, 32, wx.IMAGE_QUALITY_HIGH)
        #sample7ImgIcon = sample7ImgIcon.ConvertToBitmap()
        #sample7Button = wx.BitmapButton(self, -1, sample7ImgIcon, pos=(425, 414), size=(59, 32))
        #sample7Button.Bind(wx.EVT_BUTTON, self.selectSampleImage)
        #sample7Button.SetLabel("Save")
        saveImgButton = wx.Button(self, label="Save Password", pos=(300, 345), size=(145, 35))
        saveImgButton.SetBackgroundColour(wx.WHITE)
        saveImgButton.SetFont(SEGOE_12)
        saveImgButton.Bind(wx.EVT_BUTTON, self.selectSampleImage)
        saveImgButton.SetLabel("Save")

        chooseImgButton = wx.Button(self, label="Choose your own", pos=(25, 345), size=(145, 35))
        chooseImgButton.SetBackgroundColour(wx.WHITE)
        chooseImgButton.SetFont(SEGOE_12)
        chooseImgButton.Bind(wx.EVT_BUTTON, self.onOpenFile)
예제 #23
0
	def __init__(self, parent, size : tuple, dataset : nc.Dataset, metadata : dict):
		super(OptionPanel, self).__init__(parent=parent, id=wx.ID_ANY, size=size)
		self.parent = parent
		self.dataset = dataset
		self.metadata = metadata
		self.options = {} # It will gather all the options set by the user
		self.init_options() # Initialize the options dictionary
		
		self.var_ids = {} # Dictionary with id keys and their corresponing variable
		self.c_boxes = [] # List of ComboBox used
		self.text_entries = [] # List of text entries used
		self.chk_boxes = [] # List of check boxes used

		self.main_sizer = wx.BoxSizer(wx.VERTICAL)

		# --------------------------------------- #
		# First StaticBox, general options:
		# Variable / Time index / Level (if necessary)
		stbox_gen = wx.StaticBox(parent=self, label="General")
		stbox_gen_sizer = wx.StaticBoxSizer(stbox_gen, wx.HORIZONTAL)
		
		# Variables
		text_variables = wx.StaticText(parent=stbox_gen, label="Variable : ")
		l_variables = nc_tools.get_variables(self.dataset)
		self.c_box_variables = wx.ComboBox(
									  parent=stbox_gen,
									  id=wx.ID_ANY,
									  choices=l_variables,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY
									  )
		self.var_ids[self.c_box_variables.GetId()] = "variable"
		self.c_boxes.append(self.c_box_variables)

		# Time
		text_time = wx.StaticText(parent=stbox_gen, label="Time index : ")
		timesteps =  nc_tools.get_timesteps(self.dataset)
		self.c_box_time = wx.ComboBox(
									  parent=stbox_gen,
									  id=wx.ID_ANY,
									  choices=timesteps,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY
									  )
		self.var_ids[self.c_box_time.GetId()] = "time_index"
		self.c_boxes.append(self.c_box_time)

		# Pressure Level (if necessary) 
		if nc_tools.is_pressure_level(meta=self.metadata):
			text_levels = wx.StaticText(parent=stbox_gen, label="Pressure level : ")
			levels = nc_tools.get_pressure_levels(self.dataset)
			self.c_box_levels = wx.ComboBox(
									  		parent=stbox_gen,
									  		id=wx.ID_ANY,
									 	 	choices=levels,
									  		style=wx.CB_DROPDOWN | wx.CB_READONLY
									  		)
			self.var_ids[self.c_box_levels.GetId()] = "pl_index"
			self.c_boxes.append(self.c_box_levels)
		else:
			self.c_box_levels = None

		# StaticBox sizer setup
		stbox_gen_sizer.Add(text_variables, 0, wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		stbox_gen_sizer.Add(self.c_box_variables, 0, wx.ALIGN_CENTER | wx.ALL, 20)
		stbox_gen_sizer.Add(text_time, 0, wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		stbox_gen_sizer.Add(self.c_box_time, 0, wx.ALIGN_CENTER | wx.ALL, 20)
		if self.c_box_levels:
			# Add levels to the sizer if dataset contains levels
			stbox_gen_sizer.Add(text_levels, 0, wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
			stbox_gen_sizer.Add(self.c_box_levels, 0, wx.ALIGN_CENTER | wx.ALL, 20)

		# --------------------------------------- #
		# Second StaticBox, data corrections
		stbox_data_corr = wx.StaticBox(parent=self, label="Corrections")
		stbox_data_corr_sizer = wx.StaticBoxSizer(stbox_data_corr, wx.VERTICAL)
		pnl_data_corr = wx.Panel(parent=stbox_data_corr)
		pnl_data_corr_sizer = wx.GridSizer(cols=6, gap=(5, 5))

		# Longitude offset
		text_lon_offset = wx.StaticText(parent=pnl_data_corr, label="Longitude offset : ")
		self.te_lon_offset = NumCtrl(parent=pnl_data_corr, id=wx.ID_ANY, value=0, integerWidth=3, fractionWidth=2)
		self.var_ids[self.te_lon_offset.GetId()] = "lon_offset"
		self.text_entries.append(self.te_lon_offset)

		# Data multiplicator
		text_coef = wx.StaticText(parent=pnl_data_corr, label="Apply coefficient : ")
		self.te_coef = NumCtrl(parent=pnl_data_corr, id=wx.ID_ANY, value=1, integerWidth=3, fractionWidth=2)
		self.var_ids[self.te_coef.GetId()] = "coef"
		self.text_entries.append(self.te_coef)

		# Data offset
		text_data_offset = wx.StaticText(parent=pnl_data_corr, label="Data offset : ")
		self.te_data_offset = NumCtrl(parent=pnl_data_corr, id=wx.ID_ANY, value=0, integerWidth=3, fractionWidth=2)
		self.var_ids[self.te_data_offset.GetId()] = "offset"
		self.text_entries.append(self.te_data_offset)

		# StaticBox sizer setup
		pnl_data_corr_sizer.Add(text_lon_offset, 0, wx.EXPAND | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		pnl_data_corr_sizer.Add(self.te_lon_offset, 0, wx.EXPAND | wx.ALL, 20)
		pnl_data_corr_sizer.Add(text_coef, 0, wx.EXPAND | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		pnl_data_corr_sizer.Add(self.te_coef, 0, wx.EXPAND | wx.ALL, 20)
		pnl_data_corr_sizer.Add(text_data_offset, 0, wx.EXPAND | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		pnl_data_corr_sizer.Add(self.te_data_offset, 0, wx.EXPAND | wx.ALL, 20)
		pnl_data_corr.SetSizer(pnl_data_corr_sizer)

		stbox_data_corr_sizer.Add(pnl_data_corr, 0, wx.EXPAND)

		# --------------------------------------- #
		# Third StaticBox, projection setup
		stbox_proj = wx.StaticBox(parent=self, label="Map setup")
		stbox_proj_sizer = wx.StaticBoxSizer(stbox_proj, wx.VERTICAL)

		pnl_stbox_proj = wx.Panel(parent=stbox_proj)
		pnl_stbox_proj_sizer = wx.GridBagSizer(0, 0)

		# Panel projection #
		pnl_proj = wx.Panel(parent=pnl_stbox_proj)
		pnl_proj_sizer = wx.GridSizer(cols=2, gap=(5, 5))
		
		text_preset = wx.StaticText(parent=pnl_proj, label="Map preset : ")
		with open(MAP_PRESETS_PATH, 'r') as foo:
			self.presets = json.load(foo)
			foo.close()
		presets_list = list(self.presets.keys())
		self.c_box_presets = wx.ComboBox(
									  parent=pnl_proj,
									  id=wx.ID_ANY,
									  choices=presets_list,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY
									  )
		self.var_ids[self.c_box_presets.GetId()] = "preset"
		self.c_boxes.append(self.c_box_presets)

		# Sizer setup
		pnl_proj_sizer.Add(text_preset, 0, wx.ALIGN_CENTER_HORIZONTAL, 20)
		pnl_proj_sizer.Add(self.c_box_presets, 0, wx.ALIGN_CENTER_HORIZONTAL, 20)
		pnl_proj.SetSizer(pnl_proj_sizer)

		# Panel other options #
		pnl_other = wx.Panel(parent=pnl_stbox_proj)
		pnl_other_sizer = wx.GridSizer(cols=2, gap=(5, 5))

		text_res = wx.StaticText(parent=pnl_other, label="Resolution : ")
		l_resolutions = ['c', 'l', 'i', 'h', 'f']
		self.c_box_res = wx.ComboBox(
									 parent=pnl_other,
									 id=wx.ID_ANY,
									 choices=l_resolutions,
									 style=wx.CB_DROPDOWN | wx.CB_READONLY,
									 size=(100, 25)
									 )
		self.var_ids[self.c_box_res.GetId()] = "resolution"
		self.c_boxes.append(self.c_box_res)

		self.check_countries = wx.CheckBox(parent=pnl_other, id=wx.ID_ANY, label=" Draw countries")
		self.var_ids[self.check_countries.GetId()] = "countries"
		self.chk_boxes.append(self.check_countries)

		self.check_rivers = wx.CheckBox(parent=pnl_other, id=wx.ID_ANY, label=" Draw rivers")
		self.var_ids[self.check_rivers.GetId()] = "rivers"
		self.chk_boxes.append(self.check_rivers)

		text_cmap = wx.StaticText(parent=pnl_other, label="Colormap : ")
		colormaps = display_tools.get_cmap()
		self.c_box_cmap = wx.ComboBox(
									  parent=pnl_other,
									  id=wx.ID_ANY,
									  choices=colormaps,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY,
									  size=(100, 25)
									  )
		self.var_ids[self.c_box_cmap.GetId()] = "cmap"
		self.c_boxes.append(self.c_box_cmap)

		text_pltype = wx.StaticText(parent=pnl_other, label="Plot type : ")
		plot_types = ["pcolormesh"]
		self.c_box_pltype = wx.ComboBox(
									  parent=pnl_other,
									  id=wx.ID_ANY,
									  choices=plot_types,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY,
									  size=(100, 25)
									  )
		self.var_ids[self.c_box_pltype.GetId()] = "plot_type"
		self.c_boxes.append(self.c_box_pltype)

		self.check_colorbar = wx.CheckBox(parent=pnl_other, id=wx.ID_ANY, label=" Colorbar")
		self.var_ids[self.check_colorbar.GetId()] = "colorbar"
		self.chk_boxes.append(self.check_colorbar)

		self.check_norm = wx.CheckBox(parent=pnl_other, id=wx.ID_ANY, label=" Norm")
		self.var_ids[self.check_norm.GetId()] = "norm"
		# This check box is not added to the list of check boxes because it'll have its own binding.

		text_midpoint = wx.StaticText(parent=pnl_other, label="Midpoint : ")
		self.te_midpoint = IntCtrl(parent=pnl_other, id=wx.ID_ANY, value=25)
		self.var_ids[self.te_midpoint.GetId()] = "midpoint"
		self.text_entries.append(self.te_midpoint)
		self.te_midpoint.Enable(False)

		text_min = wx.StaticText(parent=pnl_other, label="Min : ")
		self.te_min = IntCtrl(parent=pnl_other, id=wx.ID_ANY, value=0)
		self.var_ids[self.te_min.GetId()] = "c_min"
		self.text_entries.append(self.te_min)
		self.te_min.Enable(False)

		text_max = wx.StaticText(parent=pnl_other, label="Max : ")
		self.te_max = IntCtrl(parent=pnl_other, id=wx.ID_ANY, value=50)
		self.var_ids[self.te_max.GetId()] = "c_max"
		self.text_entries.append(self.te_max)
		self.te_max.Enable(False)

		# Sizer setup
		pnl_other_sizer.Add(text_res, 0)
		pnl_other_sizer.Add(self.c_box_res, 0)
		pnl_other_sizer.Add(self.check_countries, 0)
		pnl_other_sizer.Add(self.check_rivers, 0)
		pnl_other_sizer.Add(text_cmap, 0)
		pnl_other_sizer.Add(self.c_box_cmap, 0)
		pnl_other_sizer.Add(text_pltype, 0)
		pnl_other_sizer.Add(self.c_box_pltype, 0)
		pnl_other_sizer.Add(self.check_colorbar, 0)
		pnl_other_sizer.Add(self.check_norm, 0)
		pnl_other_sizer.Add(text_midpoint, 0)
		pnl_other_sizer.Add(self.te_midpoint, 0)
		pnl_other_sizer.Add(text_min, 0)
		pnl_other_sizer.Add(self.te_min, 0)
		pnl_other_sizer.Add(text_max, 0)
		pnl_other_sizer.Add(self.te_max, 0)
		pnl_other.SetSizer(pnl_other_sizer)

		# Map preview panels
		pnl_map_preview = wx.Panel(parent=pnl_stbox_proj, style=wx.BORDER_THEME)
		pnl_map_preview.SetBackgroundColour(wx.Colour(255, 255, 255))
		pnl_map_preview_sizer = wx.BoxSizer(wx.VERTICAL)

		self.map_previews = {}
		for preset in self.presets.keys():
			filename = os.path.join(MAP_PREVIEW_PATH, self.presets[preset]['filename'])
			image = wx.Image(filename, wx.BITMAP_TYPE_ANY)
			bitmap = wx_tools.rescale_image(image, 400, 300)
			self.map_previews[preset] = wx.StaticBitmap(pnl_map_preview, wx.ID_ANY, bitmap, size=(400,300))
			pnl_map_preview_sizer.Add(self.map_previews[preset], 0, wx.EXPAND)
			self.map_previews[preset].Hide()

		self.map_previews[self.options['preset']].Show()

		pnl_map_preview.SetSizer(pnl_map_preview_sizer)

		# StaticBox Sizer setup
		pnl_stbox_proj_sizer.Add(pnl_proj, pos=(0, 0), span=(1, 1), flag=wx.EXPAND | wx.ALL, border=20)
		pnl_stbox_proj_sizer.Add(pnl_other, pos=(0, 1), span=(1, 1), flag=wx.EXPAND | wx.ALL, border=20)
		pnl_stbox_proj_sizer.Add(pnl_map_preview, pos=(0, 2), span=(1, 2), flag=wx.EXPAND | wx.ALL, border=20)
		pnl_stbox_proj.SetSizer(pnl_stbox_proj_sizer)

		stbox_proj_sizer.Add(pnl_stbox_proj, 0, wx.ALIGN_CENTER)

		# --------------------------------------- #
		# PLot Button

		self.button = wx.Button(parent=self, label="Draw", size=(200, 30))

		# --------------------------------------- #
		# Bindings
		for c_box in self.c_boxes:
			c_box.Bind(wx.EVT_COMBOBOX, handler=self.on_option_change)
		for te in self.text_entries:
			te.Bind(wx.EVT_TEXT, handler=self.on_option_change)
		for chk in self.chk_boxes:
			chk.Bind(wx.EVT_CHECKBOX, handler=self.on_option_change)
		self.check_norm.Bind(wx.EVT_CHECKBOX, handler=self.on_norm_change)

		# --------------------------------------- #
		# Add element to the main sizer
		self.main_sizer.Add(stbox_gen_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 20)
		self.main_sizer.Add(stbox_data_corr_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 20)
		self.main_sizer.Add(stbox_proj_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 20)
		self.main_sizer.Add(self.button, 0, wx.ALIGN_CENTER | wx.ALL, 20)
		self.SetSizer(self.main_sizer)
예제 #24
0
    def InitUI(self):
        panel = wx.Panel(self)

        self.quote = wx.StaticText(panel,
                                   -1,
                                   label="PROJECT DETAILS \n",
                                   pos=(10, 30))
        self.quote.SetForegroundColour((255, 0, 0))  # set text color

        start_image = wx.Image("Modules/img/logo2.png")
        start_image.Rescale(450, 450)
        image = wx.BitmapFromImage(start_image)
        pic = wx.StaticBitmap(panel,
                              -1,
                              image,
                              pos=(150, 0),
                              style=wx.BITMAP_TYPE_PNG)

        # ~ prjBtn = wx.Button(panel, -1, "Create a Project",size=(150,30), pos=(10,650))
        # ~ prjBtn.Bind(wx.EVT_BUTTON, self.create_project)
        # ~ start_image = wx.Image("img/logo2.png")
        # ~ start_image.Rescale(180, 140)
        # ~ image = wx.BitmapFromImage(start_image)
        # ~ pic=wx.StaticBitmap(pnl, -1, image, pos=(250, 50), style=wx.BITMAP_TYPE_PNG)

        panel.SetBackgroundColour('#4f5049')
        # vbox = wx.BoxSizer(wx.VERTICAL)

        self.projectname = wx.TextCtrl(panel,
                                       -1,
                                       "Project Name",
                                       size=(250, 30),
                                       pos=(10, 120))
        # self.projectname.SetBackgroundColour('#ededed')

        self.author = wx.TextCtrl(panel,
                                  -1,
                                  "Author's Full Name'",
                                  size=(250, 30),
                                  pos=(10, 160))
        # self.author.SetBackgroundColour('#ededed')

        self.targetname = wx.TextCtrl(panel,
                                      -1,
                                      "Target Name",
                                      size=(250, 30),
                                      pos=(10, 200))
        # self.targetname.SetBackgroundColour('#ededed')

        self.datename = wx.TextCtrl(panel,
                                    -1,
                                    "dd/mm/yy",
                                    size=(250, 30),
                                    pos=(10, 240))
        # self.targetname.SetBackgroundColour('#ededed')

        prjBtn = wx.Button(panel,
                           -1,
                           "Create a Project",
                           size=(150, 30),
                           pos=(10, 300))

        prjBtn.Bind(wx.EVT_BUTTON, self.create_project)

        prjBtn2 = wx.Button(panel,
                            -1,
                            "Stand alone",
                            size=(150, 30),
                            pos=(10, 350))
        prjBtn2.Bind(wx.EVT_BUTTON, self.create_std)
예제 #25
0
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, size=(300, 420))

        self.CreateStatusBar()

        self.panel = wx.Panel(self)

        config_path = os.path.expanduser('~/.surfshark/configs')

        my_path = os.path.abspath(os.path.dirname(__file__))

        clusters_url = "https://my.surfshark.com/vpn/api/v1/server/clusters"

        try:
            response = requests.get(clusters_url)
            self.serverdata = {
                rec.get('country') + " . " + rec.get('location'):
                rec.get('connectionName')
                for rec in response.json()
            }
        except:
            with open(os.path.join(my_path, 'assets/servers.json')) as s:
                self.serverdata = json.load(s)

        servers = list(self.serverdata.keys())

        self.servercmb = wx.ComboBox(self.panel, choices=servers)
        self.protocmb = wx.ComboBox(self.panel,
                                    value="udp",
                                    choices=['udp', 'tcp'])

        self.credentialsbtn = wx.Button(self.panel, -1, "Enter Credentials")
        self.credentialsbtn.SetBackgroundColour('#ffffff')
        self.credentialsbtn.SetForegroundColour('#00d18a')

        self.connectbtn = wx.Button(self.panel, -1, "Quick Connect")
        self.connectbtn.SetBackgroundColour('#00d18a')
        self.connectbtn.SetForegroundColour('#ffffff')

        self.disconnectbtn = wx.Button(self.panel, -1, "Disconnect")
        self.disconnectbtn.SetBackgroundColour('#ffffff')
        self.disconnectbtn.SetForegroundColour('#00d18a')

        logoimg = wx.Image(os.path.join(my_path, 'assets/surfsharkgui.png'),
                           wx.BITMAP_TYPE_ANY)
        logoimgBmp = wx.StaticBitmap(self.panel, wx.ID_ANY, wx.Bitmap(logoimg))

        self.Bind(wx.EVT_BUTTON, self.OnCredentials, self.credentialsbtn)
        self.Bind(wx.EVT_BUTTON, self.OnConnect, self.connectbtn)
        self.Bind(wx.EVT_BUTTON, self.OnDisconnect, self.disconnectbtn)

        sizer = wx.BoxSizer(wx.VERTICAL)

        sizer.AddSpacer(10)
        sizer.Add(self.credentialsbtn, 0, wx.ALIGN_CENTER, 10)

        sizer.Add(logoimgBmp, 0, wx.ALIGN_CENTER, 10)
        sizer.AddSpacer(10)

        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.Add(self.servercmb, 1, wx.ALIGN_LEFT, 10)
        hsizer.Add(self.protocmb, 0, wx.ALIGN_RIGHT, 10)

        sizer.Add(hsizer, 0, wx.ALIGN_CENTER, 10)
        sizer.AddSpacer(10)

        sizer.Add(self.connectbtn, 0, wx.ALIGN_CENTER, 10)
        sizer.Add(self.disconnectbtn, 0, wx.ALIGN_CENTER, 10)

        self.disconnectbtn.Hide()

        self.panel.SetSizerAndFit(sizer)
        self.panel.Layout()
예제 #26
0
    def __init__(self,
                 parent,
                 id_,
                 title,
                 style=wx.DEFAULT_DIALOG_STYLE | wx.MINIMIZE_BOX):
        """Creates a standalone window that is used for downloading
        updates for the editor.
        @param parent: Parent Window of the dialog
        @param title: Title of dialog

        """
        wx.Frame.__init__(self, parent, id_, title, style=style)
        util.SetWindowIcon(self)

        #---- Attributes/Objects ----#
        self.LOG = wx.GetApp().GetLog()
        panel = wx.Panel(self)
        self._progress = UpdateProgress(panel, self.ID_PROGRESS_BAR)
        fname = self._progress.GetCurrFileName()
        floc = self._progress.GetDownloadLocation()
        dl_file = wx.StaticText(panel, label=_("Downloading: %s") % fname)
        dl_loc = wx.StaticText(panel, wx.ID_ANY,
                               _("Downloading To: %s") % floc)
        self._cancel_bt = wx.Button(panel, wx.ID_CANCEL, _("Cancel"))
        self._timer = wx.Timer(self, id=self.ID_TIMER)
        self._proghist = list()

        #---- Layout ----#
        self.CreateStatusBar(2)
        self._sizer = wx.GridBagSizer()
        bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_WEB), wx.ART_TOOLBAR)
        mdc = wx.MemoryDC(bmp)
        tmp_bmp = wx.Image(ed_glob.CONFIG['SYSPIX_DIR'] + u"editra.png",
                           wx.BITMAP_TYPE_PNG)
        tmp_bmp.Rescale(20, 20, wx.IMAGE_QUALITY_HIGH)
        mdc.DrawBitmap(tmp_bmp.ConvertToBitmap(), 11, 11)
        mdc.SelectObject(wx.NullBitmap)
        bmp = wx.StaticBitmap(panel, wx.ID_ANY, bmp)
        self._sizer.AddMany([(bmp, (1, 1), (3, 2)), (dl_file, (1, 4), (1, 4)),
                             (dl_loc, (2, 4), (1, 4)),
                             ((15, 15), (3, 5), (1, 1))])
        self._sizer.Add(self._progress, (4, 1), (1, 10), wx.EXPAND)

        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        bsizer.AddStretchSpacer()
        bsizer.Add(self._cancel_bt, 0, wx.ALIGN_CENTER_HORIZONTAL)
        bsizer.AddStretchSpacer()

        self._sizer.Add(bsizer, (6, 1), (1, 10), wx.EXPAND)
        self._sizer.Add((5, 5), (7, 1))
        self._sizer.Add((5, 5), (7, 11))
        panel.SetSizer(self._sizer)
        mwsz = wx.BoxSizer(wx.HORIZONTAL)
        mwsz.Add(panel, 1, wx.EXPAND)
        self.SetSizer(mwsz)
        self.SetInitialSize()

        self.SetStatusWidths([-1, 100])
        self.SetStatusText(_("Downloading") + u"...", self.SB_INFO)

        #---- Bind Events ----#
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_TIMER, self.OnUpdate, id=self.ID_TIMER)
예제 #27
0
    def OnAbout(self, event):
        description = """Pinguino is an Open Software and Open Hardware Arduino-like project. Boards are based on 8 or 32-bit USB built-in Microchip microcontrollers. The main goal is to build a real USB system without USB to serial converter.
        """

        licence = """Pinguino is free software; you can redistribute it and/or modify it
        under the terms of the GNU General Public License as published by the Free Software Foundation;
        either version 2 of the License, or (at your option) any later version.

        Pinguino is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
        without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
        See the GNU General Public License for more details. You should have received a copy of
        the GNU General Public License along with File Hunter; if not, write to
        the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA"""

        info = wx.AboutDialogInfo()
        #bmp = wx.Icon(os.path.join(THEME_DIR, 'logoX3.png'), wx.BITMAP_TYPE_PNG)
        image = wx.Image(os.path.join(THEME_DIR, 'logo3D.png'),
                         wx.BITMAP_TYPE_PNG)
        image = image.Scale(400, 300, wx.IMAGE_QUALITY_HIGH)
        bmp = wx.BitmapFromImage(image)
        #bmp = image.ConvertToBitmap()

        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(bmp)
        info.SetIcon(icon)

        info.SetName('Pinguino')
        info.SetVersion(pinguino_version)
        #info.SetVersion("rev. " + self.localRev)
        info.SetDescription(description)
        # LGPL compatibility ?
        #info.SetCopyright('2008, 2009, 2010, 2011 jean-pierre mandon')
        info.SetWebSite('http://www.pinguino.cc')
        info.SetLicence(licence)

        info.AddDeveloper('Jean-Pierre Mandon')
        info.AddDeveloper('Régis Blanchot')
        info.AddDeveloper('Marcus Fazzi')
        info.AddDeveloper('Jesus Carmona Esteban')
        info.AddDeveloper('Alfred Broda')
        info.AddDeveloper('Yeison Cardona')
        info.AddDeveloper('Henk Van Beek')
        info.AddDeveloper('Björn Pfeiffer')
        info.AddDeveloper('Alexis Sánchez')

        info.AddDocWriter('Benoit Espinola')
        info.AddDocWriter('Sebastien Koechlin')
        info.AddDocWriter('Ivan Ricondo')
        info.AddDocWriter('Jesus Carmona Esteban')
        info.AddDocWriter('Marcus Fazzi')
        info.AddDocWriter('Régis Blanchot')

        info.AddArtist('France Cadet')
        info.AddArtist('Laurent Costes')
        info.AddArtist('Daniel Rodrí­guez')

        info.AddTranslator('Joan Espinoza')
        info.AddTranslator('Alexis Sánchez')
        info.AddTranslator('Régis Blanchot')
        info.AddTranslator('Moreno Manzini ')

        wx.AboutBox(info)
예제 #28
0
    def OnClickSearch(self, event):
        self.name = ''
        self.fanhaoPlus = ''
        self.av_director = ''
        self.pid_director = ''
        self.av_studio = ''
        self.pid_studio = ''
        self.av_series = ''
        self.pid_series = ''
        self.av_genres = []
        self.new_av_genres = ''
        self.pid_genres = []
        self.av_stars = []
        self.new_av_stars = ''
        self.pid_stars = []
        self.other_socre = ''
        self.comment = ''
        self.name = self.txt_fanhao.GetValue()
        self.lblStates.SetLabel('正在搜索:' + self.name)
        if self.name is None:
            return
        else:
            headers = {
                'content-type':
                'application/json',
                'User-Agent':
                'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
            }

            try:
                name_url = self.name.replace(' ', '+')
                print(name_url)
                requ = requests.get('http://www.data18.com/search/?k=' +
                                    name_url,
                                    timeout=2,
                                    headers=headers).content

            except:
                wx.MessageBox("获取网址超时", "Message", wx.OK | wx.ICON_INFORMATION)
                return

        self.lblStates.SetLabel('请求成功,正在处理内容。。。')
        # 获取标签内容
        soup = BeautifulSoup(requ, 'html.parser', from_encoding='utf-8')
        # 先判断是否能正常搜索到内容
        is404 = soup.find(text='0 Results')
        if is404 is not None:
            wx.MessageBox("该电影查不到", "Message", wx.OK | wx.ICON_INFORMATION)
            return

        new_url_soup = soup.find(
            'a', href=re.compile('http://www.data18.com/movies/\d'))
        #通过movie标签查找
        if new_url_soup is not None:
            try:
                new_url = new_url_soup.get('href')
                requ_movie = requests.get(new_url, timeout=2,
                                          headers=headers).content
            except:
                wx.MessageBox("获取新网址超时", "Message",
                              wx.OK | wx.ICON_INFORMATION)
                return

            soup_movie = BeautifulSoup(requ_movie,
                                       'html.parser',
                                       from_encoding='utf-8')
            # 获取名字
            soup_name = soup_movie.find('h1')
            soup_name = soup_name.string
            self.lblName.SetLabel('名称:' + soup_name)
            self.name = soup_name

            # 创建文件夹
            if os.path.exists('资源/' + self.name):
                print('文件夹已经存在')
                self.lblStates.SetLabel('文件夹已经存在')
            else:
                os.makedirs('资源/' + self.name)
                print('创建文件夹成功')
                self.lblStates.SetLabel('创建文件夹成功')

            # 获取图片
            cover_url = soup_movie.find_all('a', class_='grouped_elements')
            cover_front_url = cover_url[0].get('href')
            cover_back_url = cover_url[1].get('href')
            print(cover_front_url, cover_back_url)
            try:
                self.lblStates.SetLabel('正在获取图片')
                pic_front = requests.get(cover_front_url, timeout=3)
                pic_back = requests.get(cover_back_url, timeout=3)
            except:
                print('【错误】当前图片无法下载')
                self.lblStates.SetLabel('请重试')
                wx.MessageBox("获取图片超时", "Message", wx.OK | wx.ICON_INFORMATION)
                return
            self.lblStates.SetLabel('获取信息成功')
            string_front = '资源/' + self.name + '/cover_front.jpg'
            fp = open(string_front, 'wb')
            # 创建文件
            fp.write(pic_front.content)
            fp.close()

            string_back = '资源/' + self.name + '/cover_back.jpg'
            fp = open(string_back, 'wb')
            # 创建文件
            fp.write(pic_back.content)
            fp.close()

            image_front = wx.Image(string_front, wx.BITMAP_TYPE_JPEG)
            self.bmp = wx.StaticBitmap(self,
                                       bitmap=image_front.ConvertToBitmap(),
                                       pos=(394, 88),
                                       size=(370, 523))
            image_back = wx.Image(string_back, wx.BITMAP_TYPE_JPEG)
            self.bmp = wx.StaticBitmap(self,
                                       bitmap=image_back.ConvertToBitmap(),
                                       pos=(24, 88),
                                       size=(370, 523))

            # 获取制作商
            soup_studio = soup_movie.find('u').string
            print(soup_studio)
            if soup_studio is None:
                self.av_studio = ''
                self.pid_studio = ''
            else:
                self.av_studio = soup_studio.string
                self.pid_studio = 'http://www.data18.com/sites/' + self.av_studio
            self.lblStudio.SetLabel('制作商: ' + self.av_studio)

            # 获取导演
            soup_director_raw = soup_movie.find('b', text='Director:')
            soup_director = soup_director_raw.find_next('a').string
            if soup_director is None:
                self.av_director = ''
                self.pid_director = ''
            else:
                self.av_director = soup_director.string
                self.pid_director = soup_director_raw.find_next('a').get(
                    'href')
            self.lblDirector.SetLabel('导演:' + self.av_director)

            # 获取系列
            soup_series_raw = soup_movie.find('b', text='Serie:')
            soup_series = soup_series_raw.find_next('a').string
            print(soup_series)
            if soup_series is None:
                self.av_series = ''
                self.pid_series = ''
            else:
                self.av_series = soup_series.string
                self.pid_series = soup_series_raw.find_next('a').get('href')
            self.lblSeries.SetLabel('系列:' + self.av_series)

            # 获取类别
            soup_genres = soup_movie.find(
                'b', text='Categories:').find_next_siblings('a')
            print(soup_genres)
            if soup_genres is None:
                self.av_genres = ['无类别']
                self.pid_genres = ['']
            else:
                for soup_genre in soup_genres:
                    self.av_genres.append(soup_genre.string)
                    pid_genre = soup_genre.get('href')
                    self.pid_genres.append(pid_genre)

            for av_genre in self.av_genres:
                av_genre = av_genre + ','
                self.new_av_genres = av_genre + self.new_av_genres
            print(self.new_av_genres)
            print(self.pid_genres)
            self.lblGenres.SetLabel('类别:' + self.new_av_genres)

            # 获取演员
            soup_stars = soup_movie.find_all('p',
                                             class_='line1',
                                             style='align: center;')
            print(soup_stars)
            for soup_star in soup_stars:
                soup_star_txt = soup_star.a.string
                pid_star = soup_star.a.get('href')
                self.av_stars.append(soup_star_txt)
                self.pid_stars.append(pid_star)

            print(self.av_stars)
            for av_star in self.av_stars:
                av_star = av_star + ','
                self.new_av_stars = av_star + self.new_av_stars
            self.lblStars.SetLabel('演员:' + self.new_av_stars)

        #通过content标签查找
        else:
            new_url = soup.find('p', class_='line1').a.get('href')
            try:
                requ_movie = requests.get(new_url, timeout=2,
                                          headers=headers).content
            except:
                wx.MessageBox("获取新网址超时", "Message",
                              wx.OK | wx.ICON_INFORMATION)
                return

            soup_movie = BeautifulSoup(requ_movie,
                                       'html.parser',
                                       from_encoding='utf-8')

            # 获取名字
            soup_name = soup_movie.find('h1')
            soup_name = soup_name.string
            self.lblName.SetLabel('名称:' + soup_name)
            self.name = soup_name

            cover_url = soup_movie.find('div', id='moviewrap').img.get('src')
            print(cover_url)

            # 创建文件夹
            if os.path.exists('资源/' + self.name):
                print('文件夹已经存在')
                self.lblStates.SetLabel('文件夹已经存在')
            else:
                os.makedirs('资源/' + self.name)
                print('创建文件夹成功')
                self.lblStates.SetLabel('创建文件夹成功')

            # 获取图片
            try:
                self.lblStates.SetLabel('正在获取图片')
                pic = requests.get(cover_url, timeout=3)
            except:
                print('【错误】当前图片无法下载')
                self.lblStates.SetLabel('请重试')
                wx.MessageBox("获取图片超时", "Message", wx.OK | wx.ICON_INFORMATION)
                return
            self.lblStates.SetLabel('获取信息成功')
            string = '资源/' + self.name + '/cover_front.jpg'
            fp = open(string, 'wb')
            # 创建文件
            fp.write(pic.content)
            fp.close()
            image = wx.Image(string, wx.BITMAP_TYPE_JPEG)
            self.bmp = wx.StaticBitmap(self,
                                       bitmap=image.ConvertToBitmap(),
                                       pos=(75, 170))

            # 获取制作商
            soup_studio = soup_movie.find('u').string
            print(soup_studio)
            if soup_studio is None:
                self.av_studio = ''
                self.pid_studio = ''
            else:
                self.av_studio = soup_studio.string
                self.pid_studio = 'http://www.data18.com/sites/' + self.av_studio
            self.lblStudio.SetLabel('制作商: ' + self.av_studio)

            # 获取系列
            soup_series_raw = soup_movie.find(text='Site:')
            soup_series = soup_series_raw.find_next('a').string
            print(soup_series)
            if soup_series is None:
                self.av_series = ''
                self.pid_series = ''
            else:
                self.av_series = soup_series.string
                self.pid_series = soup_series_raw.find_next('a').get('href')
            self.lblSeries.SetLabel('系列:' + self.av_series)

            # 获取导演
            soup_director = soup.find('a', href=re.compile(r'director'))
            if soup_director is None:
                self.av_director = ''
                self.pid_director = ''
            else:
                self.av_director = soup_director.string
                self.pid_director = soup_director.get('href').split('/')[-1]
            self.lblDirector.SetLabel('导演:' + self.av_director)

            # 获取类别
            soup_genres = soup_movie.find(
                'div', style='margin-top: 3px;').find_all('a')
            print(soup_genres)
            if soup_genres is None:
                self.av_genres = ['无类别']
                self.pid_genres = ['']
            else:
                for soup_genre in soup_genres:
                    self.av_genres.append(soup_genre.string)
                    pid_genre = soup_genre.get('href')
                    self.pid_genres.append(pid_genre)

            for av_genre in self.av_genres:
                av_genre = av_genre + ','
                self.new_av_genres = av_genre + self.new_av_genres
            print(self.new_av_genres)
            print(self.pid_genres)
            self.lblGenres.SetLabel('类别:' + self.new_av_genres)

            # 获取演员
            soup_stars = soup_movie.find(
                'b', text='Starring:').find_next_siblings('a')
            print(soup_stars)
            for soup_star in soup_stars:
                soup_star_txt = soup_star.get_text()
                pid_star = soup_star.get('href')
                self.av_stars.append(soup_star_txt)
                self.pid_stars.append(pid_star)

            for av_star in self.av_stars:
                av_star = av_star + ','
                self.new_av_stars = av_star + self.new_av_stars
            self.lblStars.SetLabel('演员:' + self.new_av_stars)
예제 #29
0
 def test_imageGetAlpha(self):
     img = wx.Image(pngFile)
     data = img.GetAlpha()
     self.assertEqual(len(data), img.Width * img.Height)
     self.assertTrue(isinstance(data, bytearray))
예제 #30
0
    def InitUI(self):
        # Set up the panel
        panel = wx.Panel(self)
        panel.SetBackgroundColour((42, 45, 52))

        sizer = wx.GridBagSizer(5, 5)

        text1 = wx.StaticText(panel, label="CSV Downloader")
        text1.SetFont(self.static_font)
        text1.SetForegroundColour('white')
        sizer.Add(text1,
                  pos=(0, 0),
                  flag=wx.TOP | wx.LEFT | wx.BOTTOM,
                  border=30)

        path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        filename = os.path.join(path, 'images', "logo-white-bg.png")
        image = wx.Image(filename, wx.BITMAP_TYPE_ANY)
        image_bitmap = wx.StaticBitmap(panel, wx.ID_ANY, wx.Bitmap(image))
        sizer.Add(image_bitmap,
                  pos=(0, 4),
                  flag=wx.TOP | wx.RIGHT | wx.ALIGN_RIGHT,
                  border=30)

        line = wx.StaticLine(panel)
        sizer.Add(line,
                  pos=(1, 0),
                  span=(1, 5),
                  flag=wx.EXPAND | wx.BOTTOM,
                  border=30)

        # text2 = wx.StaticText(panel, label="Company Name")
        # text2.SetForegroundColour('white')
        # sizer.Add(text2, pos=(2, 0), flag=wx.LEFT, border=10)
        #
        # self.customer = wx.TextCtrl(panel)
        # sizer.Add(self.customer, pos=(2, 1), span=(1, 4), flag=wx.TOP | wx.EXPAND)
        #
        text3 = wx.StaticText(panel, label="User Name")
        text3.SetForegroundColour('white')
        sizer.Add(text3, pos=(3, 0), flag=wx.LEFT | wx.TOP, border=10)

        self.user = wx.TextCtrl(panel)
        sizer.Add(self.user,
                  pos=(3, 1),
                  span=(1, 4),
                  flag=wx.TOP | wx.EXPAND,
                  border=5)

        text4 = wx.StaticText(panel, label="Password")
        text4.SetForegroundColour('white')
        sizer.Add(text4, pos=(4, 0), flag=wx.TOP | wx.LEFT, border=10)

        self.pw = wx.TextCtrl(panel, style=wx.TE_PASSWORD)
        sizer.Add(self.pw,
                  pos=(4, 1),
                  span=(1, 4),
                  flag=wx.TOP | wx.EXPAND,
                  border=5)

        # General Download Group
        # sb1 = wx.StaticBox(panel, label="General Downloads")
        # sb1.SetForegroundColour('white')
        # boxsizer1 = wx.StaticBoxSizer(sb1, wx.VERTICAL)
        # for elem in self.general_downloads:
        #     boxsizer1.Add(self.create_checkbox(panel, elem))
        #
        # sizer.Add(boxsizer1, pos=(5, 0), span=(1, 5),
        #           flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
        #
        # # Financial Download Group
        # sb2 = wx.StaticBox(panel, label="Financial Downloads")
        # sb2.SetForegroundColour('white')
        # boxsizer2 = wx.StaticBoxSizer(sb2, wx.VERTICAL)
        # for elem in self.financial_downloads:
        #     boxsizer2.Add(self.create_checkbox(panel, elem))
        #
        # sizer.Add(boxsizer2, pos=(6, 0), span=(1, 5),
        #           flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
        #
        # # Project Management Download Group
        # sb3 = wx.StaticBox(panel, label="Project Management Downloads")
        # sb3.SetForegroundColour('white')
        # boxsizer3 = wx.StaticBoxSizer(sb3, wx.VERTICAL)
        # for elem in self.pm_downloads:
        #     boxsizer3.Add(self.create_checkbox(panel, elem))
        #
        # sizer.Add(boxsizer3, pos=(7, 0), span=(1, 5),
        #           flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
        #
        # # Print to PDF Download Group
        # sb4 = wx.StaticBox(panel, label="Print to PDF Downloads")
        # sb4.SetForegroundColour('white')
        # boxsizer4 = wx.StaticBoxSizer(sb4, wx.VERTICAL)
        # for elem in self.print_to_pdf:
        #     boxsizer4.Add(self.create_checkbox(panel, elem))
        #
        # sizer.Add(boxsizer4, pos=(8, 0), span=(1, 5),
        #           flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
        #
        # # Check All Button
        # sizer.Add(self.create_checkbox(panel, "Check All"), pos=(9, 0),
        #           flag=wx.LEFT, border=10)
        #
        button = wx.Button(panel, label='Run')
        button.Bind(wx.EVT_BUTTON, self.run_crawler)
        sizer.Add(button, pos=(10, 4), flag=wx.ALIGN_RIGHT, border=30)

        sizer.AddGrowableCol(2)
        panel.SetSizer(sizer)
        sizer.Fit(self)
        self.Bind(wx.EVT_CHECKBOX, self.check_all)