<commit_before>#!/usr/bin/python
# ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2011, 2012  <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####

# System imports
import functools
import datetime
from pprint import pformat

# PySide imports
import sys
from PySide.QtCore import *
from PySide.QtGui import *

# Project imports
import idealclient as client
from settings import *

DEBUG = __debug__

class LoginForm(QDialog):
    def __init__(self, parent=None):
        super(LoginForm, self).__init__(parent)
        self.setWindowTitle("Login")

        self.status_icon = QIcon.fromTheme("user-offline")
        self.setWindowIcon(self.status_icon)

        self.server_status = QLabel()
        self.server_status.setAlignment(Qt.AlignCenter)
        self.server_status.setPixmap(self.status_icon.pixmap(64))

        self.username = QLineEdit("Username")

        self.password = QLineEdit("Password")
        self.password.setEchoMode(QLineEdit.Password)

        self.login_button = QPushButton("Getting server status...")
        self.login_button.setEnabled(False)
        self.login_button.clicked.connect(self.login)
        self.login_button.setIcon(self.status_icon)

        self.ping_timer = QTimer(self)
        self.connect(self.ping_timer, SIGNAL("timeout()"), self.is_server_up)
        self.ping_timer.start(1000)

        layout = QVBoxLayout()
        for w in (self.server_status, self.username, self.password, self.login_button):
            layout.addWidget(w)
        self.setLayout(layout)

    def is_server_up(self):
        '''Tests to see if the authentication server is up.'''
        from requests.exceptions import ConnectionError
        try:
            if client.ping_authserver():
                self.login_button.setEnabled(True)
                self.login_button.setText("Login!")
                self.status_icon = QIcon.fromTheme("user-online")
        except(ConnectionError):
            # We can only wait until the server comes back up.
            self.login_button.setEnabled(False)
            self.login_button.setText("Server is offline. :(")
            self.status_icon = QIcon.fromTheme("user-offline")
        self.setWindowIcon(self.status_icon)
        self.server_status.setPixmap(self.status_icon.pixmap(64))
        self.login_button.setIcon(self.status_icon)

    def login(self):
        login_result = client.login(self.username.text(), self.password.text())
        if login_result is True:
            # We logged in, so show the character select dialog
            global charselect
            charselect = CharacterSelect()
            charselect.show()
            # Once its shown, mark this dialog as accepted (And by extension, close it.)
            self.accept()


class CharacterSelect(QDialog):
    def __init__(self, parent=None):
        super(CharacterSelect, self).__init__(parent)
        self.setWindowTitle("Select A Character")

        # Character Portrait
        # Character Sprite
        # Name
        # Current zone
        # Money
        self.charbuttons = {}
        for char in client.get_characters():
            button = QPushButton()
            button.setText(char)
            button.setIcon(QIcon.fromTheme('applications-games'))
            func = functools.partial(self.select_character, char=char)
            button.clicked.connect(func)
            self.charbuttons[char] = button

        layout = QVBoxLayout()
        for w in self.charbuttons.values():
            layout.addWidget(w)
        self.setLayout(layout)

    def select_character(self, char):
        print "Selected %s" % char

        zone = client.get_zone(charname=char)
        print "Player is in the %s zone." % zone

        currentzone = client.get_zoneserver(zone)
        print "Connecting to zoneserver: %s" % currentzone

        # Initialize the world viewer
        global worldviewer
        worldviewer = WorldViewer(charname=char, currentzone=currentzone)
        global worldviewerdebug
        worldviewerdebug = WorldViewerDebug(worldviewer)
        global adminpanel
        adminpanel = AdminPanel(charname=char, currentzone=currentzone)
        worldviewerdebug.show()
        worldviewer.show()
        adminpanel.show()

        # We're all done here.
        self.accept()


class WorldViewerDebug(QDialog):
    def __init__(self, worldviewer, parent=None):
        super(WorldViewerDebug, self).__init__(parent)

        self.setWindowTitle("World Viewer Debug")
        pos = QApplication.instance().desktop().availableGeometry()
        self.move(pos.width()/2, 0)

        self.worldviewer = worldviewer

        self.objects = QTextEdit("<pre>Loading...</pre>")
        self.objects.setReadOnly(True)

        layout = QVBoxLayout()
        for w in (self.objects,):
            layout.addWidget(w)
        self.setLayout(layout)

        self.obj_update_timer = QTimer(self)
        self.connect(self.obj_update_timer, SIGNAL("timeout()"), self.update)
        self.obj_update_timer.start(CLIENT_UPDATE_FREQ)

    def sizeHint(self):
        desktop = QApplication.instance().desktop()
        geom = desktop.availableGeometry()
        return QSize(geom.width()/2, geom.height())

    def show(self):
        '''This is overridden to not allow this to be shown when running in 
        non-debug mode'''
        super(WorldViewerDebug, self).show()
        if not DEBUG:
            self.hide()

    def update(self):
        self.objects.setText(pformat(self.worldviewer.world_objects))

<commit_msg>QtClient now has a debug window that shows the contents of the zone, updating in realtime.<commit_after>#!/usr/bin/python
# ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2011, 2012  <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####

# System imports
import functools
import datetime
from pprint import pformat

# PySide imports
import sys
from PySide.QtCore import *
from PySide.QtGui import *

# Project imports
import idealclient as client
from settings import *

DEBUG = __debug__

class LoginForm(QDialog):
    def __init__(self, parent=None):
        super(LoginForm, self).__init__(parent)
        self.setWindowTitle("Login")

        self.status_icon = QIcon.fromTheme("user-offline")
        self.setWindowIcon(self.status_icon)

        self.server_status = QLabel()
        self.server_status.setAlignment(Qt.AlignCenter)
        self.server_status.setPixmap(self.status_icon.pixmap(64))

        self.username = QLineEdit("Username")

        self.password = QLineEdit("Password")
        self.password.setEchoMode(QLineEdit.Password)

        self.login_button = QPushButton("Getting server status...")
        self.login_button.setEnabled(False)
        self.login_button.clicked.connect(self.login)
        self.login_button.setIcon(self.status_icon)

        self.ping_timer = QTimer(self)
        self.connect(self.ping_timer, SIGNAL("timeout()"), self.is_server_up)
        self.ping_timer.start(1000)

        layout = QVBoxLayout()
        for w in (self.server_status, self.username, self.password, self.login_button):
            layout.addWidget(w)
        self.setLayout(layout)

    def is_server_up(self):
        '''Tests to see if the authentication server is up.'''
        from requests.exceptions import ConnectionError
        try:
            if client.ping_authserver():
                self.login_button.setEnabled(True)
                self.login_button.setText("Login!")
                self.status_icon = QIcon.fromTheme("user-online")
        except(ConnectionError):
            # We can only wait until the server comes back up.
            self.login_button.setEnabled(False)
            self.login_button.setText("Server is offline. :(")
            self.status_icon = QIcon.fromTheme("user-offline")
        self.setWindowIcon(self.status_icon)
        self.server_status.setPixmap(self.status_icon.pixmap(64))
        self.login_button.setIcon(self.status_icon)

    def login(self):
        # TODO: This could be an exception if login failed. Catch it.
        login_result = client.login(self.username.text(), self.password.text())
        if login_result:
            # We logged in, so show the character select dialog
            global charselect
            charselect = CharacterSelect()
            charselect.show()
            # Once its shown, mark this dialog as accepted (And by extension, close it.)
            self.accept()


class CharacterSelect(QDialog):
    def __init__(self, parent=None):
        super(CharacterSelect, self).__init__(parent)
        self.setWindowTitle("Select A Character")

        # Character Portrait
        # Character Sprite
        # Name
        # Current zone
        # Money
        self.charbuttons = {}
        for char in client.get_characters():
            button = QPushButton()
            button.setText(char)
            button.setIcon(QIcon.fromTheme('applications-games'))
            func = functools.partial(self.select_character, char=char)
            button.clicked.connect(func)
            self.charbuttons[char] = button

        layout = QVBoxLayout()
        for w in self.charbuttons.values():
            layout.addWidget(w)
        self.setLayout(layout)

    def select_character(self, char):
        print "Selected %s" % char

        zone = client.get_zone(charname=char)
        print "Player is in the %s zone." % zone

        currentzone = client.get_zoneserver(zone)
        print "Connecting to zoneserver: %s" % currentzone

        # Initialize the world viewer
        global worldviewer
        worldviewer = WorldViewer(charname=char, currentzone=currentzone)
        global worldviewerdebug
        worldviewerdebug = WorldViewerDebug(worldviewer)
        global adminpanel
        adminpanel = AdminPanel(charname=char, currentzone=currentzone)
        worldviewerdebug.show()
        worldviewer.show()
        adminpanel.show()

        # We're all done here.
        self.accept()


class WorldViewerDebug(QDialog):
    def __init__(self, worldviewer, parent=None):
        super(WorldViewerDebug, self).__init__(parent)

        self.setWindowTitle("World Viewer Debug")
        pos = QApplication.instance().desktop().availableGeometry()
        self.move(pos.width()/2, 0)

        self.worldviewer = worldviewer

        self.objects_tree = QTreeWidget()
        self.objects_tree.setColumnCount(2)
        self.objects_tree.setHeaderLabels(["ID", "Name", "Location", "Resource", "Last Modified"])
        self.objects_tree.setSortingEnabled(True)

        layout = QVBoxLayout()
        for w in (self.objects_tree,):
            layout.addWidget(w)
        self.setLayout(layout)

        self.obj_update_timer = QTimer(self)
        self.connect(self.obj_update_timer, SIGNAL("timeout()"), self.update)
        self.obj_update_timer.start(CLIENT_UPDATE_FREQ)

    def sizeHint(self):
        desktop = QApplication.instance().desktop()
        geom = desktop.availableGeometry()
        return QSize(geom.width()/2, geom.height())

    def show(self):
        '''This is overridden to not allow this to be shown when running in
        non-debug mode'''
        super(WorldViewerDebug, self).show()
        if not DEBUG:
            self.hide()

    def update(self):
        items = []
        for objid, obj in self.worldviewer.world_objects.items():
            name = obj['name']
            locx = obj['loc']['x']
            locy = obj['loc']['y']
            locz = obj['loc']['z']
            resource = obj['resource']
            last_modified = datetime.datetime.fromtimestamp(int(str(obj['last_modified']['$date'])[:-3]))

            row = self.objects_tree.findItems(objid, Qt.MatchExactly, column=0)
            if row:
                # Update it if it exists already
                item = row[0]
            if not row:
                # If Item does not exist in the tree widget already, make a new one.
                item = QTreeWidgetItem(self.objects_tree)
                items.append(item)

            for i, param in enumerate((objid, name, (locx, locy, locz), resource, last_modified)):
                item.setText(i, str(param))

        if items:
            self.objects_tree.insertTopLevelItems(0, items)


{'fraction_non_alphanumeric': 0.09921978507286913, 'fraction_numerical': 0.0033122331812159575, 'mean_word_length': 2.61933937133724, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '558958', 'n_tokens_mistral': 3860, 'n_tokens_neox': 3732, 'n_words': 973}