Skip to content

xpuz.pages.browser ¤

GUI page for searching, viewing and loading available crosswords, as well as exporting loaded crosswords.

BrowserPage ¤

BrowserPage(master: Base)

Bases: CTkFrame, Addons

Provides an interface to view available crosswords, set a preference for the word count, generate a crossword based on the selected parameters, and launch the crossword webapp to complete the generated crossword.

Source code in src/xpuz/pages/browser.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def __init__(self, master: Base) -> None:
    super().__init__(
        Base.base_container,
        fg_color=(Colour.Light.MAIN, Colour.Dark.MAIN),
    )
    self.master = master
    self.master._set_dim()
    self._set_fonts()
    self._width, self._height = (
        self.master.winfo_width(),
        self.master.winfo_height(),
    )

    self.grid_rowconfigure(0, minsize=self._height * 0.15, weight=1)
    self.grid_rowconfigure(1, minsize=self._height * 0.85, weight=1)
    self.grid_columnconfigure(0, weight=1)

    if (
        not CrosswordWrapper.helper
    ):  # Set the CrosswordWrapper helper method
        CrosswordWrapper.helper = GUIHelper

    self.launch_options_on: bool = False
    self.webapp_on: bool = False

    self.wc_pref: IntVar = IntVar()  # Word count preference
    self.wc_pref.set(-1)

    self.browser_views = [_("Categorised"), _("Flattened")]
    self.browser_view_pref: StringVar = (
        StringVar()
    )  # Browser view preference
    self.browser_view_pref.set(_(Base.cfg.get("m", "browser_view")))

    self.app_views = [_("Browser"), _("Embedded")]
    self.app_view_pref: StringVar = StringVar()  # App view preference
    self.app_view_pref.set(_(Base.cfg.get("m", "app_view")))

    self.exports = [_("PDF"), _("ipuz")]
    self.export_pref: StringVar = StringVar()  # Export preference
    self.export_pref.set(_(Base.cfg.get("m", "export")))

    self.webview = None  # Store webview instance
    self.webview_open: bool = False

    # Notify user the first time they open this page
    if Base.cfg.get("misc", "browser_opened") == "0":
        GUIHelper.show_messagebox(first_time_browser=True)
        _update_cfg(Base.cfg, "misc", "browser_opened", "1")

_configure_word_count_prefs ¤

_configure_word_count_prefs(state: str) -> None

Configure all the word_count preference widgets to an either an interactive or disabled state (interactive when selecting a crossword, disabled when a crossword has been loaded).

Source code in src/xpuz/pages/browser.py
524
525
526
527
528
529
530
531
532
def _configure_word_count_prefs(self, state: str) -> None:
    """Configure all the word_count preference widgets to an either an
    interactive or disabled state (interactive when selecting a crossword,
    disabled when a crossword has been loaded).
    """
    self.l_wc_prefs.configure(state=state)
    self.rb_max_wc.configure(state=state)
    self.rb_custom_wc.configure(state=state)
    self.opts_custom_wc.configure(state=state)

_handle_scroll ¤

_handle_scroll(
    event: Event, container: CTkScrollableFrame
) -> None

Scroll the center scroll frame only if the viewable width is greater than the scroll region. This prevents weird scroll behaviour in cases where the above condition is inverted.

Source code in src/xpuz/pages/browser.py
464
465
466
467
468
469
470
471
472
473
474
475
def _handle_scroll(
    self, event: Event, container: CTkScrollableFrame
) -> None:
    """Scroll the center scroll frame only if the viewable width is greater
    than the scroll region. This prevents weird scroll behaviour in cases
    where the above condition is inverted.
    """
    scroll_region = container._parent_canvas.cget("scrollregion")
    viewable_width = container._parent_canvas.winfo_width()
    if scroll_region and int(scroll_region.split(" ")[2]) > viewable_width:
        # -1 * event.delta emulates a "natural" scrolling motion
        container._parent_canvas.xview("scroll", -1 * event.delta, "units")

_load ¤

_load() -> None

Gather data and use _create_app to initialise the Flask app on a new thread.

Source code in src/xpuz/pages/browser.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
def _load(self) -> None:
    """Gather data and use ``_create_app`` to initialise the Flask app on a
    new thread.
    """
    (
        self.starting_word_positions,
        self.starting_word_matrix,
        self.definitions_a,
        self.definitions_d,
    ) = _interpret_cword_data(self.cwrapper.crossword)
    colour_palette: Dict[str, str] = _get_colour_palette(
        get_appearance_mode()
    )
    _create_app(
        locale=Base.locale,
        scaling=self.master._get_widget_scaling(),
        colour_palette=colour_palette,
        json_colour_palette=dumps(colour_palette),
        port=Base.cfg.get("misc", "webapp_port"),
        name=self.cwrapper.translated_name,
        category=self.cwrapper.category,
        difficulty=self.cwrapper.difficulty,
        empty=EMPTY,
        directions=[ACROSS, DOWN],
        # Tuples in intersections must be removed. Changing this in
        # ``crossword.py`` was annoying, so it is done here instead.
        intersections=[
            list(item) if isinstance(item, tuple) else item
            for sublist in self.cwrapper.crossword.intersections
            for item in sublist
        ],
        word_count=self.cwrapper.word_count,
        failed_insertions=self.cwrapper.crossword.fails,
        dimensions=self.cwrapper.crossword.dimensions,
        starting_word_positions=self.starting_word_positions,
        starting_word_matrix=self.starting_word_matrix,
        grid=self.cwrapper.crossword.grid,
        definitions_a=self.definitions_a,
        definitions_d=self.definitions_d,
        js_err_msgs=[
            _("To perform this operation, you must first select a cell.")
        ],
        uuid=str(uuid4()),
    )

_on_cword_selection ¤

_on_cword_selection(wrapper: CrosswordWrapper) -> None

Called by an instance of CrosswordBlock, which passes the data for its given crossword into this method. The method then saves this data, deselects any previous word count radiobutton selections, reconfigures the values of the custom word count optionmenu to be compatible with the newly selected crossword, and reconfigures the max word count label to show the correct maximum word count.

Source code in src/xpuz/pages/browser.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
def _on_cword_selection(self, wrapper: CrosswordWrapper) -> None:
    """Called by an instance of ``CrosswordBlock``, which passes the
    data for its given crossword into this method. The method then saves
    this data, deselects any previous word count radiobutton selections,
    reconfigures the values of the custom word count optionmenu to be
    compatible with the newly selected crossword, and reconfigures the
    max word count label to show the correct maximum word count.
    """
    if not self.launch_options_on:
        self._configure_word_count_prefs("normal")
        self.launch_options_on: bool = True

    self.b_load_cword.configure(state="disabled")
    self.opts_custom_wc.configure(state="disabled")
    self.wc_pref.set(-1)
    self.opts_custom_wc.set(_("Select word count"))

    self.cwrapper = wrapper

    self.opts_custom_wc.configure(
        values=[
            str(numbers.format_decimal(num, locale=Base.locale))
            for num in range(3, self.cwrapper.total_definitions + 1)
        ]
    )
    self.rb_max_wc.configure(
        text=f"{_('Maximum')}: "
        f"{numbers.format_decimal(self.cwrapper.total_definitions, locale=Base.locale)}"
    )
    self.rb_max_wc.invoke()

_on_wc_sel ¤

_on_wc_sel(button_name: str) -> None

Configure custom word count optionmenu based on radiobutton selection.

Source code in src/xpuz/pages/browser.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
def _on_wc_sel(self, button_name: str) -> None:
    """Configure custom word count optionmenu based on radiobutton selection."""
    if button_name == "max":
        self.cwrapper.set_word_count(self.cwrapper.total_definitions)

        self.opts_custom_wc.set(_("Select word count"))
        self.opts_custom_wc.configure(state="disabled")

    else:
        self.cwrapper.set_word_count(3)

        self.opts_custom_wc.set(
            f"{str(numbers.format_decimal(3, locale=Base.locale))}"
        )
        self.opts_custom_wc.configure(state="normal")

    self.b_load_cword.configure(state="normal")

_on_webview_close ¤

_on_webview_close() -> None

Update self.webview_open to false when the user closes the webview.

Source code in src/xpuz/pages/browser.py
534
535
536
537
538
def _on_webview_close(self) -> None:
    """Update ``self.webview_open`` to false when the user closes the
    webview.
    """
    self.webview_open = False

_open_app_embedded ¤

_open_app_embedded(url: str) -> None

Start a webview with the webview module.

Source code in src/xpuz/pages/browser.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
def _open_app_embedded(self, url: str) -> None:
    """Start a webview with the ``webview`` module."""
    import webview

    self.webview = webview.create_window(
        _("Crossword Puzzle - Game"),
        url,
        width=self.master.winfo_screenwidth(),
        height=int(self.master.winfo_screenheight() * 0.925),
        x=0,
        y=0,
    )
    self.webview.events.closed += self._on_webview_close
    webview.start()

_reset_scroll_frame ¤

_reset_scroll_frame() -> None

Set the x position of the center scroll frame to the start.

Source code in src/xpuz/pages/browser.py
414
415
416
def _reset_scroll_frame(self) -> None:
    """Set the x position of the center scroll frame to the start."""
    self.block_container._parent_canvas.xview("moveto", 0.0)
_reset_search() -> None

Remove all text from the search box and regenerate the placeholder text.

Source code in src/xpuz/pages/browser.py
406
407
408
409
410
411
412
def _reset_search(self) -> None:
    """Remove all text from the search box and regenerate the placeholder
    text.
    """
    self.master.focus_force()
    self.e_search.delete(0, "end")
    self.e_search.configure(placeholder_text=f"{_('Search')} [↵]")

_rollback_states ¤

_rollback_states() -> None

Set all the widgets back to their default states (seen when opening the crossword browser).

Source code in src/xpuz/pages/browser.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
def _rollback_states(self) -> None:
    """Set all the widgets back to their default states (seen when opening
    the crossword browser).
    """
    if hasattr(
        self, "cwrapper"
    ):  # User selected a crossword, meaning they
        # had a category open, so this must be done
        if self.cwrapper.category_object:
            self.cwrapper.category_object.b_close.configure(state="normal")
        CrosswordBlock._config_selectors(state="normal")

    self.sb_browser_view.configure(state="normal")
    self.opts_app_view.configure(state="disabled")
    self.opts_export.configure(state="disabled")
    self.l_app_view.configure(state="disabled")
    self.l_export.configure(state="disabled")
    self.b_terminate_webapp.configure(state="disabled")
    self.b_open_webapp.grid_forget()
    self.b_load_cword.grid(row=1, column=0, sticky="nsew", padx=30, pady=7)
    self.b_load_cword.configure(state="disabled")
    self.b_export.configure(state="disabled")
    self.b_export.configure(image=self.export_img_states[1])
    self._configure_word_count_prefs("disabled")
    self.rb_max_wc.configure(text=f"{_('Maximum')}:")
    self.opts_custom_wc.set(_("Select word count"))
    self.wc_pref.set(-1)
    self.launch_options_on: bool = False

_search_crossword ¤

_search_crossword(query: str) -> None

Regenerate all the crossword blocks based on a crossword name query.

Source code in src/xpuz/pages/browser.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def _search_crossword(self, query: str) -> None:
    """Regenerate all the crossword blocks based on a crossword name query."""
    if self.browser_view_pref.get() != _(
        "Flattened"
    ):  # Only works in Flattened view
        return

    self._rollback_states()
    # Remove all blocks
    CategoryBlock._set_all(CategoryBlock._remove_block)
    CrosswordBlock._set_all(CrosswordBlock._remove_block)
    self._reset_scroll_frame()
    # Populate the info scroll container with all blocks that match ``query``
    CrosswordBlock._populate_all(self, query)

_update_segbutton_text_colours ¤

_update_segbutton_text_colours(
    view: str, sb: CTkSegmentedButton
) -> None

Configure all segmented button colours in sb to have a black text colour if unselected, otherwise, set the text colour to white.

Source code in src/xpuz/pages/browser.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def _update_segbutton_text_colours(
    self, view: str, sb: CTkSegmentedButton
) -> None:
    """Configure all segmented button colours in ``sb`` to have
    a black text colour if unselected, otherwise, set the text colour to
    white.
    """

    if get_appearance_mode().casefold() != "light":
        return

    for button in sb._buttons_dict.values():
        if button.cget("text") != _(view):
            button.configure(text_color="black")
        else:
            button.configure(text_color="white")

change_browser_view ¤

change_browser_view(callback: Optional = None) -> None

Change the browser view to Flattened or Categorical.

Source code in src/xpuz/pages/browser.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
def change_browser_view(self, callback: Optional = None) -> None:
    """Change the browser view to Flattened or Categorical."""

    self._rollback_states()
    # Remove existing blocks
    CategoryBlock._set_all(CategoryBlock._remove_block)
    CrosswordBlock._set_all(CrosswordBlock._remove_block)
    self._reset_scroll_frame()
    view = _get_english_string(
        BASE_ENG_BROWSER_VIEWS,
        self.browser_views,
        _(self.browser_view_pref.get()),
    )

    self._update_segbutton_text_colours(view, self.sb_browser_view)
    self._reset_search()
    if view == "Categorised":
        self.e_search.configure(
            state="disabled", placeholder_text_color=("gray72", "gray42")
        )
        CategoryBlock._populate(self)
    elif view == "Flattened":
        self.e_search.configure(
            state="normal", placeholder_text_color=("gray52", "gray62")
        )
        CrosswordBlock._populate_all(self)

    _update_cfg(Base.cfg, "m", "browser_view", view)

load ¤

load() -> None

Initialise the crossword and web app.

Source code in src/xpuz/pages/browser.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def load(self) -> None:
    """Initialise the crossword and web app."""
    self.cwrapper.make()
    if self.cwrapper.err_flag:  # Error in crossword generation, exit func
        return

    # It is safe to update widget states as crossword generation was OK
    self.b_load_cword.grid_forget()
    if self.cwrapper.category_object:
        self.cwrapper.category_object.b_close.configure(state="disabled")
        self.cwrapper.category_object.selected_cword.set(-1)
    else:
        CrosswordBlock.global_selected_cword.set(-1)
    CrosswordBlock._config_selectors(state="disabled")
    self._configure_word_count_prefs("disabled")
    self.sb_browser_view.configure(state="disabled")
    self.e_search.configure(state="disabled")

    self._load()
    self.webapp_on: bool = True

    self.b_open_webapp.grid(
        row=1, column=0, sticky="nsew", padx=30, pady=7
    )
    self.b_terminate_webapp.configure(state="normal")
    self.opts_app_view.configure(state="normal")
    self.opts_export.configure(state="normal")
    self.l_app_view.configure(state="normal")
    self.l_export.configure(state="normal")
    self.b_export.configure(state="normal")
    self.b_export.configure(image=self.export_img_states[0])

open_app ¤

open_app() -> None

Open the crossword web app at a port read from Base.cfg.

Source code in src/xpuz/pages/browser.py
555
556
557
558
559
560
561
562
563
564
565
566
567
def open_app(self) -> None:
    """Open the crossword web app at a port read from ``Base.cfg``."""
    _read_cfg(Base.cfg)

    url = f"http://127.0.0.1:{Base.cfg.get('misc', 'webapp_port')}/"
    app_view = BASE_ENG_APP_VIEWS[
        self.app_views.index(self.opts_app_view.get())
    ]

    if app_view == BASE_ENG_APP_VIEWS[0]:
        open_new_tab(url)
    else:
        self._open_app_embedded(url)

terminate ¤

terminate() -> None

Reconfigure the states of the GUIs buttons and terminate the app.

Source code in src/xpuz/pages/browser.py
569
570
571
572
573
574
575
576
577
578
579
580
581
def terminate(self) -> None:
    """Reconfigure the states of the GUIs buttons and terminate the app."""
    self.b_open_webapp.grid_forget()
    self._rollback_states()
    if Base.cfg.get("m", "browser_view") == "Flattened":
        self.e_search.configure(state="normal")
    self.sb_browser_view.configure(state="normal")
    if self.webview:
        if self.webview_open:
            self.webview.destroy()
        self.webview = None
    _terminate_app()
    self.webapp_on: bool = False

unbind_ ¤

unbind_() -> None

Remove bindings which can be detected on different pages.

Source code in src/xpuz/pages/browser.py
386
387
388
389
def unbind_(self) -> None:
    """Remove bindings which can be detected on different pages."""
    self.block_container.unbind_all("<MouseWheel")
    self.e_search.unbind("<Return>")

CategoryBlock ¤

CategoryBlock(
    container: CTkScrollableFrame,
    master: BrowserPage,
    name: str,
    fp: PathLike,
    value: int,
)

Bases: CTkFrame, Addons, BlockUtils

A frame containing the name of a crossword category and a buttons to open/close all the crosswords contained within that category. Opening a category block will remove all other category blocks and display only the crosswords within that category.

Source code in src/xpuz/pages/browser.py
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
def __init__(
    self,
    container: CTkScrollableFrame,
    master: BrowserPage,
    name: str,
    fp: PathLike,
    value: int,
) -> None:
    super().__init__(
        container,
        corner_radius=10,
        fg_color=(Colour.Light.MAIN, Colour.Dark.MAIN),
        border_color=(Colour.Light.SUB, Colour.Dark.SUB),
        border_width=3,
    )
    self.master = master
    self.name = name
    self.fp = fp
    self.value = value

    self.selected_cword = IntVar()
    self.selected_cword.set(-1)

    self._set_fonts()
    self._check_info()
    self._make_content()
    self._place_content()

_close ¤

_close() -> None

Remove all crossword info blocks, and regenerate the category blocks.

Source code in src/xpuz/pages/browser.py
842
843
844
845
846
847
848
849
850
851
852
def _close(self) -> None:
    """Remove all crossword info blocks, and regenerate the category blocks."""
    self.b_view.configure(state="normal")
    self.b_close.place_forget()

    CrosswordBlock._set_all(CrosswordBlock._remove_block)
    self._remove_block(self)
    self._populate(self.master)

    self.master.b_load_cword.configure(state="disabled")
    self.master.terminate()

_open ¤

_open() -> None

View all crossword info blocks for a specific category.

Source code in src/xpuz/pages/browser.py
831
832
833
834
835
836
837
838
839
840
def _open(self) -> None:
    """View all crossword info blocks for a specific category."""
    self.master._reset_scroll_frame()
    self.b_view.configure(state="disabled")

    self._set_all(self._remove_block)
    self._put_block(self)
    CrosswordBlock._populate(self.master, self)

    self.b_close.place(relx=0.5, rely=0.7, anchor="c")

_populate classmethod ¤

_populate(master: BrowserPage) -> None

Instantiate all the base category blocks and put them in the central scroll container.

Source code in src/xpuz/pages/browser.py
762
763
764
765
766
767
768
769
770
771
772
773
774
775
@classmethod
def _populate(cls, master: BrowserPage) -> None:
    """Instantiate all the base category blocks and put them in the central
    scroll container.
    """
    for i, category in enumerate(_get_base_categories()):
        block: CategoryBlock = cls(
            master.block_container,
            master,
            category.name,
            category.path,
            i,
        )
        cls._put_block(block)

CrosswordBlock ¤

CrosswordBlock(
    master: BrowserPage,
    container: CTkScrollableFrame,
    category: str,
    name: str,
    value: int,
    category_object: Optional[CategoryBlock] = None,
)

Bases: CTkFrame, Addons, BlockUtils

A frame containing a crosswords name, as well data read from its corresponding info.json file, including total definitions/word count, difficulty, and a symbol to prefix the crosswords name. A variable amount of these is created based on how many crosswords each category contains.

Source code in src/xpuz/pages/browser.py
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
def __init__(
    self,
    master: BrowserPage,
    container: CTkScrollableFrame,
    category: str,
    name: str,
    value: int,
    category_object: Optional[CategoryBlock] = None,
) -> None:
    super().__init__(
        container,
        corner_radius=10,
        fg_color=(Colour.Light.MAIN, Colour.Dark.MAIN),
        border_color=(Colour.Light.SUB, Colour.Dark.SUB),
        border_width=3,
    )
    self.master = master

    self.cwrapper: CrosswordWrapper = CrosswordWrapper(
        category,
        name,
        language=Base.locale.language,
        category_object=category_object,
        value=value,
    )

    self._set_fonts()
    self._make_content()
    self._place_content()

_populate classmethod ¤

_populate(
    master: BrowserPage, category: CategoryBlock
) -> None

Instantiate all the base crossword blocks for a given category and put them in the central scroll container.

Source code in src/xpuz/pages/browser.py
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
@classmethod
def _populate(cls, master: BrowserPage, category: CategoryBlock) -> None:
    """Instantiate all the base crossword blocks for a given category and
    put them in the central scroll container.
    """
    for i, crossword in enumerate(_get_base_crosswords(category.fp)):
        block: CrosswordBlock = cls(
            master,
            master.block_container,
            category.name,
            crossword.name,
            i,
            category,
        )
        cls._put_block(block)

_populate_all classmethod ¤

_populate_all(
    master: BrowserPage, query: Optional[str] = None
) -> None

Instantiate all the base crossword blocks and sort them holistically by difficulty suffix, putting them in the central scroll container only if they match the provided query parameter (if it is not None).

Source code in src/xpuz/pages/browser.py
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
@classmethod
def _populate_all(
    cls, master: BrowserPage, query: Optional[str] = None
) -> None:
    """Instantiate all the base crossword blocks and sort them holistically
    by difficulty suffix, putting them in the central scroll container only
    if they match the provided ``query`` parameter (if it is not None).
    """
    crosswords: List[Tuple[DirEntry, DirEntry]] = [
        (category, crossword)
        for category in _get_base_categories()
        for crossword in _get_base_crosswords(category.path, sort=False)
    ]
    cls.global_selected_cword: IntVar = IntVar()
    cls.global_selected_cword.set(-1)
    for i, (category, crossword) in enumerate(
        _sort_crosswords_by_suffix(crosswords)
    ):
        block: CrosswordBlock = cls(
            master,
            master.block_container,
            category.name,
            crossword.name,
            i,
        )
        # If a query has been provided, only put the block if the query
        # returns true
        if query and not BlockUtils._match_block_query(
            query, block.cwrapper.translated_name, _(category.name.title())
        ):
            continue
        cls._put_block(block)