Esempio n. 1
0
    def _init (cls):
        def callback (widget, allocation):
            cls.widgets["enterGameNotationFrame"].set_size_request(
                    223, allocation.height-4)
        cls.widgets["enterGameNotationSidePanel"].connect_after("size-allocate", callback)

        flags = []
        if isInstalled():
            path = gettext.find("pychess")
        else:
            path = gettext.find("pychess", localedir=addDataPrefix("lang"))
        if path:
            loc = locale.getdefaultlocale()[0][-2:].lower()
            flags.append(addDataPrefix("flags/%s.png" % loc))

        flags.append(addDataPrefix("flags/us.png"))

        cls.ib = ImageButton(flags)
        cls.widgets["imageButtonDock"].add(cls.ib)
        cls.ib.show()

        cls.sourcebuffer = GtkSource.Buffer()
        sourceview = GtkSource.View.new_with_buffer(cls.sourcebuffer)
        sourceview.set_tooltip_text(
            _("Type or paste PGN game or FEN positions here"))
        cls.widgets["scrolledwindow6"].add(sourceview)
        sourceview.show()

        # Pgn format does not allow tabulator
        sourceview.set_insert_spaces_instead_of_tabs(True)
        sourceview.set_wrap_mode(Gtk.WrapMode.WORD)

        man = GtkSource.LanguageManager()
        # Init new version
        if hasattr(man.props, 'search_path'):
            try:
                path = os.path.join(getDataPrefix(),"gtksourceview-1.0/language-specs")
                man.props.search_path = man.props.search_path + [path]
                if 'pgn' in man.get_language_ids():
                    lang = man.get_language('pgn')
                    cls.sourcebuffer.set_language(lang)
                else:
                    log.warning("Unable to load pgn syntax-highlighting.")
                cls.sourcebuffer.set_highlight_syntax(True)
            except NotImplementedError:
                # Python 2.7.3 in Ubuntu 12.04
                log.warning("Unable to load pgn syntax-highlighting.")
        # Init old version
        else:
            os.environ["XDG_DATA_DIRS"] = getDataPrefix()+":/usr/share/"
            man = LanguageManager()
            for lang in man.get_available_languages():
                if lang.get_name() == "PGN":
                    cls.sourcebuffer.set_language(lang)
                    break
            else:
                log.warning("Unable to load pgn syntax-highlighting.")
            cls.sourcebuffer.set_highlight(True)
Esempio n. 2
0
    def _init(cls):
        def callback(widget, allocation):
            cls.widgets["enterGameNotationFrame"].set_size_request(
                223, allocation.height - 4)

        cls.widgets["enterGameNotationSidePanel"].connect_after(
            "size-allocate", callback)

        flags = []
        if isInstalled():
            path = gettext.find("pychess")
        else:
            path = gettext.find("pychess", localedir=addDataPrefix("lang"))
        if path:
            loc = locale.getdefaultlocale()[0][-2:].lower()
            flags.append(addDataPrefix("flags/%s.png" % loc))

        flags.append(addDataPrefix("flags/us.png"))

        cls.ib = ImageButton(flags)
        cls.widgets["imageButtonDock"].add(cls.ib)
        cls.ib.show()

        cls.sourcebuffer = GtkSource.Buffer()
        sourceview = GtkSource.View.new_with_buffer(cls.sourcebuffer)
        sourceview.set_tooltip_text(
            _("Type or paste PGN game or FEN positions here"))
        cls.widgets["scrolledwindow6"].add(sourceview)
        sourceview.show()

        # Pgn format does not allow tabulator
        sourceview.set_insert_spaces_instead_of_tabs(True)
        sourceview.set_wrap_mode(Gtk.WrapMode.WORD)

        man = GtkSource.LanguageManager()
        # Init new version
        if hasattr(man.props, 'search_path'):
            path = os.path.join(getDataPrefix(),
                                "gtksourceview-1.0/language-specs")
            man.props.search_path = man.props.search_path + [path]
            if 'pgn' in man.get_language_ids():
                lang = man.get_language('pgn')
                cls.sourcebuffer.set_language(lang)
            else:
                log.warning("Unable to load pgn syntax-highlighting.")
            cls.sourcebuffer.set_highlight_syntax(True)
        # Init old version
        else:
            os.environ["XDG_DATA_DIRS"] = getDataPrefix() + ":/usr/share/"
            man = LanguageManager()
            for lang in man.get_available_languages():
                if lang.get_name() == "PGN":
                    cls.sourcebuffer.set_language(lang)
                    break
            else:
                log.warning("Unable to load pgn syntax-highlighting.")
            cls.sourcebuffer.set_highlight(True)
Esempio n. 3
0
    def __findRundata (self, engine):
        """ Searches for a readable, executable named 'name' in the PATH.
            For the PyChess engine, special handling is taken, and we search
            PYTHONPATH as well as the directory from where the 'os' module is
            imported """        
        if engine.get("vm_name") is not None:          
            altpath = engine.get("vm_command")
            if getattr(sys, 'frozen', False) and engine["vm_name"] == "wine":
                vmpath = None
            else:
                vmpath = searchPath(engine["vm_name"], access=os.R_OK|os.X_OK, altpath = altpath)
            
            if engine["name"] == "PyChess.py" and not getattr(sys, 'frozen', False):
                path = join(abspath(dirname(__file__)), "PyChess.py")
                if not os.access(path, os.R_OK):
                    path = None
            else:
                altpath = engine.get("command")
                path = searchPath(engine["name"], access=os.R_OK, altpath=altpath)
            
            if vmpath and path:
                return vmpath, path
            elif path and sys.platform == "win32" and engine.get("vm_name") == "wine":
                return None, path

        else:
            altpath = engine.get("command")
            if sys.platform == "win32" and not altpath:
                altpath = os.path.join(getDataPrefix(), "engines", engine["name"])
            path = searchPath(engine["name"], access=os.R_OK|os.X_OK, altpath=altpath)
            if path:
                return None, path       
        return False
Esempio n. 4
0
    def __init__(self):
        self.libgtb = None
        self.initialized = False

        # Get a list of files in the tablebase folder.
        configuredTbPath = conf.get("egtb_path", "")
        tbPath = configuredTbPath or getDataPrefix()
        try:
            tbPathContents = os.listdir(tbPath)
        except OSError as e:
            if configuredTbPath:
                log.warning("Unable to open Gaviota TB folder: %s" % repr(e))
            return

        # Find files named *.gtb.cp# and pick the most common "#".
        # (This is the compression scheme; the library currently only uses one at a time.)
        schemeCount = [0] * 10
        for filename in tbPathContents:
            match = re.search("\.gtb\.cp(\d)$", filename)
            if match:
                schemeCount[int(match.group(1))] += 1
        compressionScheme = max(zip(schemeCount, range(10)))
        if compressionScheme[0] == 0:
            if configuredTbPath:
                log.warning("Could not find any Gaviota TB files in %s" %
                            configuredTbPath)
            return
        compressionScheme = compressionScheme[1]

        # Locate and load the library.
        if not self._loadLibrary():
            return
        self._setupFunctionPrototypes()

        self.pathList = self.tbpaths_init()
        self.pathList = self.tbpaths_add(self.pathList, tbPath.encode())
        initInfo = self.tb_init(True, compressionScheme, self.pathList)
        self.initialized = (self.tb_is_initialized() != 0)
        if not self.initialized:
            log.warning(initInfo
                        or "Failed to initialize Gaviota EGTB library")
            self.pathList = self.tbpaths_done(self.pathList)
            return
        elif initInfo:
            log.info(initInfo)

        # TODO: Set up a WDL cache area once the engine can use it.
        self.initialized &= self.tbcache_init(4 * 1024 * 1024, 0)
        if not self.initialized:
            log.warning("Failed to initialize Gaviota EGTB cache")
            self.tb_done()
            self.pathList = self.tbpaths_done(self.pathList)
            return

        self.availability = self.tb_availability()
Esempio n. 5
0
    def __init__(self):
        self.libgtb = None
        self.initialized = False

        # Get a list of files in the tablebase folder.
        configuredTbPath = conf.get("egtb_path", "")
        tbPath = configuredTbPath or getDataPrefix()
        try:
            tbPathContents = os.listdir(tbPath)
        except OSError as e:
            if configuredTbPath:
                log.warning("Unable to open Gaviota TB folder: %s" % repr(e))
            return

        # Find files named *.gtb.cp# and pick the most common "#".
        # (This is the compression scheme; the library currently only uses one at a time.)
        schemeCount = [0] * 10
        for filename in tbPathContents:
            match = re.search("\.gtb\.cp(\d)$", filename)
            if match:
                schemeCount[int(match.group(1))] += 1
        compressionScheme = max(zip(schemeCount, range(10)))
        if compressionScheme[0] == 0:
            if configuredTbPath:
                log.warning("Could not find any Gaviota TB files in %s" %
                            configuredTbPath)
            return
        compressionScheme = compressionScheme[1]

        # Locate and load the library.
        if not self._loadLibrary():
            return
        self._setupFunctionPrototypes()

        self.pathList = self.tbpaths_init()
        self.pathList = self.tbpaths_add(self.pathList, tbPath.encode())
        initInfo = self.tb_init(True, compressionScheme, self.pathList)
        self.initialized = (self.tb_is_initialized() != 0)
        if not self.initialized:
            log.warning(initInfo or
                        "Failed to initialize Gaviota EGTB library")
            self.pathList = self.tbpaths_done(self.pathList)
            return
        elif initInfo:
            log.info(initInfo)

        # TODO: Set up a WDL cache area once the engine can use it.
        self.initialized &= self.tbcache_init(4 * 1024 * 1024, 0)
        if not self.initialized:
            log.warning("Failed to initialize Gaviota EGTB cache")
            self.tb_done()
            self.pathList = self.tbpaths_done(self.pathList)
            return

        self.availability = self.tb_availability()
    def __findRunData(self, engine):
        """ Searches for a readable, executable named 'name' in the PATH.
            For the PyChess engine, special handling is taken, and we search
            PYTHONPATH as well as the directory from where the 'os' module is
            imported """
        if engine.get("vm_name") is not None:
            vm_command = engine.get("vm_command")
            altpath = dirname(vm_command) if vm_command else None
            if getattr(sys, "frozen", False) and engine["vm_name"] == "wine":
                vmpath = None
            else:
                vmpath = shutil.which(engine["vm_name"],
                                      mode=os.R_OK | os.X_OK,
                                      path=altpath)

            if engine["name"] == "PyChess.py" and not getattr(
                    sys, "frozen", False):
                path = join(abspath(dirname(__file__)), "PyChess.py")
                if not vmpath.endswith(PYTHONBIN):
                    # from python to python3
                    engine["vm_name"] = PYTHONBIN
                    vmpath = shutil.which(PYTHONBIN,
                                          mode=os.R_OK | os.X_OK,
                                          path=None)
                if not os.access(path, os.R_OK):
                    path = None
            else:
                command = engine.get("command")
                altpath = dirname(command) if command else None
                path = shutil.which(engine["name"], mode=os.R_OK, path=altpath)

            if vmpath and path:
                return vmpath, path
            elif path and sys.platform == "win32" and engine.get(
                    "vm_name") == "wine":
                return None, path

        else:
            command = engine.get("command")
            altpath = dirname(command) if command else None
            if sys.platform == "win32" and not altpath:
                altpath = (os.path.join(getDataPrefix(), "engines") + ";" +
                           os.path.dirname(sys.executable))
            path = shutil.which(
                command if command else engine["name"],
                mode=os.R_OK | os.X_OK,
                path=altpath,
            )
            if path:
                return None, path
        return False
Esempio n. 7
0
    def __findRundata(self, engine):
        """ Searches for a readable, executable named 'name' in the PATH.
            For the PyChess engine, special handling is taken, and we search
            PYTHONPATH as well as the directory from where the 'os' module is
            imported """
        if engine.get("vm_name") is not None:
            altpath = engine.get("vm_command")
            if getattr(sys, 'frozen', False) and engine["vm_name"] == "wine":
                vmpath = None
            else:
                vmpath = searchPath(engine["vm_name"],
                                    access=os.R_OK | os.X_OK,
                                    altpath=altpath)

            if engine["name"] == "PyChess.py" and not getattr(
                    sys, 'frozen', False):
                path = join(abspath(dirname(__file__)), "PyChess.py")
                if not os.access(path, os.R_OK):
                    path = None
            else:
                altpath = engine.get("command")
                path = searchPath(engine["name"],
                                  access=os.R_OK,
                                  altpath=altpath)

            if vmpath and path:
                return vmpath, path
            elif path and sys.platform == "win32" and engine.get(
                    "vm_name") == "wine":
                return None, path

        else:
            altpath = engine.get("command")
            if sys.platform == "win32" and not altpath:
                altpath = os.path.join(getDataPrefix(), "engines",
                                       engine["name"])
            path = searchPath(engine["name"],
                              access=os.R_OK | os.X_OK,
                              altpath=altpath)
            if path:
                return None, path
        return False
Esempio n. 8
0
    def __findRundata(self, engine):
        """ Searches for a readable, executable named 'name' in the PATH.
            For the PyChess engine, special handling is taken, and we search
            PYTHONPATH as well as the directory from where the 'os' module is
            imported """
        if engine.get("vm_name") is not None:
            vm_command = engine.get("vm_command")
            altpath = dirname(vm_command) if vm_command else None
            if getattr(sys, 'frozen', False) and engine["vm_name"] == "wine":
                vmpath = None
            else:
                vmpath = shutil.which(engine["vm_name"], mode=os.R_OK | os.X_OK, path=altpath)

            if engine["name"] == "PyChess.py" and not getattr(sys, 'frozen', False):
                path = join(abspath(dirname(__file__)), "PyChess.py")
                if not vmpath.endswith(PYTHONBIN):
                    # from python to python3
                    engine["vm_name"] = PYTHONBIN
                    vmpath = shutil.which(PYTHONBIN, mode=os.R_OK | os.X_OK, path=None)
                if not os.access(path, os.R_OK):
                    path = None
            else:
                command = engine.get("command")
                altpath = dirname(command) if command else None
                path = shutil.which(engine["name"], mode=os.R_OK, path=altpath)

            if vmpath and path:
                return vmpath, path
            elif path and sys.platform == "win32" and engine.get("vm_name") == "wine":
                return None, path

        else:
            command = engine.get("command")
            altpath = dirname(command) if command else None
            if sys.platform == "win32" and not altpath:
                altpath = os.path.join(getDataPrefix(), "engines") + ";" + os.path.dirname(sys.executable)
            path = shutil.which(command if command else engine["name"], mode=os.R_OK | os.X_OK, path=altpath)
            if path:
                return None, path
        return False
Esempio n. 9
0
    def __init__(self, widgets):
        self.widgets = widgets

        # Options on by default
        for key in ("opening_check", "endgame_check", "online_egtb_check",
                    "analyzer_check", "inv_analyzer_check"):
            uistuff.keep(widgets[key], key, first_value=True)

        # Opening book
        default_path = os.path.join(addDataPrefix("pychess_book.bin"))
        path = conf.get("opening_file_entry", default_path)
        conf.set("opening_file_entry", path)

        book_chooser_dialog = Gtk.FileChooserDialog(
            _("Select book file"), mainwindow(), Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        book_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            book_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Opening books"))
        filter.add_pattern("*.bin")
        book_chooser_dialog.add_filter(filter)
        book_chooser_button.set_filename(path)

        self.widgets["bookChooserDock"].add(book_chooser_button)
        book_chooser_button.show()

        def select_new_book(button):
            new_book = book_chooser_dialog.get_filename()
            if new_book:
                conf.set("opening_file_entry", new_book)
            else:
                # restore the original
                book_chooser_dialog.set_filename(path)

        book_chooser_button.connect("file-set", select_new_book)

        def on_opening_check_toggled(check):
            self.widgets["opening_hbox"].set_sensitive(check.get_active())

        self.widgets["opening_check"].connect_after("toggled",
                                                    on_opening_check_toggled)

        # Endgame
        default_path = os.path.join(getDataPrefix())
        egtb_path = conf.get("egtb_path", default_path)
        conf.set("egtb_path", egtb_path)

        egtb_chooser_dialog = Gtk.FileChooserDialog(
            _("Select Gaviota TB path"), mainwindow(),
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        egtb_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            egtb_chooser_dialog)
        egtb_chooser_button.set_current_folder(egtb_path)

        self.widgets["egtbChooserDock"].add(egtb_chooser_button)
        egtb_chooser_button.show()

        def select_egtb(button):
            new_directory = egtb_chooser_dialog.get_filename()
            if new_directory != egtb_path:
                conf.set("egtb_path", new_directory)

        egtb_chooser_button.connect("current-folder-changed", select_egtb)

        def on_endgame_check_toggled(check):
            self.widgets["endgame_hbox"].set_sensitive(check.get_active())

        self.widgets["endgame_check"].connect_after("toggled",
                                                    on_endgame_check_toggled)

        # Analyzing engines
        from pychess.widgets import newGameDialog
        data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
        uistuff.createCombo(widgets["ana_combobox"], data, name="ana_combobox")
        uistuff.createCombo(widgets["inv_ana_combobox"],
                            data,
                            name="inv_ana_combobox")

        def update_analyzers_store(discoverer):
            data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
            uistuff.updateCombo(widgets["ana_combobox"], data)
            uistuff.updateCombo(widgets["inv_ana_combobox"], data)

        discoverer.connect_after("all_engines_discovered",
                                 update_analyzers_store)
        update_analyzers_store(discoverer)

        # Save, load and make analyze combos active

        # Let Stockfish to be default analyzer in Windows installer
        default = discoverer.getEngineN(-1).get("md5")
        conf.set("ana_combobox", conf.get("ana_combobox", default))
        conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", default))

        def on_analyzer_check_toggled(check):
            self.widgets["analyzers_vbox"].set_sensitive(check.get_active())
            from pychess.widgets.gamewidget import widgets
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio. async (
                            gmwidg.gamemodel.restart_analyzer(HINT))
                        if not widgets["hint_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(HINT)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(HINT)

        self.widgets["analyzers_vbox"].set_sensitive(
            widgets["analyzer_check"].get_active())
        self.widgets["analyzer_check"].connect_after(
            "toggled", on_analyzer_check_toggled)

        def on_invanalyzer_check_toggled(check):
            self.widgets["inv_analyzers_vbox"].set_sensitive(
                check.get_active())
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio. async (gmwidg.gamemodel.restart_analyzer(SPY))
                        if not widgets["spy_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(SPY)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(SPY)

        self.widgets["inv_analyzers_vbox"].set_sensitive(
            widgets["inv_analyzer_check"].get_active())
        self.widgets["inv_analyzer_check"].connect_after(
            "toggled", on_invanalyzer_check_toggled)

        # Give widgets to keeper

        uistuff.keep(
            self.widgets["ana_combobox"], "ana_combobox", anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(
                combobox, value, "hint_mode", "analyzer_check", HINT))
        uistuff.keep(
            self.widgets["inv_ana_combobox"], "inv_ana_combobox",
            anal_combo_get_value, lambda combobox, value: anal_combo_set_value(
                combobox, value, "spy_mode", "inv_analyzer_check", SPY))

        uistuff.keep(self.widgets["max_analysis_spin"],
                     "max_analysis_spin",
                     first_value=3)
Esempio n. 10
0
    def __init__(self, widgets):
        self.widgets = widgets

        # Options on by default
        for key in ("opening_check", "endgame_check", "online_egtb_check",
                    "analyzer_check", "inv_analyzer_check"):
            uistuff.keep(widgets[key], key, first_value=True)

        # Opening book
        default_path = os.path.join(addDataPrefix("pychess_book.bin"))
        path = conf.get("opening_file_entry", default_path)
        conf.set("opening_file_entry", path)

        book_chooser_dialog = Gtk.FileChooserDialog(
            _("Select book file"), None, Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        book_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            book_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Opening books"))
        filter.add_pattern("*.bin")
        book_chooser_dialog.add_filter(filter)
        book_chooser_button.set_filename(path)

        self.widgets["bookChooserDock"].add(book_chooser_button)
        book_chooser_button.show()

        def select_new_book(button):
            new_book = book_chooser_dialog.get_filename()
            if new_book:
                conf.set("opening_file_entry", new_book)
            else:
                # restore the original
                book_chooser_dialog.set_filename(path)

        book_chooser_button.connect("file-set", select_new_book)

        def on_opening_check_toggled(check):
            self.widgets["opening_hbox"].set_sensitive(check.get_active())

        self.widgets["opening_check"].connect_after("toggled",
                                                    on_opening_check_toggled)

        # Endgame
        default_path = os.path.join(getDataPrefix())
        egtb_path = conf.get("egtb_path", default_path)
        conf.set("egtb_path", egtb_path)

        egtb_chooser_dialog = Gtk.FileChooserDialog(
            _("Select Gaviota TB path"), None,
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        egtb_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            egtb_chooser_dialog)
        egtb_chooser_button.set_current_folder(egtb_path)

        self.widgets["egtbChooserDock"].add(egtb_chooser_button)
        egtb_chooser_button.show()

        def select_egtb(button):
            new_directory = egtb_chooser_dialog.get_filename()
            if new_directory != egtb_path:
                conf.set("egtb_path", new_directory)

        egtb_chooser_button.connect("current-folder-changed", select_egtb)

        def on_endgame_check_toggled(check):
            self.widgets["endgame_hbox"].set_sensitive(check.get_active())

        self.widgets["endgame_check"].connect_after("toggled",
                                                    on_endgame_check_toggled)

        # Analyzing engines
        from pychess.widgets import newGameDialog
        data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
        uistuff.createCombo(widgets["ana_combobox"], data, name="ana_combobox")
        uistuff.createCombo(widgets["inv_ana_combobox"], data, name="inv_ana_combobox")

        def update_analyzers_store(discoverer):
            data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
            uistuff.updateCombo(widgets["ana_combobox"], data)
            uistuff.updateCombo(widgets["inv_ana_combobox"], data)

        discoverer.connect_after("all_engines_discovered",
                                 update_analyzers_store)
        update_analyzers_store(discoverer)

        # Save, load and make analyze combos active

        # Let Stockfish to be default analyzer in Windows installer
        default = discoverer.getEngineN(-1).get("md5")
        conf.set("ana_combobox", conf.get("ana_combobox", default))
        conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", default))

        def on_analyzer_check_toggled(check):
            self.widgets["analyzers_vbox"].set_sensitive(check.get_active())
            from pychess.widgets.gamewidget import widgets
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio.async(gmwidg.gamemodel.restart_analyzer(HINT))
                        if not widgets["hint_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(HINT)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(HINT)

        self.widgets["analyzers_vbox"].set_sensitive(widgets[
            "analyzer_check"].get_active())
        self.widgets["analyzer_check"].connect_after("toggled",
                                                     on_analyzer_check_toggled)

        def on_invanalyzer_check_toggled(check):
            self.widgets["inv_analyzers_vbox"].set_sensitive(check.get_active())
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio.async(gmwidg.gamemodel.restart_analyzer(SPY))
                        if not widgets["spy_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(SPY)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(SPY)

        self.widgets["inv_analyzers_vbox"].set_sensitive(widgets[
            "inv_analyzer_check"].get_active())
        self.widgets["inv_analyzer_check"].connect_after(
            "toggled", on_invanalyzer_check_toggled)

        # Give widgets to keeper

        uistuff.keep(
            self.widgets["ana_combobox"], "ana_combobox", anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(combobox, value, "hint_mode", "analyzer_check", HINT))
        uistuff.keep(
            self.widgets["inv_ana_combobox"], "inv_ana_combobox",
            anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(combobox, value, "spy_mode", "inv_analyzer_check", SPY))

        uistuff.keep(self.widgets["max_analysis_spin"], "max_analysis_spin", first_value=3)
Esempio n. 11
0
 "saveRatingChange": False,
 "indentPgn": False,
 "saveOwnGames": True,
 "show_tip_at_startup": False,
 "dont_show_externals_at_startup": False,
 "max_analysis_spin": 3,
 "variation_threshold_spin": 50,
 "fromCurrent": True,
 "shouldWhite": True,
 "shouldBlack": True,
 "ThreatPV": False,
 "infinite_analysis": False,
 "opening_check": False,
 "opening_file_entry": default_book_path,
 "endgame_check": False,
 "egtb_path": os.path.join(getDataPrefix()),
 "online_egtb_check": True,
 "autoCallFlag": True,
 "hint_mode": False,
 "spy_mode": False,
 "ana_combobox": 0,
 "analyzer_check": True,
 "inv_ana_combobox": 0,
 "inv_analyzer_check": False,
 "newgametasker_playercombo": 0,
 "ics_combo": 0,
 "autoLogin": False,
 "standard_toggle": True,
 "blitz_toggle": True,
 "lightning_toggle": True,
 "variant_toggle": True,
Esempio n. 12
0
    def initGlade(self, log_viewer):
        #=======================================================================
        # Init glade and the 'GladeHandlers'
        #=======================================================================
        #Gtk.about_dialog_set_url_hook(self.website)
        widgets = uistuff.GladeWidgets("PyChess.glade")       
        widgets.getGlade().connect_signals(GladeHandlers.__dict__)

        tasker = TaskerManager()
        tasker.packTaskers (NewGameTasker(), InternetGameTasker())
        widgets["Background"].add(tasker)
        
        #------------------------------------------------------ Redirect widgets
        gamewidget.setWidgets(widgets)
        
        def on_sensitive_changed (widget, prop):
            name = widget.get_property('name')
            sensitive = widget.get_property('sensitive')
            #print "'%s' changed to '%s'" % (name, sensitive)
        widgets['pause1'].connect("notify::sensitive", on_sensitive_changed)
        widgets['resume1'].connect("notify::sensitive", on_sensitive_changed)
        #-------------------------- Main.py still needs a minimum of information
        ionest.handler.connect("gmwidg_created",
                               GladeHandlers.__dict__["on_gmwidg_created"])
        
        #---------------------- The only menuitems that need special initing
        for widget in ("hint_mode", "spy_mode"):
            widgets[widget].set_sensitive(False)

        uistuff.keep(widgets["hint_mode"], "hint_mode", first_value=True)
        uistuff.keep(widgets["spy_mode"], "spy_mode")
        uistuff.keep(widgets["show_sidepanels"], "show_sidepanels")
        uistuff.keep(widgets["auto_call_flag"], "autoCallFlag", first_value=True)
        
        #=======================================================================
        # Show main window and init d'n'd
        #=======================================================================
        widgets["window1"].set_title('%s - PyChess' % _('Welcome'))
        widgets["window1"].connect("key-press-event",
                                   GladeHandlers.__dict__["on_window_key_press"])
        uistuff.keepWindowSize("main", widgets["window1"], (575,479), POSITION_GOLDEN)
        widgets["window1"].show()
        widgets["Background"].show_all()
                
        flags = Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP
        # To get drag in the whole window, we add it to the menu and the
        # background. If it can be gotten to work, the drag_dest_set_proxy
        # method is very interesting.
        #widgets["menubar1"].drag_dest_set(flags, dnd_list, Gdk.DragAction.COPY)
        #widgets["Background"].drag_dest_set(flags, dnd_list, Gdk.DragAction.COPY)
        # TODO: http://code.google.com/p/pychess/issues/detail?id=737
        # The following two should really be set in the glade file
        #widgets["menubar1"].set_events(widgets["menubar1"].get_events() | Gdk.DRAG_STATUS)
        #widgets["Background"].set_events(widgets["Background"].get_events() | Gdk.DRAG_STATUS)
        
        #=======================================================================
        # Init 'minor' dialogs
        #=======================================================================
        
        #------------------------------------------------------------ Log dialog
        if log_viewer:
            from pychess.widgets import LogDialog
            LogDialog.add_destroy_notify(lambda: widgets["log_viewer1"].set_active(0))
        else:
            widgets["log_viewer1"].set_property('sensitive', False)
            
        #---------------------------------------------------------- About dialog
        self.aboutdialog = widgets["aboutdialog1"]
        self.aboutdialog.set_name(NAME)
        link = self.aboutdialog.get_website()
        self.aboutdialog.set_copyright("Copyright © 2006-2014")
        self.aboutdialog.set_version(VERSION_NAME+" "+VERSION)
        if os.path.isdir(prefix.addDataPrefix(".hg")):
            cmd = ["hg", "tip", "--cwd", prefix.getDataPrefix(), "--template", "{node|short} {date|isodate}"]
            process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            out = process.stdout.readline().split()
            if len(out)>=2:
                comments = self.aboutdialog.get_comments()
                self.hg_rev = out[0]
                self.hg_date = out[1]
                self.aboutdialog.set_comments("rev. %s\n%s\n%s" % (self.hg_rev, self.hg_date, comments))
        
        with open(prefix.addDataPrefix("ARTISTS")) as f:
            self.aboutdialog.set_artists(f.read().splitlines())
        with open(prefix.addDataPrefix("AUTHORS")) as f:
            self.aboutdialog.set_authors(f.read().splitlines())
        with open(prefix.addDataPrefix("DOCUMENTERS")) as f:
            self.aboutdialog.set_documenters(f.read().splitlines())
        with open(prefix.addDataPrefix("TRANSLATORS")) as f:
            self.aboutdialog.set_translator_credits(f.read())

        def on_about_response(dialog, response, *args):
            # system-defined GtkDialog responses are always negative, in which    
            # case we want to hide it
            if response < 0:
                self.aboutdialog.hide()
                self.aboutdialog.emit_stop_by_name('response')

        def on_about_close(widget, event=None):
            self.aboutdialog.hide()
            return True

        self.aboutdialog.connect("response", on_about_response)
        self.aboutdialog.connect("close", on_about_close)
        self.aboutdialog.connect("delete-event", on_about_close)

        #---------------------------------------------------- RecentChooser
        def recent_item_activated (self):
            uri = self.get_current_uri()
            try:
                urlopen(uri).close()
                newGameDialog.LoadFileExtension.run(self.get_current_uri())
            except (IOError, OSError):
                #shomething wrong whit the uri
                recentManager.remove_item(uri)
                
        #self.menu_recent = Gtk.RecentChooserMenu(recentManager)
        self.menu_recent = Gtk.RecentChooserMenu()
        self.menu_recent.set_show_tips(True)
        self.menu_recent.set_sort_type(Gtk.RecentSortType.MRU)
        self.menu_recent.set_limit(10)
        self.menu_recent.set_name("menu_recent")
        
        self.file_filter = Gtk.RecentFilter()
        self.file_filter.add_mime_type("application/x-chess-pgn")
        self.menu_recent.set_filter(self.file_filter)

        self.menu_recent.connect("item-activated", recent_item_activated)
        widgets["load_recent_game1"].set_submenu(self.menu_recent)
        
        #----------------------------------------------------- Discoverer dialog
        def discovering_started (discoverer, binnames):
            GObject.idle_add(DiscovererDialog.show, discoverer, widgets["window1"])
        discoverer.connect("discovering_started", discovering_started)
        DiscovererDialog.init(discoverer)
        discoverer.discover()
        
        #------------------------------------------------- Tip of the day dialog
        if conf.get("show_tip_at_startup", False):
            tipOfTheDay.TipOfTheDay.show()
Esempio n. 13
0
    def __init__ (self, widgets):
        self.widgets = widgets
    
        # Opening book
        default_path = os.path.join(addDataPrefix("pychess_book.bin"))
        path = conf.get("opening_file_entry", default_path)
        conf.set("opening_file_entry", path)

        book_chooser_dialog = gtk.FileChooserDialog(_("Select book file"), None, gtk.FILE_CHOOSER_ACTION_OPEN,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        book_chooser_button = gtk.FileChooserButton(book_chooser_dialog)

        filter = gtk.FileFilter()
        filter.set_name(_("Opening books"))
        filter.add_pattern("*.bin")
        book_chooser_dialog.add_filter(filter)
        book_chooser_button.set_filename(path)

        self.widgets["bookChooserDock"].add(book_chooser_button)
        book_chooser_button.show()
        
        def select_new_book(button):
            new_book = book_chooser_dialog.get_filename()
            if new_book:
                conf.set("opening_file_entry", new_book)
            else:
                # restore the original
                book_chooser_dialog.set_filename(path)
                
        book_chooser_button.connect("file-set", select_new_book)

        def on_opening_check_toggled (check):
            widgets["opening_hbox"].set_sensitive(check.get_active())
        widgets["opening_check"].connect_after("toggled",
                                                on_opening_check_toggled)
        uistuff.keep(widgets["opening_check"], "opening_check")

        # Endgame
        conf.set("online_egtb_check", conf.get("online_egtb_check", 0))
        uistuff.keep(widgets["online_egtb_check"], "online_egtb_check")

        default_path = os.path.join(getDataPrefix())
        egtb_path = conf.get("egtb_path", default_path)
        conf.set("egtb_path", egtb_path)

        egtb_chooser_dialog = gtk.FileChooserDialog(_("Select Gaviota TB path"), None, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        egtb_chooser_button = gtk.FileChooserButton(egtb_chooser_dialog)
        egtb_chooser_button.set_current_folder(egtb_path)

        self.widgets["egtbChooserDock"].add(egtb_chooser_button)
        egtb_chooser_button.show()

        def select_egtb(button):
            new_directory = egtb_chooser_dialog.get_filename()
            if new_directory != egtb_path:
                conf.set("egtb_path", new_directory)

        egtb_chooser_button.connect("current-folder-changed", select_egtb)

        def on_endgame_check_toggled (check):
            widgets["endgame_hbox"].set_sensitive(check.get_active())
        
        widgets["endgame_check"].connect_after("toggled",
                                                on_endgame_check_toggled)
        uistuff.keep(widgets["endgame_check"], "endgame_check")

        # Analyzing engines
        uistuff.createCombo(widgets["ana_combobox"])
        uistuff.createCombo(widgets["inv_ana_combobox"])

        from pychess.widgets import newGameDialog
        def update_analyzers_store(discoverer):
            data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
            uistuff.updateCombo(widgets["ana_combobox"], data)
            uistuff.updateCombo(widgets["inv_ana_combobox"], data)
        glock_connect_after(discoverer, "all_engines_discovered",
                            update_analyzers_store)
        update_analyzers_store(discoverer)

        # Save, load and make analyze combos active
        
        conf.set("ana_combobox", conf.get("ana_combobox", 0))
        conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", 0))
        
        def on_analyzer_check_toggled (check):
            widgets["analyzers_vbox"].set_sensitive(check.get_active())
            from pychess.Main import gameDic
            if gameDic:
                if check.get_active():
                    for gmwidg in gameDic.keys():
                        gmwidg.gamemodel.restart_analyzer(HINT)
                else:
                    for gmwidg in gameDic.keys():
                        gmwidg.gamemodel.remove_analyzer(HINT)
        
        widgets["analyzer_check"].connect_after("toggled",
                                                on_analyzer_check_toggled)
        uistuff.keep(widgets["analyzer_check"], "analyzer_check")
        
        def on_invanalyzer_check_toggled (check):
            widgets["inv_analyzers_vbox"].set_sensitive(check.get_active())
            from pychess.Main import gameDic
            if gameDic:
                if check.get_active():
                    for gmwidg in gameDic.keys():
                        gmwidg.gamemodel.restart_analyzer(SPY)
                else:
                    for gmwidg in gameDic.keys():
                        gmwidg.gamemodel.remove_analyzer(SPY)

        widgets["inv_analyzer_check"].connect_after("toggled",
                                              on_invanalyzer_check_toggled)
        uistuff.keep(widgets["inv_analyzer_check"], "inv_analyzer_check")
        
        # Give widgets to keeper
        
        def get_value (combobox):
            engine = list(discoverer.getAnalyzers())[combobox.get_active()]
            return engine.get("md5")
        
        def set_value (combobox, value, show_arrow_check, ana_check, analyzer_type):
            engine = discoverer.getEngineByMd5(value)
            if engine is None:
                combobox.set_active(0)
                # This return saves us from the None-engine being used
                # in later code  -Jonas Thiem
                return
            else:
                try:
                    index = list(discoverer.getAnalyzers()).index(engine)
                except ValueError:
                    index = 0
                combobox.set_active(index)
            
            replace_analyzers = False
            if widgets[show_arrow_check].get_active() is True and \
                    widgets[ana_check].get_active() is True:
                replace_analyzers = True
            
            from pychess.Main import gameDic
            for gmwidg in gameDic.keys():
                spectators = gmwidg.gamemodel.spectators
                md5 = engine.get('md5')
                
                if analyzer_type in spectators and \
                        spectators[analyzer_type].md5 != md5:
                    gmwidg.gamemodel.remove_analyzer(analyzer_type)
                    if replace_analyzers:
                        gmwidg.gamemodel.start_analyzer(analyzer_type)
        
        uistuff.keep(widgets["ana_combobox"], "ana_combobox", get_value,
            lambda combobox, value: set_value(combobox, value, "hint_mode",
                                              "analyzer_check", HINT))
        uistuff.keep(widgets["inv_ana_combobox"], "inv_ana_combobox", get_value,
            lambda combobox, value: set_value(combobox, value, "spy_mode",
                                              "inv_analyzer_check", SPY))
Esempio n. 14
0
    def initGlade(self, log_viewer):
        #=======================================================================
        # Init glade and the 'GladeHandlers'
        #=======================================================================
        #Gtk.about_dialog_set_url_hook(self.website)
        widgets = uistuff.GladeWidgets("PyChess.glade")
        widgets.getGlade().connect_signals(GladeHandlers.__dict__)

        tasker = TaskerManager()
        tasker.packTaskers(NewGameTasker(), InternetGameTasker())
        widgets["Background"].add(tasker)

        #------------------------------------------------------ Redirect widgets
        gamewidget.setWidgets(widgets)

        def on_sensitive_changed(widget, prop):
            name = widget.get_property('name')
            sensitive = widget.get_property('sensitive')
            #print "'%s' changed to '%s'" % (name, sensitive)

        widgets['pause1'].connect("notify::sensitive", on_sensitive_changed)
        widgets['resume1'].connect("notify::sensitive", on_sensitive_changed)
        #-------------------------- Main.py still needs a minimum of information
        ionest.handler.connect("gmwidg_created",
                               GladeHandlers.__dict__["on_gmwidg_created"])

        #---------------------- The only menuitems that need special initing
        for widget in ("hint_mode", "spy_mode"):
            widgets[widget].set_sensitive(False)

        uistuff.keep(widgets["hint_mode"], "hint_mode", first_value=True)
        uistuff.keep(widgets["spy_mode"], "spy_mode")
        uistuff.keep(widgets["show_sidepanels"], "show_sidepanels")
        uistuff.keep(widgets["auto_call_flag"],
                     "autoCallFlag",
                     first_value=True)

        #=======================================================================
        # Show main window and init d'n'd
        #=======================================================================
        widgets["window1"].set_title('%s - PyChess' % _('Welcome'))
        widgets["window1"].connect(
            "key-press-event", GladeHandlers.__dict__["on_window_key_press"])
        uistuff.keepWindowSize("main", widgets["window1"], (575, 479),
                               POSITION_GOLDEN)
        widgets["window1"].show()
        widgets["Background"].show_all()

        flags = Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP
        # To get drag in the whole window, we add it to the menu and the
        # background. If it can be gotten to work, the drag_dest_set_proxy
        # method is very interesting.
        #widgets["menubar1"].drag_dest_set(flags, dnd_list, Gdk.DragAction.COPY)
        #widgets["Background"].drag_dest_set(flags, dnd_list, Gdk.DragAction.COPY)
        # TODO: http://code.google.com/p/pychess/issues/detail?id=737
        # The following two should really be set in the glade file
        #widgets["menubar1"].set_events(widgets["menubar1"].get_events() | Gdk.DRAG_STATUS)
        #widgets["Background"].set_events(widgets["Background"].get_events() | Gdk.DRAG_STATUS)

        #=======================================================================
        # Init 'minor' dialogs
        #=======================================================================

        #------------------------------------------------------------ Log dialog
        if log_viewer:
            from pychess.widgets import LogDialog
            LogDialog.add_destroy_notify(
                lambda: widgets["log_viewer1"].set_active(0))
        else:
            widgets["log_viewer1"].set_property('sensitive', False)

        #---------------------------------------------------------- About dialog
        self.aboutdialog = widgets["aboutdialog1"]
        self.aboutdialog.set_name(NAME)
        link = self.aboutdialog.get_website()
        self.aboutdialog.set_copyright("Copyright © 2006-2014")
        self.aboutdialog.set_version(VERSION_NAME + " " + VERSION)
        if os.path.isdir(prefix.addDataPrefix(".hg")):
            cmd = [
                "hg", "tip", "--cwd",
                prefix.getDataPrefix(), "--template",
                "{node|short} {date|isodate}"
            ]
            process = subprocess.Popen(cmd,
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE)
            out = process.stdout.readline().split()
            if len(out) >= 2:
                comments = self.aboutdialog.get_comments()
                self.hg_rev = out[0]
                self.hg_date = out[1]
                self.aboutdialog.set_comments(
                    "rev. %s\n%s\n%s" % (self.hg_rev, self.hg_date, comments))

        with open(prefix.addDataPrefix("ARTISTS")) as f:
            self.aboutdialog.set_artists(f.read().splitlines())
        with open(prefix.addDataPrefix("AUTHORS")) as f:
            self.aboutdialog.set_authors(f.read().splitlines())
        with open(prefix.addDataPrefix("DOCUMENTERS")) as f:
            self.aboutdialog.set_documenters(f.read().splitlines())
        with open(prefix.addDataPrefix("TRANSLATORS")) as f:
            self.aboutdialog.set_translator_credits(f.read())

        def on_about_response(dialog, response, *args):
            # system-defined GtkDialog responses are always negative, in which
            # case we want to hide it
            if response < 0:
                self.aboutdialog.hide()
                self.aboutdialog.emit_stop_by_name('response')

        def on_about_close(widget, event=None):
            self.aboutdialog.hide()
            return True

        self.aboutdialog.connect("response", on_about_response)
        self.aboutdialog.connect("close", on_about_close)
        self.aboutdialog.connect("delete-event", on_about_close)

        #---------------------------------------------------- RecentChooser
        def recent_item_activated(self):
            uri = self.get_current_uri()
            try:
                urlopen(uri).close()
                newGameDialog.LoadFileExtension.run(self.get_current_uri())
            except (IOError, OSError):
                #shomething wrong whit the uri
                recentManager.remove_item(uri)

        #self.menu_recent = Gtk.RecentChooserMenu(recentManager)
        self.menu_recent = Gtk.RecentChooserMenu()
        self.menu_recent.set_show_tips(True)
        self.menu_recent.set_sort_type(Gtk.RecentSortType.MRU)
        self.menu_recent.set_limit(10)
        self.menu_recent.set_name("menu_recent")

        self.file_filter = Gtk.RecentFilter()
        self.file_filter.add_mime_type("application/x-chess-pgn")
        self.menu_recent.set_filter(self.file_filter)

        self.menu_recent.connect("item-activated", recent_item_activated)
        widgets["load_recent_game1"].set_submenu(self.menu_recent)

        #----------------------------------------------------- Discoverer dialog
        def discovering_started(discoverer, binnames):
            GObject.idle_add(DiscovererDialog.show, discoverer,
                             widgets["window1"])

        discoverer.connect("discovering_started", discovering_started)
        DiscovererDialog.init(discoverer)
        discoverer.discover()

        #------------------------------------------------- Tip of the day dialog
        if conf.get("show_tip_at_startup", False):
            tipOfTheDay.TipOfTheDay.show()
Esempio n. 15
0
###############################################################################
# Set up translations

import gettext, locale

# http://stackoverflow.com/questions/3678174/python-gettext-doesnt-load-translations-on-windows
if sys.platform.startswith('win'):
    if os.getenv('LANG') is None:
        lang, enc = locale.getdefaultlocale()
        os.environ['LANG'] = lang

locale.setlocale(locale.LC_ALL, '')

domain = "pychess"
if isInstalled():
    locale_dir = os.path.join(os.path.dirname(getDataPrefix()), "locale")
    if PY2:
        gettext.install(domain, unicode=1, names=('ngettext',))
    else:
        gettext.install(domain, names=('ngettext',))
else:
    locale_dir = addDataPrefix("lang")
    if PY2:
        gettext.install(domain, localedir=locale_dir, unicode=1, names=('ngettext',))
    else:
        gettext.install(domain, localedir=locale_dir, names=('ngettext',))

# http://stackoverflow.com/questions/10094335/how-to-bind-a-text-domain-to-a-local-folder-for-gettext-under-gtk3
if sys.platform == "win32":
    from ctypes import cdll
    libintl = cdll.LoadLibrary("libintl-8")