-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
321 lines (262 loc) · 11.9 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
from datetime import datetime
from functools import partial
from kivy.app import App
from kivy.base import Clock, Config
from kivy.core.text import LabelBase
from kivy.logger import Logger
from kivy.metrics import sp
from kivy.network.urlrequest import UrlRequest
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.uix.listview import ListItemButton
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import Screen, ScreenManager, RiseInTransition
from kivy.utils import get_color_from_hex as c, Platform
from string import Formatter
import database
LabelBase.register('symbols', fn_regular='assets/weathersymbols.ttf')
COLOURS = ['FF3B30', '2ECC71', '3498DB', '1ABC9C', '27AE60', 'E74C3C']
mobile_platform = Platform() in ('ios', 'android')
if not mobile_platform:
# This must be here because a mobile screen is high density
Config.set('graphics', 'height', int(1280 * 0.5)) # 50% of screen size
Config.set('graphics', 'width', int(720 * 0.5)) # 50% of screen size
Config.set('kivy', 'log_level', 'warning')
def find_location(location, on_success):
url = Formatter().format(database.URLS['find_location'], location=location, appid=database.OPENWEATHERKEY)
UrlRequest(url, on_success=on_success)
class LargeButton(Button):
pass
class LocationButton(LargeButton):
def __init__(self, location, **kwargs):
self.location = location # This is here because object is linked to .kv in super and we need location attribute
self.current_weather = self.location.get_current_weather
super(LocationButton, self).__init__(**kwargs)
self.long_press_clock = None
def on_location_button_press(self):
if not root.has_screen(self.location.town):
root.add_widget(
SimpleWeatherScreen(self.location)
)
root.current = self.location.town
def create_clock(self, touch):
function = partial(self.menu, touch)
self.long_press_clock = Clock.schedule_once(function, 2)
touch.ud['event'] = function # So we can unschedule it if the button is pressed early
def delete_clock(self, touch):
try:
Clock.unschedule(touch.ud['event'])
except KeyError:
pass
self.long_press_clock = None
def menu(self, touch, time):
menu = DeleteDialog(self.location)
menu.open()
def close_menu(self, widget):
self.root.remove_widget(widget)
def on_touch_down(self, touch):
super(LocationButton, self).on_touch_down(touch)
if self.collide_point(*touch.pos):
self.create_clock(touch)
def on_touch_up(self, touch):
if self.collide_point(*touch.pos):
if self.long_press_clock is not None:
if self.long_press_clock.is_triggered: # Has 2 seconds gone past when we lifted the finger?
# If not we display simple location screen instead
# Seems to work in opposite way to expected?
self.on_location_button_press()
else:
return
self.delete_clock(touch)
super(LocationButton, self).on_touch_up(touch)
class LargeGrid:
pass
class RectangleButton(ListItemButton):
iter_number = 0
def __init__(self, forecast=None, **kwargs): # I dont think this should have forecast in it
super(RectangleButton, self).__init__(**kwargs)
self.background_color = c(COLOURS[RectangleButton.iter_number % len(COLOURS)])
RectangleButton.iter_number += 1
self.forecast = forecast
class SearchRectangleButton(RectangleButton):
def __init__(self, location, **kwargs):
self.location = location
super(SearchRectangleButton, self).__init__(**kwargs)
def on_result_press(self, button):
location = button.location
location.save_to_db()
root.get_screen('menu').populate()
root.current = 'menu'
root.get_screen('addform').reset()
class RectangleGrid: # Used as a references
pass
class DeleteDialog(Popup):
location = ObjectProperty()
def __init__(self, location, **kwargs):
super(DeleteDialog, self).__init__(**kwargs)
self.title = 'Delete Location'
self.location = location
self.ids.get('dialog_base_title').text = Formatter().format('Are you sure you\nwant to delete\n{location}?',
location=self.location.town)
self.separator_color = (0, 0, 0, 0)
self.title_align = 'center'
self.title_size = 60 if mobile_platform else 30
def on_yes_press(self):
self.location.remove_from_db()
root.get_screen('menu').populate()
self.dismiss()
def on_no_press(self):
self.dismiss()
# Screens
class AddLocationForm(Screen):
def __init__(self):
super(AddLocationForm, self).__init__()
self.results = self.ids.get('results')
self.results.bind(minimum_height=self.results.setter('height'))
self.input = self.ids.get('input')
def on_search(self):
location = self.input.text
if len(location) < 3:
popup_widget = AddLocErrorForm()
popup_widget.open()
else:
find_location(location, self.on_found_search)
def on_found_search(self, _, data):
self.results.clear_widgets()
if data['count'] > 0:
for count in range(data['count']):
location = database.location_from_json(data, count)
button = SearchRectangleButton(
location,
font_size=60 if mobile_platform else 30,
)
button.bind(on_release=self.reset)
self.results.add_widget(button)
else: # else nothing found
button = RectangleButton(
font_size=60 if mobile_platform else 30,
text='Nothing Found',
)
button.bind(on_release=self.on_remove_nothing_found_button)
self.results.add_widget(button)
Logger.warn('We didn\'t find anything when searching')
def on_remove_nothing_found_button(self, button):
self.results.remove_widget(button)
def reset(self, widget=None):
self.input.text = ''
self.results.clear_widgets()
if widget is not None:
widget.on_result_press(widget)
def reset_and_back(self):
self.reset()
root.current = 'menu'
class AddLocErrorForm(Popup):
def __init__(self):
super(AddLocErrorForm, self).__init__()
self.separator_color = (0, 0, 0, 0)
self.title_align = 'center'
self.title_size = 60 if mobile_platform else 30
self.title = 'Error'
class SimpleWeatherScreen(Screen):
location = ObjectProperty()
def __init__(self, location):
super(SimpleWeatherScreen, self).__init__()
self.location = location
self.name = self.location.town
self.simple_weather_scroll = self.ids.get('SimpleWeatherScroll')
self.simple_weather_scroll.bind(minimum_height=self.simple_weather_scroll.setter('height'))
self.forecasts = self.location.forecasts
self.ids.get('simple_menu_title').text = self.location.town
for count, forecast in enumerate(self.forecasts):
day_time = datetime.fromtimestamp(forecast.time)
day = database.weekdays[day_time.weekday()]
if day_time.day == datetime.now().day:
day = 'Today'
elif day_time.day == datetime.now().day + 1: # Not sure this is gonna work at the end of the month
day = 'Tomorrow'
button_text = Formatter().format('[font=symbols]{symbol}[/font] {weekday} {time}:00',
symbol=forecast.symbol,
weekday=day,
time=(day_time.hour + location.timezone) % 24)
widget = RectangleButton(forecast=forecast,
text=button_text,
background_color=c(COLOURS[count % len(COLOURS)]),
font_size=80 if mobile_platform else 40)
widget.bind(on_release=self.on_weather_time_press)
self.simple_weather_scroll.add_widget(widget)
def on_weather_time_press(self, widget):
new_screen = DetailedWeatherScreen(widget.forecast)
self.manager.add_widget(new_screen)
self.manager.current = new_screen.name
def refresh_and_change_screen(self):
self.manager.current = 'menu'
class DetailedWeatherScreen(Screen):
def __init__(self, forecast):
location = forecast.location
name = location.town + str(forecast.time)
super(DetailedWeatherScreen, self).__init__(name=name)
self.location = location
self.forecast = forecast
day_time = datetime.fromtimestamp(forecast.time)
detailed_menu_title = self.ids.get('detailed_menu_title')
detailed_menu_title.text = Formatter().format('{town} {hour}:00', town=self.location.town, hour=(day_time.hour + self.location.timezone) % 24)
self.ids.get('detailed_return_button').bind(on_release=self.return_to_simple_screen)
detailed_menu_symbol = self.ids.get('detailed_menu_symbol')
detailed_menu_symbol.text = Formatter().format('[font=symbols]{symbol}[/font]', symbol=forecast.symbol)
text = Formatter().format('[font=symbols]k[/font]Temperature: {temperature}[sup]o[/sup]C\n'
'Pressure: {pressure} Pa\nHumidity: {humidity} %\n'
'\nClouds Cover: {clouds} %\nWind Speed: {clouds} m/s\n'
'Wind Direction: {direction}[sup]o[/sup]',
temperature=int(self.forecast.temp - 273),
pressure=int(self.forecast.pressure) * 100, # To convert hPa to Pa
humidity=self.forecast.humidity,
clouds=self.forecast.clouds,
wind_speed=self.forecast.wind_speed,
direction=int(self.forecast.wind_direction))
self.ids.get('detailed_menu_text').text = text
def return_to_simple_screen(self, widget):
self.manager.current = self.location.town
class MenuScreen(Screen):
def __init__(self):
super(MenuScreen, self).__init__()
self.location_grid = self.ids.get('location_grid')
self.location_grid.bind(minimum_height=self.location_grid.setter('height'))
self.populate()
def populate(self):
self.location_grid.clear_widgets()
locations = database.Location.all_locations()
for iteration, location in enumerate(locations):
button = LocationButton(
location,
background_color=c(COLOURS[iteration % len(COLOURS)]),
)
self.location_grid.add_widget(button)
button = LargeButton(
text='+',
font_size=sp(150),
background_color=c('#16a085')
)
button.bind(on_release=self.on_add_button_press)
self.location_grid.add_widget(button)
@staticmethod
def on_add_button_press(widget):
root.current = 'addform'
class WeatherApp(App): # Will import weather.kv automatically
def __init__(self):
super(WeatherApp, self).__init__()
self.title = 'Weather Application'
self.icon = 'assets\\icon.png'
database._db.remove_old_forecasts()
database.refresh_forecasts()
def build(self):
root.add_widget(MenuScreen())
root.add_widget(AddLocationForm())
return root
def on_pause(self): # For mobile devices
return True
def on_stop(self):
database._db.close()
root = ScreenManager(transition=RiseInTransition())
if __name__ in ('__main__', '__android__'):
app = WeatherApp()
app.run()