Example #1
0
    def run(self):
        self._logger.info("Starting TSM Application r{} ({})".format(Config.CURRENT_VERSION, Config.GIT_COMMIT))

        # Create the windows
        self._login_window = LoginWindow()
        self._main_window = MainWindow()
        self._settings_window = SettingsWindow(self._main_window)
        self._settings = load_settings(Config.DEFAULT_SETTINGS)

        # Setup the main thread which handles all the business logic
        self._main_thread = MainThread()
        # connect login window signals / slots
        self._login_window.login_button_clicked.connect(self._main_thread.login_button_clicked)
        self._main_thread.set_login_window_visible.connect(self._login_window.setVisible)
        self._main_thread.set_login_window_enabled.connect(self._login_window.set_enabled)
        self._main_thread.set_login_window_form_values.connect(self._login_window.set_form_values)
        self._main_thread.set_login_window_button_text.connect(self._login_window.set_button_text)
        self._main_thread.set_login_window_error_text.connect(self._login_window.set_error_text)
        # connect main window signals / slots
        self._main_window.settings_button_clicked.connect(self._settings_window.show)
        self._main_window.status_table_clicked.connect(self._main_thread.status_table_clicked, Qt.QueuedConnection)
        self._main_window.export_accounting.connect(self._main_thread.accounting_export)
        self._main_thread.set_main_window_visible.connect(self._main_window.set_visible)
        self._main_thread.set_main_window_header_text.connect(self._main_window._ui.header_text.setText)
        self._main_thread.set_main_window_sync_status_data.connect(self._main_window.set_sync_status_data)
        self._main_thread.set_main_window_addon_status_data.connect(self._main_window.set_addon_status_data)
        self._main_thread.set_main_window_backup_status_data.connect(self._main_window.set_backup_status_data)
        self._main_thread.set_main_window_accounting_accounts.connect(self._main_window.set_accounting_accounts)
        self._main_thread.show_desktop_notification.connect(self._main_window.show_notification)
        self._main_thread.set_main_window_title.connect(self._main_window.setWindowTitle)
        self._main_thread.set_main_window_premium_button_visible.connect(self._main_window._ui.premium_button.setVisible)
        # connect settings window signals / slots
        self._settings_window.settings_changed.connect(self._main_thread.on_settings_changed)
        self._settings_window.upload_log_file.connect(self._main_thread.upload_log_file)
        self._settings_window.reset_settings.connect(self._main_thread.reset_settings)
        self._settings_window.run_at_startup_changed.connect(self._main_thread.update_run_at_startup)
        self._main_thread.settings_changed.connect(self._settings_window.on_settings_changed)
        self._main_thread.log_uploaded.connect(self._settings_window.log_uploaded)
        # connect general signals / slots
        self._main_thread.finished.connect(self._app.exit)
        self._main_thread.show_terms.connect(self.show_terms)
        self.terms_accepted.connect(self._main_thread.terms_accepted)
        self._main_thread.run_updater.connect(self.run_updater)
        # start the thread
        self._main_thread.start()

        # Start the app
        self._app.exec_()
    def __init__(self):

        # initialize base class
        wx.Frame.__init__(self, None, title=__program_name__, size=(600, 183))
        self.SetMinSize((400, 175))

        # load the settings here very early; the tilde is cross platform thanks to Python
        self.settings_file_name = os.path.join(os.path.expanduser("~"), ".idfversionupdater.json")
        self.settings = load_settings(self.settings_file_name)

        # initialize some class-level "constants"
        self.box_spacing = 4

        # reset the restart flag
        global _doing_restart
        _doing_restart = False

        # initialize instance variables to be set later
        self.btn_select_idf = None
        self.btn_about = None
        self.lbl_path = None
        self.lbl_old_version = None
        self.chk_create_inter_versions = None
        self.btn_update_file = None
        self.btn_open_run_dir = None
        self.btn_cancel = None
        self.btn_exit = None
        self.status_bar = None
        self.idf_version = None
        self.running_transition_thread = None

        # try to load the settings very early since it includes initialization
        set_language(self.settings[Keys.language])

        # connect signals for the GUI
        self.Bind(wx.EVT_CLOSE, self.on_closing_form)

        # build up the GUI itself
        self.build_gui()

        # update the list of E+ versions
        self.ep_run_folder = EnergyPlusPath()
        title = TransitionRunThread.get_ep_version(os.path.join(self.ep_run_folder.installation_path, 'EnergyPlus'))
        self.SetTitle(__program_name__ + " -- " + title)
        self.status_bar.SetStatusText(_("Program Initialized"))

        # check the validity of the idf versions once at load time to initialize the action availability
        self.on_update_for_new_file(None)
Example #3
0
    def __init__(self, maps):
        settings_values = load_settings()
        self.result = -1  # переменная для отслеживания состояния экрана

        self.maps = maps
        # создание кнопок
        self.exit_btn = Button(-30,
                               615,
                               222,
                               92,
                               '',
                               exit_button_image,
                               self.back,
                               glow=glow_left)

        self.chr_btn = Button(-30,
                              -30,
                              223,
                              92,
                              '',
                              chr_button_image,
                              self.chr_menu,
                              glow=glow_left)

        self.play_btn = Button(908,
                               650,
                               222,
                               92,
                               '',
                               play_button_image,
                               self.start_game,
                               glow=glow_right)

        self.settings_btn = Button(908,
                                   0,
                                   223,
                                   92,
                                   '',
                                   settings_button_image,
                                   self.open_settings,
                                   glow=glow_right)
        self.active_map = 0
        self.maps[0][0] -= 30
        self.menu_background = self.maps[self.active_map][2].background
        # загрузка аудиофайла
        map = f'maps/{self.maps[0][2].dir}/{self.maps[0][2].general["AudioFilename"]}'
        pygame.mixer.music.load(map)
        pygame.mixer.music.set_volume(0.1 *
                                      int(settings_values['music_volume']))
        pygame.mixer.music.play(-1)

        # загрузка рекордов для всех карт
        self.records = {}
        con = sqlite3.connect('records.db')
        cur = con.cursor()
        result = cur.execute("SELECT * FROM Records")
        for elem in result:
            # преобразование элементов словаря с рекордами
            # из текста в изображения с текстом
            elem = list(elem)
            elem[6] = 'Сыграно ' + elem[6] + ', ' + elem[7]
            elem[3] = 'Score: ' + str(elem[3])
            elem[5] = 'Combo: ' + str(elem[5]) + 'x'
            elem[4] = str('%.2f' % elem[4]) + '%'
            for i in range(3, 8):
                elem[i] = drawing_text(str(elem[i]), (-100, -100),
                                       font_color=(255, 255, 255),
                                       font_size=15)
            if elem[1] in self.records:
                self.records[elem[1]].append(elem)
            else:
                self.records[elem[1]] = [elem]
        for i in self.records:
            self.records[i] = list(reversed(self.records[i]))
        self.cache = {}  # кеш для быстрой отрисовки текста
Example #4
0
from Settings import load_settings

exit_button_image = [load_image(f'menu_back_{i}.png') for i in range(2)]
chr_button_image = [load_image(f'chr_button_{i}.png') for i in range(2)]
play_button_image = (load_image('play_button_0.png'),
                     load_image('play_button_1.png'))
settings_button_image = [
    load_image(f'settings_button_{i}.png') for i in range(2)
]
song_rect = load_image('select_menu_rect.png')
song_rect_active = load_image('select_menu_rect_active.png')
menu_back_plus = load_image('menu_back+.png')
menu_plus = load_image('menu+.png')
back_mask = load_image('back_mask.png')
records_rect = load_image('record_rect.png')
settings_values = load_settings()
glow_left = load_image('glow_left.png')
glow_right = load_image('glow_right.png')
shift_v = 300


class SelectMenu:
    def __init__(self, maps):
        settings_values = load_settings()
        self.result = -1  # переменная для отслеживания состояния экрана

        self.maps = maps
        # создание кнопок
        self.exit_btn = Button(-30,
                               615,
                               222,
Example #5
0
    def __init__(self, map):
        global v, time_uprise
        settings_values = load_settings()  # загрузка настроек игрока
        v = int(settings_values['scroll_speed'])  # обновление значения скорости игрока
        time_uprise = ((720 - 130) / v * 1000) // 1  # обновление времени начала движения нот

        self.map = map[2]
        self.score = 0  # общий счет игрока
        self.accuracy = 100  # точность нажатий игрока
        self.max_combo = 0  # максимальное комбо игрока
        self.combo = 0  # комбо игрока

        # настройка времени для получения соответсвующей оценки
        od = float(self.map.OD)
        # время, за которое нужно нажать на ноту для какой-то оценки
        self.od_max = 16.5 * 2
        self.od_300 = (64 - (od * 3)) * 2
        self.od_200 = (97 - (od * 3)) * 2
        self.od_100 = (127 - (od * 3)) * 2
        self.od_50 = (151 - (od * 3)) * 2

        self.marks = []
        # подсчет кол-ва всех оценок
        self.count_marks = {0: 0, 50: 0, 100: 0, 200: 0, 300: 0, 301: 0}

        # создания списков для отслеживания состояния одиночных нот
        self.notes_near = []  # нота находится в области нажатий игрока
        self.notes_active = []  # нота присутсвует на игровом поле
        self.notes = [i.copy() for i in self.map.objects if i[2] == 1]  # все ноты карты
        for i in range(len(self.notes)):  # заполнения массива 'self.notes'
            self.notes[i].append(self.notes[i][1])
            self.notes[i][1] -= time_uprise

        # преобразование массива для удобства отслеживания нот
        self.notes.sort(key=lambda x: x[1], reverse=True)
        while self.notes[-1][1] <= 0:
            self.notes.pop()

        # создания списков для отслеживания состояния длинных нот(или по другому slider)
        self.sliders_active = []  # длинная нота находится в области нажатий игрока
        self.sliders_near = []  # длинная нота присутсвует на игровом поле
        self.sliders_pressed = [-1, -1, -1, -1]  # массив для хранения нажатых слайдеров
        self.sliders_pressed_ms = [-1, -1, -1, -1]  # массив для отслеживания кол-ва времен
        # потраченного на прожатие слайдера
        self.sliders_failed = []  # пропущенная или ненажатая длинная нота
        self.sliders = [i.copy() for i in self.map.objects if i[2] == 128]  # все длинные ноты
        for i in range(len(self.sliders)):  # заполнения массива 'self.sliders'
            self.sliders[i].append(self.sliders[i][1])
            self.sliders[i][1] -= time_uprise

        # преобразование массива для удобства отслеживания длинных нот
        self.sliders.sort(key=lambda x: x[1], reverse=True)
        while self.sliders[-1][1] < 0:
            self.sliders.pop()

        self.end_time = max((self.notes[0][4], self.sliders[0][3])) + 1500  # время оканчания карты

        self.map.background.set_alpha(100)  # задней фон карты
        display.fill((0, 0, 0))
        display.blit(self.map.background, (0, 0))

        # загрузка музыки карты
        pygame.mixer.music.load(f'maps/{self.map.dir}/{self.map.general["AudioFilename"]}')
        pygame.mixer.music.set_volume(0.1 * int(settings_values['music_volume']))
        pygame.mixer.music.play(1)

        # создание изображения для обновления значения общего счета игрока
        score_surface = self.map.background.subsurface((670, 30, 290, 50))
        self.score_surface = pygame.surface.Surface((290, 50))
        self.score_surface.fill((0, 0, 0))
        score_surface.set_alpha(100)
        self.score_surface.blit(score_surface, (0, 0))

        # создание изображения для обновления значения точности попадания игрока
        acc_surface = self.map.background.subsurface((670, 90, 200, 50))
        self.acc_surface = pygame.surface.Surface((200, 50))
        self.acc_surface.fill((0, 0, 0))
        acc_surface.set_alpha(100)
        self.acc_surface.blit(acc_surface, (0, 0))

        # создание изображения для обновления значения комбо игрока
        combo_surface = self.map.background.subsurface((670, 150, 150, 50))
        self.combo_surface = pygame.surface.Surface((150, 50))
        self.combo_surface.fill((0, 0, 0))
        combo_surface.set_alpha(100)
        self.combo_surface.blit(combo_surface, (0, 0))

        # анимация заполненой способности персонажа
        self.ability_sprite = AnimatedSprite('ability_bar/ability_bar', 17, 645, 230, 15)
        self.ability_score = 10000  # значение при котором способность можно буде использовать
        self.activate_ability = False  # переменная для отслеживания активации способности

        self.character = int(settings_values['character'])  # персонаж
        # создание изображения для обновления персонажа
        surface_chr = self.map.background.subsurface((600, 300, 500, 355))
        self.surface_chr = pygame.surface.Surface((500, 355))
        self.surface_chr.fill((0, 0, 0))
        surface_chr.set_alpha(100)
        self.surface_chr.blit(surface_chr, (0, 0))
        # коэффициэнт очков игрока
        if self.character == 4:  # множитель будет 1.5, если выбран персонаж 'Sakuya'
            self.coefficient = 1.5
        else:  # множитель будет 1 у всех персонажей, кроме 'Sakuya'
            self.coefficient = 1
        self.character_stand = AnimatedSprite(*character_dict[self.character])  # анимация персонажа
        if self.character != 2 and self.character != 4:  # анимация способности персонажа(если есть)
            self.character_ability = AnimatedSprite(*ability_dict[self.character])

        # массив для отслеживания, на каких линиях нужно сделать вспышки
        self.lightnings = [-1, -1, -1, -1]
        self.time = pygame.time.get_ticks()  # время начала игры
Example #6
0
stage_image = load_image('skin/stage.png')
stage_light_image = load_image('skin/stage_light.png')

lightning_image = load_image('skin/lighting.png')  # изображение вспышки при уничтожение ноты

# загрузка изображений оценок
hit0 = load_image('skin/hit0.png')  # оценка - Miss
hit50 = load_image('skin/hit50.png')  # оценка - Bad
hit100 = load_image('skin/hit100.png')  # оценка - Good
hit200 = load_image('skin/hit200.png')  # оценка - Great
hit300 = load_image('skin/hit300.png')  # оценка - Perfect
hit301 = load_image('skin/hit300g.png')  # оценка - Marvelous

st_x = 350  # координата по 'x' от которой отрисовываются все игровые объекты
keyboard = [pygame.K_d, pygame.K_f, pygame.K_j, pygame.K_k]  # кнопки на клавиатуре
settings_values = load_settings()  # загрузка настроек игрока
v = int(settings_values['scroll_speed'])  # скорость нот(в px/second)
time_uprise = ((720 - 130) / v * 1000) // 1  # время начала появления нот

# словарь обычного состояния персонажа
character_dict = {0: ('flandre/flandre', 3, 700, 300, 10),
                  1: ('marisa/marisa', 4, 700, 300, 10),
                  2: ('reimu/reimu', 10, 700, 300, 8, True),
                  3: ('remilia/remilia', 5, 700, 300, 10),
                  4: ('sakuya/sakuya', 7, 700, 300, 10, True)}

# словарь анимации способностей персонажей(персонажи со способностями: Flandre, Marisa, Remilia)
ability_dict = {0: ('flandre/flandre_ability', 6, 600, 300, 10, True),
                1: ('marisa/marisa_ability', 11, 700, 300, 10, True),
                3: ('remilia/remilia_ability', 16, 600, 300, 10, True)}
Example #7
0
    def __init__(self):
        # initi parent class and get a refernece to the logger
        QThread.__init__(self)
        self._logger = logging.getLogger()

        # load settings in temp variable first to migrate versions
        temp_settings = QSettings()
        settings_version = temp_settings.value("version", 0)
        if settings_version == 300:
            # upgrade from version 300 (some beta app users) to 1
            temp_settings.setValue("addon_beta",
                                   temp_settings.value("tsm3_beta", False))
            temp_settings.remove("tsm3_beta")
            temp_settings.setValue("version", 1)
        settings_version = temp_settings.value("version", 0)
        if settings_version == 1:
            # removed beta settings with version 2
            temp_settings.remove("addon_beta")
            temp_settings.remove("has_beta_access")
            temp_settings.setValue("version", 2)
        del temp_settings

        # load settings for real
        self._settings = load_settings(Config.DEFAULT_SETTINGS)
        if self._settings.version == 0:
            # this is the first time we've run r300 or higher
            old_login_settings = load_settings(
                Config.DEFAULT_OLD_LOGIN_SETTINGS, Config.ORG_NAME,
                "TSMAppLogin")
            try:
                if old_login_settings.userId > 0:
                    # import the settings we care about from the old app
                    self._settings.email = old_login_settings.email
                    self._settings.password = str(old_login_settings.password,
                                                  encoding="ascii")
                    self._settings.accepted_terms = (
                        old_login_settings.touAccepted == "true")
                    # need to use QSettings directly for the regular settings since it uses groups / arrays
                    old_settings = QSettings(QSettings.IniFormat,
                                             QSettings.UserScope,
                                             Config.ORG_NAME, "TSMApplication")
                    self._settings.wow_path = old_settings.value(
                        "core/wowDirPath", Config.DEFAULT_SETTINGS['wow_path'])
                    self._logger.info("Imported old settings!")
            except Exception as e:
                # just log it and move on
                self._logger.warn(
                    "Error while importing old settings: {}".format(str(e)))
        self._settings.version = Config.SETTINGS_VERSION
        self._prev_close_reason = self._settings.close_reason
        self._settings.close_reason = Config.CLOSE_REASON_UNKNOWN
        self.update_run_at_startup()

        # set system ID if it's not already set
        if not self._settings.system_id:
            alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-="
            assert (len(alphabet) == 64)
            mac = uuid.getnode()
            assert (mac < 2**48)
            result = ""
            for i in range(0, 8):
                result += alphabet[mac % 64]
                mac //= 64
            self._settings.system_id = result
        Config.SYSTEM_ID = self._settings.system_id
        self._temp_backup_path = os.path.abspath(
            os.path.join(Config.BACKUP_DIR_PATH, os.pardir,
                         Config.TEMP_BACKUP_DIR))
        os.makedirs(self._temp_backup_path, exist_ok=True)

        # initialize other helper classes
        self._api = AppAPI()
        self._wow_helper = WoWHelper()
        self._wow_helper.addons_folder_changed.connect(
            self._update_addon_status)

        # initialize the variables which allow us to wait for signals
        self._wait_event = self.WaitEvent.NONE
        self._wait_context = None
        self._wait_condition = QWaitCondition()
        self._wait_mutex = QMutex()

        # initialize the FSM state and related variables
        self._state = self.State.INIT
        self._sleep_time = 0
        self._addon_versions = []
        self._data_sync_status = {}
        self._backups = []
        self._last_news = ""
        self._is_logged_out = None
        self._status_message = ""
        self._status_message_strong = False
Example #8
0
    def __init__(self):
        # Init the base class
        QMainWindow.__init__(self)

        self._settings = load_settings(Config.DEFAULT_SETTINGS)

        # Init the processed .ui file
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self)
        self.setWindowTitle("TradeSkillMaster Application r{}".format(Config.CURRENT_VERSION))

        # connect signals / slots
        self._ui.addon_status_table.doubleClicked.connect(self._addon_status_table_clicked)
        self._ui.backup_status_table.doubleClicked.connect(self._backup_status_table_clicked)
        self._ui.settings_button.clicked.connect(self.settings_button_clicked.emit)
        self._ui.accounts_dropdown.activated['QString'].connect(self.accounts_dropdown_changed)
        self._ui.realm_dropdown.activated['QString'].connect(self.realm_dropdown_changed)
        self._ui.export_button.clicked.connect(self.export_button_clicked)
        self._ui.help_button.setProperty("url", "http://tradeskillmaster.com/site/getting-help")
        self._ui.help_button.clicked.connect(self._link_button_clicked)
        self._ui.premium_button.setProperty("url", "http://tradeskillmaster.com/premium")
        self._ui.premium_button.clicked.connect(self._link_button_clicked)
        self._ui.logo_button.setProperty("url", "http://tradeskillmaster.com")
        self._ui.logo_button.clicked.connect(self._link_button_clicked)
        self._ui.twitter_button.setProperty("url", "http://twitter.com/TSMAddon")
        self._ui.twitter_button.clicked.connect(self._link_button_clicked)

        # Apply the stylesheet
        file = QFile(":/resources/main_window.css")
        file.open(QIODevice.ReadOnly)
        data = str(file.readAll(), encoding="ascii")
        self.setStyleSheet(data)

        # set properties which are necessary for tweaking the style
        self._ui.help_button.setProperty("id", "premiumButton")
        self._ui.premium_button.setProperty("id", "premiumButton")
        self._ui.header_text.setProperty("id", "headerText")

        # stylesheet tweaks for things which don't work when put into the .css for some unknown reason
        self._ui.accounting_tab.setStyleSheet("QCheckBox:disabled { color : #666; } QCheckBox { color : white; }");

        self._sync_status_table_model = TableModel(self, ['Region/Realm', 'AuctionDB', 'Great Deals', 'Last Updated'])
        self._ui.sync_status_table.setModel(self._sync_status_table_model)

        self._addon_status_table_model = TableModel(self, ['Name', 'Version', 'Status'])
        self._ui.addon_status_table.setModel(self._addon_status_table_model)

        self._backup_status_table_model = TableModel(self, ['System ID', 'Account', 'Timestamp', 'Sync Status'])
        self._ui.backup_status_table.setModel(self._backup_status_table_model)

        self._accounting_info = {}
        self._accounting_current_account = ""
        self._accounting_current_realm = ""

        if Config.IS_WINDOWS:
            # create the system tray icon / menu
            self._tray_icon = QSystemTrayIcon(QIcon(":/resources/logo.png"), self)
            self._tray_icon.setToolTip("TradeSkillMaster Application r{}".format(Config.CURRENT_VERSION))
            self._tray_icon.activated.connect(self._icon_activated)
            tray_icon_menu = QMenu(self)
            restore_action = QAction("Restore", tray_icon_menu)
            restore_action.triggered.connect(self._restore_from_tray)
            tray_icon_menu.addAction(restore_action)
            tray_icon_menu.addSeparator()
            quit_action = QAction("Quit", tray_icon_menu)
            quit_action.triggered.connect(self.close)
            tray_icon_menu.addAction(quit_action)
            self._tray_icon.setContextMenu(tray_icon_menu)
            self._tray_icon.hide()
    def __init__(self, parent):
        # Init the base class
        QMainWindow.__init__(self, parent)
        self.setWindowFlags(Qt.Window | Qt.WindowCloseButtonHint)

        self._ignore_changes = False
        self._settings = load_settings(Config.DEFAULT_SETTINGS)

        # Init the processed .ui file
        self._ui = Ui_SettingsWindow()
        self._ui.setupUi(self)
        self.setWindowTitle("Settings - r{}".format(Config.CURRENT_VERSION))

        # connect signals / slots
        self._ui.realm_setup_button.setProperty(
            "url", "http://tradeskillmaster.com/realms")
        self._ui.realm_setup_button.clicked.connect(self._link_button_clicked)
        self._ui.open_backups_button.clicked.connect(self._open_backups)
        self._ui.upload_log_button.clicked.connect(
            self.upload_log_button_clicked)
        self._ui.done_button.clicked.connect(self.hide)
        self._ui.wow_dir_browse_button.clicked.connect(
            self.wow_dir_button_clicked)
        self._ui.reset_button.clicked.connect(self.reset_button_clicked)
        self._settings_widgets = {
            'run_at_startup': self._ui.run_at_startup_checkbox,
            'start_minimized': self._ui.start_minimized_checkbox,
            'minimize_to_tray': self._ui.minimize_to_tray_checkbox,
            'confirm_exit': self._ui.confirm_exit_checkbox,
            'realm_data_notification':
            self._ui.realm_data_notification_checkbox,
            'addon_notification': self._ui.addon_notification_checkbox,
            'backup_notification': self._ui.backup_notification_checkbox,
            'news_notification': self._ui.news_notification_checkbox,
        }
        for setting_key, widget in self._settings_widgets.items():
            if isinstance(widget, QCheckBox):
                widget.stateChanged.connect(self.checkbox_changed)
                widget.setProperty("setting_key", setting_key)

        # populate dropdowns
        def get_seconds(**kwargs):
            return int(timedelta(**kwargs).total_seconds())

        # populate backup period dropdown
        self._backup_period_text = [
            "30 minutes", "1 hour", "3 hours", "12 hours", "1 day", "3 days"
        ]
        self._backup_period_value = [
            get_seconds(minutes=30),
            get_seconds(hours=1),
            get_seconds(hours=3),
            get_seconds(hours=12),
            get_seconds(days=1),
            get_seconds(days=3)
        ]
        assert (len(self._backup_period_text) == len(
            self._backup_period_value))
        for item in self._backup_period_text:
            self._ui.backup_period_dropdown.addItem(item)
        if self._settings.backup_period not in self._backup_period_value:
            logging.getLogger().warning(
                "Resetting backup expiration to default")
            self._settings.backup_period = Config.DEFAULT_SETTINGS[
                'backup_period']
        self._ui.backup_period_dropdown.setCurrentIndex(
            self._backup_period_value.index(self._settings.backup_period))
        self._ui.backup_period_dropdown.activated['int'].connect(
            self.backup_period_dropdown_changed)

        # populate backup expiration dropdown
        self._backup_expire_text = ["3 days", "1 week", "1 month", "1 year"]
        self._backup_expire_value = [
            get_seconds(days=3),
            get_seconds(days=7),
            get_seconds(days=30),
            get_seconds(days=365)
        ]
        assert (len(self._backup_expire_text) == len(
            self._backup_expire_value))
        for item in self._backup_expire_text:
            self._ui.backup_expiration_dropdown.addItem(item)
        if self._settings.backup_expire not in self._backup_expire_value:
            logging.getLogger().warning(
                "Resetting backup expiration to default")
            self._settings.backup_expire = Config.DEFAULT_SETTINGS[
                'backup_expire']
        self._ui.backup_expiration_dropdown.setCurrentIndex(
            self._backup_expire_value.index(self._settings.backup_expire))
        self._ui.backup_expiration_dropdown.activated['int'].connect(
            self.backup_expire_dropdown_changed)

        # Apply the stylesheet
        file = QFile(":/resources/settings_window.css")
        file.open(QIODevice.ReadOnly)
        data = str(file.readAll(), encoding="ascii")
        self.setStyleSheet(data)

        # stylesheet tweaks for things which don't work when put into the .css for some unknown reason
        self._ui.general_tab.setStyleSheet(
            "QCheckBox:disabled { color : #666; } QCheckBox { color : white; }"
        )
        self._ui.notifications_tab.setStyleSheet(
            "QCheckBox:disabled { color : #666; } QCheckBox { color : white; }"
        )
        self._ui.advanced_tab.setStyleSheet(
            "QCheckBox:disabled { color : #666; } QCheckBox { color : white; }"
        )
Example #10
0
    factory.protocol = EmuServerProtocol

    if get_setting('secure'):

        contextFactory = ssl.DefaultOpenSSLContextFactory(
            get_setting('tls', 'private'), get_setting('tls', 'cert'))

        reactor.listenSSL(get_setting('port'), factory, contextFactory)
    else:
        reactor.listenTCP(get_setting('port'), factory)

    reactor.run()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='EMU-webApp server program')
    parser.add_argument('settings', help='Settings file', nargs='?')

    args = parser.parse_args()

    if args.settings:
        load_settings(args.settings)

    if get_setting('daemonize'):
        d = daemonize.Daemonize(app=os.path.basename(sys.argv[0]),
                                pid=get_setting('pid'),
                                action=run_server)
        d.start()
    else:
        run_server()