Пример #1
0
 def send_message(self, *args):
     if len(self.text) > 250:
         popup = MOPopup("Warning", "Message too long", "OK")
         popup.open()
         return
     elif len(self.text) == 0 and not self.icon_change_spam:
         self.icon_change_spam = True
         Clock.schedule_once(self.enable_icon_change, 0.25)
         App.get_running_app().get_user_handler().send_icon()
         return
     main_scr = App.get_running_app().get_main_screen()
     Clock.schedule_once(main_scr.refocus_text)
     msg = escape_markup(self.text)
     if not self.message_is_valid(msg):
         return
     self.text = ""
     msg = self.extend_message(msg)
     if self.message_is_command(msg):
         try:
             self.handle_command(msg)
         except (AttributeError, IndexError) as e:
             Logger.warning(traceback.format_exc())
             return
     else:
         user_handler = App.get_running_app().get_user_handler()
         try:
             user_handler.send_message(msg)
         except Exception as e:
             popup = MOPopup("Warning", "Something went wrong. " + str(e),
                             "OK")
             popup.open()
Пример #2
0
        def webpage_image_updater(self):
            while True:
                if self.do_webpage_image_update:
                    t = time.time()

                    Logger.debug("WebpageImage: Starting image update")

                    data = io.BytesIO(self.driver.get_screenshot_as_png())

                    coreImage = CoreImage(data, ext="png")
                    Clock.schedule_once(
                        lambda _: self.Gui.update_webpage_image(coreImage, t),
                        0)

                    try:
                        time.sleep(self.webpage_image_update_interval -
                                   (time.time() - t))
                    except ValueError:
                        Logger.warning(
                            "WebpageImage: Convert took to long, took " +
                            str(time.time() - t) + " and it should've took " +
                            str(self.webpage_image_update_interval))

                else:
                    time.sleep(self.webpage_image_update_interval)
Пример #3
0
 def open_popup(self):
     try:
         popup = self.build_item_window()
         popup.bind(on_dismiss=self.clear_cache)
         popup.open()
     except AttributeError:
         Logger.warning(traceback.format_exc())
         return
Пример #4
0
 def __draw_shadow__(self, origin, end, context=None):
     Logger.warning(
         f"KivyMD: "
         f"If you see this error, this means that either youre using "
         f"`CommonElevationBehavio`r directly or your 'shader' dont have a "
         f"`_draw_shadow` instruction, remember to overwrite this function"
         f"to draw over the image context. Тhe figure you would like. "
         f"Or your class {self.__class__.__name__} is not inherited from "
         f"any of the classes {__all__}")
Пример #5
0
 def increment_achievement(self, name, value=1):
     if self.client and self.is_connected():
         Logger.info('Google: incremented achievement %s' % name)
         try:
             Games.Achievements.increment(self.client, settings.GOOGLE_PLAY_ACHIEVEMENT_IDS[name], value)
         except JavaException:
             Logger.warning("Google: error while increment achievement, pass...")
     else:
         Logger.info("Google: achievement is not submitted. Client: %s, is connected: %s" % (
             self.client, self.is_connected()))
Пример #6
0
 def notification(self, title: str = "Mystery Online", content: str = "Bottom text"):
     icon: str = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "icon.png")
     if platform == 'linux':
         import subprocess
         subprocess.run(["notify-send", "-u", "normal", "-t", "10000", "-i", icon, title, content])
     elif platform == 'win':
         try:
             from win10toast import ToastNotifier
         except ImportError as e:
             Logger.warning("Missing win10toast library.")
             return
         ToastNotifier().show_toast(title, content, duration=10, icon_path=icon)
Пример #7
0
 def on_activity_result(self, requestCode, resultCode, intent):
     Logger.info("Google: back to activity result. %s, %s" % (requestCode, resultCode))
     if requestCode == self.RC_RESOLUTION:
         self.in_resolving_connection = False
         if resultCode == self.RESULT_OK:
             Logger.info("Google: resolving result okay")
             self.client.connect()
         elif resultCode == self.RESULT_CANCELLED:
             Logger.info("Google: resolving cancelled")
         else:
             Logger.warning("Google: resolving failed. Error code: %s" % resultCode)
             if self.resolving_failure_callback:
                 self.resolving_failure_callback(resultCode)
Пример #8
0
 def clear_cache(self, instance):
     try:
         shutil.rmtree('imgcache/')
         os.makedirs(
             'imgcache'
         )  #this is the exact same code used for the music cache
     except FileNotFoundError:  #i disgust myself too.
         os.makedirs('imgcache')
     except PermissionError:
         Logger.warning(
             "Cannot clear inventory cache due to permission error.")
     except Exception as e:
         Logger.warning(traceback.format_exc())
Пример #9
0
 def handle_command(self, msg):
     try:
         cmd_name, cmd = msg.split(' ', 1)
     except ValueError:
         cmd_name = msg
         cmd = None
     cmd_name = cmd_name[1:]
     try:
         command_processor.process_command(cmd_name, cmd)
     except CommandInvalidArgumentsError:
         Logger.warning("Invalid arguments")
         pass
     except CommandNoArgumentsError:
         Logger.warning("No arguments given")
         pass
Пример #10
0
    def remove_from_cart(self, purchase: Purchase):
        # Check if the item is in the list
        duplicate = self.__find_duplicate(purchase)

        # Check if the purchase actually exists
        if duplicate is not None:
            if duplicate.amount == 1:
                self.basket.remove(duplicate)
            else:
                duplicate.amount -= purchase.amount
        else:

            Logger.warning(
                "StellaPayUI: Tried to remove a purchase from the basket that was not present!"
            )

        self.notify_listener()
Пример #11
0
    def FindChannelLogo(self,*,uChannelName:str, uReference:str, uLogoPackFolderName:str) -> str:
        """
        Finds a channel Logo in the list of all logo files

        :param str uChannelName: The name of the channel to look for
        :param str uReference: The SAT Reference
        :param str uLogoPackFolderName: the name of the folder (only the folder name, not the fullpath) in "recources" , below "tvlogos"
        :return: The logo file name (full path), or "text:Channelname" if logo file can't be found
        """
        iPos = uChannelName.find("/")
        if iPos>0:
            uChannelName=uChannelName[:iPos]

        uFnLogo = self.FindChannelLogo_sub(uChannelName=uChannelName,uReference=uReference,uLogoPackFolderName=uLogoPackFolderName)
        if uFnLogo == u"" or uFnLogo is None:
            uFnLogo = u"text:"+uChannelName
            Logger.warning("Can't find logo [%s] [%s] in [%s]:" % ( uChannelName,uReference,uLogoPackFolderName))
        return uFnLogo
Пример #12
0
 def __init__(self, name, description, image_link, inventory: UserInventory,
              username, **kwargs):
     super(Item, self).__init__(**kwargs)
     try:
         os.makedirs('imgcache')
     except FileExistsError:
         Logger.warning("Image Cache Exists.")
     self.size_hint_y = None
     self.height = 50
     self.cols = 3
     self.inventory = inventory
     self.name = Label(text=name)
     self.name.bind(on_touch_down=self.on_item_pressed)
     self.add_widget(self.name)
     self.description = Label(text=description)
     self.image_link = image_link
     try:
         r = requests.get(image_link, timeout=(5, 20))
     except requests.exceptions.MissingSchema:
         return
     r.raise_for_status()
     if r.ok:
         picname = os.path.basename(urllib.parse.urlparse(image_link).path)
         if picname is None:
             picname = "temp.jpg"
         f = open("imgcache/" + picname, mode="wb")
         f.write(r.content)
         f.close()
     self.image = AsyncImage(source="imgcache/" + picname,
                             pos_hint={'left': 1})
     self.image.bind(on_touch_down=self.open_image)
     self.owner_username = username
     delete_btn = Button(text="X", size_hint=[None, 1], width=60)
     delete_btn.bind(on_press=lambda x: self.delete_item())
     self.add_widget(delete_btn)
     self.popup = None
     self.description.text_size = [
         self.description.size[0] * 3, self.description.size[1]
     ]
Пример #13
0
    def take_not_window_screenshot(self, shouldWholeWindowIfNone=False, *args):
        if globals.baseSysConfig.get("background_image", "see_through"):
            img = ImageGrab.grab()

            try:
                im = CoreImage(self.ids["ParentScreenImage"].texture)

            except Exception:
                Logger.warning(
                    globals.baseSysConfig.get("main", "parent_name") +
                    ": Window background image does not have a texture")

                if shouldWholeWindowIfNone:
                    self.minimize_screenshot()

                return

            data = BytesIO()
            im.save(data, fmt="png")
            data.seek(0)
            im = PILImage.open(data)

            wx, wy, ww, wh = CoreWindow.left, CoreWindow.top, CoreWindow.width, CoreWindow.height
            remAmount = globals.baseSysConfig.get("background_image",
                                                  "crop_distance")
            remAmountTop = globals.baseSysConfig.get("background_image",
                                                     "crop_distance_top")
            x, y, x2, y2 = wx - remAmount, wy - remAmountTop, wx + ww + remAmount, wy + wh + remAmount
            im = im.crop((x, y, x2, y2))

            img.paste(im, (x, y))

            data = BytesIO()
            img.save(data, format="png")
            data.seek(0)
            img = CoreImage(BytesIO(data.read()), ext='png')

            self.ids["ParentScreenImage"].texture = img.texture
Пример #14
0
    def load(filename):
        """Load a sound, and return a sound() instance."""
        rfn = resource_find(filename)
        if rfn is not None:
            filename = rfn

        ext = filename.split('.')[-1].lower()
        if '#' in ext:
            tryext = ext.split('#')[-1].lower()
            if len(tryext)<=4:
                ext = tryext
            else:
                ext = ext.split('#')[0]

        if '?' in ext:
            ext = ext.split('?')[0]

        for classobj in SoundLoader._classes:
            if ext in classobj.extensions():
                return classobj(source=filename)
        Logger.warning('Audio: Unable to find a loader for <%s>' %
                       filename)
        return None
Пример #15
0
 def open(self, *largs):
     '''Show the view window from the :attr:`attach_to` widget. If set, it
     will attach to the nearest window. If the widget is not attached to any
     window, the view will attach to the global
     :class:`~kivy.core.window.Window`.
     '''
     if self._window is not None:
         Logger.warning('ModalView: you can only open once.')
         return self
     # search window
     self._window = self._search_window()
     if not self._window:
         Logger.warning('ModalView: cannot open view, no window found.')
         return self
     self._window.add_widget(self)
     self._window.bind(on_resize=self._align_center,
                       on_keyboard=self._handle_keyboard)
     self.center = self._window.center
     self.bind(size=self._align_center)
     a = Animation(_anim_alpha=1., d=self._anim_duration)
     a.bind(on_complete=lambda *x: self.dispatch('on_open'))
     a.start(self)
     return self
Пример #16
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     Logger.warning(
         "MDChooseChip: "
         "class is deprecated and will be removed in a future version")
Пример #17
0
SHUTDOWN_UUID = uuid.uuid4()

sct_cls = Sct_loop(quality)


def client_loop():
    global do_run
    while do_run:
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + sct_cls.get_value() + b'\r\n\r\n')
        time.sleep(1/30)
    return "Server exited!"


if DEBUG:
    Logger.warning("!!!!!DEBUG TRUE!!!!!!!")
    app = Flask(__name__, template_folder="templates", static_folder="static")
else:
    app = Flask(__name__, template_folder=resource_path("app/server/templates/"))



# === DEBUG時、Cache使われるとDEBUGしにくいので。 ===
@app.context_processor
def override_url_for():
    return dict(url_for=dated_url_for)


def dated_url_for(endpoint, **values):
    if endpoint == 'static':
        filename = values.get('filename', None)
Пример #18
0
from kivy.uix.screenmanager import Screen
# from kivy.uix.widget import Widget
# from kivy.utils import get_hex_from_color
from kivymd.app import MDApp
from kivy.lang import Builder
import threading

from DEBUG import DEBUG, resource_path

Logger.info("importTime:{}".format(time.time() - importstart))

if DEBUG:
    Logger.warning("""

    /////////////////////////////////////
    //      WARNING -> DEBUG TRUE      //
    /////////////////////////////////////
    
    """)
    resource_add_path("fonts/")
    LabelBase.register(DEFAULT_FONT, "fonts/SourceHanSans.otf")
    help_icon_path = "images/help_icon.png"
    schreen_icon_path = "images/icon.png"
else:
    resource_add_path(resource_path("app/fonts/"))
    LabelBase.register(DEFAULT_FONT,
                       resource_path("app/fonts/SourceHanSans.otf"))
    # FIXME: PyinstallerでBuildすると、自動でmain.kvが読まれないが、
    #  DEBUG環境だと両方読まれて色々めんどくさいからデフォルト読まれるようにするのもありかも。
    Builder.load_file(resource_path("app/main.kv"))
    help_icon_path = resource_path("app/images/help_icon.png")
Пример #19
0
    def calc_mesh_vertices(self, step = None, update_mesh=True, preserve_uv=True):
        """Calculate Mesh.vertices and indices from the ControlPoints
        If step omitted, uses ControlPoints at current position, otherwise
        vertices at that animation step (ControlPoint.positions[step]).
        Central vertice at center is added as first item in list if mesh_mode=='triangle_fan'
        preserve_uv: Do not overwrite the uv coordinates in the current Mesh.vertices
        (only has an effect if update_mesh==True and vertices are already set)

        returns vertices, indices
        """
        if step is not None and not isinstance(step, basestring):
            raise ValueError('step must be a string')

        num = len(self.control_points)
        if num == 0:
            Logger.warning("AnimationConstructor: Called calc_mesh_vertices without any control_points")
            return [], []


        triangle_fan_mode = self.mesh_mode == 'triangle_fan'

        verts = []
        cent_x, cent_y, cent_u, cent_v = 0.0, 0.0, 0.0, 0.0

        # Need to calculate Centroid first, then do pass through to calculate vertices
        for cp in self.control_points:
            tx, ty = cp.get_tex_coords(step)
            cent_x += tx
            cent_y += ty

        cent_x /= num
        cent_y /= num

        # step may be None if moving points
        if triangle_fan_mode and self.animation_step==setup_step:
            # Sort by angle from centroid in case user didn't place around perimeter in order

            cent_vec = Vector(cent_x, cent_y)
            ref = Vector(1, 0) # Reference vector to measure angle from
            for cp in self.control_points:
                cp.centroid_angle = ref.angle(Vector(cp.get_tex_coords(step)) - cent_vec)

            # ListProperty.sort does not exist
            #self.control_points.sort(key = lambda cp: cp.centroid_angle)
            self.control_points = sorted(self.control_points, key = lambda cp: cp.centroid_angle)

        # TODO Need to figure out similar solution if using triangle_strip

        # Create vertices list
        # centroid added as first vertex in triangle-fan mode
        start = 1 if triangle_fan_mode else 0
        # enumerate always goes through all items, start is just where the count starts
        for index, cp in enumerate(self.control_points, start=start):
            coords = cp.calc_vertex_coords(pos_index=step)
            # Need to calculate u, v centroid still
            cent_u += coords[2]
            cent_v += coords[3]

            cp.vertex_index = index
            verts.extend(coords)

        cent_u /= num
        cent_v /= num

        if triangle_fan_mode:
            # Calculate mean centroid and add to beginning of vertices
            verts.insert(0, cent_v)
            verts.insert(0, cent_u)
            verts.insert(0, cent_y)
            verts.insert(0, cent_x)

            # PERF: Technically don't need to recalculate indices except step 0, but not bothering with optimization now
            indices = range(1, num + 1)
            indices.insert(0, 0)
            indices.append(1)

        else:
            indices = range(num)

        if update_mesh:
            mesh_verts = self.mesh.vertices
            num_mesh_verts = len(mesh_verts)

            # preserve_uv: Do not overwrite the uv coordinates in the current Mesh.vertices
            # None: False if self.animation_step == setup_step
            # specified: False if step == setup_step
            # Refactored this way earlier, but went back because Animation uses None and when animating
            # back to setup_step we want preserve_uv false
            # preserve_uv = True
            # if step is None and self.animation_step == setup_step:
            #     preserve_uv = False
            # elif step == setup_step:
            #     preserve_uv = False

            if preserve_uv and num_mesh_verts > 0:
                if num_mesh_verts != len(verts):
                    raise AssertionError('Number of calculated vertices (%d) != number Mesh.vertices (%d) step=%s'
                                         %(len(verts), num_mesh_verts, step))

                # Only overwrite x, y mesh coords
                for x in range(0, num_mesh_verts, 4):
                    mesh_verts[x] = verts[x]
                    mesh_verts[x+1] = verts[x+1]

                self.mesh.vertices = mesh_verts

            else:
                self.mesh.vertices = verts

            self.mesh.indices = indices

        return verts, indices
Пример #20
0
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Amber"
        self.theme_cls.primary_hue = "600"
        self.theme_cls.accent_pallet = "Teal"
        self.theme_cls.accent_hue = "300"
        self.theme_cls.green_button = (0.262, 0.627, 0.278, 1)
        self.theme_cls.red_button = (0.898, 0.450, 0.450, 1)
        self.theme_cls.purple_button = (0.694, 0.612, 0.851, 1)
        self.theme_cls.complementary_color_1 = (0.623, 0.858, 0.180, 1)
        self.theme_cls.complementary_color_2 = (0, 0.525, 0.490, 1)

        # Set background image to match color of STE logo
        Window.clearcolor = (0.12549, 0.12549, 0.12549, 0)

        # Set size of the window
        Window.size = (int(self.config.get('device', 'width')),
                       int(self.config.get('device', 'height')))
        Logger.info(
            f"StellaPayUI: Window height {self.config.get('device', 'height')} and width {self.config.get('device', 'width')}."
        )

        # Don't run in borderless mode when we're running on Linux (it doesn't seem to work so well).
        Window.borderless = False if sys.platform.startswith("linux") else True

        hostname = None

        try:
            hostname = self.config.get('server', 'hostname')

            Logger.info(f"StellaPayUI: Hostname for server: {hostname}")

            Connections.hostname = hostname
        except Exception:
            Logger.warning(
                "StellaPayUI: Using default hostname, since none was provided")
            pass

        if self.config.get('device', 'fullscreen') == 'True':
            Logger.info(f"StellaPayUI: Running in fullscreen mode!")
            Window.fullscreen = True
        else:
            Logger.info(f"StellaPayUI: Running in windowed mode!")
            Window.fullscreen = False

        if self.config.get('device', 'show_cursor') == 'True':
            Window.show_cursor = True
        else:
            Window.show_cursor = False

        # Load .kv file
        Builder.load_file('kvs/DefaultScreen.kv')

        Logger.debug("StellaPayUI: Starting event loop")
        self.loop: AbstractEventLoop = asyncio.new_event_loop()
        self.event_loop_thread = threading.Thread(target=self.run_event_loop,
                                                  args=(self.loop, ),
                                                  daemon=True)
        self.event_loop_thread.start()

        Logger.debug("StellaPayUI: Start authentication to backend")

        self.loop.call_soon_threadsafe(self.session_manager.setup_session,
                                       self.load_categories_and_products)

        # Initialize defaultScreen (to create session cookies for API calls)
        ds_screen = DefaultScreen(name=Screens.DEFAULT_SCREEN.value)

        # Load screenloader and add screens
        screen_manager.add_widget(
            StartupScreen(name=Screens.STARTUP_SCREEN.value))
        screen_manager.add_widget(ds_screen)
        screen_manager.add_widget(
            WelcomeScreen(name=Screens.WELCOME_SCREEN.value))
        screen_manager.add_widget(
            RegisterUIDScreen(name=Screens.REGISTER_UID_SCREEN.value))
        screen_manager.add_widget(
            ConfirmedScreen(name=Screens.CONFIRMED_SCREEN.value))
        screen_manager.add_widget(
            CreditsScreen(name=Screens.CREDITS_SCREEN.value))
        screen_manager.add_widget(
            ProductScreen(name=Screens.PRODUCT_SCREEN.value))
        screen_manager.add_widget(
            ProfileScreen(name=Screens.PROFILE_SCREEN.value))

        Logger.debug(
            "StellaPayUI: Registering default screen as card listener")
        ds_screen.register_card_listener(self.card_connection_manager)

        Logger.debug("StellaPayUI: Starting NFC reader")
        self.card_connection_manager.start_nfc_reader()

        screen_manager.get_screen(
            Screens.CREDITS_SCREEN.value).ids.version_build.text = str(
                self.build_version)

        return screen_manager
Пример #21
0
    Environment = autoclass('android.os.Environment')
    path = os.path.join(
        unicode(Environment.getExternalStorageDirectory().getAbsolutePath()),
        DATABASE_NAME)
except Exception:
    path = ""

if writable(path):
    DATABASE_PATH = path
else:
    from settings import DATABASE_PATH
    if not writable(DATABASE_PATH):
        variants = ("/sdcard", "./", "/data/data/kognitivo.kognitivo.org")
        for variant in variants:
            path = os.path.join(variant, DATABASE_NAME)
            Logger.warning("Android Settings: try database path %s" % path)
            if writable(path):
                DATABASE_PATH = path
                break
            else:
                DATABASE_PATH = None

        if not DATABASE_PATH:
            try:
                Context = autoclass('android.content.Context')
                path = os.path.join(unicode(Context.getFilesDir()),
                                    DATABASE_NAME)
            except Exception:
                path = ""
            if writable(path):
                DATABASE_PATH = path
Пример #22
0
"""
FitImage
========

.. note:: See :class:`~kivymd.uix.fitimage.FitImage` for more information
"""

__all__ = ("FitImage", )

from kivy import Logger

from kivymd.uix.fitimage import FitImage

Logger.warning(
    "FitImage: Note!"
    "\nIn the near future the `FitImage` widget will be moved to the "
    "`kivymd.uix.fitimage` package.\nUse import of this widget like this:"
    "`from kivymd.uix.fitimage import FitImage`.")