Esempio n. 1
0
 def open_preferences(self, event):  # wxGlade: MeerK40t.<event_handler>
     project.close_old_window("preferences")
     from Preferences import Preferences
     window = Preferences(None, wx.ID_ANY, "")
     window.set_project(project)
     window.Show()
     project.windows["preferences"] = window
Esempio n. 2
0
 def __init__(self, config):
     self.radarr = Radarr(config.radarr_url, config.radarr_base_path,
                          config.radarr_api_key,
                          config.radarr_quality_profile)
     self.imdb = Imdb()
     self.score11 = Score11(self.imdb)
     self.ask = Preferences(self.imdb)
Esempio n. 3
0
 def init(self):
     self._preferences = Preferences()
     if constants.IS_DEVELOPMENT:
         self.__servers = DevelopmentServers(self._preferences)
     else:
         self.__servers = Servers(self._preferences)
     connectionManager.onLoggedOn += self._onLoggedOn
Esempio n. 4
0
 def init(self):
     self.tryPrepareWGCLogin()
     self._preferences = Preferences()
     if constants.IS_DEVELOPMENT:
         self.__servers = DevelopmentServers(self._preferences)
     else:
         self.__servers = Servers(self._preferences)
     self.connectionMgr.onLoggedOn += self._onLoggedOn
Esempio n. 5
0
    def __init__(self, arguments):
        super().__init__(arguments)

        self.mainWindow = None

        self.setOrganizationName('QtHEP')
        self.setApplicationName('QtHEP')
        QStandardPaths.setTestModeEnabled(__DEVELOPEMENT__)

        preferencesPath = QStandardPaths.writableLocation(
            QStandardPaths.AppDataLocation)
        if (not os.path.exists(preferencesPath)):
            os.makedirs(preferencesPath)
        self.preferencesFilename = os.path.join(
            preferencesPath,
            '{}.preferences.xml'.format(self.applicationName()))

        self.preferences = Preferences()
        if (os.path.exists(self.preferencesFilename)):
            self.preferences.fromXML(self.preferencesFilename)
            self.preferences.logging.initializeLog()
        else:
            self.preferences.toXML(self.preferencesFilename)

        DiscFilenameTemplatesSingleton().set(
            self.preferences.filenameTemplates)
        DiscMixdownsSingleton().set(self.preferences.mixdowns.getMixdowns())
        DiscPresetsSingleton().set(self.preferences.presets.getNames())

        self.disc = Disc(self)

        TitleVisibleSingleton().set(
            self.preferences.autoTitle.minimumTitleSeconds,
            self.disc.hideShortTitles)

        self.defaultSessionFilename = "{}.state.xml".format(
            self.applicationName())

        if __DEVELOPEMENT__:
            # 	self.settingsFilename = os.path.join(os.getcwd(), "{}.settings.xml".format(APP_NAME))
            # 	self.fullDefaultSessionFilename = os.path.join(os.getcwd(), self.defaultSessionFilename)
            s = os.path.join(os.getcwd(), 'TestFiles')
            self.temporarySessionFilename = os.path.join(
                s, "temp.{}".format(self.defaultSessionFilename))
        # 	self.logFilename = os.path.join(os.getcwd(), "{}.log".format(APP_NAME))
        else:
            if (os.path.exists(self.standardPaths.GetUserDataDir()) == False):
                os.makedirs(self.standardPaths.GetUserDataDir())
                SingletonLog().writeline('{} created'.format(
                    self.standardPaths.GetUserDataDir()))

        # 	self.settingsFilename = os.path.join(self.standardPaths.GetUserDataDir(), "{}.settings.xml".format(APP_NAME))
        # 	self.fullDefaultSessionFilename = os.path.join(self.standardPaths.GetUserDataDir(), self.defaultSessionFilename)
            self.temporarySessionFilename = os.path.join(
                self.standardPaths.GetUserDataDir(),
                "temp.{}".format(self.defaultSessionFilename))
Esempio n. 6
0
    def __init__(self, *args, **kwds):
        # begin wxGlade: MainFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        
        # Menu Bar
        self.main_frame_menubar = wx.MenuBar()
        self.File = wx.Menu()
        self.Exit = wx.MenuItem(self.File, wx.ID_EXIT, _("E&xit\tCtrl-Q"), _("Exit"), wx.ITEM_NORMAL)
        self.File.AppendItem(self.Exit)
        self.main_frame_menubar.Append(self.File, _("&File"))
        self.Help = wx.Menu()
        self.About = wx.MenuItem(self.Help, wx.ID_ABOUT, _("&About"), _("About"), wx.ITEM_NORMAL)
        self.Help.AppendItem(self.About)
        self.main_frame_menubar.Append(self.Help, _("&Help"))
        self.SetMenuBar(self.main_frame_menubar)
        # Menu Bar end
        self.logo_bitmap = wx.StaticBitmap(self, wx.ID_ANY, wx.NullBitmap)
        self.src_dir_text_ctrl = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
        self.src_dir_button = wx.Button(self, wx.ID_ANY, _("Source folder"))
        self.dest_dir_text_ctrl = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
        self.dst_folder_button = wx.Button(self, wx.ID_ANY, _("Destination folder"))
        self.tiff_checkbox = wx.CheckBox(self, wx.ID_ANY, _("TIFF"))
        self.dng_checkbox = wx.CheckBox(self, wx.ID_ANY, _("DNG"))
        self.thumb_checkbox = wx.CheckBox(self, wx.ID_ANY, _("Thumbnail"))
        self.rotate_checkbox = wx.CheckBox(self, wx.ID_ANY, _("Rotation"))
        self.convert_button = wx.Button(self, wx.ID_ANY, _("Convert"))
        self.status_text_ctrl = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.abort_button = wx.Button(self, wx.ID_ANY, _("Abort"))

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_MENU, self.OnClose, self.Exit)
        self.Bind(wx.EVT_MENU, self.OnMenuAbout, self.About)
        self.Bind(wx.EVT_BUTTON, self.OnSrcFolder, self.src_dir_button)
        self.Bind(wx.EVT_BUTTON, self.OnDstFolder, self.dst_folder_button)
        self.Bind(wx.EVT_CHECKBOX, self.OnTIFFClicked, self.tiff_checkbox)
        self.Bind(wx.EVT_CHECKBOX, self.OnDNGClicked, self.dng_checkbox)
        self.Bind(wx.EVT_CHECKBOX, self.OnThumbnailClicked, self.thumb_checkbox)
        self.Bind(wx.EVT_CHECKBOX, self.OnRotationClicked, self.rotate_checkbox)
        self.Bind(wx.EVT_BUTTON, self.OnConvert, self.convert_button)
        self.Bind(wx.EVT_BUTTON, self.OnAbort, self.abort_button)
        # end wxGlade
        self.images = Images()
        self.logo_bitmap.SetBitmap(self.images.bmp_logo)
        self.proc = None
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.SetMinSize(self.GetSize())
        self.prefs = Preferences()
        self.dng_checkbox.SetValue(self.prefs.get_dng())
        self.tiff_checkbox.SetValue(self.prefs.get_tiff())
        self.thumb_checkbox.SetValue(self.prefs.get_thumbnail())
        self.rotate_checkbox.SetValue(self.prefs.get_rotate())
 def init(self):
     if WGC.prepare():
         self.__wgcPublication = WGC.getPublication()
     else:
         _logger.error('WGC API initialization failed')
     self.tryPrepareWGCLogin()
     self._preferences = Preferences()
     if constants.IS_DEVELOPMENT:
         self.__servers = DevelopmentServers(self._preferences)
     else:
         self.__servers = Servers(self._preferences)
     self.connectionMgr.onLoggedOn += self._onLoggedOn
Esempio n. 8
0
    def __init__(self, master):
        self.valves = self.get_valves()

        self.master = master
        self.master.configure(bg='sky blue')
        self.password = '******'

        self.momentary = Momentary(self.master, self.valves)
        self.edit = Edit(self.master, self.valves)
        self.summary = Summary(self.master, self.valves)
        self.preferences = Preferences(self.master, self.valves)
        self.run_screen = RunScreen(self.master, self.valves)

        self.header = self.make_header(self.master)
        self.home = self.home_page(self.master)
        self.frame = self.home
Esempio n. 9
0
    def __init__(self, layout='MainLayout', settings_key=""):
        super(Plugin, self).__init__()

        # Name of layout that this plugin should be added (see PluginManager.py)
        self._main_layout_name = layout

        # The default size policy
        self.setSizePolicy(QtWidgets.QSizePolicy.Preferred,
                           QtWidgets.QSizePolicy.Fixed)

        # Must be a QtWidget
        if not isinstance(self, QtWidgets.QWidget):
            mooseutils.mooseError("A Plugin must also be a QWidget.")
            return

        # The Peacock tab index
        self._index = None
        self._plugin_manager = None
        self._preferences = Preferences(settings_key)
Esempio n. 10
0
def main():
    from Preferences import Preferences
    app = wx.PySimpleApp()
    preferences = Preferences()
    frame = PreferencesDialog(preferences)
    result = frame.ShowModal()
    if result == wx.ID_OK:
        print 'OK'
        for subject in preferences.default:
            category = subject[0]
            print category
            for (field, value, width) in subject[1:]:
                if type(value) == type([]):
                    print '  ', field,\
                        frame.controls[category][field].GetSelection()
                else:
                    print '  ', field,\
                        frame.controls[category][field].GetValue()
    else:
        print 'Cancel'
    frame.Destroy()
    app.MainLoop()
Esempio n. 11
0
    def __init__(self):

        # On cree l'instance de la classe dialog
        self.dialog = Dialog()
        self.dialog.setBackgroundTitle("TVDownloader")

        # On recupere l'instance de API
        self.api = API.getInstance()
        # On instancie le gestionnaire de download
        self.downloader = Downloader()
        # On instancie le gestionnaire d'historique
        self.historique = Historique()
        # On instancie le gestionnaire de preferences
        self.preferences = Preferences()

        # Liste des telechargements
        self.listeTelechargements = []

        # Quand le programme se termine, on execute la fonction actionsAvantQuitter
        atexit.register(self.actionsAvantQuitter)

        # On commence
        self.bouclePrincipale()
Esempio n. 12
0
    def __init__(self, parent, signaux):

        # Appel au constructeur de la classe mere
        QtGui.QDialog.__init__(self, parent)

        self.preferences = Preferences()
        self.pluginManager = PluginManager()
        self.signaux = signaux

        ###########
        # Fenetre #
        ###########

        ###
        # Reglages de la fenetre principale
        ###

        # Nom de la fenetre
        self.setWindowTitle(u"Préférences")
        # Dimensions la fenetre
        self.resize(280, 340)
        # Mise en place de son icone
        self.setWindowIcon(QtGui.QIcon("ico/gtk-preferences.svg"))

        ###
        # Mise en place des widgets dans la fenetre
        ###

        # Layout de grille principal
        self.gridLayout = QtGui.QGridLayout(self)

        # Font pour les titres
        fontTitres = QtGui.QFont()
        fontTitres.setPointSize(11)
        fontTitres.setWeight(75)
        fontTitres.setBold(True)

        #
        # Choix du repertoire telechargement
        #

        # Label
        self.labelRepertoire = QtGui.QLabel(self)
        self.labelRepertoire.setFont(fontTitres)
        self.labelRepertoire.setText(u"Répertoire de téléchargement :")

        # Repertoire de telechargement
        self.lineEditRepertoireTelechargement = QtGui.QLineEdit(self)

        # Bouton pour ouvrir la fenetre de selection de repertoire
        self.pushButtonSelectionDossier = QtGui.QPushButton(self)
        self.pushButtonSelectionDossier.setIcon(
            QtGui.QIcon("ico/gtk-folder.svg"))

        #
        # Choix du plugin par defaut
        #

        # Label
        self.labelPluginDefaut = QtGui.QLabel(self)
        self.labelPluginDefaut.setFont(fontTitres)
        self.labelPluginDefaut.setText(u"Plugin par défaut :")

        # Liste de choix du plugin par defaut
        self.comboBoxPluginDefaut = QtGui.QComboBox(self)

        #
        # Choix des plugins a activer
        #

        # Label
        self.labelPlugins = QtGui.QLabel(self)
        self.labelPlugins.setFont(fontTitres)
        self.labelPlugins.setText("Plugins actifs :")

        # Liste des plugins
        self.listWidgetPlugin = QtGui.QListWidget(self)

        #
        # Choix des parametres Internet
        #

        # Label
        self.labelInternet = QtGui.QLabel(self)
        self.labelInternet.setFont(fontTitres)
        self.labelInternet.setText(u"Paramètres Internet :")

        # Layout formulaire
        self.layoutInternet = QtGui.QFormLayout()

        # SpinBox pour choisir le timeOut
        self.spinBoxTimeOut = QtGui.QSpinBox()
        self.spinBoxTimeOut.setMinimum(1)
        self.spinBoxTimeOut.setMaximum(60)
        self.layoutInternet.addRow(u"Time out (en s) :", self.spinBoxTimeOut)

        # SpinBox pour choisir le nombre de threads max
        self.spinBoxNbThread = QtGui.QSpinBox()
        self.spinBoxNbThread.setMinimum(1)
        self.spinBoxNbThread.setMaximum(100)
        self.layoutInternet.addRow(u"Nombre de threads max :",
                                   self.spinBoxNbThread)

        # Bouton pour enregistrer/annuler les preferences
        self.buttonBox = QtGui.QDialogButtonBox(self)
        self.buttonBox.addButton("Enregistrer",
                                 QtGui.QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton("Fermer", QtGui.QDialogButtonBox.RejectRole)

        # On ajoute le tout au layout
        self.gridLayout.addWidget(self.labelRepertoire, 0, 0, 1, 2)
        self.gridLayout.addWidget(self.lineEditRepertoireTelechargement, 1, 0,
                                  1, 1)
        self.gridLayout.addWidget(self.pushButtonSelectionDossier, 1, 1, 1, 1)
        self.gridLayout.addWidget(self.labelPluginDefaut, 2, 0, 1, 2)
        self.gridLayout.addWidget(self.comboBoxPluginDefaut, 3, 0, 1, 2)
        self.gridLayout.addWidget(self.labelPlugins, 4, 0, 1, 2)
        self.gridLayout.addWidget(self.listWidgetPlugin, 5, 0, 1, 2)
        self.gridLayout.addWidget(self.labelInternet, 6, 0, 1, 2)
        self.gridLayout.addLayout(self.layoutInternet, 7, 0, 1, 2)
        self.gridLayout.addWidget(self.buttonBox, 8, 0, 1, 2)

        ###
        # Signaux provenants de l'interface
        ###

        QtCore.QObject.connect(self.pushButtonSelectionDossier,
                               QtCore.SIGNAL("clicked()"),
                               self.afficherSelecteurDossier)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"),
                               self.enregistrerPreferences)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"),
                               self.reject)
Esempio n. 13
0
# Dynamically imports all of the modules in the "animations" folder
animations = []
animationNames = []
for (_, name,
     _) in pkgutil.iter_modules([Path('/home/pi/LEDWebsite/src/animations')]):
    animations.append(import_module('animations.' + name, package=__name__))
    for i in dir(animations[len(animations) - 1]):
        attribute = getattr(animations[len(animations) - 1], i)
        for i in dir(animations[len(animations) - 1]):
            attribute = getattr(animations[len(animations) - 1], i)
            if inspect.isclass(attribute):
                setattr(sys.modules[__name__], name, attribute)

# Set up the preferences class
preferences = Preferences()

# Define the number of pixels for the LED Strip
numPixels = preferences.get_setup_preferences('num-pixels')

# Initializes the LED strip
pixels = neopixel.NeoPixel(
    board.D18,
    numPixels,
    brightness=preferences.get_setup_preferences('brightness'),
    auto_write=False,
    pixel_order=neopixel.GRB)


def getAnimationOptions():
    global thread
Esempio n. 14
0
 def __init__(self, pixels, numPixels, name):
     threading.Thread.__init__(self)
     self.preferences = Preferences()
     self.pixels = pixels
     self.numPixels = numPixels
     self.name = name
Esempio n. 15
0
    def __init__(self):
        #declaration des variables
        global choice, temp, plugins, chaines, programs, fichiers, DLlist
        chaines = ''
        programs = ''
        fichiers = ''
        temp = 0
        choice = ""
        selectedPlugin = ''
        selectedChaine = ''
        selectedProgram = ''
        DLlist = []

        ################################################
        # Instanciations + initialisation de variables #
        ################################################

        # On instancie le plugin manager
        self.pluginManager = PluginManager()
        # On instancie le gestionnaire de preferences
        self.preferences = Preferences()
        # On instancie le gestionnaire de download
        self.downloader = Downloader()
        # On recupere l'instance de API
        self.api = API.getInstance()
        #		# On instancie le gestionnaire d'historique
        #		self.historique = Historique()

        # Si aucun plugin n'est active, on ouvre la fenetre des preferences
        if (len(self.preferences.getPreference("pluginsActifs")) == 0):
            choice = 'p'
            self.api.pluginRafraichirAuto()

        # On met en place la liste des plugins dans API
        plugins = self.preferences.getPreference("pluginsActifs")
        plugins.sort()

        # On actualise tous les plugins
        self.api.pluginRafraichirAuto()

        #boucle qui raffraichit l'affichage apres chaque interaction utilisateur
        while choice != 'exit':
            #ouverture du menu de preferences
            if choice == 'p' or choice == 'P':
                prefs()
                # On met en place la liste des plugins dans API
                plugins = self.preferences.getPreference("pluginsActifs")
                plugins.sort()
                # On actualise tous les plugins
                self.api.pluginRafraichirAuto()
            #ouverture du menu de telechargement
            elif choice == 't' or choice == 'T':
                dl(DLlist)
                #ouverture de l'invite de fermeture
            elif choice == 'q' or choice == 'Q':
                quitter()
                #actualisation de l'affichage ecran
            elif choice == 'i' or choice == 'I':
                info()
                #actualisation de l'affichage ecran
            elif choice == 'a' or choice == 'A':
                header(selectedPlugin, selectedChaine, selectedProgram)
                print "\n\n\n\n\t\tRafraichissement\n\n\n"
                self.api.pluginRafraichirAuto()
                #recharger les listes
                if len(selectedProgram) != 0:
                    fichiers = self.api.getPluginListeFichiers(
                        selectedPlugin, selectedProgram)
                elif len(selectedChaine) != 0:
                    programs = self.api.getPluginListeEmissions(
                        selectedPlugin, selectedChaine)
                elif len(selectedPlugin) != 0:
                    chaines = self.api.getPluginListeChaines(selectedPlugin)
                elif len(selectedPlugin) == 0 and len(
                        selectedChaine) == 0 and len(selectedProgram) == 0:
                    plugins = self.preferences.getPreference("pluginsActifs")
                    plugins.sort()
                #mise a jour de l'affichage
                header(selectedPlugin, selectedChaine, selectedProgram)
                print "\n\n\n\n\t\tVeuillez patientez pendant la mise a jour des informations\n\n\n"
                time.sleep(1)
                show(selectedPlugin, selectedChaine, selectedProgram, temp)
            elif choice == 'r' or choice == 'R':
                temp = 0
                if len(selectedProgram) != 0:
                    selectedProgram = ""
                elif len(selectedChaine) != 0:
                    selectedChaine = ""
                    if len(chaines) == 1:
                        selectedPlugin = ""
                elif len(selectedPlugin) != 0:
                    selectedPlugin = ""
            elif choice.isdigit() and int(choice) >= 0:
                choice = 10 * temp + int(choice)
                if len(selectedPlugin) == 0 and len(plugins) > choice:
                    temp = 0
                    selectedPlugin = plugins[choice]
                    chaines = self.api.getPluginListeChaines(selectedPlugin)
                    if len(chaines) == 1:
                        header(selectedPlugin, '', '')
                        print "Une seule chaine :", chaines
                        time.sleep(0.5)
                        selectedChaine = chaines[0]
                        programs = self.api.getPluginListeEmissions(
                            selectedPlugin, selectedChaine)
                elif len(selectedChaine) == 0 and len(chaines) > choice:
                    temp = 0
                    selectedChaine = chaines[choice]
                    programs = self.api.getPluginListeEmissions(
                        selectedPlugin, selectedChaine)
                elif len(selectedProgram) == 0 and len(programs) > choice:
                    selectedProgram = programs[choice]
                    header(selectedPlugin, selectedChaine, selectedProgram)
                    print "\n\n\n\n\t\tVeuillez patientez pendant le chargement des informations\n\n\n"
                    fichiers = self.api.getPluginListeFichiers(
                        selectedPlugin, selectedProgram)
                    if len(fichiers) == 0:
                        header(selectedPlugin, selectedChaine, selectedProgram)
                        print "\n\n\n\n\n\n\n\t\tAucun fichier dans le programme :", selectedProgram
                        time.sleep(1)
                        selectedProgram = ''
                    else:
                        temp = 0
                elif len(selectedPlugin) != 0 and len(
                        selectedChaine) != 0 and len(
                            selectedProgram) != 0 and len(fichiers) > choice:
                    header(selectedPlugin, selectedChaine, selectedProgram)
                    if fichiers[choice] not in DLlist:
                        print "\n\n\n\n\n\n\najout", fichiers[
                            choice].nom, "a la liste de telechargement\n\n\n\n\n\n\n\n\n"
                        DLlist.append(fichiers[choice])
                    else:
                        print "\n\n\n\n\n\n\n\t\tFichier deja dans la liste de telechargement\n\n\n\n\n\n\n\n\n"
                    time.sleep(1)
                    os.system(['clear', 'cls'][os.name == 'nt'])

            elif choice == '*':
                #				if len(selectedPlugin)==0:
                #					temp=0
                #					selectedPlugin = 'None'
                #					chaines = self.api.getPluginListeChaines()
                #				elif len(selectedChaine)==0:
                #					temp=0
                #					selectedChaine='None'
                #					programs = self.api.getPluginListeEmissions(selectedPlugin,selectedChaine)
                #				el
                if len(selectedProgram) == 0:
                    selectedProgram = 'Tous'
                    header(selectedPlugin, selectedChaine, selectedProgram)
                    print "\n\n\n\n\t\tVeuillez patientez pendant le chargement des informations\n\n\n"
                    #					for choice in range(len(programs)) :
                    fichiers = self.api.getPluginListeFichiers(
                        selectedPlugin, None)  #programs[choice])
                elif len(selectedPlugin) != 0 and len(
                        selectedChaine) != 0 and len(selectedProgram) != 0:
                    header(selectedPlugin, selectedChaine, selectedProgram)
                    for choice in range(len(fichiers)):
                        if fichiers[int(choice)] not in DLlist:
                            header(selectedPlugin, selectedChaine,
                                   selectedProgram)
                            print "\n\n\n\n\t\tajout", fichiers[int(
                                choice)].nom, "a la liste de telechargement"
                            DLlist.append(fichiers[int(choice)])
                        else:
                            print "\t\tFichier deja dans la liste de telechargement"
                        time.sleep(0.5)

                #afficher la suite de la liste
            elif choice == '+':
                if len(selectedPlugin) == 0:
                    if len(plugins) > temp * 10 + 10: temp += 1
                elif len(selectedChaine) == 0:
                    if len(chaines) > temp * 10 + 10: temp += 1
                elif len(selectedProgram) == 0:
                    if len(programs) > temp * 10 + 10: temp += 1
                elif len(selectedPlugin) != 0 and len(
                        selectedChaine) != 0 and len(selectedProgram) != 0:
                    if len(fichiers) > temp * 10 + 10: temp += 1
                #afficher le debut de la liste
            elif choice == '-':
                if temp != 0: temp -= 1
            show(selectedPlugin, selectedChaine, selectedProgram, temp)
            choice = ''
            #			if not choice:choice=raw_input("\n\t\tEntrez votre choix : ")
            if not choice: choice = getch()
Esempio n. 16
0
 def __init__(self, res):
     SDIMainFrame.__init__(
         self,
         res,
         'MainFrame',
         'songpress',
         'Skeed',
         _('song'),
         'crd',
         _('Songpress - Il Canzonatore'),
         glb.AddPath('img/songpress.ico'),
         glb.VERSION,
         _("http://www.skeed.it/songpress"),
         (_(u"Copyright (c) 2009-{year} Luca Allulli - Skeed\nLocalization:\n{translations}"
            )).format(year=glb.YEAR,
                      translations="\n".join([
                          u"- {}: {}".format(glb.languages[x],
                                             glb.translators[x])
                          for x in glb.languages
                      ])),
         _("Licensed under the terms and conditions of the GNU General Public License, version 2"
           ),
         _("Special thanks to:\n  * The Pyhton programming language (http://www.python.org)\n  * wxWidgets (http://www.wxwidgets.org)\n  * wxPython (http://www.wxpython.org)\n  * Editra (http://editra.org/) (for the error reporting dialog and... the editor itself!)\n  * python-pptx (for PowerPoint export)"
           ),
         _import_formats,
     )
     self.pref = Preferences()
     self.SetDefaultExtension(self.pref.defaultExtension)
     self.text = Editor(self)
     dt = SDIDropTarget(self)
     self.text.SetDropTarget(dt)
     self.frame.Bind(wx.stc.EVT_STC_UPDATEUI, self.OnUpdateUI, self.text)
     # Other objects
     self.previewCanvas = PreviewCanvas(self.frame, self.pref.format,
                                        self.pref.notations,
                                        self.pref.decorator)
     self.AddMainPane(self.text)
     self.AddPane(self.previewCanvas.main_panel,
                  aui.AuiPaneInfo().Right().BestSize(240, 400),
                  _('Preview'), 'preview')
     if self.previewCanvas.link is not None:
         self.previewCanvas.main_panel.Bind(wx.adv.EVT_HYPERLINK,
                                            self.OnCopyAsImage,
                                            self.previewCanvas.link)
     self.mainToolBar = aui.AuiToolBar(self.frame,
                                       wx.ID_ANY,
                                       wx.DefaultPosition,
                                       agwStyle=aui.AUI_TB_PLAIN_BACKGROUND)
     self.mainToolBar.SetToolBitmapSize(wx.Size(16, 16))
     self.AddTool(self.mainToolBar, 'new', 'img/new.png', _("New"),
                  _("Create a new song"))
     self.AddTool(self.mainToolBar, 'open', 'img/open.png', _("Open"),
                  _("Open an existing song"))
     self.AddTool(self.mainToolBar, 'save', 'img/save.png', _("Save"),
                  _("Save song with the current filename"))
     self.mainToolBar.AddSeparator()
     self.undoTool = self.AddTool(self.mainToolBar, 'undo', 'img/undo.png',
                                  _("Undo"), _("Undo last edit"))
     self.redoTool = self.AddTool(self.mainToolBar, 'redo', 'img/redo.png',
                                  _("Redo"),
                                  _("Redo previously undone edit"))
     self.redoTool = wx.xrc.XRCID('redo')
     self.mainToolBar.AddSeparator()
     self.cutTool = self.AddTool(self.mainToolBar, 'cut', 'img/cut.png',
                                 _("Cut"),
                                 _("Move selected text in the clipboard"))
     self.copyTool = self.AddTool(self.mainToolBar, 'copy', 'img/copy.png',
                                  _("Copy"),
                                  _("Copy selected text in the clipboard"))
     self.copyOnlyTextTool = wx.xrc.XRCID('copyOnlyText')
     if platform.system() == 'Windows':
         self.AddTool(
             self.mainToolBar, 'copyAsImage', 'img/copyAsImage2.png',
             _("Copy as Image"),
             _("Copy the whole FORMATTED song (or selected verses) to the clipboard"
               ))
     self.pasteTool = self.AddTool(
         self.mainToolBar, 'paste', 'img/paste.png', _("Paste"),
         _("Read text from the clipboard and place it at the cursor position"
           ))
     self.pasteChordsTool = self.AddTool(
         self.mainToolBar, 'pasteChords', 'img/pasteChords.png',
         _("PasteChords"),
         _("Integrate chords of copied text into current selection"))
     self.mainToolBar.Realize()
     self.mainToolBarPane = self.AddPane(
         self.mainToolBar,
         aui.AuiPaneInfo().ToolbarPane().Top().Row(1).Position(1),
         _('Standard'), 'standard')
     self.formatToolBar = aui.AuiToolBar(
         self.frame, wx.ID_ANY, agwStyle=aui.AUI_TB_PLAIN_BACKGROUND)
     self.formatToolBar.SetExtraStyle(aui.AUI_TB_PLAIN_BACKGROUND)
     self.fontChooser = FontComboBox(self.formatToolBar, -1,
                                     self.pref.format.face)
     self.formatToolBar.AddControl(self.fontChooser)
     self.frame.Bind(wx.EVT_COMBOBOX, self.OnFontSelected, self.fontChooser)
     wx.UpdateUIEvent.SetUpdateInterval(500)
     self.frame.Bind(wx.EVT_UPDATE_UI, self.OnIdle, self.frame)
     self.frame.Bind(wx.EVT_TEXT_CUT, self.OnTextCutCopy, self.text)
     self.frame.Bind(wx.EVT_TEXT_COPY, self.OnTextCutCopy, self.text)
     self.fontChooser.Bind(wx.EVT_TEXT_ENTER, self.OnFontSelected,
                           self.fontChooser)
     self.fontChooser.Bind(wx.EVT_KILL_FOCUS, self.OnFontSelected,
                           self.fontChooser)
     self.AddTool(self.formatToolBar, 'title', 'img/title.png',
                  _("Insert title"),
                  _("Insert a command to display song title"))
     self.AddTool(self.formatToolBar, 'chord', 'img/chord.png',
                  _("Insert chord"),
                  _("Insert square brackets that will host a chord"))
     self.AddTool(self.formatToolBar, 'chorus', 'img/chorus.png',
                  _("Insert chorus"),
                  _("Insert a couple of commands that will contain chorus"))
     self.AddTool(
         self.formatToolBar,
         'verseWithCustomLabelOrWithoutLabel',
         'img/verse.png',
         _("Insert verse with custom label or without label"),
         _("Insert a commands that will display a verse with a custom label"
           ),
     )
     labelVersesTool = self.formatToolBar.AddToggleTool(  # AddToggleTool (agw) or AddTool
         wx.xrc.XRCID('labelVerses'),
         wx.Bitmap(wx.Image(glb.AddPath("img/labelVerses.png"))),
         wx.NullBitmap,
         True,
         None,
         _("Show verse labels"),
         _("Show or hide verse and chorus labels"),
     )
     self.labelVersesToolId = labelVersesTool.GetId()
     showChordsIcon = wx.StaticBitmap(
         self.formatToolBar, -1,
         wx.Bitmap(wx.Image(glb.AddPath('img/showChords.png'))))
     self.formatToolBar.AddControl(showChordsIcon)
     self.showChordsChooser = wx.Slider(self.formatToolBar, -1, 0, 0, 2,
                                        wx.DefaultPosition, (100, -1),
                                        wx.SL_AUTOTICKS | wx.SL_HORIZONTAL)
     tt1 = wx.ToolTip(_("Hide or show chords in formatted song"))
     tt2 = wx.ToolTip(_("Hide or show chords in formatted song"))
     self.showChordsChooser.SetToolTip(tt1)
     showChordsIcon.SetToolTip(tt2)
     self.frame.Bind(wx.EVT_SCROLL, self.OnFontSelected,
                     self.showChordsChooser)
     self.formatToolBar.AddControl(self.showChordsChooser, "pippo")
     self.formatToolBar.Realize()
     self.formatToolBarPane = self.AddPane(
         self.formatToolBar,
         aui.AuiPaneInfo().ToolbarPane().Top().Row(1).Position(2),
         _('Format'), 'format')
     self.BindMyMenu()
     self.frame.Bind(EVT_TEXT_CHANGED, self.OnTextChanged)
     self.exportMenuId = xrc.XRCID('export')
     self.exportToClipboardAsAVectorImage = xrc.XRCID(
         'exportToClipboardAsAVectorImage')
     self.exportAsEmfMenuId = xrc.XRCID('exportAsEmf')
     self.cutMenuId = xrc.XRCID('cut')
     self.copyMenuId = xrc.XRCID('copy')
     self.copyAsImageMenuId = xrc.XRCID('copyAsImage')
     self.pasteMenuId = xrc.XRCID('paste')
     self.pasteChordsMenuId = xrc.XRCID('pasteChords')
     self.removeChordsMenuId = xrc.XRCID('removeChords')
     self.labelVersesMenuId = xrc.XRCID('labelVerses')
     self.noChordsMenuId = xrc.XRCID('noChords')
     self.oneVerseForEachChordPatternMenuId = xrc.XRCID(
         'oneVerseForEachChordPattern')
     self.wholeSongMenuId = xrc.XRCID('wholeSong')
     if platform.system() != 'Windows':
         self.menuBar.GetMenu(0).FindItemById(
             self.exportMenuId).GetSubMenu().Delete(
                 self.exportToClipboardAsAVectorImage)
         self.menuBar.GetMenu(1).Delete(self.copyAsImageMenuId)
         self.menuBar.GetMenu(0).FindItemById(
             self.exportMenuId).GetSubMenu().Delete(self.exportAsEmfMenuId)
     self.findReplaceDialog = None
     self.CheckLabelVerses()
     self.SetFont()
     self.text.SetFont(self.pref.editorFace, self.pref.editorSize)
     self.FinalizePaneInitialization()
     # Reassign caption value to override caption saved in preferences (it could be another language)
     self._mgr.GetPane('preview').caption = _('Preview')
     self._mgr.GetPane('standard').caption = _('Standard')
     self._mgr.GetPane('format').caption = _('Format')
     if 'firstTimeEasyKey' in self.pref.notices:
         msg = _(
             "You are not a skilled guitarist? Songpress can help you: when you open a song, it can detect if chords are difficult. If this is the case, Songpress will alert you, and offer to transpose your song to the easiest key, automatically.\n\nDo you want to turn this option on?"
         )
         d = wx.MessageDialog(self.frame, msg, _("Songpress"),
                              wx.YES_NO | wx.ICON_QUESTION)
         if d.ShowModal() == wx.ID_YES:
             self.pref.autoAdjustEasyKey = True
             msg = _(
                 "Please take a minute to set up your skill as a guitarist. For each group of chords, tell Songpress how much you like them."
             )
             d = wx.MessageDialog(self.frame, msg, _("Songpress"), wx.OK)
             d.ShowModal()
             f = MyPreferencesDialog(self.frame, self.pref, easyChords)
             f.notebook.SetSelection(1)
             if f.ShowModal() == wx.ID_OK:
                 self.text.SetFont(self.pref.editorFace,
                                   int(self.pref.editorSize))
                 self.SetDefaultExtension(self.pref.defaultExtension)
     MyUpdateDialog.check_and_update(self.frame, self.pref)
     self.frame.Maximize(True)
Esempio n. 17
0
    def setupUi(self, parent_window):
        self.central_widget = QtGui.QWidget(parent_window)
        parent_window.setCentralWidget(self.central_widget)
        # the basic layout:
        central_layout = QtGui.QGridLayout()
        central_splitter = QtGui.QSplitter(Qt.Qt.Vertical)  # Below tabbed area
        central_splitter.setSizes([300, 800])
        central_layout.addWidget(central_splitter)
        self.central_widget.setLayout(central_layout)
        self.tabbed_area = QtGui.QTabWidget()
        central_splitter.addWidget(self.tabbed_area)

        # Tabbed Area
        # Stock group
        self.grain_stock = QtGui.QTableWidget()
        self.grain_stock.setColumnCount(4)
        self.grain_stock.setRowCount(12)
        self.grain_stock.setHorizontalHeaderLabels(
            ['Grain', 'EBC', 'Extract L/Kg.', 'Kg.'])
        self.grain_stock.verticalHeader().setVisible(False)
        self.grain_stock.setAlternatingRowColors(True)
        self.grain_stock.setDragDropMode(QtGui.QAbstractItemView.DragOnly)
        gr_stck_header = self.grain_stock.horizontalHeader()
        gr_stck_header.setResizeMode(QtGui.QHeaderView.Stretch)
        self.hop_stock = QtGui.QTableWidget()
        self.hop_stock.setColumnCount(3)
        self.hop_stock.setRowCount(12)
        self.hop_stock.setHorizontalHeaderLabels(['Hop', 'Alpha', 'Grams'])
        self.hop_stock.verticalHeader().setVisible(False)
        self.hop_stock.setAlternatingRowColors(True)
        self.hop_stock.setDragDropMode(QtGui.QAbstractItemView.DragOnly)
        hop_stck_header = self.hop_stock.horizontalHeader()
        hop_stck_header.setResizeMode(QtGui.QHeaderView.Stretch)

        recipe_tab = QtGui.QWidget()
        self.tabbed_area.addTab(recipe_tab, 'Recipe')
        recipe_layout = QtGui.QVBoxLayout()
        recipe_tab.setLayout(recipe_layout)
        stock_layout = QtGui.QHBoxLayout()
        stock_layout.addWidget(self.grain_stock)
        stock_layout.addWidget(self.hop_stock)
        recipe_layout.addLayout(stock_layout)
        # Recipe
        self.recipe_box = QtGui.QGroupBox('Current Recipe')
        curr_recipe_layout = QtGui.QHBoxLayout()
        self.recipe_box.setLayout(curr_recipe_layout)
        self.rcg = ControlGroup('new')
        curr_recipe_layout.addWidget(self.rcg)
        recipe_layout.addWidget(self.recipe_box)

        # File group
        file_tab = QtGui.QWidget()
        self.tabbed_area.addTab(file_tab, 'Files')
        # Top button bar
        self.button_back = QtGui.QPushButton("<<")
        self.button_forward = QtGui.QPushButton(">>")
        self.label_year = QtGui.QLabel()
        top_button_widget = QtGui.QWidget()
        top_button_layout = QtGui.QHBoxLayout()
        top_button_widget.setLayout(top_button_layout)
        top_button_layout.addWidget(self.button_back)
        top_button_layout.addWidget(self.label_year)
        top_button_layout.addWidget(self.button_forward)
        self.label_year.setAlignment(Qt.Qt.AlignCenter)
        # Year view
        self.yearView = YearView(parent_window)

        file_layout = QtGui.QVBoxLayout()
        file_tab.setLayout(file_layout)
        file_layout.addWidget(top_button_widget)
        file_layout.addWidget(self.yearView)
        # Search
        search_layout = QtGui.QHBoxLayout()
        search_panel = QtGui.QWidget()
        label_search = QtGui.QLabel('Search For...')
        label_results = QtGui.QLabel('Results')
        label_filter = QtGui.QLabel('Filter By Rating')
        label_filter.setAlignment(QtCore.Qt.AlignRight)
        plus_minus = chr(0x00B1)
        label_plus_minus = QtGui.QLabel(plus_minus)
        font = label_plus_minus.font()
        font.setPixelSize(20)
        label_plus_minus.setFont(font)
        label_plus_minus.setAlignment(QtCore.Qt.AlignRight)
        self.search_box = QtGui.QLineEdit()
        self.results_box = QtGui.QLineEdit()
        self.button_clear = QtGui.QPushButton('Clear')
        self.rating_plus_minus = QtGui.QSpinBox()
        self.rating_input = QtGui.QSpinBox()
        self.button_search = QtGui.QPushButton('Search')
        self.button_search.setMinimumWidth(100)
        self.button_clear.setMinimumWidth(100)
        search_layout.addWidget(label_search)
        search_layout.addWidget(self.search_box)
        search_layout.addWidget(self.button_search)

        search_layout.addWidget(self.button_clear)
        search_layout.addWidget(label_filter)
        search_layout.addWidget(self.rating_input)
        search_layout.addWidget(label_plus_minus)
        search_layout.addWidget(self.rating_plus_minus)
        search_layout.addWidget(label_results)
        search_layout.addWidget(self.results_box)
        search_layout.addWidget(self.button_clear)

        search_panel.setLayout(search_layout)
        file_layout.addWidget(search_panel)

        # Settings Group
        settings_tab = QtGui.QWidget()
        self.tabbed_area.addTab(settings_tab, 'Settings')
        settings_layout = QtGui.QHBoxLayout()
        settings_tab.setLayout(settings_layout)
        # Next line has to be before preferences to all preferences to load
        # colour settings
        self.colourSettings = ColourSettings(parent_window)
        preferences = Preferences(parent_window)
        settings_layout.addWidget(preferences)
        preferences.setMaximumWidth(400)
        settings_layout.addWidget(self.colourSettings)
        self.colourSettings.setMaximumWidth(400)
        calculators = Calculators()
        settings_layout.addWidget(calculators)
        calculators.setMaximumWidth(400)

        spare_box = QtGui.QGroupBox()
        settings_layout.addWidget(spare_box)

        #######################################################################
        # History
        history_area = QtGui.QWidget()
        history_layout = QtGui.QVBoxLayout()
        history_area.setLayout(history_layout)
        central_splitter.addWidget(history_area)
        self.date_box = QtGui.QGroupBox('Date')
        date_layout = QtGui.QVBoxLayout()
        self.date_box.setLayout(date_layout)
        sel_recipe_layout = QtGui.QHBoxLayout()
        date_layout.addLayout(sel_recipe_layout)
        self.hcg = ControlGroup('history')
        sel_recipe_layout.addWidget(self.hcg)
        history_layout.addWidget(self.date_box)

        # Notes
        notes_layout = QtGui.QHBoxLayout()
        date_layout.addLayout(notes_layout)
        self.process_notes = QtGui.QTextEdit()
        proc_note_box = QtGui.QGroupBox('Process Notes')
        proc_notes_layout = QtGui.QVBoxLayout()
        proc_note_box.setLayout(proc_notes_layout)
        proc_notes_layout.addWidget(self.process_notes)
        notes_layout.addWidget(proc_note_box)

        self.tasting_notes = QtGui.QTextEdit()
        tast_note_box = QtGui.QGroupBox('Tasting Notes')
        tast_notes_layout = QtGui.QVBoxLayout()
        tast_note_box.setLayout(tast_notes_layout)
        tast_notes_layout.addWidget(self.tasting_notes)
        notes_layout.addWidget(tast_note_box)

        info_box = QtGui.QGroupBox()
        info_layout = QtGui.QVBoxLayout()
        info_box.setLayout(info_layout)
        notes_layout.addWidget(info_box)

        label_rating = QtGui.QLabel('Rating')
        self.rating = QtGui.QSpinBox()
        self.box_style = QtGui.QComboBox()
        self.box_style.setMinimumWidth(160)
        style_layout = QtGui.QHBoxLayout()
        style_layout.addWidget(self.box_style)
        style_layout.addWidget(label_rating)
        style_layout.addWidget(self.rating)
        info_layout.addLayout(style_layout)

        brew_date_box = QtGui.QGroupBox('Date Brewed')
        self.brew_date = QtGui.QLabel()
        bold_font = QtGui.QFont()
        bold_font.setBold(True)
        bold_font.setPixelSize(16)
        self.brew_date.setFont(bold_font)
        brew_date_layout = QtGui.QVBoxLayout()
        brew_date_box.setLayout(brew_date_layout)
        brew_date_layout.addWidget(self.brew_date)
        self.brew_date.setAlignment(QtCore.Qt.AlignCenter)
        since_brew_box = QtGui.QGroupBox('Time Since Brewing')
        self.since_brew = QtGui.QLabel()
        self.since_brew.setFont(bold_font)
        since_brew_layout = QtGui.QVBoxLayout()
        since_brew_box.setLayout(since_brew_layout)
        since_brew_layout.addWidget(self.since_brew)
        self.since_brew.setAlignment(QtCore.Qt.AlignCenter)
        info_layout.addWidget(brew_date_box)
        info_layout.addWidget(since_brew_box)
        self.brew_date.setStyleSheet("""QLabel{
                Background-color:#42464a}""")
        self.since_brew.setStyleSheet("""QLabel{
                Background-color:#42464a}""")
Esempio n. 18
0
    def __init__(self):
        # Appel au constructeur de la classe mere
        QtGui.QMainWindow.__init__(self)

        ###########
        # Fenetre #
        ###########

        ###
        # Reglages de la fenetre principale
        ###

        # Nom de la fenetre
        self.setWindowTitle("TVDownloader")
        # Mise en place de son icone
        self.setWindowIcon(QtGui.QIcon("ico/TVDownloader.png"))

        ###
        # Mise en place des widgets dans la fenetre
        ###

        # Widget central qui contiendra tout
        self.centralWidget = QtGui.QWidget(self)

        #
        # Barre du haut
        #

        # Layout horizontal qui contiendra les listes deroulantes
        self.horizontalLayoutBarreHaut = QtGui.QHBoxLayout()

        # Liste deroulante pour choisir le site (plugin)
        self.comboBoxSite = QtGui.QComboBox(self.centralWidget)
        self.horizontalLayoutBarreHaut.addWidget(self.comboBoxSite)

        # Liste deroulante pour choisir une chaine du site courant
        self.comboBoxChaine = QtGui.QComboBox(self.centralWidget)
        self.horizontalLayoutBarreHaut.addWidget(self.comboBoxChaine)

        # Liste deroulante pour choisir une emission de la chaine courante
        self.comboBoxEmission = QtGui.QComboBox(self.centralWidget)
        self.horizontalLayoutBarreHaut.addWidget(self.comboBoxEmission)

        #
        # Onglets
        #

        # Gestionnaire onglets
        self.tabWidget = QtGui.QTabWidget(self.centralWidget)

        # Onglet Fichiers
        self.tabFichiers = QtGui.QSplitter(
            self.centralWidget)  # L'onglet Fichier contient un splitter
        self.tabWidget.addTab(self.tabFichiers, u"Choix des fichiers")

        # Onglet Telechargements
        self.tabTelechargements = QtGui.QWidget(self.centralWidget)
        self.tabWidget.addTab(self.tabTelechargements, u"Téléchargements")

        #
        # Liste des fichiers
        #

        # Layout de grille qui contient le tableau qui liste les fichiers + boutons
        self.gridLayoutFichiers = QtGui.QGridLayout(self.tabFichiers)

        # Tableau qui contient la liste des fichiers disponibles pour l'emission courante
        self.tableWidgetFichier = MyQTableWidget(self.tabFichiers)
        # Il a 4 colonnes et 0 ligne (pour l'instant)
        self.tableWidgetFichier.setColumnCount(3)
        self.tableWidgetFichier.setRowCount(0)
        # On ajoute les titres
        self.tableWidgetFichier.setHorizontalHeaderItem(
            0, self.tableWidgetFichier.creerItem(""))
        self.tableWidgetFichier.setHorizontalHeaderItem(
            1, self.tableWidgetFichier.creerItem("Date"))
        self.tableWidgetFichier.setHorizontalHeaderItem(
            2, self.tableWidgetFichier.creerItem("Emission"))
        # On l'ajoute au layout
        self.gridLayoutFichiers.addWidget(self.tableWidgetFichier, 0, 1, 6, 1)

        # Icones du tableWidget
        self.iconeFichier = QtGui.QIcon("ico/gtk-file.svg")
        self.iconeAjoute = QtGui.QIcon("ico/gtk-add.svg")
        self.iconeTelecharge = QtGui.QIcon("ico/gtk-apply.svg")

        # Bouton pour ajouter tous les fichiers a la liste des telechargements
        self.pushButtonToutAjouter = MyQPushButton(self.tabFichiers)
        self.pushButtonToutAjouter.setIcon(QtGui.QIcon("ico/gtk-add.svg"))
        self.pushButtonToutAjouter.setToolTip(
            u"Ajouter tous les fichiers à la liste des téléchargements")
        self.gridLayoutFichiers.addWidget(self.pushButtonToutAjouter, 0, 0, 2,
                                          1)

        # Bouton pour rafraichir le plugin courant
        self.pushButtonRafraichirPlugin = MyQPushButton(self.tabFichiers)
        self.pushButtonRafraichirPlugin.setIcon(
            QtGui.QIcon("ico/gtk-refresh.svg"))
        self.pushButtonRafraichirPlugin.setToolTip("Rafraichir le plugin")
        self.gridLayoutFichiers.addWidget(self.pushButtonRafraichirPlugin, 2,
                                          0, 2, 1)

        # Bouton pour ouvrir la fenetre des preferences du plugin courant
        self.pushButtonPreferencesPlugin = MyQPushButton(self.tabFichiers)
        self.pushButtonPreferencesPlugin.setIcon(
            QtGui.QIcon("ico/gtk-preferences.svg"))
        self.pushButtonPreferencesPlugin.setToolTip(
            u"Ouvrir les préférences du plugin")
        self.gridLayoutFichiers.addWidget(self.pushButtonPreferencesPlugin, 4,
                                          0, 2, 1)

        # On met en place ce layout sur un widget (pour le splitter)
        self.widgetFichiers = QtGui.QWidget()
        self.widgetFichiers.setLayout(self.gridLayoutFichiers)

        #
        # Descriptif des fichiers
        #

        # Layout de grille
        self.gridLayoutDescriptif = QtGui.QGridLayout()

        # Label pour afficher un logo
        self.logoFichierDefaut = QtGui.QPixmap()
        self.logoFichierDefaut.load("img/gtk-dialog-question.svg")

        self.labelLogo = QtGui.QLabel(self.centralWidget)
        self.labelLogo.setPixmap(
            self.logoFichierDefaut.scaled(QtCore.QSize(150, 150),
                                          QtCore.Qt.KeepAspectRatio))

        self.gridLayoutDescriptif.addWidget(self.labelLogo, 0, 0, 1, 1)

        # Zone de texte pour afficher un descriptif
        self.plainTextEdit = QtGui.QPlainTextEdit(self.centralWidget)
        self.gridLayoutDescriptif.addWidget(self.plainTextEdit, 0, 1, 1, 2)

        # On met en place ce layout sur un widget (pour le splitter)
        self.widgetDescriptif = QtGui.QWidget()
        self.widgetDescriptif.setLayout(self.gridLayoutDescriptif)

        # Onrientation verticale du splitter
        self.tabFichiers.setOrientation(QtCore.Qt.Vertical)

        # On ajoute les 2 elements au splitter (qui est notre onglet)
        self.tabFichiers.addWidget(self.widgetFichiers)
        self.tabFichiers.addWidget(self.widgetDescriptif)

        #
        # Liste des telechargements
        #

        # Layout de grille qui contient le tableau qui liste les fichiers a telecharger + les boutons pour le controller
        self.gridLayoutTelechargement = QtGui.QGridLayout(
            self.tabTelechargements)

        # Tableau qui contient la liste des fichiers a telecharger
        self.tableWidgetTelechargement = MyQTableWidget(
            self.tabTelechargements)
        # Il a 5 colonnes et 0 ligne (pour l'instant)
        self.tableWidgetTelechargement.setColumnCount(3)
        self.tableWidgetTelechargement.setRowCount(0)
        # On ajoute le titre des 5 colonnes
        self.tableWidgetTelechargement.setHorizontalHeaderItem(
            0, self.tableWidgetTelechargement.creerItem("Date"))
        self.tableWidgetTelechargement.setHorizontalHeaderItem(
            1, self.tableWidgetTelechargement.creerItem("Emission"))
        self.tableWidgetTelechargement.setHorizontalHeaderItem(
            2, self.tableWidgetTelechargement.creerItem("Etat"))
        # On l'ajoute au layout
        self.gridLayoutTelechargement.addWidget(self.tableWidgetTelechargement,
                                                0, 1, 4, 1)

        # Bouton pour monter l'element selectionne tout en haut de la liste
        self.pushButtonExtremiteMonter = MyQPushButton(self.tabTelechargements)
        self.pushButtonExtremiteMonter.setIcon(
            QtGui.QIcon("ico/gtk-jump-to-rtl.svg"))
        self.pushButtonExtremiteMonter.setToolTip(
            u"Placer l'élément sélectionné tout en haut")
        self.gridLayoutTelechargement.addWidget(self.pushButtonExtremiteMonter,
                                                0, 0, 1, 1)

        # Bouton pour monter l'element selectionne d'un cran dans la liste
        self.pushButtonMonter = MyQPushButton(self.tabTelechargements)
        self.pushButtonMonter.setIcon(QtGui.QIcon("ico/gtk-go-up.svg"))
        self.pushButtonMonter.setToolTip(u"Monter l'élément sélectionné")
        self.gridLayoutTelechargement.addWidget(self.pushButtonMonter, 1, 0, 1,
                                                1)

        # Bouton pour descendre l'element selectionne d'un cran dans la liste
        self.pushButtonDescendre = MyQPushButton(self.tabTelechargements)
        self.pushButtonDescendre.setIcon(QtGui.QIcon("ico/gtk-go-down.svg"))
        self.pushButtonDescendre.setToolTip(u"Descendre l'élément selectionné")
        self.gridLayoutTelechargement.addWidget(self.pushButtonDescendre, 2, 0,
                                                1, 1)

        # Bouton pour descendre l'element selectionne tout en bas de la liste
        self.pushButtonExtremiteDescendre = MyQPushButton(
            self.tabTelechargements)
        self.pushButtonExtremiteDescendre.setIcon(
            QtGui.QIcon("ico/gtk-jump-to-ltr.svg"))
        self.pushButtonExtremiteDescendre.setToolTip(
            u"Placer l'élément sélectionné tout en bas")
        self.gridLayoutTelechargement.addWidget(
            self.pushButtonExtremiteDescendre, 3, 0, 1, 1)

        # Bouton pour supprimer tous les elements de la liste
        self.pushButtonToutSupprimer = MyQPushButton(self.tabTelechargements)
        self.pushButtonToutSupprimer.setIcon(QtGui.QIcon("ico/gtk-cancel.svg"))
        self.pushButtonToutSupprimer.setToolTip(
            u"Supprimer tous les téléchargements")
        self.gridLayoutTelechargement.addWidget(self.pushButtonToutSupprimer,
                                                0, 2, 1, 1)

        # Bouton pour supprimer de la liste les telechargements termines
        self.pushButtonNettoyer = MyQPushButton(self.tabTelechargements)
        self.pushButtonNettoyer.setIcon(QtGui.QIcon("ico/gtk-delete-full.svg"))
        self.pushButtonNettoyer.setToolTip(
            u"Supprimer les téléchargement terminés")
        self.gridLayoutTelechargement.addWidget(self.pushButtonNettoyer, 1, 2,
                                                1, 1)

        # Bouton pour ouvrir le dossier des telechargements
        self.pushButtonOuvrirDossierTelechargement = MyQPushButton(
            self.tabTelechargements)
        self.pushButtonOuvrirDossierTelechargement.setIcon(
            QtGui.QIcon("ico/gtk-folder.svg"))
        self.pushButtonOuvrirDossierTelechargement.setToolTip(
            u"Ouvrir le dossier des téléchargements")
        self.gridLayoutTelechargement.addWidget(
            self.pushButtonOuvrirDossierTelechargement, 2, 2, 1, 1)

        #
        # Barre progression de telechargement d'un fichier
        #
        self.progressBarTelechargementFichier = QtGui.QProgressBar(
            self.centralWidget)
        self.progressBarTelechargementFichier.setProperty("value", 0)

        #
        # Barre de progression de telechargement des fichiers
        #
        self.progressBarTelechargement = QtGui.QProgressBar(self.centralWidget)
        self.progressBarTelechargement.setProperty("value", 0)

        #
        # Boutons du bas pour gerer ajouter/supprimer/lancer telechargements
        #

        # Layout horizontal qui contiendra les boutons
        self.horizontalLayoutBarreBas = QtGui.QHBoxLayout()

        # Bouton pour lancer les telechargements
        self.pushButtonLancer = QtGui.QPushButton(
            QtGui.QIcon("ico/gtk-media-play-ltr.svg"),
            u"Lancer téléchargement", self.centralWidget)
        self.horizontalLayoutBarreBas.addWidget(self.pushButtonLancer)

        # Bouton pour stopper les telechargements
        self.pushButtonStop = QtGui.QPushButton(
            QtGui.QIcon("ico/gtk-media-stop.svg"),
            u"Stopper le téléchargement", self.centralWidget)
        self.pushButtonStop.setEnabled(False)
        self.horizontalLayoutBarreBas.addWidget(self.pushButtonStop)

        ###
        # Positionnement des differents widgets/layouts sur le layout de grille
        ###

        # Layout de grille dans lequel on va placer nos widgets/layouts
        self.gridLayout = QtGui.QGridLayout(self.centralWidget)
        # On ajoute la barre du haut
        self.gridLayout.addLayout(self.horizontalLayoutBarreHaut, 0, 0, 1, 3)
        # On ajoute le gestionnaire d'onglets
        self.gridLayout.addWidget(self.tabWidget, 1, 0, 1, 3)
        # On ajoute la barre de progression de telechargement d'un fichier
        self.gridLayout.addWidget(self.progressBarTelechargementFichier, 2, 0,
                                  1, 3)
        # On ajoute la barre de progression de telechargement des fichiers
        self.gridLayout.addWidget(self.progressBarTelechargement, 3, 0, 1, 3)
        # On ajoute les boutons ajouter/supprimer/lancer
        self.gridLayout.addLayout(self.horizontalLayoutBarreBas, 4, 0, 1, 3)

        ###
        # Mise en place le central widget dans la fenetre
        ###
        self.setCentralWidget(self.centralWidget)

        ###
        # Mise en place du menu
        ###

        # Menu barre
        self.menubar = QtGui.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 480, 25))

        # Menu Fichier
        self.menuFichier = QtGui.QMenu("&Fichier", self.menubar)
        self.menubar.addAction(self.menuFichier.menuAction())

        # Action Fichier -> Quitter
        self.actionQuitter = QtGui.QAction(QtGui.QIcon("ico/gtk-quit.svg"),
                                           "&Quitter", self)
        self.actionQuitter.setIconVisibleInMenu(True)
        self.menuFichier.addAction(self.actionQuitter)

        # Menu Edition
        self.menuEdition = QtGui.QMenu("&Edition", self.menubar)
        self.menubar.addAction(self.menuEdition.menuAction())

        # Action Edition -> Mise a jour
        self.actionMAJ = QtGui.QAction(QtGui.QIcon("ico/gtk-refresh.svg"),
                                       u"&Mise à jour des plugins", self)
        self.actionMAJ.setIconVisibleInMenu(True)
        self.menuEdition.addAction(self.actionMAJ)

        # Action Edition -> Preferences
        self.actionPreferences = QtGui.QAction(
            QtGui.QIcon("ico/gtk-preferences.svg"), u"&Préférences", self)
        self.actionPreferences.setIconVisibleInMenu(True)
        self.menuEdition.addAction(self.actionPreferences)

        # Menu Aide
        self.menuAide = QtGui.QMenu("&Aide", self.menubar)
        self.menubar.addAction(self.menuAide.menuAction())

        # Action Aide -> A propos
        self.actionAPropos = QtGui.QAction(QtGui.QIcon("ico/gtk-about.svg"),
                                           u"À p&ropos", self)
        self.actionAPropos.setIconVisibleInMenu(True)
        self.menuAide.addAction(self.actionAPropos)

        # Ajout du menu a l'interface
        self.setMenuBar(self.menubar)

        ###
        # Signaux provenants de l'interface
        ###

        QtCore.QObject.connect(self.tableWidgetFichier,
                               QtCore.SIGNAL("cellClicked(int,int)"),
                               self.afficherInformationsFichier)

        QtCore.QObject.connect(self.tableWidgetFichier,
                               QtCore.SIGNAL("cellDoubleClicked(int,int)"),
                               self.gererTelechargement)

        QtCore.QObject.connect(self.pushButtonToutAjouter,
                               QtCore.SIGNAL("clicked()"),
                               self.ajouterTousLesFichiers)

        QtCore.QObject.connect(self.pushButtonRafraichirPlugin,
                               QtCore.SIGNAL("clicked()"),
                               self.rafraichirPlugin)

        QtCore.QObject.connect(self.tableWidgetTelechargement,
                               QtCore.SIGNAL("cellDoubleClicked(int,int)"),
                               self.supprimerTelechargement)

        QtCore.QObject.connect(
            self.pushButtonExtremiteMonter,
            QtCore.SIGNAL("clicked()"),
            lambda versLeHaut=True, extremite=True: self.
            tableWidgetTelechargement.deplacerLigne(versLeHaut, extremite))

        QtCore.QObject.connect(
            self.pushButtonMonter,
            QtCore.SIGNAL("clicked()"),
            lambda versLeHaut=True, extremite=False: self.
            tableWidgetTelechargement.deplacerLigne(versLeHaut, extremite))

        QtCore.QObject.connect(
            self.pushButtonDescendre,
            QtCore.SIGNAL("clicked()"),
            lambda versLeHaut=False, extremite=False: self.
            tableWidgetTelechargement.deplacerLigne(versLeHaut, extremite))

        QtCore.QObject.connect(
            self.pushButtonExtremiteDescendre,
            QtCore.SIGNAL("clicked()"),
            lambda versLeHaut=False, extremite=True: self.
            tableWidgetTelechargement.deplacerLigne(versLeHaut, extremite))

        QtCore.QObject.connect(self.pushButtonToutSupprimer,
                               QtCore.SIGNAL("clicked()"),
                               self.supprimerTousLesTelechargements)

        QtCore.QObject.connect(self.pushButtonNettoyer,
                               QtCore.SIGNAL("clicked()"), self.nettoyer)

        QtCore.QObject.connect(self.pushButtonLancer,
                               QtCore.SIGNAL("clicked()"),
                               self.lancerTelechargement)

        QtCore.QObject.connect(self.pushButtonStop, QtCore.SIGNAL("clicked()"),
                               self.stopperTelechargement)

        QtCore.QObject.connect(self.actionQuitter,
                               QtCore.SIGNAL("triggered()"), self.close)

        ################################################
        # Instanciations + initialisation de variables #
        ################################################

        # Fenetre About
        self.aProposDialog = None
        # Fenetre des preferences du logiciel
        self.preferencesDialog = None
        # Fenetre de mise a jour des plugins
        self.updateManagerDialog = None
        # Nom plugin courant
        self.nomPluginCourant = ""
        # Liste des fichiers
        self.listeFichiers = []
        # Liste des fichiers a telecharger
        self.listeFichiersATelecharger = []
        # Cache des images descriptive
        # Clef : urlImage Valeur : image (binaire)
        self.cacheImage = {}

        # On intancie le lanceur de signaux
        self.signaux = Signaux()
        # On instancie le gestionnaire de preferences
        self.preferences = Preferences()
        # On instancie le gestionnaire de preferences des plugins
        self.preferencesPluginDialog = PreferencePluginDialog(self)
        # On instancie le gestionnaire de download
        self.downloader = Downloader(self.signaux)
        # On recupere l'instance de API
        self.api = API.getInstance()
        # On instancie le gestionnaire d'historique
        self.historique = Historique()
        # On instancie la fenetre d'attente
        self.fenetreAttenteProgressDialog = FenetreAttenteProgressDialog(self)
        # On instancie le gest

        #
        # Fenetre de confirmation pour quitter le logiciel
        #
        self.quitterMessageBox = QtGui.QMessageBox(self)
        self.quitterMessageBox.setWindowTitle("Fermeture de TVDownloader")
        self.quitterMessageBox.setText(
            u"Voulez-vous réellement quitter TVDownloader ?")
        self.quitterMessageBox.setInformativeText(
            u"Votre liste de téléchargement sera perdue")
        self.quitterMessageBox.addButton("Oui", QtGui.QMessageBox.AcceptRole)
        self.quitterMessageBox.addButton("Non", QtGui.QMessageBox.RejectRole)

        ############################################################
        # On connecte les signaux des instances precedements crees #
        ############################################################

        QtCore.QObject.connect(self.pushButtonOuvrirDossierTelechargement,
                               QtCore.SIGNAL("clicked()"),
                               self.ouvrirRepertoireTelechargement)

        QtCore.QObject.connect(self.comboBoxSite,
                               QtCore.SIGNAL("activated(QString)"),
                               self.listerChaines)

        QtCore.QObject.connect(self.comboBoxChaine,
                               QtCore.SIGNAL("activated(QString)"),
                               self.listerEmissions)

        QtCore.QObject.connect(self.comboBoxEmission,
                               QtCore.SIGNAL("activated(QString)"),
                               self.listerFichiers)

        QtCore.QObject.connect(self.pushButtonPreferencesPlugin,
                               QtCore.SIGNAL("clicked()"),
                               self.ouvrirPreferencesPlugin)

        QtCore.QObject.connect(self.actionPreferences,
                               QtCore.SIGNAL("triggered()"),
                               self.ouvrirPreferencesLogiciel)

        QtCore.QObject.connect(self.actionMAJ, QtCore.SIGNAL("triggered()"),
                               self.ouvrirFenetreMiseAJour)

        QtCore.QObject.connect(self.actionAPropos,
                               QtCore.SIGNAL("triggered()"),
                               self.ouvrirFenetreAPropos)

        QtCore.QObject.connect(
            self.signaux, QtCore.SIGNAL("debutActualisation(PyQt_PyObject)"),
            self.fenetreAttenteProgressDialog.ouvrirFenetreAttente)
        QtCore.QObject.connect(
            self.signaux, QtCore.SIGNAL("finActualisation()"),
            self.fenetreAttenteProgressDialog.fermerFenetreAttente)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("actualiserListesDeroulantes()"),
                               self.actualiserListesDeroulantes)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("listeChaines(PyQt_PyObject)"),
                               self.ajouterChaines)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("listeEmissions(PyQt_PyObject)"),
                               self.ajouterEmissions)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("listeFichiers(PyQt_PyObject)"),
                               self.ajouterFichiers)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("nouvelleImage(PyQt_PyObject)"),
                               self.mettreEnPlaceImage)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("debutTelechargement(int)"),
                               self.debutTelechargement)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("finTelechargement(int)"),
                               self.finTelechargement)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("finDesTelechargements()"),
                               self.activerDesactiverInterface)
        QtCore.QObject.connect(self.signaux,
                               QtCore.SIGNAL("pourcentageFichier(int)"),
                               self.progressBarTelechargementFichier.setValue)

        #########
        # Début #
        #########

        # La fenetre prend la dimension qu'elle avait a sa fermeture
        taille = self.preferences.getPreference("tailleFenetre")
        self.resize(taille[0], taille[1])

        # Si aucun plugin n'est active, on ouvre la fenetre des preferences
        if (len(self.preferences.getPreference("pluginsActifs")) == 0):
            self.ouvrirPreferencesLogiciel()

        # On actualise tous les plugins
        self.rafraichirTousLesPlugins()
Esempio n. 19
0
    def __init__(self, signaux=None):
        self.preferences = Preferences()
        self.signaux = signaux

        self.arreter = True
        self.process = None
Esempio n. 20
0
	log = log[:len(log)-4]+'done\n'



# check if log directorie exist, otherwise create it and create a log file anyway
if not os.path.exists(os.getcwd()+'/log/'):
	log += 'No log directorie, create it: fail'
	os.mkdir(os.getcwd()+'/log')
	log = log[:len(log)-4]+'done\n'
log = Log(start,log)


# check Preferences file exist: create it if necessary and open it
if not os.path.exists(os.getcwd()+'/preferences'):
	log.write('no preferences file, create default file : ', '')
	preferences = Preferences()
	savePreferences(preferences)
	log.write('done')
else:
	log.write('get saved preferences : ', '')
	with open(os.getcwd()+'/preferences','r') as prefFile:
		preferences = Preferences( xmlMod.fromstring( (prefFile.read( ) ) ) )
	log.write('done')



# check task list file exist: create it if necessary and open it
if not os.path.exists(os.getcwd()+'/Tasks'):
	log.write('no task list file, create default file empty file : ', '')
	tasks = TaskList()
	saveTasks(tasks)
class WordFrequencies:
###############################################################################################
# Members
###############################################################################################
    namesSet = set()
    wordDict = WordDict()
    namesDict = {} #{ name : ( count , last occurence ) }
    # wordsPerDayDict = {} #{ word : { 'count': count , 'lastOccurence': last occurence } } only counts one occurence per day
    wordsPerDayDict = WordsPerDayDict()
    namesPerDayDict = {} #{ word : ( count , last occurence ) }
    namesToGraphDict = {} #{ word : [ [ date , count ] ] }
    namesToGraphDictUniqueOccurences = {} #{ word : [ date ] }
    wordCountOfEntriesDict = {} #{ date : word count }
    relatedNamesDict = {} #{ name : { name : unique day count } }
    lastNamesForFirstNameDict = {} #{ first name : [ last names ] }
    totalNumberOfWords = 0
    dayEntryHashTable = {} #{ date : hash }

    firstDate = datetime.datetime(datetime.MAXYEAR,12,31)
    mostRecentDate = datetime.datetime(datetime.MINYEAR,1,1)

    namesURL = os.path.dirname(os.path.realpath(__file__)) + '/names.txt'
    prefs = Preferences() #stored the user's preferences for various things
    printer = PrintHelper(prefs)


###############################################################################################
# Loading and Setup
###############################################################################################    


###############################################################################################
# Data Processing
###############################################################################################
    #parse a line and add the words to the dictionaries
    #print the line to markunder file, with the proper qualification on names
    #all markunder printing should happen here
    def addLine(self, line, currentDate):
        # markunderFile = open(self.markUnderFilePath, 'a')

        words = line.split(' ')

        wordsToCount = 0 #used to calculate the length of entries - don't want to include invalid words in the word count TODO: rethink this?
        namesFound = set()
        for word in words:
            if word == '' or word == None or re.compile('^\s+$').search(word) != None:
                continue

            (beforeStuff, word, afterStuff) = Helper.cleanWordForInitialAdd(word)

            word = WordClass(word) #words are represented by the WordClass, which is basically an encapsulation of normal words and markup names in one object

            if self.prefs.COMBINE_PLURALS:
                if word.endswith("'s"):
                    word = WordClass.addWordOrMarkup(word.toString()[:len(word)-2]) #TODO: this is broken

            wasUpper = False;
            if word.toString()[:1].isupper():
                wasUpper = True;
            originalWord = word
            word = Helper.cleanWord(word) #this strips off all punctuation and other information that we want to pass into markup.

            if not Helper.valid(word):
                continue
            wordsToCount += 1

            #names
            if word in self.namesSet and (Preferences.REQUIRE_CAPS_FOR_NAMES and wasUpper):
                namesFound.add(word)

                try:
                    self.namesDict[word] = (self.namesDict[word][0] + 1, currentDate)
                except:
                    self.namesDict[word] = (1, currentDate)

                #names per day
                try:
                    if self.namesPerDayDict[word][1] != currentDate:
                        self.namesPerDayDict[word] = (self.namesPerDayDict[word][0] + 1, currentDate)
                except:
                    self.namesPerDayDict[word] = (1, currentDate)

                #names for graphing purposes
                try: #{ word : [ [ date , count ] ] }
                    self.namesToGraphDict[word] #trigger exception
                    if self.namesToGraphDict[word][-1][0] == currentDate: #increment count
                        self.namesToGraphDict[word][-1][1] += 1
                    else: #start a new tuple with a new date
                        self.namesToGraphDict[word].append([currentDate, 1])
                except: #this name hasn't been encountered yet
                    self.namesToGraphDict[word] = [[currentDate, 1]]

                #names for graph, counting on unique occurences
                try: #{ word : [ date ] }
                    self.namesToGraphDictUniqueOccurences[word].append(currentDate)
                except:
                    self.namesToGraphDictUniqueOccurences[word] = [currentDate]

            #words
            if self.wordDict.exists(word):
                self.wordDict.addOrReplaceWord(word, self.wordDict.getCount(word) + 1, currentDate, self.wordDict.getFirstOccurrence(word), wasUpper)
            else:
                self.wordDict.addWord(word, 1, currentDate, currentDate, wasUpper) #TODO: wasUpper wasn't there originally
            
            #words per day
            if self.wordsPerDayDict.exists(word):
                self.wordsPerDayDict.addWord(word, self.wordsPerDayDict.getCount(word), currentDate) #TODO: was addOrReplaceWord, need to think what it should be
            else:
                self.wordsPerDayDict(word, 1, currentDate)

            #TODO: this is being moved to its own class to be called separately
            # if self.prefs.DO_MARK_UNDER:
            #     #if it's a name, qualify it for the markunder
            #     if word in self.namesSet:# or not (Preferences.REQUIRE_CAPS_FOR_NAMES and wasUpper):
            #         markUnderWord = self.getMarkUnderWord(word, originalWord, line, currentDate)
            #     else:
            #         markUnderWord = word

            #     markunderFile.write(markUnderWord + ' ')

        # markunderFile.close()
        return (wordsToCount, namesFound)


###############################################################################################
# Graphing and Printing
###############################################################################################
    #print the x most occuring words
    #num: number to print. if 'all', prints all
    #TODO: it would be nice to move at least part of this function to the printer class
    def printHighest(self, args, option):
        if self.prefs.VERBOSE:
            print('args: ', end=' ')
            print(args)
            print('option: ', end=' ')
            print(option)

        if option == PrintOption.RELATED:
            nameForRelated = args[0]
            args = args[1:]
            if len(args) < 1:
                print('Too few arguments.')
                return
            if self.prefs.VERBOSE:
                print('nameForRelated: ' + nameForRelated)

        start_num = 0
        end_num = 0
        index1 = 0
        index2 = 1

        if len(args) == 1: #only an end num
            try:
                if (args[index1] == 'all'):
                    end_num = float('inf')
                else:
                    end_num = int(args[index1])
            except:
                print('Invalid arguments')
                return
        elif len(args) >= 2: #start and end
            try:
                start_num = int(args[index1])
                if (args[index2] == 'all'):
                    end_num = float('inf')
                else:
                    end_num = int(args[index2])
            except:
                print('Invalid arguments')
                return

        if self.prefs.VERBOSE:
            print('start_num: ', end=' ')
            print(start_num, end=' ')
            print(' end_num ', end=' ')
            print(end_num)

        #TODO: add headers to all cases
        if option == PrintOption.NAMES:
            sortedNamesDict = sorted(list(self.namesDict.items()), key=operator.itemgetter(1))
            sortedNamesDict.reverse()
            end_num = min(end_num, len(sortedNamesDict))
            self.printer.makePrettyHeader('Word', 'Count', 'Last Occurence')
            for x in range(start_num, end_num):
                self.printer.makeOutputPretty(sortedNamesDict[x])
        elif option == PrintOption.RELATED:
            #TODO: deal with 'all' here, since it won't be caught earlier
            sortedRelatedNamesDict = sorted(list(self.relatedNamesDict[nameForRelated].items()), key=operator.itemgetter(1))
            sortedRelatedNamesDict.reverse()
            print('Related names for ' + nameForRelated + ':\n')
            self.printer.makePrettyHeader('Name', 'Count')
            end_num = min(end_num, len(sortedRelatedNamesDict))
            for x in range(start_num, end_num):
                self.printer.makeOutputPrettyRelated(sortedRelatedNamesDict[x])
        elif option == PrintOption.WORDSPERDAY:
            sortedWordsPerDayDict = self.wordsPerDayDict.getSortedDictByCount()
            sortedWordsPerDayDict.reverse()
            end_num = min(end_num, len(sortedWordsPerDayDict))
            self.printer.makePrettyHeader('Word', 'Count', 'Last Occurence')
            for x in range(start_num, end_num):
                self.printer.makeOutputPrettyWPD(sortedWordsPerDayDict[x])
        elif option == PrintOption.NAMESPERDAY:
            sortedNamesPerDayDict = sorted(list(self.namesPerDayDict.items()), key=operator.itemgetter(1))
            sortedNamesPerDayDict.reverse()
            end_num = min(end_num, len(sortedNamesPerDayDict))
            self.printer.makePrettyHeader('Name', 'Count', 'Last Occurence')
            for x in range(start_num, end_num):
                self.printer.makeOutputPretty(sortedNamesPerDayDict[x])
        elif option == PrintOption.LENGTH:
            sortedLengthOfEntriesDict = sorted(list(self.wordCountOfEntriesDict.items()), key=operator.itemgetter(1))
            sortedLengthOfEntriesDict.reverse()
            end_num = min(end_num, len(sortedLengthOfEntriesDict))
            self.printer.makePrettyHeader('Date', 'Count')
            for x in range(start_num, end_num):
                self.printer.makeOutputPrettyLength(sortedLengthOfEntriesDict[x])
        else: #regular words
            self.printer.makePrettyHeader('Word', 'Count', 'Last Occurence')
            sortedWordsDict = self.wordDict.getSortedDictByCount()
            sortedWordsDict.reverse()
            end_num = min(end_num, len(sortedWordsDict))
            for x in range(start_num, end_num):
                self.printer.makeOutputPrettyWordsDict(sortedWordsDict[x])


    #graphs the number of occurences of the name per day
    def graphAnalytics(self, args):
        #{ word : [ [ date , count ] ] }
        name = args[0]
        try:
            self.namesToGraphDict[name]
        except:
            print('Invalid input - must be a valid name')
            return
        try:
            x = [date[0] for date in self.namesToGraphDict[name]]
            y = [count[1] for count in self.namesToGraphDict[name]]
            
            ax = plt.subplot(111)
            ax.bar(x, y, width=2)
            ax.xaxis_date()

            plt.show()
        except:
            print('Unknown error occured while graphing')

    #graphs a bar for each day that an entry exists
    def graphEntries(self, args):
        #{ date : word count }
        sortedLengthOfEntriesDict = sorted(list(self.wordCountOfEntriesDict.items()), key=operator.itemgetter(1))
        x = [i[0] for i in sortedLengthOfEntriesDict]
        y = [1 for j in sortedLengthOfEntriesDict]
        self.graphHelper(x, y)

    def graphHelper(self, x, y):
        ax = plt.subplot(111)
        ax.bar(x, y, width=2)
        ax.xaxis_date()
        plt.show()

    def graphNameValue(self, in_dict):
        x = list(in_dict.keys())
        y = list(in_dict.values())
        self.graphHelper(x, y)

    def lookupWord(self, args):
        word = args[0]
        if not self.wordDict.exists(word):
            print('Invalid word')
            return
        print(word + ': ')
        print('First usage: ' + str(self.wordDict.getFirstOccurrence(word)))
        print('Last usage: ' + str(self.wordDict.getLastOccurrence(word)))
        total_uses = self.wordDict.getCount(word)
        total_days_used = self.wordsPerDayDict.getCount(word)
        total_number_of_days = len(self.wordCountOfEntriesDict)
        print('Total usages: ' + str(total_uses))
        print('Total days with at least one usage: ' + str(total_days_used))
        length = (self.wordDict.getLastOccurrence(word) - self.wordDict.getFirstOccurrence(word)).days
        print('Length from first use to last: ' + Helper.daysAsPrettyLength(length))
        print('Average usages per day: ' + str(float(total_uses) / length))
        print('Percentage of days with at least one useage: ' + str(round(float(total_days_used) / total_number_of_days * 100, 2)) + '%')

    def overallAnalytics(self):
        print('Total number of entries: ', end=' ')
        print(len(self.wordCountOfEntriesDict))
        print('First entry: ', end=' ')
        print(Helper.prettyPrintDate(self.firstDate))
        print('Last entry: ', end=' ')
        print(Helper.prettyPrintDate(self.mostRecentDate))
        print('Total days from first to last entry: ', end=' ')
        totalDays = self.mostRecentDate - self.firstDate #this is correct
        days = totalDays.days
        print(days)
        print('Percentage of days from first to last with an entry: ', end=' ')
        print(str(round(float(len(self.wordCountOfEntriesDict)) / days * 100, 2)) + '%')
        print('Average length per entry: ', end=' ')
        numberOfEntries = len(self.wordCountOfEntriesDict)
        sumOfLengths = 0
        longestEntryLength = 0
        for date in list(self.wordCountOfEntriesDict.keys()):
            length = self.wordCountOfEntriesDict[date]
            if length > longestEntryLength:
                longestEntryLength = length
                longestEntryDate = date
            sumOfLengths += length 
        print(round(float(sumOfLengths) / numberOfEntries, 2))
        print('Longest entry: ' + str(longestEntryLength) + ' words on ', end=' ')
        print(Helper.prettyPrintDate(longestEntryDate))
        print('Total number of words written: ', end=' ')
        print(locale.format("%d", self.totalNumberOfWords, grouping=True))



###############################################################################################
# Names
###############################################################################################
    def addRelatedNames(self, namesFound):
        #{ name : { name : unique day count } }
        for keyName in namesFound:
            for otherName in namesFound:
                if keyName == otherName:
                    continue
                try:
                    self.relatedNamesDict[keyName]
                except:
                    self.relatedNamesDict[keyName] = {}
                try: 
                    self.relatedNamesDict[keyName][otherName] += 1
                except:
                    self.relatedNamesDict[keyName][otherName] = 1

    #populate namesList from file
    def makeNamesSet(self):
        try:
            f = open(self.namesURL, 'r') #TODO: error handling
        except:
            raise Exception("Names file not found")
        self.namesSet.clear()
        line = f.readline()
        while line != '':
            self.namesSet.add(line.strip().lower()) #TODO: does this do anything? What?
            line = f.readline()
        f.close()

    #iterate over 
    def guessNamesHelper(self, guessedNamesSet):
        newNames = set()
        print('Are these names? (y/n)')
        for name in guessedNamesSet:
            if name in self.namesSet:
                break
            inp = input(name + ': ')
            if inp == 'y':
                newNames.add(name.lower())

        f = open(self.namesURL, 'r+')
        for name in newNames:
            f.write(name + '\n')
        f.close()

    #try to guess what is a name by looking for capitalized letters in the middle of sentences
    def guessNames(self, line, testFlag = False):
        guessedNamesSet = set()
        names = regex.findall('[^\.]\s+([ABCDEFGHIJKLMNOPQRSTUVWXYZ][\w]+)\W', line, overlapped=True)

        try: 
            for name in names:
                if name.lower() not in self.namesSet:
                    guessedNamesSet.add(name)
        except:
            return

        #want to return the guessedNamesSet here if this is running for a test 
        #TODO: figure out how to send more input during a test and get rid of this hack
        if testFlag:
            return guessedNamesSet
        self.guessNamesHelper(guessedNamesSet)

    #Add a name manually to the names set
    def addName(self, args):
        name = args[0]
        if name in self.namesDict:
            print("Name already added")
            return
        self.namesSet.add(name);
        f = open(self.namesURL, 'a')
        f.write('\n' + name)
        f.close()

    def removeName(self, name):
        self.namesSet.remove(name);
        f = open(self.namesURL, 'r+')
        f.clear()
        for name in self.namesSet:
            f.write(name) + '\n'
        f.close()


###############################################################################################
# Control Loop
###############################################################################################
    def main(self, args):
        self.mainSetup(args)
        self.runMainLoop()

    #break apart the main function for testing
    def mainSetup(self, args):
        locale.setlocale(locale.LC_ALL, 'en_US')
        fileurl = args.file

        if args.verbosity:
            self.prefs.VERBOSE = True
        if args.combineplurals:
            self.prefs.COMBINE_PLURALS = True
        if args.guessnames:
            self.prefs.GUESS_NAMES = True
        if args.markunder:
            self.prefs.DO_MARK_UNDER = True
            print('Set DO_MARK_UNDER=True')
#        if args.noMarkunder:
#            self.prefs.DO_MARK_UNDER = False
#            print 'Set DO_MARK_UNDER=False'

        self.makeNamesSet()
        self.readFile(fileurl)

    def runMainLoop(self):
        # if self.prefs.GUESS_NAMES:
        #     self.getGuessedNames()
        while True:
            print('''
    Options:
    Highest x words             highest [num | all] (num | all)
    Highest x words per day     wpd [num | all]
    Lookup                      lookup [word]
    Highest x names             names [num | all]
    Related Names               related [name] [num | all]
    Highest x names per day     npd [num | all]
    Graph names                 graph [name]
    Graph entries               graphentries
    Graph length                graphlength
    Add name                    add name [name]
    Set Options                 option [option_name] [value]
    Length                      length [num | all]
    Overall analytics           overall
    Exit                        exit
    ''')
            if not self.parseInput(input('>')):
                return

    def parseInput(self, inpStr):
        parts = inpStr.split()
        command = parts[0].lower().strip().lstrip()
        args = parts[1:]
        if (self.prefs.VERBOSE):
            print('Parsed arguments: command: ' + str(command) + ' args: ' + str(args))
        return self.callInputFunction(command, args)

    def readFile(self, url):
        try:
            f = open(url, 'r')
        except:
            print('File not found')
            newPath = input('Enter new path > ');
            return self.readFile(newPath) #TODO: this doesn't work for entirely unknown reasons

        newdate = re.compile('\s*([0-9]{1,2}-[0-9]{1,2}-[0-9]{2})\s*')
        currentDateStr = None
        currentDateObj = None
        numWords = 0
        namesFound = set()
        totalWordNum = 0

        currentDayEntry = '' #holds all the lines for the current day, so we can compute a hash of the day later on
        
        line = f.readline()
        while (line != ''):
            if self.prefs.GUESS_NAMES:
                self.guessNames(line)
            #check a line to see if it's a date, therefore a new day
            dateFound = newdate.match(line)
            if dateFound != None: #it's a new date, so wrapup the previous date and set up to move onto the next one
                if namesFound != None:
                    self.addRelatedNames(namesFound)
                    namesFound = set()
                    self.dayEntryHashTable[currentDateObj] = hashlib.md5(currentDayEntry.encode()) #TODO: deal with first date

                if numWords > 0:
                    self.wordCountOfEntriesDict[currentDateObj] = numWords #should be here, since we want it triggered at the end
                totalWordNum += numWords
                numWords = 0
                currentDateStr = dateFound.group(0)
                currentDateStr = Helper.formatDateStringIntoCleanedString(currentDateStr)
                currentDateObj = Helper.makeDateObject(currentDateStr)

                if currentDateObj > self.mostRecentDate: #found a higher date than what we've seen so far
                    self.mostRecentDate = currentDateObj
                if currentDateObj < self.firstDate: #found a lower date than what we have now
                    self.firstDate = currentDateObj
                line = line[len(currentDateStr):] #remove date from line, so it's not a word

            if currentDateStr != None:
                (wordsFound, namesFoundThisLine) = self.addLine(line, currentDateObj)
                for name in namesFoundThisLine:
                    namesFound.add(name)
                numWords += wordsFound
            line = f.readline()
            currentDayEntry += line #add line to the day's entry

        #need to capture the last date for the entry length
        self.wordCountOfEntriesDict[currentDateObj] = numWords 
        self.totalNumberOfWords = totalWordNum + numWords #need to get words from last line
        f.close()

    #args is a list of arguments in order
    def callInputFunction(self, inp, args):
        if inp == CommandOptions.HIGHEST.value:
            self.printHighest(args, None)
        elif inp == CommandOptions.LOOKUP.value:
            self.lookupWord(args)
        elif inp == CommandOptions.NAMES.value:
            self.printHighest(args, PrintOption.NAMES)
        elif inp == CommandOptions.RELATED.value:
            self.printHighest(args, PrintOption.RELATED)
        elif inp == CommandOptions.GRAPH.value:
            self.graphAnalytics(args)
        elif inp == CommandOptions.GRAPH_ENTRIES.value:
            self.graphEntries(args)
        # elif inp == 'gpd':
        #     self.graphAnalyticsPerDay(args)
        elif inp == CommandOptions.WPD.value:
            self.printHighest(args, PrintOption.WORDSPERDAY)
        elif inp == CommandOptions.NPD.value:
            self.printHighest(args, PrintOption.NAMESPERDAY)
        elif inp == CommandOptions.ADDNAME.value:
            self.addName(args)
        elif inp == CommandOptions.OPTION.value:
            print("Setting options isn't supported yet")
            pass
        elif inp == CommandOptions.LENGTH.value:
            self.printHighest(args, PrintOption.LENGTH)
        elif inp == CommandOptions.GRAPH_LENGTH.value:
            self.graphNameValue(self.wordCountOfEntriesDict)
        elif inp == CommandOptions.OVERALL.value:
            self.overallAnalytics()
        elif inp == CommandOptions.EXIT.value:
            return False
        else:
            print('Unknown command.')
        return True